fixes-6
This commit is contained in:
parent
3d12dc0f6a
commit
4452ddad79
48
src/main.rs
48
src/main.rs
|
@ -52,6 +52,38 @@ async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> {
|
|||
Ok(id)
|
||||
}
|
||||
|
||||
|
||||
async fn create_first_chat(author_id: i32) -> Vec<String> {
|
||||
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<String>,
|
||||
mut rx: web::Data<Receiver<String>>,
|
||||
|
@ -71,14 +103,20 @@ async fn sse_handler(
|
|||
.await
|
||||
.unwrap();
|
||||
|
||||
let chats: Vec<String> = con
|
||||
.smembers(format!("chats_by_author/{}", author_id))
|
||||
.await
|
||||
.unwrap();
|
||||
let chats: Vec<String> = 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();
|
||||
|
|
Loading…
Reference in New Issue
Block a user