From e4b33c11c9b88ab11362ad6bf6ad0042b5240e3f Mon Sep 17 00:00:00 2001 From: alemi Date: Wed, 21 Feb 2024 21:06:35 +0100 Subject: [PATCH] fix: update list and send event for user removal --- src/main.rs | 9 +++++++-- src/session.rs | 19 ++++++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index f111852..656023e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -100,9 +100,14 @@ async fn server_ws(ws: WebSocketUpgrade, State(session): State>) -> ws.on_upgrade(|socket| handle_ws(socket, sub)) } -async fn handle_ws(mut socket: WebSocket, mut sub: broadcast::Receiver) { +async fn handle_ws(mut socket: WebSocket, mut sub: broadcast::Receiver) { while let Ok(event) = sub.recv().await { - socket.send(Message::Text(serde_json::to_string(&event).unwrap())).await.unwrap(); + match event { + session::SessionEvent::AddUser(user) => + socket.send(Message::Text(serde_json::to_string(&user).expect("could not serialize user"))).await.unwrap(), + session::SessionEvent::RemoveUser(id) => + socket.send(Message::Text(format!("{{\"remove\":{id}}}"))).await.unwrap(), + } } } diff --git a/src/session.rs b/src/session.rs index 466e966..2ee12a4 100644 --- a/src/session.rs +++ b/src/session.rs @@ -11,7 +11,13 @@ pub struct Session { host: String, sync: watch::Receiver, drop: mpsc::Sender<()>, - events: broadcast::Sender, + events: broadcast::Sender, +} + +#[derive(Debug, Clone)] +pub enum SessionEvent { + AddUser(User), + RemoveUser(u32), } impl Drop for Session { @@ -75,7 +81,7 @@ impl Session { self.host.to_string() } - pub fn events(&self) -> broadcast::Receiver { + pub fn events(&self) -> broadcast::Receiver { self.events.subscribe() } @@ -129,6 +135,11 @@ impl Session { Err(e) => break tracing::warn!("disconnected from server: {}", e), // Ok(tcp::proto::Packet::TextMessage(msg)) => tracing::info!("{}", msg.message), // Ok(tcp::proto::Packet::ChannelState(channel)) => tracing::info!("discovered channel: {:?}", channel.name), + Ok(proto::Packet::UserRemove(user)) => { + tracing::info!("remove user: {:?}", user); + session.users.write().await.remove(&user.session); + let _ = session.events.send(SessionEvent::RemoveUser(user.session)); + }, Ok(proto::Packet::ServerSync(_sync)) => { tracing::info!("synched: {:?}", _sync); ready.send(true).unwrap(); @@ -141,7 +152,9 @@ impl Session { Some(u) => u.update(user), None => { users.insert(user.session(), User::from(user)); }, } - let _ = session.events.send(users.get(&id).cloned().expect("just inserted")); // if it fails nobody is listening + let _ = session.events.send( + SessionEvent::AddUser(users.get(&id).cloned().expect("just inserted")) + ); // if it fails nobody is listening }, Ok(pkt) => tracing::info!("ignoring packet {:?}", pkt), }