refactor: clients now have a single websocket that handles all rooms the user is in

This commit is contained in:
2026-01-16 11:35:07 +01:00
parent 376353833c
commit 37e6bb25fc
8 changed files with 74 additions and 66 deletions
+27 -3
View File
@@ -18,6 +18,7 @@ pub struct MessageRow {
pub uuid: Uuid,
pub sender: String,
pub sender_uuid: Uuid,
pub room_uuid: Uuid,
pub message_type: String,
pub content: String,
pub sent_at: chrono::NaiveDateTime,
@@ -26,6 +27,7 @@ pub struct MessageRow {
#[derive(serde::Serialize, Debug, Clone)]
pub struct Message {
pub uuid: Uuid,
pub room_uuid: Uuid,
pub sender: String,
pub sender_uuid: Uuid,
pub message_type: String,
@@ -77,7 +79,7 @@ async fn list_messages(
m.uuid,
u.username AS sender,
u.uuid AS sender_uuid,
r.uuid AS room,
r.uuid AS room_uuid,
m.message_type,
m.content,
m.sent_at
@@ -106,6 +108,7 @@ async fn list_messages(
.into_iter()
.map(|m| Message {
uuid: m.uuid,
room_uuid: m.room_uuid,
sender: m.sender,
sender_uuid: m.sender_uuid,
message_type: m.message_type,
@@ -157,6 +160,7 @@ async fn create_message(
let message = Message {
uuid: uuid,
room_uuid,
sender: sender_name,
sender_uuid: claims.sub,
message_type: payload.message_type,
@@ -164,8 +168,28 @@ async fn create_message(
sent_at: sent_at.format("%Y-%m-%d %H:%M:%S").to_string(),
};
let rt_sender = realtime.sender_for(room_id);
let _ = rt_sender.send(message.clone());
let recipients: Vec<Uuid> = sqlx::query_scalar(
r#"
SELECT u.uuid
FROM membership_ m
JOIN user_ u ON u.id = m.user_id
WHERE m.room = $1
"#,
)
.bind(room_id)
.fetch_all(&db)
.await
.map_err(|e| {
tracing::error!("Error fetching message recipients: {e}");
(StatusCode::INTERNAL_SERVER_ERROR, "DB error".into())
})?;
let rt = realtime.clone();
let msg_clone = message.clone();
tokio::spawn(async move {
rt.broadcast(recipients, msg_clone);
});
Ok((StatusCode::CREATED, Json(message)))
}