diff --git a/src/main.rs b/src/main.rs index a9069a4..f030675 100644 --- a/src/main.rs +++ b/src/main.rs @@ -52,6 +52,38 @@ async fn get_auth_id(token: &str) -> Result> { Ok(id) } + +async fn create_first_chat(author_id: i32) -> Vec { + let chat_id = uuid::Uuid::new_v4().to_string(); + let members = vec![author_id.to_string(), "1".to_string()]; + let title = ""; + let created_by = author_id; + let timestamp = chrono::Utc::now().timestamp(); + let admins = if members.len() == 2 && title.is_empty() { members.clone() } else { vec![] }; + + let chat = serde_json::json!({ + "id": chat_id, + "users": members, + "title": title, + "createdBy": created_by, + "createdAt": timestamp, + "updatedAt": timestamp, + "admins": admins, + }); + + let _: () = redis::pipe() + .atomic() + .sadd_multiple(format!("chats_by_author/{}", author_id), &members) + .set(format!("chats/{}", chat_id), chat.to_string()) + .set(format!("chats/{}/next_message_id", chat_id), "0") + .query_async(&mut con) + .await + .unwrap(); + + vec![chat, ] +} + + async fn sse_handler( token: web::Path, mut rx: web::Data>, @@ -71,14 +103,20 @@ async fn sse_handler( .await .unwrap(); - let chats: Vec = con - .smembers(format!("chats_by_author/{}", author_id)) - .await - .unwrap(); + let chats: Vec = match con.smembers(format!("chats_by_author/{}", author_id)).await { + Ok(chats) => { + if chats.is_empty() { + create_first_chat(author_id).await + } else { + chats + } + }, + Err(_) => create_first_chat(author_id).await + }; let mut pubsub = con.into_pubsub(); for chat_id in chats { - pubsub.subscribe(format!("message:{}", chat_id)).await.unwrap(); + pubsub.subscribe(format!("chat:{}", chat_id)).await.unwrap(); } let server_event = rx.recv().await.unwrap();