Fixed auth per connection, one hub, one fan-out and one room owner
Browse files at this commit700e2a49bd41079cec24b74833faa3354b2cc327Parent: e2d1bd5- refactor
- fixed auth per connection, one hub, one fan-out and one room owner
27 changed files +1978 -1843
- crates/client/src/accounts.rs +4 -0
- crates/client/src/gui.rs +4 -8
- crates/client/src/gui/chat.rs +10 -6
- crates/client/src/gui/composer.rs +1 -6
- crates/client/src/gui/settings_page.rs +3 -0
- crates/client/src/net/events.rs +14 -9
- crates/client/src/net/link.rs +55 -39
- crates/client/src/net/mod.rs +28 -13
- crates/client/src/net/share.rs +11 -8
- crates/common/src/event.rs +18 -30
- crates/common/src/lib.rs +1 -0
- crates/common/src/request.rs +3 -7
- crates/common/src/session.rs +14 -0
- crates/server/src/attachment.rs +9 -8
- crates/server/src/authentication.rs +39 -6
- crates/server/src/datagram.rs +5 -12
- crates/server/src/hub.rs +218 -0
- crates/server/src/lib.rs +3 -3
- crates/server/src/network.rs +186 -342
- crates/server/src/overview.rs +4 -8
- crates/server/src/publish.rs +117 -0
- crates/server/src/request.rs +442 -652
- crates/server/src/retention.rs +32 -16
- crates/server/src/rooms.rs +748 -0
- crates/server/src/share.rs +0 -347
- crates/server/src/user_community.rs +9 -0
- crates/server/src/voice.rs +0 -323
crates/client/src/accounts.rsmodified+4 -0
| @@ -48,6 +48,10 @@ impl Accounts { | |||
| 48 | } | 48 | } |
| 49 | } | 49 | } |
| 50 | 50 | ||
| 51 | + pub fn suspend(&mut self) { | ||
| 52 | + self.active = None; | ||
| 53 | + } | ||
| 54 | + | ||
| 51 | pub fn detach(&mut self) { | 55 | pub fn detach(&mut self) { |
| 52 | self.active = None; | 56 | self.active = None; |
| 53 | save(self); | 57 | save(self); |
crates/client/src/gui.rsmodified+4 -8
| @@ -735,6 +735,7 @@ impl Yumush { | |||
| 735 | if self.user.is_some() { | 735 | if self.user.is_some() { |
| 736 | self.end_session(window, cx); | 736 | self.end_session(window, cx); |
| 737 | } | 737 | } |
| 738 | + self.accounts.suspend(); | ||
| 738 | let network = self.network.clone(); | 739 | let network = self.network.clone(); |
| 739 | 740 | ||
| 740 | cx.spawn_in(window, async move |this, cx| { | 741 | cx.spawn_in(window, async move |this, cx| { |
| @@ -945,6 +946,7 @@ impl Yumush { | |||
| 945 | Event::VoiceMuted { | 946 | Event::VoiceMuted { |
| 946 | user_id, | 947 | user_id, |
| 947 | muted: true, | 948 | muted: true, |
| 949 | + .. | ||
| 948 | } if self.is_me(user_id) => self.set_muted(true, cx), | 950 | } if self.is_me(user_id) => self.set_muted(true, cx), |
| 949 | Event::ShareStopped { user_id, kind, .. } if self.is_watching(user_id, *kind) => { | 951 | Event::ShareStopped { user_id, kind, .. } if self.is_watching(user_id, *kind) => { |
| 950 | self.close_viewer(cx) | 952 | self.close_viewer(cx) |
| @@ -1182,7 +1184,7 @@ impl Yumush { | |||
| 1182 | self.apply_pushed(Event::CommunityDeleted { community_id }, cx); | 1184 | self.apply_pushed(Event::CommunityDeleted { community_id }, cx); |
| 1183 | } | 1185 | } |
| 1184 | Event::ReportCreated => self.report_created(window, cx), | 1186 | Event::ReportCreated => self.report_created(window, cx), |
| 1185 | - Event::Announcement { text } => self.set_announcement(text), | 1187 | + Event::SettingsUpdated(settings) => self.server = Some(settings), |
| 1186 | event => { | 1188 | event => { |
| 1187 | let voice = matches!( | 1189 | let voice = matches!( |
| 1188 | event, | 1190 | event, |
| @@ -1231,12 +1233,6 @@ impl Yumush { | |||
| 1231 | } | 1233 | } |
| 1232 | } | 1234 | } |
| 1233 | 1235 | ||
| 1234 | - fn set_announcement(&mut self, text: String) { | ||
| 1235 | - if let Some(settings) = self.server.as_mut() { | ||
| 1236 | - settings.announcement = text; | ||
| 1237 | - } | ||
| 1238 | - } | ||
| 1239 | - | ||
| 1240 | fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context<Self>) { | 1236 | fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context<Self>) { |
| 1241 | match event { | 1237 | match event { |
| 1242 | NetworkEvent::Connected => { | 1238 | NetworkEvent::Connected => { |
| @@ -1250,7 +1246,7 @@ impl Yumush { | |||
| 1250 | | Event::Removed { .. } | 1246 | | Event::Removed { .. } |
| 1251 | | Event::CommunityDeleted { .. } | 1247 | | Event::CommunityDeleted { .. } |
| 1252 | | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), | 1248 | | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), |
| 1253 | - Event::Announcement { text } => self.set_announcement(text), | 1249 | + Event::SettingsUpdated(settings) => self.server = Some(settings), |
| 1254 | event => self.apply_pushed(event, cx), | 1250 | event => self.apply_pushed(event, cx), |
| 1255 | }, | 1251 | }, |
| 1256 | } | 1252 | } |
crates/client/src/gui/chat.rsmodified+10 -6
| @@ -547,9 +547,11 @@ impl Chat { | |||
| 547 | } | 547 | } |
| 548 | } | 548 | } |
| 549 | } | 549 | } |
| 550 | - Event::MessageDeleted(message) => { | 550 | + Event::MessagesDeleted { community_id, ids } => { |
| 551 | - if self.is_selected(&message.community_id) { | 551 | + if self.is_selected(&community_id) { |
| 552 | - self.forget_message(&message.id); | 552 | + for id in &ids { |
| 553 | + self.forget_message(id); | ||
| 554 | + } | ||
| 553 | } | 555 | } |
| 554 | } | 556 | } |
| 555 | Event::MemberJoined { | 557 | Event::MemberJoined { |
| @@ -613,7 +615,7 @@ impl Chat { | |||
| 613 | } | 615 | } |
| 614 | } | 616 | } |
| 615 | } | 617 | } |
| 616 | - Event::VoiceMuted { user_id, muted } => { | 618 | + Event::VoiceMuted { user_id, muted, .. } => { |
| 617 | if muted { | 619 | if muted { |
| 618 | self.server_muted.insert(user_id); | 620 | self.server_muted.insert(user_id); |
| 619 | } else { | 621 | } else { |
| @@ -648,8 +650,7 @@ impl Chat { | |||
| 648 | shares.retain(|share| share.user_id != user_id || share.kind != kind); | 650 | shares.retain(|share| share.user_id != user_id || share.kind != kind); |
| 649 | } | 651 | } |
| 650 | } | 652 | } |
| 651 | - Event::ShareLayers { .. } | Event::KeyframeWanted { .. } => {} | 653 | + Event::ReportCreated | Event::SettingsUpdated(_) => {} |
| 652 | - Event::ReportCreated | Event::Announcement { .. } => {} | ||
| 653 | } | 654 | } |
| 654 | } | 655 | } |
| 655 | 656 | ||
| @@ -1839,6 +1840,9 @@ impl Yumush { | |||
| 1839 | let latest = before.is_none() && window.is_window_active(); | 1840 | let latest = before.is_none() && window.is_window_active(); |
| 1840 | 1841 | ||
| 1841 | cx.spawn_in(window, async move |this, cx| { | 1842 | cx.spawn_in(window, async move |this, cx| { |
| 1843 | + if before.is_none() { | ||
| 1844 | + let _ = network.watch_community(Some(&community_id)).await; | ||
| 1845 | + } | ||
| 1842 | let Some(page) = ok_or_notify( | 1846 | let Some(page) = ok_or_notify( |
| 1843 | network | 1847 | network |
| 1844 | .read_messages(&community_id, before.as_deref()) | 1848 | .read_messages(&community_id, before.as_deref()) |
crates/client/src/gui/composer.rsmodified+1 -6
| @@ -321,12 +321,7 @@ impl Yumush { | |||
| 321 | cx.notify(); | 321 | cx.notify(); |
| 322 | } | 322 | } |
| 323 | 323 | ||
| 324 | - fn slow_down( | 324 | + fn slow_down(&mut self, seconds: u64, window: &mut Window, cx: &mut Context<Self>) { |
| 325 | - &mut self, | ||
| 326 | - seconds: u64, | ||
| 327 | - window: &mut Window, | ||
| 328 | - cx: &mut Context<Self>, | ||
| 329 | - ) { | ||
| 330 | self.chat.slowed_until = Some(now_ms() + seconds * 1000); | 325 | self.chat.slowed_until = Some(now_ms() + seconds * 1000); |
| 331 | 326 | ||
| 332 | cx.spawn_in(window, async move |this, cx| { | 327 | cx.spawn_in(window, async move |this, cx| { |
crates/client/src/gui/settings_page.rsmodified+3 -0
| @@ -230,6 +230,9 @@ impl Yumush { | |||
| 230 | let _ = this.update_in(cx, |yumush, window, cx| { | 230 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 231 | yumush.end_session(window, cx); | 231 | yumush.end_session(window, cx); |
| 232 | }); | 232 | }); |
| 233 | + if let Err(error) = network.detach().await { | ||
| 234 | + notify_error(&this, cx, error); | ||
| 235 | + } | ||
| 233 | } | 236 | } |
| 234 | Err(error) => notify_error(&this, cx, error), | 237 | Err(error) => notify_error(&this, cx, error), |
| 235 | } | 238 | } |
crates/client/src/net/events.rsmodified+14 -9
| @@ -1,5 +1,5 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | - event::Event, | 2 | + event::Down, |
| 3 | frame::{self, DOWN_MAX}, | 3 | frame::{self, DOWN_MAX}, |
| 4 | }; | 4 | }; |
| 5 | use tokio::sync::mpsc; | 5 | use tokio::sync::mpsc; |
| @@ -15,14 +15,19 @@ pub(super) async fn event_receive_loop( | |||
| 15 | return; | 15 | return; |
| 16 | }; | 16 | }; |
| 17 | 17 | ||
| 18 | - while let Ok(event) = frame::read::<Event>(&mut receive_stream, DOWN_MAX).await { | 18 | + while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await { |
| 19 | - share.lock().unwrap().event(&event); | 19 | + match down { |
| 20 | - if event_sender | 20 | + Down::Event(event) => { |
| 21 | - .send(NetworkEvent::Pushed(Box::new(event))) | 21 | + share.lock().unwrap().event(&event); |
| 22 | - .await | 22 | + if event_sender |
| 23 | - .is_err() | 23 | + .send(NetworkEvent::Pushed(event)) |
| 24 | - { | 24 | + .await |
| 25 | - return; | 25 | + .is_err() |
| 26 | + { | ||
| 27 | + return; | ||
| 28 | + } | ||
| 29 | + } | ||
| 30 | + Down::Media(media) => share.lock().unwrap().media(&media), | ||
| 26 | } | 31 | } |
| 27 | } | 32 | } |
| 28 | } | 33 | } |
crates/client/src/net/link.rsmodified+55 -39
| @@ -4,10 +4,11 @@ use common::{ | |||
| 4 | constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, | 4 | constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, |
| 5 | error::Error, | 5 | error::Error, |
| 6 | frame::{self, DOWN_MAX, Sending, UP_MAX}, | 6 | frame::{self, DOWN_MAX, Sending, UP_MAX}, |
| 7 | - model::Attachment, | 7 | + model::{Attachment, User}, |
| 8 | open::{Blob, Open, Upload}, | 8 | open::{Blob, Open, Upload}, |
| 9 | request::Request, | 9 | request::Request, |
| 10 | response::Response, | 10 | response::Response, |
| 11 | + session::{Hello, Welcome}, | ||
| 11 | transport::{Close, alpn, transport}, | 12 | transport::{Close, alpn, transport}, |
| 12 | validate::{validate_attachment_name, validate_attachment_size}, | 13 | validate::{validate_attachment_name, validate_attachment_size}, |
| 13 | }; | 14 | }; |
| @@ -272,6 +273,19 @@ pub(super) async fn send( | |||
| 272 | Ok(frame::read::<Result<Response, Error>>(&mut receive_stream, DOWN_MAX).await??) | 273 | Ok(frame::read::<Result<Response, Error>>(&mut receive_stream, DOWN_MAX).await??) |
| 273 | } | 274 | } |
| 274 | 275 | ||
| 276 | +async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> { | ||
| 277 | + let (send_stream, mut receive_stream) = connection.open_bi().await?; | ||
| 278 | + let mut send_stream = Sending::new(send_stream); | ||
| 279 | + let hello = Hello { | ||
| 280 | + token, | ||
| 281 | + device: device_name(), | ||
| 282 | + }; | ||
| 283 | + frame::write(&mut send_stream, &hello, UP_MAX).await?; | ||
| 284 | + send_stream.finish()?; | ||
| 285 | + | ||
| 286 | + Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??) | ||
| 287 | +} | ||
| 288 | + | ||
| 275 | pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> { | 289 | pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> { |
| 276 | match send(connection, &request).await? { | 290 | match send(connection, &request).await? { |
| 277 | Response::Done => Ok(()), | 291 | Response::Done => Ok(()), |
| @@ -410,6 +424,7 @@ async fn actor( | |||
| 410 | shared: Shared, | 424 | shared: Shared, |
| 411 | ) { | 425 | ) { |
| 412 | let mut token: Option<String> = None; | 426 | let mut token: Option<String> = None; |
| 427 | + let mut pending: Option<oneshot::Sender<Result<Option<User>, Fail>>> = None; | ||
| 413 | let mut endpoints = Endpoints::default(); | 428 | let mut endpoints = Endpoints::default(); |
| 414 | let mut attempt = 0u32; | 429 | let mut attempt = 0u32; |
| 415 | 'session: loop { | 430 | 'session: loop { |
| @@ -441,42 +456,52 @@ async fn actor( | |||
| 441 | }; | 456 | }; |
| 442 | }; | 457 | }; |
| 443 | 458 | ||
| 444 | - if let Some(stored) = token.clone() { | 459 | + let welcome = match hello(&connection, token.clone()).await { |
| 445 | - let request = Request::Resume { token: stored }; | 460 | + Ok(welcome) => welcome, |
| 446 | - match send(&connection, &request).await { | 461 | + Err(Fail::Server(error)) |
| 447 | - Ok(Response::Session { token: resumed, .. }) => { | 462 | + if token.is_some() |
| 448 | - token = Some(resumed); | 463 | + && (pending.is_some() |
| 449 | - } | 464 | + || matches!(error, Error::Unauthenticated | Error::NotFound)) => |
| 450 | - Err(error) => { | 465 | + { |
| 451 | - warn!("session resume failed: {error}"); | 466 | + warn!("session rejected: {error}"); |
| 452 | - if let Some(reason) = connection.close_reason() { | 467 | + token = None; |
| 453 | - let event = LinkError::from(reason); | 468 | + connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); |
| 454 | - if event == LinkError::Closed(Close::Banned) { | 469 | + match pending.take() { |
| 455 | - let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; | 470 | + Some(reply) => { |
| 456 | - while command_receiver.recv().await.is_some() {} | 471 | + let _ = reply.send(Err(Fail::Server(error))); |
| 472 | + } | ||
| 473 | + None => { | ||
| 474 | + if event_sender.send(NetworkEvent::SessionLost).await.is_err() { | ||
| 457 | return; | 475 | return; |
| 458 | } | 476 | } |
| 459 | } | 477 | } |
| 460 | - tokio::time::sleep(backoff(attempt)).await; | ||
| 461 | - attempt += 1; | ||
| 462 | - continue 'session; | ||
| 463 | } | 478 | } |
| 464 | - Ok(_) => { | 479 | + continue 'session; |
| 465 | - warn!("session resume rejected"); | 480 | + } |
| 466 | - token = None; | 481 | + Err(error) => { |
| 467 | - | 482 | + warn!("hello failed: {error}"); |
| 468 | - if event_sender.send(NetworkEvent::SessionLost).await.is_err() { | 483 | + if let Some(reason) = connection.close_reason() { |
| 484 | + let event = LinkError::from(reason); | ||
| 485 | + if event == LinkError::Closed(Close::Banned) { | ||
| 486 | + let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; | ||
| 487 | + while command_receiver.recv().await.is_some() {} | ||
| 469 | return; | 488 | return; |
| 470 | } | 489 | } |
| 471 | } | 490 | } |
| 491 | + tokio::time::sleep(backoff(attempt)).await; | ||
| 492 | + attempt += 1; | ||
| 493 | + continue 'session; | ||
| 472 | } | 494 | } |
| 473 | - } | 495 | + }; |
| 474 | 496 | ||
| 475 | attempt = 0; | 497 | attempt = 0; |
| 476 | info!("connected"); | 498 | info!("connected"); |
| 477 | if event_sender.send(NetworkEvent::Connected).await.is_err() { | 499 | if event_sender.send(NetworkEvent::Connected).await.is_err() { |
| 478 | return; | 500 | return; |
| 479 | } | 501 | } |
| 502 | + if let Some(reply) = pending.take() { | ||
| 503 | + let _ = reply.send(Ok(welcome.user)); | ||
| 504 | + } | ||
| 480 | 505 | ||
| 481 | tokio::spawn(event_receive_loop( | 506 | tokio::spawn(event_receive_loop( |
| 482 | connection.clone(), | 507 | connection.clone(), |
| @@ -490,22 +515,6 @@ async fn actor( | |||
| 490 | tokio::select! { | 515 | tokio::select! { |
| 491 | command = command_receiver.recv() => match command { | 516 | command = command_receiver.recv() => match command { |
| 492 | Some(Command::Request { request, reply }) => match &request { | 517 | Some(Command::Request { request, reply }) => match &request { |
| 493 | - Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { | ||
| 494 | - hang_up(&shared); | ||
| 495 | - | ||
| 496 | - let response = send(&connection, &request).await; | ||
| 497 | - if let Ok(Response::Session { token: session_token, .. }) = &response { | ||
| 498 | - token = Some(session_token.clone()); | ||
| 499 | - } | ||
| 500 | - let _ = reply.send(response); | ||
| 501 | - } | ||
| 502 | - Request::Logout | Request::Detach => { | ||
| 503 | - token = None; | ||
| 504 | - hang_up(&shared); | ||
| 505 | - | ||
| 506 | - let connection = connection.clone(); | ||
| 507 | - answer(reply, async move { send(&connection, &request).await }); | ||
| 508 | - } | ||
| 509 | Request::JoinVoice { .. } => { | 518 | Request::JoinVoice { .. } => { |
| 510 | let shared = shared.clone(); | 519 | let shared = shared.clone(); |
| 511 | let settings = shared.voice_settings.lock().unwrap().clone(); | 520 | let settings = shared.voice_settings.lock().unwrap().clone(); |
| @@ -532,6 +541,13 @@ async fn actor( | |||
| 532 | answer(reply, async move { send(&connection, &request).await }); | 541 | answer(reply, async move { send(&connection, &request).await }); |
| 533 | } | 542 | } |
| 534 | }, | 543 | }, |
| 544 | + Some(Command::SignIn { token: next, reply }) => { | ||
| 545 | + token = next; | ||
| 546 | + pending = Some(reply); | ||
| 547 | + hang_up(&shared); | ||
| 548 | + connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); | ||
| 549 | + break; | ||
| 550 | + } | ||
| 535 | Some(Command::StartShare { kind, settings, reply }) => { | 551 | Some(Command::StartShare { kind, settings, reply }) => { |
| 536 | let connection = connection.clone(); | 552 | let connection = connection.clone(); |
| 537 | let share = shared.share.clone(); | 553 | let share = shared.share.clone(); |
crates/client/src/net/mod.rsmodified+28 -13
| @@ -105,6 +105,10 @@ enum Command { | |||
| 105 | request: Request, | 105 | request: Request, |
| 106 | reply: oneshot::Sender<Result<Response, Fail>>, | 106 | reply: oneshot::Sender<Result<Response, Fail>>, |
| 107 | }, | 107 | }, |
| 108 | + SignIn { | ||
| 109 | + token: Option<String>, | ||
| 110 | + reply: oneshot::Sender<Result<Option<User>, Fail>>, | ||
| 111 | + }, | ||
| 108 | Upload { | 112 | Upload { |
| 109 | community_id: String, | 113 | community_id: String, |
| 110 | path: PathBuf, | 114 | path: PathBuf, |
| @@ -160,18 +164,18 @@ impl NetworkHandle { | |||
| 160 | self.ask(|reply| Command::Request { request, reply }).await | 164 | self.ask(|reply| Command::Request { request, reply }).await |
| 161 | } | 165 | } |
| 162 | 166 | ||
| 167 | + async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> { | ||
| 168 | + self.ask(|reply| Command::SignIn { token, reply }).await | ||
| 169 | + } | ||
| 170 | + | ||
| 163 | async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> { | 171 | async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> { |
| 164 | - let session = match self.request(request).await? { | 172 | + let (user, token) = match self.request(request).await? { |
| 165 | Response::Session { user, token } => (user, token), | 173 | Response::Session { user, token } => (user, token), |
| 166 | _ => return Err(Fail::Protocol), | 174 | _ => return Err(Fail::Protocol), |
| 167 | }; | 175 | }; |
| 168 | - let _ = self | 176 | + self.switch(Some(token.clone())).await?; |
| 169 | - .done(Request::SetDevice { | ||
| 170 | - name: device_name(), | ||
| 171 | - }) | ||
| 172 | - .await; | ||
| 173 | 177 | ||
| 174 | - Ok(session) | 178 | + Ok((user, token)) |
| 175 | } | 179 | } |
| 176 | 180 | ||
| 177 | pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> { | 181 | pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> { |
| @@ -206,14 +210,16 @@ impl NetworkHandle { | |||
| 206 | } | 210 | } |
| 207 | 211 | ||
| 208 | pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { | 212 | pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { |
| 209 | - self.sign_in(Request::Resume { | 213 | + let user = self |
| 210 | - token: token.to_string(), | 214 | + .switch(Some(token.to_string())) |
| 211 | - }) | 215 | + .await? |
| 212 | - .await | 216 | + .ok_or(Fail::Protocol)?; |
| 217 | + | ||
| 218 | + Ok((user, token.to_string())) | ||
| 213 | } | 219 | } |
| 214 | 220 | ||
| 215 | pub async fn detach(&self) -> Result<(), Fail> { | 221 | pub async fn detach(&self) -> Result<(), Fail> { |
| 216 | - self.done(Request::Detach).await | 222 | + self.switch(None).await.map(|_| ()) |
| 217 | } | 223 | } |
| 218 | 224 | ||
| 219 | pub async fn register( | 225 | pub async fn register( |
| @@ -244,7 +250,9 @@ impl NetworkHandle { | |||
| 244 | } | 250 | } |
| 245 | 251 | ||
| 246 | pub async fn logout(&self) -> Result<(), Fail> { | 252 | pub async fn logout(&self) -> Result<(), Fail> { |
| 247 | - self.done(Request::Logout).await | 253 | + let result = self.done(Request::Logout).await; |
| 254 | + self.detach().await?; | ||
| 255 | + result | ||
| 248 | } | 256 | } |
| 249 | 257 | ||
| 250 | pub async fn update_user(&self, username: &str) -> Result<User, Fail> { | 258 | pub async fn update_user(&self, username: &str) -> Result<User, Fail> { |
| @@ -995,6 +1003,13 @@ impl NetworkHandle { | |||
| 995 | .await | 1003 | .await |
| 996 | } | 1004 | } |
| 997 | 1005 | ||
| 1006 | + pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> { | ||
| 1007 | + self.done(Request::WatchCommunity { | ||
| 1008 | + community_id: community_id.map(str::to_string), | ||
| 1009 | + }) | ||
| 1010 | + .await | ||
| 1011 | + } | ||
| 1012 | + | ||
| 998 | pub async fn read_messages( | 1013 | pub async fn read_messages( |
| 999 | &self, | 1014 | &self, |
| 1000 | community_id: &str, | 1015 | community_id: &str, |
crates/client/src/net/share.rsmodified+11 -8
| @@ -1,7 +1,7 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | 2 | ||
| 3 | use common::{ | 3 | use common::{ |
| 4 | - event::Event, | 4 | + event::{Event, Media}, |
| 5 | request::Request, | 5 | request::Request, |
| 6 | response::Response, | 6 | response::Response, |
| 7 | share::{Fps, Kind, Quality, Resolution, Source}, | 7 | share::{Fps, Kind, Quality, Resolution, Source}, |
| @@ -28,21 +28,24 @@ pub(super) struct Share { | |||
| 28 | 28 | ||
| 29 | impl Share { | 29 | impl Share { |
| 30 | pub(super) fn event(&mut self, event: &Event) { | 30 | pub(super) fn event(&mut self, event: &Event) { |
| 31 | - match event { | 31 | + if let Event::ShareStopped { user_id, kind, .. } = event { |
| 32 | - Event::ShareLayers { kind, layers } => { | 32 | + self.watching.remove(&(user_id.clone(), *kind)); |
| 33 | + } | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + pub(super) fn media(&mut self, media: &Media) { | ||
| 37 | + match media { | ||
| 38 | + Media::Layers { kind, layers } => { | ||
| 33 | if let Some(sharing) = self.sharing.get_mut(kind) { | 39 | if let Some(sharing) = self.sharing.get_mut(kind) { |
| 34 | sharing.set_layers(layers); | 40 | sharing.set_layers(layers); |
| 35 | } | 41 | } |
| 36 | } | 42 | } |
| 37 | - Event::KeyframeWanted { kind, layer } => { | 43 | + Media::Keyframe { kind, layer } => { |
| 38 | if let Some(sharing) = self.sharing.get(kind) { | 44 | if let Some(sharing) = self.sharing.get(kind) { |
| 39 | sharing.keyframe(*layer); | 45 | sharing.keyframe(*layer); |
| 40 | } | 46 | } |
| 41 | } | 47 | } |
| 42 | - Event::ShareStopped { user_id, kind, .. } => { | 48 | + Media::VoiceEnded => {} |
| 43 | - self.watching.remove(&(user_id.clone(), *kind)); | ||
| 44 | - } | ||
| 45 | - _ => {} | ||
| 46 | } | 49 | } |
| 47 | } | 50 | } |
| 48 | 51 | ||
crates/common/src/event.rsmodified+18 -30
| @@ -1,7 +1,7 @@ | |||
| 1 | use bitcode::{Decode, Encode}; | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | ||
| 3 | use crate::model::{ | 3 | use crate::model::{ |
| 4 | - Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User, | 4 | + Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, User, |
| 5 | }; | 5 | }; |
| 6 | use crate::share::{Kind, Layer, Share}; | 6 | use crate::share::{Kind, Layer, Share}; |
| 7 | 7 | ||
| @@ -9,7 +9,10 @@ use crate::share::{Kind, Layer, Share}; | |||
| 9 | pub enum Event { | 9 | pub enum Event { |
| 10 | MessageCreated(Message), | 10 | MessageCreated(Message), |
| 11 | MessageUpdated(Message), | 11 | MessageUpdated(Message), |
| 12 | - MessageDeleted(Message), | 12 | + MessagesDeleted { |
| 13 | + community_id: String, | ||
| 14 | + ids: Vec<String>, | ||
| 15 | + }, | ||
| 13 | MemberJoined { | 16 | MemberJoined { |
| 14 | community_id: String, | 17 | community_id: String, |
| 15 | member: Member, | 18 | member: Member, |
| @@ -54,12 +57,11 @@ pub enum Event { | |||
| 54 | }, | 57 | }, |
| 55 | ReportCreated, | 58 | ReportCreated, |
| 56 | VoiceMuted { | 59 | VoiceMuted { |
| 60 | + community_id: Option<String>, | ||
| 57 | user_id: String, | 61 | user_id: String, |
| 58 | muted: bool, | 62 | muted: bool, |
| 59 | }, | 63 | }, |
| 60 | - Announcement { | 64 | + SettingsUpdated(ServerSettings), |
| 61 | - text: String, | ||
| 62 | - }, | ||
| 63 | Typing { | 65 | Typing { |
| 64 | community_id: String, | 66 | community_id: String, |
| 65 | user_id: String, | 67 | user_id: String, |
| @@ -73,31 +75,17 @@ pub enum Event { | |||
| 73 | user_id: String, | 75 | user_id: String, |
| 74 | kind: Kind, | 76 | kind: Kind, |
| 75 | }, | 77 | }, |
| 76 | - ShareLayers { | ||
| 77 | - kind: Kind, | ||
| 78 | - layers: Vec<Layer>, | ||
| 79 | - }, | ||
| 80 | - KeyframeWanted { | ||
| 81 | - kind: Kind, | ||
| 82 | - layer: Layer, | ||
| 83 | - }, | ||
| 84 | } | 78 | } |
| 85 | 79 | ||
| 86 | -impl Event { | 80 | +#[derive(Debug, Clone, Encode, Decode)] |
| 87 | - pub fn community_id(&self) -> Option<&str> { | 81 | +pub enum Media { |
| 88 | - match self { | 82 | + Layers { kind: Kind, layers: Vec<Layer> }, |
| 89 | - Self::MessageCreated(message) | 83 | + Keyframe { kind: Kind, layer: Layer }, |
| 90 | - | Self::MessageUpdated(message) | 84 | + VoiceEnded, |
| 91 | - | Self::MessageDeleted(message) => Some(&message.community_id), | 85 | +} |
| 92 | - Self::CommunityUpdated(community) => Some(&community.id), | 86 | + |
| 93 | - Self::MemberJoined { community_id, .. } | 87 | +#[derive(Debug, Clone, Encode, Decode)] |
| 94 | - | Self::MemberLeft { community_id, .. } | 88 | +pub enum Down { |
| 95 | - | Self::RankChanged { community_id, .. } | 89 | + Event(Box<Event>), |
| 96 | - | Self::VoiceJoined { community_id, .. } | 90 | + Media(Media), |
| 97 | - | Self::VoiceLeft { community_id, .. } | ||
| 98 | - | Self::ShareStarted { community_id, .. } | ||
| 99 | - | Self::ShareStopped { community_id, .. } => Some(community_id), | ||
| 100 | - _ => None, | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | } | 91 | } |
crates/common/src/lib.rsmodified+1 -0
| @@ -9,6 +9,7 @@ pub mod open; | |||
| 9 | pub mod permission; | 9 | pub mod permission; |
| 10 | pub mod request; | 10 | pub mod request; |
| 11 | pub mod response; | 11 | pub mod response; |
| 12 | +pub mod session; | ||
| 12 | pub mod share; | 13 | pub mod share; |
| 13 | pub mod time; | 14 | pub mod time; |
| 14 | pub mod transport; | 15 | pub mod transport; |
crates/common/src/request.rsmodified+3 -7
| @@ -16,9 +16,6 @@ pub enum Request { | |||
| 16 | username: String, | 16 | username: String, |
| 17 | password: String, | 17 | password: String, |
| 18 | }, | 18 | }, |
| 19 | - Resume { | ||
| 20 | - token: String, | ||
| 21 | - }, | ||
| 22 | Logout, | 19 | Logout, |
| 23 | ReadUser { | 20 | ReadUser { |
| 24 | user_id: String, | 21 | user_id: String, |
| @@ -131,6 +128,9 @@ pub enum Request { | |||
| 131 | Pins { | 128 | Pins { |
| 132 | community_id: String, | 129 | community_id: String, |
| 133 | }, | 130 | }, |
| 131 | + WatchCommunity { | ||
| 132 | + community_id: Option<String>, | ||
| 133 | + }, | ||
| 134 | ReadMessages { | 134 | ReadMessages { |
| 135 | community_id: String, | 135 | community_id: String, |
| 136 | before: Option<String>, | 136 | before: Option<String>, |
| @@ -205,7 +205,6 @@ pub enum Request { | |||
| 205 | DeclineInvitation { | 205 | DeclineInvitation { |
| 206 | community_id: String, | 206 | community_id: String, |
| 207 | }, | 207 | }, |
| 208 | - Detach, | ||
| 209 | Logs { | 208 | Logs { |
| 210 | community_id: String, | 209 | community_id: String, |
| 211 | }, | 210 | }, |
| @@ -249,9 +248,6 @@ pub enum Request { | |||
| 249 | username: String, | 248 | username: String, |
| 250 | password: String, | 249 | password: String, |
| 251 | }, | 250 | }, |
| 252 | - SetDevice { | ||
| 253 | - name: String, | ||
| 254 | - }, | ||
| 255 | Sessions { | 251 | Sessions { |
| 256 | user_id: String, | 252 | user_id: String, |
| 257 | }, | 253 | }, |
crates/common/src/session.rsadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +use bitcode::{Decode, Encode}; | ||
| 2 | + | ||
| 3 | +use crate::model::User; | ||
| 4 | + | ||
| 5 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 6 | +pub struct Hello { | ||
| 7 | + pub token: Option<String>, | ||
| 8 | + pub device: String, | ||
| 9 | +} | ||
| 10 | + | ||
| 11 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 12 | +pub struct Welcome { | ||
| 13 | + pub user: Option<User>, | ||
| 14 | +} | ||
crates/server/src/attachment.rsmodified+9 -8
| @@ -668,7 +668,7 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { | |||
| 668 | 668 | ||
| 669 | #[cfg(test)] | 669 | #[cfg(test)] |
| 670 | mod tests { | 670 | mod tests { |
| 671 | - use std::{io::Cursor, sync::Mutex}; | 671 | + use std::io::Cursor; |
| 672 | 672 | ||
| 673 | use common::{ | 673 | use common::{ |
| 674 | model::{AttachmentKind, Rank}, | 674 | model::{AttachmentKind, Rank}, |
| @@ -679,8 +679,10 @@ mod tests { | |||
| 679 | 679 | ||
| 680 | use crate::{ | 680 | use crate::{ |
| 681 | attachment::{store, thumb_path}, | 681 | attachment::{store, thumb_path}, |
| 682 | - community, database, message, | 682 | + community, database, |
| 683 | - network::{Services, State}, | 683 | + hub::{Client, Signed}, |
| 684 | + message, | ||
| 685 | + network::Services, | ||
| 684 | request::handle, | 686 | request::handle, |
| 685 | test, user, user_community, | 687 | test, user, user_community, |
| 686 | }; | 688 | }; |
| @@ -710,10 +712,10 @@ mod tests { | |||
| 710 | .await | 712 | .await |
| 711 | .unwrap(); | 713 | .unwrap(); |
| 712 | 714 | ||
| 713 | - let state = Mutex::new(State::Authenticated { | 715 | + let client = Client::detached(Some(Signed { |
| 714 | - user: user.clone(), | 716 | + user_id: user.id.clone(), |
| 715 | token: "token".to_string(), | 717 | token: "token".to_string(), |
| 716 | - }); | 718 | + })); |
| 717 | let (reply, _) = handle( | 719 | let (reply, _) = handle( |
| 718 | Request::CreateMessage { | 720 | Request::CreateMessage { |
| 719 | community_id: community.id.clone(), | 721 | community_id: community.id.clone(), |
| @@ -721,10 +723,9 @@ mod tests { | |||
| 721 | attachments: vec![attachment.id.clone()], | 723 | attachments: vec![attachment.id.clone()], |
| 722 | reply_to: None, | 724 | reply_to: None, |
| 723 | }, | 725 | }, |
| 724 | - &state, | 726 | + &client, |
| 725 | &db, | 727 | &db, |
| 726 | &Services::default(), | 728 | &Services::default(), |
| 727 | - None, | ||
| 728 | &test::directory(), | 729 | &test::directory(), |
| 729 | &test::directory(), | 730 | &test::directory(), |
| 730 | ) | 731 | ) |
crates/server/src/authentication.rsmodified+39 -6
| @@ -3,11 +3,14 @@ use common::{ | |||
| 3 | error::Error as CommonError, | 3 | error::Error as CommonError, |
| 4 | model::{SessionInfo, User}, | 4 | model::{SessionInfo, User}, |
| 5 | permission, time, | 5 | permission, time, |
| 6 | + transport::Close, | ||
| 6 | validate::{validate_device, validate_password, validate_username}, | 7 | validate::{validate_device, validate_password, validate_username}, |
| 7 | }; | 8 | }; |
| 8 | use turso::Connection; | 9 | use turso::Connection; |
| 9 | 10 | ||
| 10 | -use crate::{database::new_id, error::ServerError, invite, server_ban, server_settings, user}; | 11 | +use crate::{ |
| 12 | + database::new_id, error::ServerError, hub::Hub, invite, server_ban, server_settings, user, | ||
| 13 | +}; | ||
| 11 | 14 | ||
| 12 | const SALT_LENGTH: usize = 16; | 15 | const SALT_LENGTH: usize = 16; |
| 13 | const TOKEN_LENGTH: usize = 32; | 16 | const TOKEN_LENGTH: usize = 32; |
| @@ -101,7 +104,7 @@ pub async fn sessions(user_id: &str, conn: &Connection) -> Result<Vec<SessionInf | |||
| 101 | Ok(sessions) | 104 | Ok(sessions) |
| 102 | } | 105 | } |
| 103 | 106 | ||
| 104 | -pub async fn revoke_session( | 107 | +async fn revoke_session( |
| 105 | user_id: &str, | 108 | user_id: &str, |
| 106 | session_id: &str, | 109 | session_id: &str, |
| 107 | conn: &Connection, | 110 | conn: &Connection, |
| @@ -183,7 +186,12 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> { | |||
| 183 | } | 186 | } |
| 184 | 187 | ||
| 185 | pub async fn resume(token: &str, conn: &Connection) -> Result<User, ServerError> { | 188 | pub async fn resume(token: &str, conn: &Connection) -> Result<User, ServerError> { |
| 186 | - let user = user::by_session_token(token, conn).await?; | 189 | + let user = match user::by_session_token(token, conn).await { |
| 190 | + Err(ServerError::Wire(CommonError::WrongCredentials)) => { | ||
| 191 | + return Err(CommonError::Unauthenticated.into()); | ||
| 192 | + } | ||
| 193 | + user => user?, | ||
| 194 | + }; | ||
| 187 | admit(&user, conn).await?; | 195 | admit(&user, conn).await?; |
| 188 | seen(&user.id, token, conn).await?; | 196 | seen(&user.id, token, conn).await?; |
| 189 | 197 | ||
| @@ -197,7 +205,7 @@ pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { | |||
| 197 | Ok(()) | 205 | Ok(()) |
| 198 | } | 206 | } |
| 199 | 207 | ||
| 200 | -pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { | 208 | +pub(crate) async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { |
| 201 | conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) | 209 | conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) |
| 202 | .await?; | 210 | .await?; |
| 203 | 211 | ||
| @@ -210,8 +218,33 @@ pub async fn reset_password( | |||
| 210 | conn: &Connection, | 218 | conn: &Connection, |
| 211 | ) -> Result<(), ServerError> { | 219 | ) -> Result<(), ServerError> { |
| 212 | validate_password(password)?; | 220 | validate_password(password)?; |
| 213 | - user::set_password_hash(user_id, &hash(password)?, conn).await?; | 221 | + user::set_password_hash(user_id, &hash(password)?, conn).await |
| 214 | - revoke_sessions(user_id, conn).await | 222 | +} |
| 223 | + | ||
| 224 | +pub enum Revoke<'a> { | ||
| 225 | + User(&'a str), | ||
| 226 | + Session { | ||
| 227 | + user_id: &'a str, | ||
| 228 | + session_id: &'a str, | ||
| 229 | + }, | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result<(), ServerError> { | ||
| 233 | + match target { | ||
| 234 | + Revoke::User(user_id) => { | ||
| 235 | + revoke_sessions(user_id, conn).await?; | ||
| 236 | + hub.kick_user(user_id, Close::Revoked); | ||
| 237 | + } | ||
| 238 | + Revoke::Session { | ||
| 239 | + user_id, | ||
| 240 | + session_id, | ||
| 241 | + } => { | ||
| 242 | + let token = revoke_session(user_id, session_id, conn).await?; | ||
| 243 | + hub.kick_token(&token, Close::Revoked); | ||
| 244 | + } | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + Ok(()) | ||
| 215 | } | 248 | } |
| 216 | 249 | ||
| 217 | #[cfg(test)] | 250 | #[cfg(test)] |
crates/server/src/datagram.rsmodified+5 -12
| @@ -1,19 +1,12 @@ | |||
| 1 | -use std::sync::{Arc, Mutex}; | 1 | +use std::sync::Arc; |
| 2 | 2 | ||
| 3 | use quinn::Connection; | 3 | use quinn::Connection; |
| 4 | 4 | ||
| 5 | -use crate::network::{Shared, State, publish}; | 5 | +use crate::{hub::Client, network::Shared, publish::publish}; |
| 6 | 6 | ||
| 7 | -pub(crate) async fn relay_datagrams( | 7 | +pub(crate) async fn relay_datagrams(connection: Connection, client: Arc<Client>, shared: Shared) { |
| 8 | - connection: Connection, | ||
| 9 | - state: Arc<Mutex<State>>, | ||
| 10 | - shared: Shared, | ||
| 11 | -) { | ||
| 12 | while let Ok(bytes) = connection.read_datagram().await { | 8 | while let Ok(bytes) = connection.read_datagram().await { |
| 13 | - if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { | 9 | + let broadcasts = shared.services.rooms.relay(&client, &bytes); |
| 14 | - shared.services.voice.relay(connection.stable_id(), &bytes); | 10 | + publish(&shared, broadcasts).await; |
| 15 | - let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); | ||
| 16 | - publish(&shared, broadcasts).await; | ||
| 17 | - } | ||
| 18 | } | 11 | } |
| 19 | } | 12 | } |
crates/server/src/hub.rsadded+218 -0
| @@ -0,0 +1,218 @@ | |||
| 1 | +use std::{ | ||
| 2 | + collections::{HashMap, HashSet}, | ||
| 3 | + sync::{ | ||
| 4 | + Arc, Mutex, | ||
| 5 | + atomic::{AtomicBool, AtomicU64, Ordering}, | ||
| 6 | + }, | ||
| 7 | +}; | ||
| 8 | + | ||
| 9 | +use bytes::Bytes; | ||
| 10 | +use common::transport::Close; | ||
| 11 | +use quinn::Connection; | ||
| 12 | +use tokio::sync::mpsc::{self, error::TrySendError}; | ||
| 13 | +use tracing::warn; | ||
| 14 | + | ||
| 15 | +pub type ConnId = u64; | ||
| 16 | + | ||
| 17 | +const QUEUE_LENGTH: usize = 256; | ||
| 18 | + | ||
| 19 | +static NEXT_ID: AtomicU64 = AtomicU64::new(1); | ||
| 20 | + | ||
| 21 | +pub struct Signed { | ||
| 22 | + pub user_id: String, | ||
| 23 | + pub token: String, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +pub struct Client { | ||
| 27 | + pub id: ConnId, | ||
| 28 | + pub conn: Option<Connection>, | ||
| 29 | + pub me: Option<Signed>, | ||
| 30 | + tx: mpsc::Sender<Bytes>, | ||
| 31 | + pub closed: AtomicBool, | ||
| 32 | + pub watching: Mutex<Option<String>>, | ||
| 33 | + pub ghost_logged: Mutex<HashSet<String>>, | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +impl Client { | ||
| 37 | + pub fn new(conn: Option<Connection>, me: Option<Signed>) -> (Arc<Self>, mpsc::Receiver<Bytes>) { | ||
| 38 | + let (tx, rx) = mpsc::channel(QUEUE_LENGTH); | ||
| 39 | + let client = Arc::new(Self { | ||
| 40 | + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), | ||
| 41 | + conn, | ||
| 42 | + me, | ||
| 43 | + tx, | ||
| 44 | + closed: AtomicBool::new(false), | ||
| 45 | + watching: Mutex::new(None), | ||
| 46 | + ghost_logged: Mutex::new(HashSet::new()), | ||
| 47 | + }); | ||
| 48 | + | ||
| 49 | + (client, rx) | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + pub fn detached(me: Option<Signed>) -> Arc<Self> { | ||
| 53 | + Self::new(None, me).0 | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + pub fn user_id(&self) -> Option<&str> { | ||
| 57 | + self.me.as_ref().map(|me| me.user_id.as_str()) | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + pub fn close(&self, close: Close) { | ||
| 61 | + if let Some(conn) = &self.conn { | ||
| 62 | + conn.close(close.code(), close.reason().as_bytes()); | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + pub fn first_visit(&self, community_id: &str) -> bool { | ||
| 67 | + self.ghost_logged | ||
| 68 | + .lock() | ||
| 69 | + .unwrap() | ||
| 70 | + .insert(community_id.to_string()) | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + pub fn watch(&self, community_id: Option<&str>) { | ||
| 74 | + *self.watching.lock().unwrap() = community_id.map(str::to_string); | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + fn watches(&self, community_id: &str) -> bool { | ||
| 78 | + self.watching.lock().unwrap().as_deref() == Some(community_id) | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +pub enum Presence { | ||
| 83 | + None, | ||
| 84 | + Online(String), | ||
| 85 | + Offline(String), | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +#[derive(Clone, Default)] | ||
| 89 | +pub struct Hub(Arc<Mutex<HashMap<ConnId, Arc<Client>>>>); | ||
| 90 | + | ||
| 91 | +impl Hub { | ||
| 92 | + pub fn add(&self, client: Arc<Client>) -> Presence { | ||
| 93 | + let mut clients = self.0.lock().unwrap(); | ||
| 94 | + let user_id = client.user_id().map(str::to_string); | ||
| 95 | + let was_online = user_id | ||
| 96 | + .as_deref() | ||
| 97 | + .is_some_and(|user_id| Self::online_in(&clients, user_id)); | ||
| 98 | + clients.insert(client.id, client); | ||
| 99 | + | ||
| 100 | + match user_id { | ||
| 101 | + Some(user_id) if !was_online => Presence::Online(user_id), | ||
| 102 | + _ => Presence::None, | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + pub fn remove(&self, id: ConnId) -> Presence { | ||
| 107 | + let mut clients = self.0.lock().unwrap(); | ||
| 108 | + let Some(client) = clients.remove(&id) else { | ||
| 109 | + return Presence::None; | ||
| 110 | + }; | ||
| 111 | + | ||
| 112 | + match client.user_id() { | ||
| 113 | + Some(user_id) if !Self::online_in(&clients, user_id) => { | ||
| 114 | + Presence::Offline(user_id.to_string()) | ||
| 115 | + } | ||
| 116 | + _ => Presence::None, | ||
| 117 | + } | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + fn online_in(clients: &HashMap<ConnId, Arc<Client>>, user_id: &str) -> bool { | ||
| 121 | + clients | ||
| 122 | + .values() | ||
| 123 | + .any(|client| client.user_id() == Some(user_id)) | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + pub fn is_online(&self, user_id: &str) -> bool { | ||
| 127 | + Self::online_in(&self.0.lock().unwrap(), user_id) | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + pub fn user_ids(&self) -> Vec<String> { | ||
| 131 | + let mut user_ids: Vec<String> = self | ||
| 132 | + .0 | ||
| 133 | + .lock() | ||
| 134 | + .unwrap() | ||
| 135 | + .values() | ||
| 136 | + .filter_map(|client| client.user_id().map(str::to_string)) | ||
| 137 | + .collect(); | ||
| 138 | + user_ids.sort(); | ||
| 139 | + user_ids.dedup(); | ||
| 140 | + | ||
| 141 | + user_ids | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + pub fn online(&self) -> usize { | ||
| 145 | + self.user_ids().len() | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + pub fn conns_of(&self, user_ids: &[String]) -> Vec<ConnId> { | ||
| 149 | + self.0 | ||
| 150 | + .lock() | ||
| 151 | + .unwrap() | ||
| 152 | + .values() | ||
| 153 | + .filter(|client| { | ||
| 154 | + client | ||
| 155 | + .user_id() | ||
| 156 | + .is_some_and(|id| user_ids.iter().any(|u| u == id)) | ||
| 157 | + }) | ||
| 158 | + .map(|client| client.id) | ||
| 159 | + .collect() | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + pub fn watchers(&self, community_id: &str) -> Vec<ConnId> { | ||
| 163 | + self.0 | ||
| 164 | + .lock() | ||
| 165 | + .unwrap() | ||
| 166 | + .values() | ||
| 167 | + .filter(|client| client.watches(community_id)) | ||
| 168 | + .map(|client| client.id) | ||
| 169 | + .collect() | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + pub fn all(&self) -> Vec<ConnId> { | ||
| 173 | + self.0.lock().unwrap().keys().copied().collect() | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + pub fn send(&self, ids: &[ConnId], bytes: &Bytes, droppable: bool) { | ||
| 177 | + let clients = self.0.lock().unwrap(); | ||
| 178 | + for id in ids { | ||
| 179 | + let Some(client) = clients.get(id) else { | ||
| 180 | + continue; | ||
| 181 | + }; | ||
| 182 | + match client.tx.try_send(bytes.clone()) { | ||
| 183 | + Ok(()) | Err(TrySendError::Closed(_)) => {} | ||
| 184 | + Err(TrySendError::Full(_)) if droppable => {} | ||
| 185 | + Err(TrySendError::Full(_)) => { | ||
| 186 | + warn!("client {} too slow", client.id); | ||
| 187 | + client.close(Close::Slow); | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | + | ||
| 193 | + fn kick_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { | ||
| 194 | + let targets: Vec<Arc<Client>> = self | ||
| 195 | + .0 | ||
| 196 | + .lock() | ||
| 197 | + .unwrap() | ||
| 198 | + .values() | ||
| 199 | + .filter(|client| client.me.as_ref().is_some_and(&matches)) | ||
| 200 | + .cloned() | ||
| 201 | + .collect(); | ||
| 202 | + for client in targets { | ||
| 203 | + client.close(close); | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + pub fn kick_user(&self, user_id: &str, close: Close) { | ||
| 208 | + self.kick_where(|me| me.user_id == user_id, close); | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + pub fn kick_token(&self, token: &str, close: Close) { | ||
| 212 | + self.kick_where(|me| me.token == token, close); | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + pub fn kick_all_except(&self, keep: &[String], close: Close) { | ||
| 216 | + self.kick_where(|me| !keep.contains(&me.user_id), close); | ||
| 217 | + } | ||
| 218 | +} | ||
crates/server/src/lib.rsmodified+3 -3
| @@ -9,6 +9,7 @@ pub mod datagram; | |||
| 9 | pub mod direct; | 9 | pub mod direct; |
| 10 | pub mod error; | 10 | pub mod error; |
| 11 | pub mod friend; | 11 | pub mod friend; |
| 12 | +pub mod hub; | ||
| 12 | pub mod invitation; | 13 | pub mod invitation; |
| 13 | pub mod invite; | 14 | pub mod invite; |
| 14 | pub mod log; | 15 | pub mod log; |
| @@ -16,17 +17,17 @@ pub mod message; | |||
| 16 | pub mod network; | 17 | pub mod network; |
| 17 | pub mod notes; | 18 | pub mod notes; |
| 18 | pub mod overview; | 19 | pub mod overview; |
| 20 | +pub mod publish; | ||
| 19 | pub mod rate_limit; | 21 | pub mod rate_limit; |
| 20 | pub mod report; | 22 | pub mod report; |
| 21 | pub mod request; | 23 | pub mod request; |
| 22 | pub mod retention; | 24 | pub mod retention; |
| 25 | +pub mod rooms; | ||
| 23 | pub mod server_ban; | 26 | pub mod server_ban; |
| 24 | pub mod server_settings; | 27 | pub mod server_settings; |
| 25 | -pub mod share; | ||
| 26 | pub mod stats; | 28 | pub mod stats; |
| 27 | pub mod user; | 29 | pub mod user; |
| 28 | pub mod user_community; | 30 | pub mod user_community; |
| 29 | -pub mod voice; | ||
| 30 | 31 | ||
| 31 | #[cfg(test)] | 32 | #[cfg(test)] |
| 32 | mod test; | 33 | mod test; |
| @@ -87,7 +88,6 @@ pub async fn showtime() -> Result<(), ServerError> { | |||
| 87 | let attachments = sibling_directory(&config.database_path, "attachments")?; | 88 | let attachments = sibling_directory(&config.database_path, "attachments")?; |
| 88 | let backups = sibling_directory(&config.database_path, "backups")?; | 89 | let backups = sibling_directory(&config.database_path, "backups")?; |
| 89 | tokio::spawn(attachment::collect(database.clone(), attachments.clone())); | 90 | tokio::spawn(attachment::collect(database.clone(), attachments.clone())); |
| 90 | - tokio::spawn(retention::collect(database.clone(), attachments.clone())); | ||
| 91 | 91 | ||
| 92 | network::serve( | 92 | network::serve( |
| 93 | &config.server_address, | 93 | &config.server_address, |
crates/server/src/network.rsmodified+186 -342
| @@ -1,19 +1,16 @@ | |||
| 1 | -use std::{ | 1 | +use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; |
| 2 | - collections::{HashMap, HashSet}, | ||
| 3 | - path::PathBuf, | ||
| 4 | - sync::{Arc, Mutex}, | ||
| 5 | -}; | ||
| 6 | 2 | ||
| 3 | +use bytes::Bytes; | ||
| 7 | use common::{ | 4 | use common::{ |
| 8 | - event::Event as Push, | ||
| 9 | frame::{self, DOWN_MAX, Sending, UP_MAX}, | 5 | frame::{self, DOWN_MAX, Sending, UP_MAX}, |
| 10 | model::User, | 6 | model::User, |
| 11 | open::Open, | 7 | open::Open, |
| 12 | request::Request, | 8 | request::Request, |
| 9 | + session::{Hello, Welcome}, | ||
| 13 | transport::Close, | 10 | transport::Close, |
| 14 | }; | 11 | }; |
| 15 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; | 12 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; |
| 16 | -use tokio::{sync::mpsc, task::JoinHandle}; | 13 | +use tokio::sync::mpsc; |
| 17 | use tracing::{info, warn}; | 14 | use tracing::{info, warn}; |
| 18 | 15 | ||
| 19 | use crate::{ | 16 | use crate::{ |
| @@ -21,187 +18,38 @@ use crate::{ | |||
| 21 | database::{self, DB}, | 18 | database::{self, DB}, |
| 22 | datagram, | 19 | datagram, |
| 23 | error::ServerError, | 20 | error::ServerError, |
| 21 | + hub::{Client, Hub, Presence, Signed}, | ||
| 22 | + publish::publish, | ||
| 24 | rate_limit::RateLimit, | 23 | rate_limit::RateLimit, |
| 25 | - request::{self, Broadcast}, | 24 | + request, retention, |
| 26 | - server_ban, | 25 | + rooms::Rooms, |
| 27 | - share::Shares, | 26 | + server_ban, stats, user, |
| 28 | - voice::Voice, | ||
| 29 | }; | 27 | }; |
| 30 | 28 | ||
| 31 | -const CHANNEL_LENGTH: usize = 2048; | 29 | +const HELLO_DEADLINE: Duration = Duration::from_secs(5); |
| 32 | -const SESSION_LENGTH: usize = 64; | ||
| 33 | - | ||
| 34 | -struct Signed { | ||
| 35 | - user_id: String, | ||
| 36 | - token: String, | ||
| 37 | - connection: Connection, | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -#[derive(Clone, Default)] | ||
| 41 | -pub struct Presence(Arc<Mutex<HashMap<usize, Signed>>>); | ||
| 42 | - | ||
| 43 | -#[derive(Default)] | ||
| 44 | -struct VisitBook { | ||
| 45 | - seen: HashMap<usize, HashSet<String>>, | ||
| 46 | - watching: HashMap<usize, String>, | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -#[derive(Clone, Default)] | ||
| 50 | -pub struct Visits(Arc<Mutex<VisitBook>>); | ||
| 51 | - | ||
| 52 | -impl Visits { | ||
| 53 | - pub fn first(&self, connection_id: usize, community_id: &str) -> bool { | ||
| 54 | - self.0 | ||
| 55 | - .lock() | ||
| 56 | - .unwrap() | ||
| 57 | - .seen | ||
| 58 | - .entry(connection_id) | ||
| 59 | - .or_default() | ||
| 60 | - .insert(community_id.to_string()) | ||
| 61 | - } | ||
| 62 | - | ||
| 63 | - pub fn watch(&self, connection_id: usize, community_id: Option<&str>) { | ||
| 64 | - let watching = &mut self.0.lock().unwrap().watching; | ||
| 65 | - match community_id { | ||
| 66 | - Some(community_id) => watching.insert(connection_id, community_id.to_string()), | ||
| 67 | - None => watching.remove(&connection_id), | ||
| 68 | - }; | ||
| 69 | - } | ||
| 70 | - | ||
| 71 | - fn watches(&self, connection_id: usize, community_id: &str) -> bool { | ||
| 72 | - self.0 | ||
| 73 | - .lock() | ||
| 74 | - .unwrap() | ||
| 75 | - .watching | ||
| 76 | - .get(&connection_id) | ||
| 77 | - .is_some_and(|watched| watched == community_id) | ||
| 78 | - } | ||
| 79 | - | ||
| 80 | - pub fn forget(&self, connection_id: usize) { | ||
| 81 | - let mut book = self.0.lock().unwrap(); | ||
| 82 | - book.seen.remove(&connection_id); | ||
| 83 | - book.watching.remove(&connection_id); | ||
| 84 | - } | ||
| 85 | -} | ||
| 86 | 30 | ||
| 87 | #[derive(Clone, Default)] | 31 | #[derive(Clone, Default)] |
| 88 | pub struct Services { | 32 | pub struct Services { |
| 89 | - pub voice: Voice, | 33 | + pub rooms: Rooms, |
| 90 | - pub share: Shares, | 34 | + pub hub: Hub, |
| 91 | - pub presence: Presence, | ||
| 92 | pub rate_limit: RateLimit, | 35 | pub rate_limit: RateLimit, |
| 93 | - pub visits: Visits, | ||
| 94 | -} | ||
| 95 | - | ||
| 96 | -impl Presence { | ||
| 97 | - pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { | ||
| 98 | - let mut signed = self.0.lock().unwrap(); | ||
| 99 | - if connection.close_reason().is_some() { | ||
| 100 | - return; | ||
| 101 | - } | ||
| 102 | - signed.insert( | ||
| 103 | - connection.stable_id(), | ||
| 104 | - Signed { | ||
| 105 | - user_id: user_id.to_string(), | ||
| 106 | - token: token.to_string(), | ||
| 107 | - connection: connection.clone(), | ||
| 108 | - }, | ||
| 109 | - ); | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - pub fn is_online(&self, user_id: &str) -> bool { | ||
| 113 | - self.0 | ||
| 114 | - .lock() | ||
| 115 | - .unwrap() | ||
| 116 | - .values() | ||
| 117 | - .any(|signed| signed.user_id == user_id) | ||
| 118 | - } | ||
| 119 | - | ||
| 120 | - pub fn sign_out(&self, connection_id: usize) { | ||
| 121 | - self.0.lock().unwrap().remove(&connection_id); | ||
| 122 | - } | ||
| 123 | - | ||
| 124 | - pub fn user_ids(&self) -> Vec<String> { | ||
| 125 | - let mut user_ids: Vec<String> = self | ||
| 126 | - .0 | ||
| 127 | - .lock() | ||
| 128 | - .unwrap() | ||
| 129 | - .values() | ||
| 130 | - .map(|signed| signed.user_id.clone()) | ||
| 131 | - .collect(); | ||
| 132 | - user_ids.sort(); | ||
| 133 | - user_ids.dedup(); | ||
| 134 | - | ||
| 135 | - user_ids | ||
| 136 | - } | ||
| 137 | - | ||
| 138 | - pub fn online(&self) -> usize { | ||
| 139 | - self.user_ids().len() | ||
| 140 | - } | ||
| 141 | - | ||
| 142 | - fn close_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { | ||
| 143 | - let connections: Vec<Connection> = self | ||
| 144 | - .0 | ||
| 145 | - .lock() | ||
| 146 | - .unwrap() | ||
| 147 | - .values() | ||
| 148 | - .filter(|signed| matches(signed)) | ||
| 149 | - .map(|signed| signed.connection.clone()) | ||
| 150 | - .collect(); | ||
| 151 | - for connection in connections { | ||
| 152 | - connection.close(close.code(), close.reason().as_bytes()); | ||
| 153 | - } | ||
| 154 | - } | ||
| 155 | - | ||
| 156 | - pub fn disconnect(&self, user_id: &str, close: Close) { | ||
| 157 | - self.close_where(|signed| signed.user_id == user_id, close); | ||
| 158 | - } | ||
| 159 | - | ||
| 160 | - pub fn disconnect_except(&self, keep: &[String], close: Close) { | ||
| 161 | - self.close_where(|signed| !keep.contains(&signed.user_id), close); | ||
| 162 | - } | ||
| 163 | - | ||
| 164 | - pub fn disconnect_token(&self, token: &str) { | ||
| 165 | - self.close_where(|signed| signed.token == token, Close::Revoked); | ||
| 166 | - } | ||
| 167 | -} | ||
| 168 | - | ||
| 169 | -#[derive(Clone)] | ||
| 170 | -pub enum State { | ||
| 171 | - Anonymous, | ||
| 172 | - Authenticated { user: User, token: String }, | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | -enum Event { | ||
| 176 | - Connected { | ||
| 177 | - connection_id: usize, | ||
| 178 | - connection: Connection, | ||
| 179 | - send_stream: SendStream, | ||
| 180 | - }, | ||
| 181 | - Signed { | ||
| 182 | - connection_id: usize, | ||
| 183 | - user_id: Option<String>, | ||
| 184 | - }, | ||
| 185 | - Broadcast(Box<Broadcast>), | ||
| 186 | -} | ||
| 187 | - | ||
| 188 | -struct Session { | ||
| 189 | - connection_id: usize, | ||
| 190 | - user_id: Option<String>, | ||
| 191 | - connection: Connection, | ||
| 192 | - event_sender: mpsc::Sender<Arc<Push>>, | ||
| 193 | - writer: JoinHandle<()>, | ||
| 194 | } | 36 | } |
| 195 | 37 | ||
| 196 | #[derive(Clone)] | 38 | #[derive(Clone)] |
| 197 | pub(crate) struct Shared { | 39 | pub(crate) struct Shared { |
| 198 | - event_sender: mpsc::Sender<Event>, | 40 | + pub(crate) db: DB, |
| 199 | - db: DB, | ||
| 200 | pub(crate) services: Services, | 41 | pub(crate) services: Services, |
| 201 | - directory: PathBuf, | 42 | + pub(crate) directory: PathBuf, |
| 202 | backups: PathBuf, | 43 | backups: PathBuf, |
| 203 | } | 44 | } |
| 204 | 45 | ||
| 46 | +struct Pending { | ||
| 47 | + client: Arc<Client>, | ||
| 48 | + events: mpsc::Receiver<Bytes>, | ||
| 49 | + reply_stream: Sending, | ||
| 50 | + user: Option<User>, | ||
| 51 | +} | ||
| 52 | + | ||
| 205 | pub async fn serve( | 53 | pub async fn serve( |
| 206 | server_address: &str, | 54 | server_address: &str, |
| 207 | server_config: quinn::ServerConfig, | 55 | server_config: quinn::ServerConfig, |
| @@ -212,17 +60,15 @@ pub async fn serve( | |||
| 212 | let endpoint = Endpoint::server(server_config, server_address.parse()?)?; | 60 | let endpoint = Endpoint::server(server_config, server_address.parse()?)?; |
| 213 | info!("listening on {server_address}"); | 61 | info!("listening on {server_address}"); |
| 214 | 62 | ||
| 215 | - let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); | ||
| 216 | - let services = Services::default(); | ||
| 217 | - tokio::spawn(the_actor(event_receiver, services.visits.clone())); | ||
| 218 | let shared = Shared { | 63 | let shared = Shared { |
| 219 | - event_sender, | ||
| 220 | db, | 64 | db, |
| 221 | - services, | 65 | + services: Services::default(), |
| 222 | directory, | 66 | directory, |
| 223 | backups, | 67 | backups, |
| 224 | }; | 68 | }; |
| 225 | 69 | ||
| 70 | + tokio::spawn(retention::collect(shared.clone())); | ||
| 71 | + | ||
| 226 | while let Some(incoming) = endpoint.accept().await { | 72 | while let Some(incoming) = endpoint.accept().await { |
| 227 | tokio::spawn(handle_connection(incoming, shared.clone())); | 73 | tokio::spawn(handle_connection(incoming, shared.clone())); |
| 228 | } | 74 | } |
| @@ -247,31 +93,58 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv | |||
| 247 | return Ok(()); | 93 | return Ok(()); |
| 248 | } | 94 | } |
| 249 | let connection = incoming.await?; | 95 | let connection = incoming.await?; |
| 250 | - let send_stream = connection.open_uni().await?; | 96 | + let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { |
| 251 | - let _ = shared | 97 | + Ok(Ok(Some(pending))) => pending, |
| 252 | - .event_sender | 98 | + Ok(Ok(None)) => return Ok(()), |
| 253 | - .send(Event::Connected { | 99 | + Ok(Err(error)) => { |
| 254 | - connection_id: connection.stable_id(), | 100 | + close(&connection, Close::Protocol); |
| 255 | - connection: connection.clone(), | 101 | + return Err(error); |
| 256 | - send_stream, | 102 | + } |
| 257 | - }) | 103 | + Err(_) => { |
| 258 | - .await; | 104 | + close(&connection, Close::Protocol); |
| 259 | - | 105 | + return Ok(()); |
| 260 | - let state = Arc::new(Mutex::new(State::Anonymous)); | 106 | + } |
| 107 | + }; | ||
| 108 | + let Pending { | ||
| 109 | + client, | ||
| 110 | + events, | ||
| 111 | + reply_stream, | ||
| 112 | + user, | ||
| 113 | + } = pending; | ||
| 114 | + let hub = &shared.services.hub; | ||
| 115 | + | ||
| 116 | + let presence = hub.add(Arc::clone(&client)); | ||
| 117 | + match welcome(&client, reply_stream, user, &shared).await { | ||
| 118 | + Ok(true) => {} | ||
| 119 | + Ok(false) => { | ||
| 120 | + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; | ||
| 121 | + let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; | ||
| 122 | + return Ok(()); | ||
| 123 | + } | ||
| 124 | + Err(error) => { | ||
| 125 | + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; | ||
| 126 | + close(&connection, Close::Protocol); | ||
| 127 | + return Err(error); | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + let send_stream = match connection.open_uni().await { | ||
| 131 | + Ok(stream) => stream, | ||
| 132 | + Err(error) => { | ||
| 133 | + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; | ||
| 134 | + return Err(error.into()); | ||
| 135 | + } | ||
| 136 | + }; | ||
| 137 | + tokio::spawn(write_events(events, send_stream)); | ||
| 138 | + publish_presence(&shared, presence).await; | ||
| 261 | 139 | ||
| 262 | tokio::spawn(datagram::relay_datagrams( | 140 | tokio::spawn(datagram::relay_datagrams( |
| 263 | connection.clone(), | 141 | connection.clone(), |
| 264 | - Arc::clone(&state), | 142 | + Arc::clone(&client), |
| 265 | shared.clone(), | 143 | shared.clone(), |
| 266 | )); | 144 | )); |
| 267 | 145 | ||
| 268 | while let Ok(streams) = connection.accept_bi().await { | 146 | while let Ok(streams) = connection.accept_bi().await { |
| 269 | - let route = route( | 147 | + let route = route(Arc::clone(&client), streams, shared.clone()); |
| 270 | - connection.clone(), | ||
| 271 | - Arc::clone(&state), | ||
| 272 | - streams, | ||
| 273 | - shared.clone(), | ||
| 274 | - ); | ||
| 275 | tokio::spawn(async move { | 148 | tokio::spawn(async move { |
| 276 | if let Err(error) = route.await { | 149 | if let Err(error) = route.await { |
| 277 | warn!("stream: {error}"); | 150 | warn!("stream: {error}"); |
| @@ -279,39 +152,114 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv | |||
| 279 | }); | 152 | }); |
| 280 | } | 153 | } |
| 281 | 154 | ||
| 282 | - shared.services.presence.sign_out(connection.stable_id()); | 155 | + client.closed.store(true, Ordering::Release); |
| 283 | - shared.services.visits.forget(connection.stable_id()); | 156 | + let presence = hub.remove(client.id); |
| 284 | 157 | ||
| 285 | - if let Some((user_id, token)) = signed_in(&state) { | 158 | + if let Some(me) = &client.me { |
| 286 | let conn = database::connect(&shared.db).await?; | 159 | let conn = database::connect(&shared.db).await?; |
| 287 | - let mut broadcasts = request::leave_connection_voice( | 160 | + let mut broadcasts = match shared.services.rooms.leave(client.id) { |
| 288 | - &shared.services.voice, | 161 | + Some(departure) => request::departed(departure, &conn).await?, |
| 289 | - &shared.services.share, | 162 | + None => Vec::new(), |
| 290 | - Some(&connection), | 163 | + }; |
| 291 | - &conn, | 164 | + if let Presence::Offline(user_id) = &presence { |
| 292 | - ) | 165 | + broadcasts.extend(request::presence_changed(hub, user_id, &conn).await?); |
| 293 | - .await?; | 166 | + } |
| 294 | - broadcasts | ||
| 295 | - .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); | ||
| 296 | publish(&shared, broadcasts).await; | 167 | publish(&shared, broadcasts).await; |
| 297 | - authentication::seen(&user_id, &token, &conn).await?; | 168 | + authentication::seen(&me.user_id, &me.token, &conn).await?; |
| 298 | } | 169 | } |
| 299 | 170 | ||
| 300 | Ok(()) | 171 | Ok(()) |
| 301 | } | 172 | } |
| 302 | 173 | ||
| 174 | +fn close(connection: &Connection, close: Close) { | ||
| 175 | + connection.close(close.code(), close.reason().as_bytes()); | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pending>, ServerError> { | ||
| 179 | + let (send_stream, mut receive_stream) = connection.accept_bi().await?; | ||
| 180 | + let mut reply_stream = Sending::new(send_stream); | ||
| 181 | + let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; | ||
| 182 | + | ||
| 183 | + match admit(hello, connection, shared).await { | ||
| 184 | + Ok((me, user)) => { | ||
| 185 | + let (client, events) = Client::new(Some(connection.clone()), me); | ||
| 186 | + | ||
| 187 | + Ok(Some(Pending { | ||
| 188 | + client, | ||
| 189 | + events, | ||
| 190 | + reply_stream, | ||
| 191 | + user, | ||
| 192 | + })) | ||
| 193 | + } | ||
| 194 | + Err(error) => { | ||
| 195 | + let reply: Result<Welcome, common::error::Error> = Err(error.into()); | ||
| 196 | + frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; | ||
| 197 | + reply_stream.finish()?; | ||
| 198 | + let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; | ||
| 199 | + | ||
| 200 | + Ok(None) | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +async fn admit( | ||
| 206 | + hello: Hello, | ||
| 207 | + connection: &Connection, | ||
| 208 | + shared: &Shared, | ||
| 209 | +) -> Result<(Option<Signed>, Option<User>), ServerError> { | ||
| 210 | + let Some(token) = hello.token else { | ||
| 211 | + return Ok((None, None)); | ||
| 212 | + }; | ||
| 213 | + let conn = database::connect(&shared.db).await?; | ||
| 214 | + let user = authentication::resume(&token, &conn).await?; | ||
| 215 | + stats::mark_active(&user.id, &conn).await?; | ||
| 216 | + request::record_address(&user, Some(connection), &conn).await?; | ||
| 217 | + if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await { | ||
| 218 | + warn!("device: {error}"); | ||
| 219 | + } | ||
| 220 | + let me = Signed { | ||
| 221 | + user_id: user.id.clone(), | ||
| 222 | + token, | ||
| 223 | + }; | ||
| 224 | + | ||
| 225 | + Ok((Some(me), Some(user))) | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +async fn welcome( | ||
| 229 | + client: &Client, | ||
| 230 | + mut reply_stream: Sending, | ||
| 231 | + user: Option<User>, | ||
| 232 | + shared: &Shared, | ||
| 233 | +) -> Result<bool, ServerError> { | ||
| 234 | + let checked = match &client.me { | ||
| 235 | + Some(me) => { | ||
| 236 | + let conn = database::connect(&shared.db).await?; | ||
| 237 | + authentication::resume(&me.token, &conn).await.map(Some) | ||
| 238 | + } | ||
| 239 | + None => Ok(user.clone()), | ||
| 240 | + }; | ||
| 241 | + let accepted = checked.is_ok(); | ||
| 242 | + let reply: Result<Welcome, common::error::Error> = match checked { | ||
| 243 | + Ok(_) => Ok(Welcome { user }), | ||
| 244 | + Err(error) => Err(error.into()), | ||
| 245 | + }; | ||
| 246 | + frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; | ||
| 247 | + reply_stream.finish()?; | ||
| 248 | + | ||
| 249 | + Ok(accepted) | ||
| 250 | +} | ||
| 251 | + | ||
| 303 | async fn route( | 252 | async fn route( |
| 304 | - connection: Connection, | 253 | + client: Arc<Client>, |
| 305 | - state: Arc<Mutex<State>>, | ||
| 306 | (send_stream, mut receive_stream): (SendStream, RecvStream), | 254 | (send_stream, mut receive_stream): (SendStream, RecvStream), |
| 307 | shared: Shared, | 255 | shared: Shared, |
| 308 | ) -> Result<(), ServerError> { | 256 | ) -> Result<(), ServerError> { |
| 309 | let send_stream = Sending::new(send_stream); | 257 | let send_stream = Sending::new(send_stream); |
| 310 | let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; | 258 | let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; |
| 311 | - let user = signed_user(&state); | ||
| 312 | match open { | 259 | match open { |
| 313 | - Open::Call(request) => answer(connection, state, request, send_stream, shared).await, | 260 | + Open::Call(request) => answer(client, request, send_stream, shared).await, |
| 314 | Open::Upload(upload) => { | 261 | Open::Upload(upload) => { |
| 262 | + let user = signed_user(&client, &shared).await?; | ||
| 315 | attachment::upload( | 263 | attachment::upload( |
| 316 | user.as_ref(), | 264 | user.as_ref(), |
| 317 | upload, | 265 | upload, |
| @@ -323,6 +271,7 @@ async fn route( | |||
| 323 | .await | 271 | .await |
| 324 | } | 272 | } |
| 325 | Open::Fetch(blob) => { | 273 | Open::Fetch(blob) => { |
| 274 | + let user = signed_user(&client, &shared).await?; | ||
| 326 | attachment::fetch( | 275 | attachment::fetch( |
| 327 | user.as_ref(), | 276 | user.as_ref(), |
| 328 | blob, | 277 | blob, |
| @@ -336,54 +285,30 @@ async fn route( | |||
| 336 | } | 285 | } |
| 337 | } | 286 | } |
| 338 | 287 | ||
| 288 | +async fn signed_user(client: &Client, shared: &Shared) -> Result<Option<User>, ServerError> { | ||
| 289 | + let Some(me) = &client.me else { | ||
| 290 | + return Ok(None); | ||
| 291 | + }; | ||
| 292 | + let conn = database::connect(&shared.db).await?; | ||
| 293 | + | ||
| 294 | + Ok(Some(user::read(&me.user_id, &conn).await?)) | ||
| 295 | +} | ||
| 296 | + | ||
| 339 | async fn answer( | 297 | async fn answer( |
| 340 | - connection: Connection, | 298 | + client: Arc<Client>, |
| 341 | - state: Arc<Mutex<State>>, | ||
| 342 | request: Request, | 299 | request: Request, |
| 343 | mut send_stream: Sending, | 300 | mut send_stream: Sending, |
| 344 | shared: Shared, | 301 | shared: Shared, |
| 345 | ) -> Result<(), ServerError> { | 302 | ) -> Result<(), ServerError> { |
| 346 | - let before = signed_in(&state); | ||
| 347 | let (response, broadcasts) = request::handle( | 303 | let (response, broadcasts) = request::handle( |
| 348 | request, | 304 | request, |
| 349 | - &state, | 305 | + &client, |
| 350 | &shared.db, | 306 | &shared.db, |
| 351 | &shared.services, | 307 | &shared.services, |
| 352 | - Some(&connection), | ||
| 353 | &shared.directory, | 308 | &shared.directory, |
| 354 | &shared.backups, | 309 | &shared.backups, |
| 355 | ) | 310 | ) |
| 356 | .await; | 311 | .await; |
| 357 | - let after = signed_in(&state); | ||
| 358 | - | ||
| 359 | - if before != after { | ||
| 360 | - let connection_id = connection.stable_id(); | ||
| 361 | - shared.services.visits.forget(connection_id); | ||
| 362 | - match &after { | ||
| 363 | - Some((user_id, token)) => shared | ||
| 364 | - .services | ||
| 365 | - .presence | ||
| 366 | - .sign_in(&connection, user_id, token), | ||
| 367 | - None => shared.services.presence.sign_out(connection_id), | ||
| 368 | - } | ||
| 369 | - let before_id = before.map(|(user_id, _)| user_id); | ||
| 370 | - let after_id = after.map(|(user_id, _)| user_id); | ||
| 371 | - let _ = shared | ||
| 372 | - .event_sender | ||
| 373 | - .send(Event::Signed { | ||
| 374 | - connection_id, | ||
| 375 | - user_id: after_id.clone(), | ||
| 376 | - }) | ||
| 377 | - .await; | ||
| 378 | - if let Some(user_id) = &before_id { | ||
| 379 | - broadcast_presence(&shared, user_id).await; | ||
| 380 | - } | ||
| 381 | - if after_id != before_id | ||
| 382 | - && let Some(user_id) = &after_id | ||
| 383 | - { | ||
| 384 | - broadcast_presence(&shared, user_id).await; | ||
| 385 | - } | ||
| 386 | - } | ||
| 387 | 312 | ||
| 388 | publish(&shared, broadcasts).await; | 313 | publish(&shared, broadcasts).await; |
| 389 | 314 | ||
| @@ -393,18 +318,19 @@ async fn answer( | |||
| 393 | Ok(()) | 318 | Ok(()) |
| 394 | } | 319 | } |
| 395 | 320 | ||
| 396 | -pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | 321 | +fn first_named(first: Presence, second: Presence) -> Presence { |
| 397 | - for broadcast in broadcasts { | 322 | + match first { |
| 398 | - let _ = shared | 323 | + Presence::None => second, |
| 399 | - .event_sender | 324 | + named => named, |
| 400 | - .send(Event::Broadcast(Box::new(broadcast))) | ||
| 401 | - .await; | ||
| 402 | } | 325 | } |
| 403 | } | 326 | } |
| 404 | 327 | ||
| 405 | -async fn broadcast_presence(shared: &Shared, user_id: &str) { | 328 | +async fn publish_presence(shared: &Shared, presence: Presence) { |
| 329 | + let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { | ||
| 330 | + return; | ||
| 331 | + }; | ||
| 406 | let broadcasts = match database::connect(&shared.db).await { | 332 | let broadcasts = match database::connect(&shared.db).await { |
| 407 | - Ok(conn) => request::presence_changed(&shared.services.presence, user_id, &conn).await, | 333 | + Ok(conn) => request::presence_changed(&shared.services.hub, &user_id, &conn).await, |
| 408 | Err(error) => Err(error), | 334 | Err(error) => Err(error), |
| 409 | }; | 335 | }; |
| 410 | match broadcasts { | 336 | match broadcasts { |
| @@ -413,94 +339,12 @@ async fn broadcast_presence(shared: &Shared, user_id: &str) { | |||
| 413 | } | 339 | } |
| 414 | } | 340 | } |
| 415 | 341 | ||
| 416 | -fn signed_user(state: &Mutex<State>) -> Option<User> { | 342 | +async fn write_events(mut events: mpsc::Receiver<Bytes>, send_stream: SendStream) { |
| 417 | - match &*state.lock().unwrap() { | ||
| 418 | - State::Anonymous => None, | ||
| 419 | - State::Authenticated { user, .. } => Some(user.clone()), | ||
| 420 | - } | ||
| 421 | -} | ||
| 422 | - | ||
| 423 | -fn signed_in(state: &Mutex<State>) -> Option<(String, String)> { | ||
| 424 | - match &*state.lock().unwrap() { | ||
| 425 | - State::Anonymous => None, | ||
| 426 | - State::Authenticated { user, token } => Some((user.id.clone(), token.clone())), | ||
| 427 | - } | ||
| 428 | -} | ||
| 429 | - | ||
| 430 | -async fn write_session(mut event_receiver: mpsc::Receiver<Arc<Push>>, send_stream: SendStream) { | ||
| 431 | let mut send_stream = Sending::new(send_stream); | 343 | let mut send_stream = Sending::new(send_stream); |
| 432 | - while let Some(event) = event_receiver.recv().await { | 344 | + while let Some(bytes) = events.recv().await { |
| 433 | - if let Err(error) = frame::write(&mut send_stream, &*event, DOWN_MAX).await { | 345 | + if let Err(error) = send_stream.get().write_all(&bytes).await { |
| 434 | - warn!("session write: {error}"); | 346 | + warn!("event write: {error}"); |
| 435 | break; | 347 | break; |
| 436 | } | 348 | } |
| 437 | } | 349 | } |
| 438 | } | 350 | } |
| 439 | - | ||
| 440 | -async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) { | ||
| 441 | - let mut sessions: Vec<Session> = Vec::new(); | ||
| 442 | - | ||
| 443 | - while let Some(event) = event_receiver.recv().await { | ||
| 444 | - sessions.retain(|session| { | ||
| 445 | - !session.writer.is_finished() && session.connection.close_reason().is_none() | ||
| 446 | - }); | ||
| 447 | - | ||
| 448 | - match event { | ||
| 449 | - Event::Connected { | ||
| 450 | - connection_id, | ||
| 451 | - connection, | ||
| 452 | - send_stream, | ||
| 453 | - } => { | ||
| 454 | - let (event_sender, event_receiver) = mpsc::channel(SESSION_LENGTH); | ||
| 455 | - let writer = tokio::spawn(write_session(event_receiver, send_stream)); | ||
| 456 | - | ||
| 457 | - sessions.push(Session { | ||
| 458 | - connection_id, | ||
| 459 | - user_id: None, | ||
| 460 | - connection, | ||
| 461 | - event_sender, | ||
| 462 | - writer, | ||
| 463 | - }); | ||
| 464 | - } | ||
| 465 | - Event::Signed { | ||
| 466 | - connection_id, | ||
| 467 | - user_id, | ||
| 468 | - } => { | ||
| 469 | - if let Some(session) = sessions | ||
| 470 | - .iter_mut() | ||
| 471 | - .find(|session| session.connection_id == connection_id) | ||
| 472 | - { | ||
| 473 | - session.user_id = user_id; | ||
| 474 | - } | ||
| 475 | - } | ||
| 476 | - Event::Broadcast(broadcast) => { | ||
| 477 | - let community_id = broadcast.event.community_id().map(str::to_string); | ||
| 478 | - let event = Arc::new(broadcast.event); | ||
| 479 | - | ||
| 480 | - sessions.retain(|session| { | ||
| 481 | - let Some(user_id) = &session.user_id else { | ||
| 482 | - return true; | ||
| 483 | - }; | ||
| 484 | - let watching = community_id.as_deref().is_some_and(|community_id| { | ||
| 485 | - visits.watches(session.connection_id, community_id) | ||
| 486 | - }); | ||
| 487 | - if !broadcast.user_ids.contains(user_id) && !watching { | ||
| 488 | - return true; | ||
| 489 | - } | ||
| 490 | - | ||
| 491 | - match session.event_sender.try_send(Arc::clone(&event)) { | ||
| 492 | - Ok(()) => true, | ||
| 493 | - Err(error) => { | ||
| 494 | - warn!("session dropped {user_id}: {error}"); | ||
| 495 | - session.writer.abort(); | ||
| 496 | - session | ||
| 497 | - .connection | ||
| 498 | - .close(Close::Slow.code(), Close::Slow.reason().as_bytes()); | ||
| 499 | - false | ||
| 500 | - } | ||
| 501 | - } | ||
| 502 | - }); | ||
| 503 | - } | ||
| 504 | - } | ||
| 505 | - } | ||
| 506 | -} | ||
crates/server/src/overview.rsmodified+4 -8
| @@ -1,13 +1,9 @@ | |||
| 1 | use common::model::{Overview, Role}; | 1 | use common::model::{Overview, Role}; |
| 2 | use turso::Connection; | 2 | use turso::Connection; |
| 3 | 3 | ||
| 4 | -use crate::{community::Kind, error::ServerError, network::Presence, voice::Voice}; | 4 | +use crate::{community::Kind, error::ServerError, hub::Hub, rooms::Rooms}; |
| 5 | 5 | ||
| 6 | -pub async fn read( | 6 | +pub async fn read(hub: &Hub, rooms: &Rooms, conn: &Connection) -> Result<Overview, ServerError> { |
| 7 | - presence: &Presence, | ||
| 8 | - voice: &Voice, | ||
| 9 | - conn: &Connection, | ||
| 10 | -) -> Result<Overview, ServerError> { | ||
| 11 | let mut rows = conn | 7 | let mut rows = conn |
| 12 | .query( | 8 | .query( |
| 13 | "SELECT | 9 | "SELECT |
| @@ -33,8 +29,8 @@ pub async fn read( | |||
| 33 | users: count(0)?, | 29 | users: count(0)?, |
| 34 | builders: count(1)?, | 30 | builders: count(1)?, |
| 35 | communities: count(2)?, | 31 | communities: count(2)?, |
| 36 | - online: presence.online() as u64, | 32 | + online: hub.online() as u64, |
| 37 | - voice: voice.count() as u64, | 33 | + voice: rooms.count() as u64, |
| 38 | storage_bytes: count(3)?, | 34 | storage_bytes: count(3)?, |
| 39 | }) | 35 | }) |
| 40 | } | 36 | } |
crates/server/src/publish.rsadded+117 -0
| @@ -0,0 +1,117 @@ | |||
| 1 | +use std::collections::BTreeSet; | ||
| 2 | + | ||
| 3 | +use bytes::Bytes; | ||
| 4 | +use common::{ | ||
| 5 | + event::{Down, Event, Media}, | ||
| 6 | + frame::{self, DOWN_MAX}, | ||
| 7 | +}; | ||
| 8 | +use tracing::warn; | ||
| 9 | + | ||
| 10 | +use crate::{ | ||
| 11 | + community, database, error::ServerError, friend, hub::ConnId, network::Shared, user, | ||
| 12 | + user_community, | ||
| 13 | +}; | ||
| 14 | + | ||
| 15 | +pub enum To { | ||
| 16 | + User(String), | ||
| 17 | + Users(Vec<String>), | ||
| 18 | + Community(String), | ||
| 19 | + CommunityExcept(String, String), | ||
| 20 | + Related(String), | ||
| 21 | + Builders, | ||
| 22 | + Everyone, | ||
| 23 | + Conn(ConnId), | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +pub struct Broadcast { | ||
| 27 | + pub to: To, | ||
| 28 | + pub down: Down, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl Broadcast { | ||
| 32 | + pub fn new(to: To, event: Event) -> Self { | ||
| 33 | + Self { | ||
| 34 | + to, | ||
| 35 | + down: Down::Event(Box::new(event)), | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + pub fn media(conn: ConnId, media: Media) -> Self { | ||
| 40 | + Self { | ||
| 41 | + to: To::Conn(conn), | ||
| 42 | + down: Down::Media(media), | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | ||
| 48 | + for broadcast in broadcasts { | ||
| 49 | + let ids = match resolve(shared, &broadcast.to).await { | ||
| 50 | + Ok(ids) => ids, | ||
| 51 | + Err(error) => { | ||
| 52 | + warn!("resolve: {error}"); | ||
| 53 | + continue; | ||
| 54 | + } | ||
| 55 | + }; | ||
| 56 | + let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. })); | ||
| 57 | + let framed = frame::encode(&broadcast.down); | ||
| 58 | + if framed.len() - 4 > DOWN_MAX as usize { | ||
| 59 | + warn!("event too large: {} bytes", framed.len() - 4); | ||
| 60 | + continue; | ||
| 61 | + } | ||
| 62 | + let bytes = Bytes::from(framed); | ||
| 63 | + shared.services.hub.send(&ids, &bytes, droppable); | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +async fn resolve(shared: &Shared, to: &To) -> Result<Vec<ConnId>, ServerError> { | ||
| 68 | + let hub = &shared.services.hub; | ||
| 69 | + let ids = match to { | ||
| 70 | + To::Conn(id) => vec![*id], | ||
| 71 | + To::Everyone => hub.all(), | ||
| 72 | + To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), | ||
| 73 | + To::Users(user_ids) => hub.conns_of(user_ids), | ||
| 74 | + To::Builders => { | ||
| 75 | + let conn = database::connect(&shared.db).await?; | ||
| 76 | + hub.conns_of(&user::builder_ids(&conn).await?) | ||
| 77 | + } | ||
| 78 | + To::Community(community_id) => community_conns(shared, community_id).await?, | ||
| 79 | + To::CommunityExcept(community_id, user_id) => { | ||
| 80 | + let mut ids = community_conns(shared, community_id).await?; | ||
| 81 | + let own = hub.conns_of(std::slice::from_ref(user_id)); | ||
| 82 | + ids.retain(|id| !own.contains(id)); | ||
| 83 | + ids | ||
| 84 | + } | ||
| 85 | + To::Related(user_id) => { | ||
| 86 | + let conn = database::connect(&shared.db).await?; | ||
| 87 | + hub.conns_of(&related_user_ids(user_id, &conn).await?) | ||
| 88 | + } | ||
| 89 | + }; | ||
| 90 | + | ||
| 91 | + Ok(ids) | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +async fn community_conns(shared: &Shared, community_id: &str) -> Result<Vec<ConnId>, ServerError> { | ||
| 95 | + let hub = &shared.services.hub; | ||
| 96 | + let conn = database::connect(&shared.db).await?; | ||
| 97 | + let mut ids = hub.conns_of(&user_community::member_ids(community_id, &conn).await?); | ||
| 98 | + ids.extend(hub.watchers(community_id)); | ||
| 99 | + ids.sort_unstable(); | ||
| 100 | + ids.dedup(); | ||
| 101 | + Ok(ids) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +pub(crate) async fn related_user_ids( | ||
| 105 | + user_id: &str, | ||
| 106 | + conn: &turso::Connection, | ||
| 107 | +) -> Result<Vec<String>, ServerError> { | ||
| 108 | + let mut user_ids = BTreeSet::from([user_id.to_string()]); | ||
| 109 | + for community in community::communities_of(user_id, conn).await? { | ||
| 110 | + user_ids.extend(user_community::member_ids(&community.id, conn).await?); | ||
| 111 | + } | ||
| 112 | + for friend in friend::state(user_id, conn).await?.friends { | ||
| 113 | + user_ids.insert(friend.id); | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + Ok(user_ids.into_iter().collect()) | ||
| 117 | +} | ||
crates/server/src/request.rsmodified+442 -652
Diff too large; view file
| @@ -1,8 +1,4 @@ | |||
| 1 | -use std::{ | 1 | +use std::{collections::BTreeMap, path::Path}; |
| 2 | - collections::{BTreeMap, BTreeSet}, | ||
| 3 | - path::Path, | ||
| 4 | - sync::Mutex, | ||
| 5 | -}; | ||
| 6 | 2 | ||
| 7 | use common::{ | 3 | use common::{ |
| 8 | error::Error as CommonError, | 4 | error::Error as CommonError, |
| @@ -29,33 +25,29 @@ use crate::{ | |||
| 29 | database::{self, DB}, | 25 | database::{self, DB}, |
| 30 | direct, | 26 | direct, |
| 31 | error::ServerError, | 27 | error::ServerError, |
| 32 | - friend, invitation, invite, log, message, | 28 | + friend, |
| 33 | - network::{self, Services, State}, | 29 | + hub::{Client, Hub}, |
| 30 | + invitation, invite, log, message, | ||
| 31 | + network::Services, | ||
| 34 | notes, overview, | 32 | notes, overview, |
| 33 | + publish::{Broadcast, To, related_user_ids}, | ||
| 35 | rate_limit::RateLimit, | 34 | rate_limit::RateLimit, |
| 36 | - report, server_ban, server_settings, | 35 | + report, |
| 37 | - share::Shares, | 36 | + rooms::{Departure, Rooms}, |
| 38 | - stats, user, user_community, | 37 | + server_ban, server_settings, stats, user, user_community, |
| 39 | - voice::{CallEnd, Left, Voice}, | ||
| 40 | }; | 38 | }; |
| 41 | 39 | ||
| 42 | -pub struct Broadcast { | ||
| 43 | - pub event: Event, | ||
| 44 | - pub user_ids: Vec<String>, | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | type Outcome = (Response, Vec<Broadcast>); | 40 | type Outcome = (Response, Vec<Broadcast>); |
| 48 | 41 | ||
| 49 | pub async fn handle( | 42 | pub async fn handle( |
| 50 | request: Request, | 43 | request: Request, |
| 51 | - state: &Mutex<State>, | 44 | + client: &Client, |
| 52 | db: &DB, | 45 | db: &DB, |
| 53 | services: &Services, | 46 | services: &Services, |
| 54 | - connection: Option<&quinn::Connection>, | ||
| 55 | directory: &Path, | 47 | directory: &Path, |
| 56 | backups: &Path, | 48 | backups: &Path, |
| 57 | ) -> (Result<Response, CommonError>, Vec<Broadcast>) { | 49 | ) -> (Result<Response, CommonError>, Vec<Broadcast>) { |
| 58 | - match dispatch(request, state, db, services, connection, directory, backups).await { | 50 | + match dispatch(request, client, db, services, directory, backups).await { |
| 59 | Ok((response, broadcasts)) => (Ok(response), broadcasts), | 51 | Ok((response, broadcasts)) => (Ok(response), broadcasts), |
| 60 | Err(error) => (Err(error.into()), Vec::new()), | 52 | Err(error) => (Err(error.into()), Vec::new()), |
| 61 | } | 53 | } |
| @@ -63,20 +55,18 @@ pub async fn handle( | |||
| 63 | 55 | ||
| 64 | async fn dispatch( | 56 | async fn dispatch( |
| 65 | request: Request, | 57 | request: Request, |
| 66 | - state: &Mutex<State>, | 58 | + client: &Client, |
| 67 | db: &DB, | 59 | db: &DB, |
| 68 | services: &Services, | 60 | services: &Services, |
| 69 | - connection: Option<&quinn::Connection>, | ||
| 70 | directory: &Path, | 61 | directory: &Path, |
| 71 | backups: &Path, | 62 | backups: &Path, |
| 72 | ) -> Result<Outcome, ServerError> { | 63 | ) -> Result<Outcome, ServerError> { |
| 73 | let Services { | 64 | let Services { |
| 74 | - voice, | 65 | + rooms, |
| 75 | - share, | 66 | + hub, |
| 76 | - presence, | ||
| 77 | rate_limit, | 67 | rate_limit, |
| 78 | - visits, | ||
| 79 | } = services; | 68 | } = services; |
| 69 | + let connection = client.conn.as_ref(); | ||
| 80 | let mut conn = database::connect(db).await?; | 70 | let mut conn = database::connect(db).await?; |
| 81 | 71 | ||
| 82 | let outcome = match request { | 72 | let outcome = match request { |
| @@ -89,43 +79,30 @@ async fn dispatch( | |||
| 89 | let (user, token) = | 79 | let (user, token) = |
| 90 | authentication::register(&username, &password, invite.as_deref(), &mut conn) | 80 | authentication::register(&username, &password, invite.as_deref(), &mut conn) |
| 91 | .await?; | 81 | .await?; |
| 92 | - enter(state, user, token, voice, share, connection, &conn).await? | 82 | + (Response::Session { user, token }, Vec::new()) |
| 93 | } | 83 | } |
| 94 | Request::Login { username, password } => { | 84 | Request::Login { username, password } => { |
| 95 | limit_logins(rate_limit, connection, &conn).await?; | 85 | limit_logins(rate_limit, connection, &conn).await?; |
| 96 | let (user, token) = authentication::login(&username, &password, &conn).await?; | 86 | let (user, token) = authentication::login(&username, &password, &conn).await?; |
| 97 | - enter(state, user, token, voice, share, connection, &conn).await? | 87 | + (Response::Session { user, token }, Vec::new()) |
| 98 | - } | ||
| 99 | - Request::Resume { token } => { | ||
| 100 | - let user = authentication::resume(&token, &conn).await?; | ||
| 101 | - enter(state, user, token, voice, share, connection, &conn).await? | ||
| 102 | - } | ||
| 103 | - Request::Detach => { | ||
| 104 | - authenticated(state, &conn).await?; | ||
| 105 | - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; | ||
| 106 | - set_state(state, State::Anonymous); | ||
| 107 | - (Response::Done, broadcasts) | ||
| 108 | } | 88 | } |
| 109 | Request::Logout => { | 89 | Request::Logout => { |
| 110 | - authenticated(state, &conn).await?; | 90 | + authenticated(client, &conn).await?; |
| 111 | - let token = session_token(state)?; | 91 | + let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; |
| 112 | - authentication::logout(&token, &conn).await?; | 92 | + authentication::logout(&me.token, &conn).await?; |
| 113 | - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; | 93 | + (Response::Done, Vec::new()) |
| 114 | - set_state(state, State::Anonymous); | ||
| 115 | - (Response::Done, broadcasts) | ||
| 116 | } | 94 | } |
| 117 | Request::ReadUser { user_id } => { | 95 | Request::ReadUser { user_id } => { |
| 118 | - authenticated(state, &conn).await?; | 96 | + authenticated(client, &conn).await?; |
| 119 | ( | 97 | ( |
| 120 | Response::User(user::read(&user_id, &conn).await?), | 98 | Response::User(user::read(&user_id, &conn).await?), |
| 121 | Vec::new(), | 99 | Vec::new(), |
| 122 | ) | 100 | ) |
| 123 | } | 101 | } |
| 124 | Request::UpdateUser { username } => { | 102 | Request::UpdateUser { username } => { |
| 125 | - let me = authenticated(state, &conn).await?; | 103 | + let me = authenticated(client, &conn).await?; |
| 126 | let user = user::update(&me.id, &username, &conn).await?; | 104 | let user = user::update(&me.id, &username, &conn).await?; |
| 127 | - cache_user(state, user.clone()); | 105 | + let broadcasts = user_updated(&user); |
| 128 | - let broadcasts = user_updated(&user, &conn).await?; | ||
| 129 | (Response::User(user), broadcasts) | 106 | (Response::User(user), broadcasts) |
| 130 | } | 107 | } |
| 131 | Request::ServerSettings => ( | 108 | Request::ServerSettings => ( |
| @@ -133,9 +110,8 @@ async fn dispatch( | |||
| 133 | Vec::new(), | 110 | Vec::new(), |
| 134 | ), | 111 | ), |
| 135 | Request::UpdateServerSettings { settings } => { | 112 | Request::UpdateServerSettings { settings } => { |
| 136 | - let me = builder(state, &conn).await?; | 113 | + let me = builder(client, &conn).await?; |
| 137 | validate_server_settings(&settings)?; | 114 | validate_server_settings(&settings)?; |
| 138 | - let previous = server_settings::read(&conn).await?; | ||
| 139 | server_settings::update(&settings, &conn).await?; | 115 | server_settings::update(&settings, &conn).await?; |
| 140 | admin_log::record( | 116 | admin_log::record( |
| 141 | Some(&me.id), | 117 | Some(&me.id), |
| @@ -147,28 +123,16 @@ async fn dispatch( | |||
| 147 | .await?; | 123 | .await?; |
| 148 | if settings.maintenance { | 124 | if settings.maintenance { |
| 149 | let builders = user::builder_ids(&conn).await?; | 125 | let builders = user::builder_ids(&conn).await?; |
| 150 | - presence.disconnect_except(&builders, Close::Maintenance); | 126 | + hub.kick_all_except(&builders, Close::Maintenance); |
| 151 | } | 127 | } |
| 152 | - let broadcasts = if settings.announcement == previous.announcement { | 128 | + let broadcasts = vec![Broadcast::new( |
| 153 | - Vec::new() | 129 | + To::Everyone, |
| 154 | - } else { | 130 | + Event::SettingsUpdated(settings.clone()), |
| 155 | - vec![Broadcast { | 131 | + )]; |
| 156 | - event: Event::Announcement { | ||
| 157 | - text: settings.announcement.clone(), | ||
| 158 | - }, | ||
| 159 | - user_ids: presence.user_ids(), | ||
| 160 | - }] | ||
| 161 | - }; | ||
| 162 | (Response::ServerSettings(settings), broadcasts) | 132 | (Response::ServerSettings(settings), broadcasts) |
| 163 | } | 133 | } |
| 164 | - Request::SetDevice { name } => { | ||
| 165 | - authenticated(state, &conn).await?; | ||
| 166 | - let token = session_token(state)?; | ||
| 167 | - authentication::set_device(&token, &name, &conn).await?; | ||
| 168 | - (Response::Done, Vec::new()) | ||
| 169 | - } | ||
| 170 | Request::Sessions { user_id } => { | 134 | Request::Sessions { user_id } => { |
| 171 | - let me = authenticated(state, &conn).await?; | 135 | + let me = authenticated(client, &conn).await?; |
| 172 | managed(&me, &user_id, &conn).await?; | 136 | managed(&me, &user_id, &conn).await?; |
| 173 | ( | 137 | ( |
| 174 | Response::Sessions(authentication::sessions(&user_id, &conn).await?), | 138 | Response::Sessions(authentication::sessions(&user_id, &conn).await?), |
| @@ -179,10 +143,17 @@ async fn dispatch( | |||
| 179 | user_id, | 143 | user_id, |
| 180 | session_id, | 144 | session_id, |
| 181 | } => { | 145 | } => { |
| 182 | - let me = authenticated(state, &conn).await?; | 146 | + let me = authenticated(client, &conn).await?; |
| 183 | managed(&me, &user_id, &conn).await?; | 147 | managed(&me, &user_id, &conn).await?; |
| 184 | - let token = authentication::revoke_session(&user_id, &session_id, &conn).await?; | 148 | + authentication::revoke( |
| 185 | - presence.disconnect_token(&token); | 149 | + hub, |
| 150 | + authentication::Revoke::Session { | ||
| 151 | + user_id: &user_id, | ||
| 152 | + session_id: &session_id, | ||
| 153 | + }, | ||
| 154 | + &conn, | ||
| 155 | + ) | ||
| 156 | + .await?; | ||
| 186 | admin_log::record( | 157 | admin_log::record( |
| 187 | Some(&me.id), | 158 | Some(&me.id), |
| 188 | Some(&user_id), | 159 | Some(&user_id), |
| @@ -194,7 +165,7 @@ async fn dispatch( | |||
| 194 | (Response::Done, Vec::new()) | 165 | (Response::Done, Vec::new()) |
| 195 | } | 166 | } |
| 196 | Request::RenameUser { user_id, username } => { | 167 | Request::RenameUser { user_id, username } => { |
| 197 | - let me = authenticated(state, &conn).await?; | 168 | + let me = authenticated(client, &conn).await?; |
| 198 | let target = managed(&me, &user_id, &conn).await?; | 169 | let target = managed(&me, &user_id, &conn).await?; |
| 199 | let user = user::update(&user_id, &username, &conn).await?; | 170 | let user = user::update(&user_id, &username, &conn).await?; |
| 200 | admin_log::record( | 171 | admin_log::record( |
| @@ -207,11 +178,11 @@ async fn dispatch( | |||
| 207 | &conn, | 178 | &conn, |
| 208 | ) | 179 | ) |
| 209 | .await?; | 180 | .await?; |
| 210 | - let broadcasts = user_updated(&user, &conn).await?; | 181 | + let broadcasts = user_updated(&user); |
| 211 | (Response::User(user), broadcasts) | 182 | (Response::User(user), broadcasts) |
| 212 | } | 183 | } |
| 213 | Request::CreateUser { username, password } => { | 184 | Request::CreateUser { username, password } => { |
| 214 | - let me = builder(state, &conn).await?; | 185 | + let me = builder(client, &conn).await?; |
| 215 | let user = authentication::create_account(&username, &password, &conn).await?; | 186 | let user = authentication::create_account(&username, &password, &conn).await?; |
| 216 | admin_log::record( | 187 | admin_log::record( |
| 217 | Some(&me.id), | 188 | Some(&me.id), |
| @@ -224,7 +195,7 @@ async fn dispatch( | |||
| 224 | (Response::User(user), Vec::new()) | 195 | (Response::User(user), Vec::new()) |
| 225 | } | 196 | } |
| 226 | Request::Users => { | 197 | Request::Users => { |
| 227 | - builder(state, &conn).await?; | 198 | + builder(client, &conn).await?; |
| 228 | (Response::Users(user::all(&conn).await?), Vec::new()) | 199 | (Response::Users(user::all(&conn).await?), Vec::new()) |
| 229 | } | 200 | } |
| 230 | Request::AdminLogs { | 201 | Request::AdminLogs { |
| @@ -234,7 +205,7 @@ async fn dispatch( | |||
| 234 | after_ms, | 205 | after_ms, |
| 235 | before_ms, | 206 | before_ms, |
| 236 | } => { | 207 | } => { |
| 237 | - builder(state, &conn).await?; | 208 | + builder(client, &conn).await?; |
| 238 | ( | 209 | ( |
| 239 | Response::AdminLogs( | 210 | Response::AdminLogs( |
| 240 | admin_log::list( | 211 | admin_log::list( |
| @@ -251,21 +222,21 @@ async fn dispatch( | |||
| 251 | ) | 222 | ) |
| 252 | } | 223 | } |
| 253 | Request::DailyStats { days } => { | 224 | Request::DailyStats { days } => { |
| 254 | - builder(state, &conn).await?; | 225 | + builder(client, &conn).await?; |
| 255 | ( | 226 | ( |
| 256 | Response::DailyStats(stats::daily(days, &conn).await?), | 227 | Response::DailyStats(stats::daily(days, &conn).await?), |
| 257 | Vec::new(), | 228 | Vec::new(), |
| 258 | ) | 229 | ) |
| 259 | } | 230 | } |
| 260 | Request::Overview => { | 231 | Request::Overview => { |
| 261 | - builder(state, &conn).await?; | 232 | + builder(client, &conn).await?; |
| 262 | ( | 233 | ( |
| 263 | - Response::Overview(overview::read(presence, voice, &conn).await?), | 234 | + Response::Overview(overview::read(hub, rooms, &conn).await?), |
| 264 | Vec::new(), | 235 | Vec::new(), |
| 265 | ) | 236 | ) |
| 266 | } | 237 | } |
| 267 | Request::SuspendUser { user_id, suspended } => { | 238 | Request::SuspendUser { user_id, suspended } => { |
| 268 | - let me = authenticated(state, &conn).await?; | 239 | + let me = authenticated(client, &conn).await?; |
| 269 | managed(&me, &user_id, &conn).await?; | 240 | managed(&me, &user_id, &conn).await?; |
| 270 | user::set_suspended(&user_id, suspended, &conn).await?; | 241 | user::set_suspended(&user_id, suspended, &conn).await?; |
| 271 | let action = if suspended { | 242 | let action = if suspended { |
| @@ -275,16 +246,14 @@ async fn dispatch( | |||
| 275 | }; | 246 | }; |
| 276 | admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; | 247 | admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; |
| 277 | if suspended { | 248 | if suspended { |
| 278 | - authentication::revoke_sessions(&user_id, &conn).await?; | 249 | + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; |
| 279 | - presence.disconnect(&user_id, Close::Revoked); | ||
| 280 | } | 250 | } |
| 281 | (Response::Done, Vec::new()) | 251 | (Response::Done, Vec::new()) |
| 282 | } | 252 | } |
| 283 | Request::RevokeSessions { user_id } => { | 253 | Request::RevokeSessions { user_id } => { |
| 284 | - let me = authenticated(state, &conn).await?; | 254 | + let me = authenticated(client, &conn).await?; |
| 285 | managed(&me, &user_id, &conn).await?; | 255 | managed(&me, &user_id, &conn).await?; |
| 286 | - authentication::revoke_sessions(&user_id, &conn).await?; | 256 | + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; |
| 287 | - presence.disconnect(&user_id, Close::Revoked); | ||
| 288 | admin_log::record( | 257 | admin_log::record( |
| 289 | Some(&me.id), | 258 | Some(&me.id), |
| 290 | Some(&user_id), | 259 | Some(&user_id), |
| @@ -296,10 +265,10 @@ async fn dispatch( | |||
| 296 | (Response::Done, Vec::new()) | 265 | (Response::Done, Vec::new()) |
| 297 | } | 266 | } |
| 298 | Request::ResetPassword { user_id, password } => { | 267 | Request::ResetPassword { user_id, password } => { |
| 299 | - let me = authenticated(state, &conn).await?; | 268 | + let me = authenticated(client, &conn).await?; |
| 300 | managed(&me, &user_id, &conn).await?; | 269 | managed(&me, &user_id, &conn).await?; |
| 301 | authentication::reset_password(&user_id, &password, &conn).await?; | 270 | authentication::reset_password(&user_id, &password, &conn).await?; |
| 302 | - presence.disconnect(&user_id, Close::Revoked); | 271 | + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; |
| 303 | admin_log::record( | 272 | admin_log::record( |
| 304 | Some(&me.id), | 273 | Some(&me.id), |
| 305 | Some(&user_id), | 274 | Some(&user_id), |
| @@ -311,7 +280,7 @@ async fn dispatch( | |||
| 311 | (Response::Done, Vec::new()) | 280 | (Response::Done, Vec::new()) |
| 312 | } | 281 | } |
| 313 | Request::ClearProfile { user_id } => { | 282 | Request::ClearProfile { user_id } => { |
| 314 | - let me = authenticated(state, &conn).await?; | 283 | + let me = authenticated(client, &conn).await?; |
| 315 | managed(&me, &user_id, &conn).await?; | 284 | managed(&me, &user_id, &conn).await?; |
| 316 | user::set_avatar(&user_id, None, &mut conn).await?; | 285 | user::set_avatar(&user_id, None, &mut conn).await?; |
| 317 | let user = user::update_status(&user_id, "", &conn).await?; | 286 | let user = user::update_status(&user_id, "", &conn).await?; |
| @@ -323,11 +292,11 @@ async fn dispatch( | |||
| 323 | &conn, | 292 | &conn, |
| 324 | ) | 293 | ) |
| 325 | .await?; | 294 | .await?; |
| 326 | - let broadcasts = user_updated(&user, &conn).await?; | 295 | + let broadcasts = user_updated(&user); |
| 327 | (Response::User(user), broadcasts) | 296 | (Response::User(user), broadcasts) |
| 328 | } | 297 | } |
| 329 | Request::SetRole { user_id, role } => { | 298 | Request::SetRole { user_id, role } => { |
| 330 | - let me = authenticated(state, &conn).await?; | 299 | + let me = authenticated(client, &conn).await?; |
| 331 | ensure(permission::can_set_role(me.role, me.id == user_id))?; | 300 | ensure(permission::can_set_role(me.role, me.id == user_id))?; |
| 332 | let user = user::set_role_by_id(&user_id, role, &conn).await?; | 301 | let user = user::set_role_by_id(&user_id, role, &conn).await?; |
| 333 | admin_log::record( | 302 | admin_log::record( |
| @@ -338,33 +307,32 @@ async fn dispatch( | |||
| 338 | &conn, | 307 | &conn, |
| 339 | ) | 308 | ) |
| 340 | .await?; | 309 | .await?; |
| 341 | - let mut broadcasts = user_updated(&user, &conn).await?; | 310 | + let mut broadcasts = user_updated(&user); |
| 342 | if permission::is_builder(role) { | 311 | if permission::is_builder(role) { |
| 343 | - broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); | 312 | + broadcasts.extend(voice_unmuted(rooms, &user_id, &conn).await?); |
| 344 | } else { | 313 | } else { |
| 345 | user::set_ghost(&user_id, false, &conn).await?; | 314 | user::set_ghost(&user_id, false, &conn).await?; |
| 346 | - presence.disconnect(&user_id, Close::Revoked); | 315 | + hub.kick_user(&user_id, Close::Revoked); |
| 347 | } | 316 | } |
| 348 | (Response::User(user), broadcasts) | 317 | (Response::User(user), broadcasts) |
| 349 | } | 318 | } |
| 350 | Request::UpdateStatus { status } => { | 319 | Request::UpdateStatus { status } => { |
| 351 | - let me = authenticated(state, &conn).await?; | 320 | + let me = authenticated(client, &conn).await?; |
| 352 | let user = user::update_status(&me.id, &status, &conn).await?; | 321 | let user = user::update_status(&me.id, &status, &conn).await?; |
| 353 | - cache_user(state, user.clone()); | 322 | + let broadcasts = user_updated(&user); |
| 354 | - let broadcasts = user_updated(&user, &conn).await?; | ||
| 355 | (Response::User(user), broadcasts) | 323 | (Response::User(user), broadcasts) |
| 356 | } | 324 | } |
| 357 | Request::UpdatePresence { presence: chosen } => { | 325 | Request::UpdatePresence { presence: chosen } => { |
| 358 | - let me = authenticated(state, &conn).await?; | 326 | + let me = authenticated(client, &conn).await?; |
| 359 | user::update_presence(&me.id, chosen, &conn).await?; | 327 | user::update_presence(&me.id, chosen, &conn).await?; |
| 360 | - let broadcasts = presence_changed(presence, &me.id, &conn).await?; | 328 | + let broadcasts = presence_changed(hub, &me.id, &conn).await?; |
| 361 | (Response::Done, broadcasts) | 329 | (Response::Done, broadcasts) |
| 362 | } | 330 | } |
| 363 | Request::ReadPresences => { | 331 | Request::ReadPresences => { |
| 364 | - let me = authenticated(state, &conn).await?; | 332 | + let me = authenticated(client, &conn).await?; |
| 365 | let mut presences = Vec::new(); | 333 | let mut presences = Vec::new(); |
| 366 | for user_id in related_user_ids(&me.id, &conn).await? { | 334 | for user_id in related_user_ids(&me.id, &conn).await? { |
| 367 | - let effective = effective_presence(presence, &user_id, &conn).await?; | 335 | + let effective = effective_presence(hub, &user_id, &conn).await?; |
| 368 | if effective != Presence::Offline || user_id == me.id { | 336 | if effective != Presence::Offline || user_id == me.id { |
| 369 | presences.push((user_id, effective)); | 337 | presences.push((user_id, effective)); |
| 370 | } | 338 | } |
| @@ -372,29 +340,27 @@ async fn dispatch( | |||
| 372 | (Response::Presences(presences), Vec::new()) | 340 | (Response::Presences(presences), Vec::new()) |
| 373 | } | 341 | } |
| 374 | Request::UpdateAvatar { image } => { | 342 | Request::UpdateAvatar { image } => { |
| 375 | - let me = authenticated(state, &conn).await?; | 343 | + let me = authenticated(client, &conn).await?; |
| 376 | validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?; | 344 | validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?; |
| 377 | let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?; | 345 | let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?; |
| 378 | - cache_user(state, user.clone()); | 346 | + let broadcasts = user_updated(&user); |
| 379 | - let broadcasts = user_updated(&user, &conn).await?; | ||
| 380 | (Response::User(user), broadcasts) | 347 | (Response::User(user), broadcasts) |
| 381 | } | 348 | } |
| 382 | Request::RemoveAvatar => { | 349 | Request::RemoveAvatar => { |
| 383 | - let me = authenticated(state, &conn).await?; | 350 | + let me = authenticated(client, &conn).await?; |
| 384 | let user = user::set_avatar(&me.id, None, &mut conn).await?; | 351 | let user = user::set_avatar(&me.id, None, &mut conn).await?; |
| 385 | - cache_user(state, user.clone()); | 352 | + let broadcasts = user_updated(&user); |
| 386 | - let broadcasts = user_updated(&user, &conn).await?; | ||
| 387 | (Response::User(user), broadcasts) | 353 | (Response::User(user), broadcasts) |
| 388 | } | 354 | } |
| 389 | Request::ReadAvatar { avatar_id } => { | 355 | Request::ReadAvatar { avatar_id } => { |
| 390 | - authenticated(state, &conn).await?; | 356 | + authenticated(client, &conn).await?; |
| 391 | ( | 357 | ( |
| 392 | Response::Avatar(user::avatar(&avatar_id, &conn).await?), | 358 | Response::Avatar(user::avatar(&avatar_id, &conn).await?), |
| 393 | Vec::new(), | 359 | Vec::new(), |
| 394 | ) | 360 | ) |
| 395 | } | 361 | } |
| 396 | Request::DeleteUser { user_id } => { | 362 | Request::DeleteUser { user_id } => { |
| 397 | - let me = authenticated(state, &conn).await?; | 363 | + let me = authenticated(client, &conn).await?; |
| 398 | let target = user::read(&user_id, &conn).await?; | 364 | let target = user::read(&user_id, &conn).await?; |
| 399 | ensure(permission::can_delete_user( | 365 | ensure(permission::can_delete_user( |
| 400 | me.role, | 366 | me.role, |
| @@ -414,34 +380,32 @@ async fn dispatch( | |||
| 414 | .await?; | 380 | .await?; |
| 415 | } | 381 | } |
| 416 | for community_id in user_community::owned(&user_id, &tx).await? { | 382 | for community_id in user_community::owned(&user_id, &tx).await? { |
| 417 | - let members = user_community::members(&community_id, &tx).await?; | 383 | + let member_ids = user_community::member_ids(&community_id, &tx).await?; |
| 418 | - broadcasts.extend(voice_closed(voice, share, &community_id, &tx).await?); | 384 | + broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?); |
| 419 | community::delete(&community_id, &user_id, &tx).await?; | 385 | community::delete(&community_id, &user_id, &tx).await?; |
| 420 | let event = Event::CommunityDeleted { community_id }; | 386 | let event = Event::CommunityDeleted { community_id }; |
| 421 | - broadcasts.push(broadcast(event, &members)); | 387 | + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); |
| 422 | } | 388 | } |
| 423 | for community in community::communities_of(&user_id, &tx).await? { | 389 | for community in community::communities_of(&user_id, &tx).await? { |
| 424 | - let members = user_community::members(&community.id, &tx).await?; | 390 | + let member_ids = user_community::member_ids(&community.id, &tx).await?; |
| 425 | if community.kind.is_direct() { | 391 | if community.kind.is_direct() { |
| 426 | community::delete(&community.id, &user_id, &tx).await?; | 392 | community::delete(&community.id, &user_id, &tx).await?; |
| 427 | } | 393 | } |
| 428 | let event = Event::UserDeleted { | 394 | let event = Event::UserDeleted { |
| 429 | user_id: user_id.clone(), | 395 | user_id: user_id.clone(), |
| 430 | }; | 396 | }; |
| 431 | - broadcasts.push(broadcast(event, &members)); | 397 | + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); |
| 432 | } | 398 | } |
| 433 | - broadcasts.extend(leave_user_voice(voice, share, &user_id, &tx).await?); | 399 | + broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?); |
| 434 | let deleted = user::delete(&user_id, &tx).await?; | 400 | let deleted = user::delete(&user_id, &tx).await?; |
| 435 | tx.commit().await?; | 401 | tx.commit().await?; |
| 436 | - if me.id == user_id { | 402 | + if me.id != user_id { |
| 437 | - set_state(state, State::Anonymous); | 403 | + hub.kick_user(&user_id, Close::Revoked); |
| 438 | - } else { | ||
| 439 | - presence.disconnect(&user_id, Close::Revoked); | ||
| 440 | } | 404 | } |
| 441 | (Response::User(deleted), broadcasts) | 405 | (Response::User(deleted), broadcasts) |
| 442 | } | 406 | } |
| 443 | Request::CreateCommunity { name } => { | 407 | Request::CreateCommunity { name } => { |
| 444 | - let me = authenticated(state, &conn).await?; | 408 | + let me = authenticated(client, &conn).await?; |
| 445 | let limit = server_settings::read(&conn).await?.max_communities_per_user; | 409 | let limit = server_settings::read(&conn).await?.max_communities_per_user; |
| 446 | let owned = user_community::owned_groups(&me.id, &conn).await?; | 410 | let owned = user_community::owned_groups(&me.id, &conn).await?; |
| 447 | ensure_with( | 411 | ensure_with( |
| @@ -456,7 +420,7 @@ async fn dispatch( | |||
| 456 | (Response::Community(community), Vec::new()) | 420 | (Response::Community(community), Vec::new()) |
| 457 | } | 421 | } |
| 458 | Request::ReadCommunity { community_id } => { | 422 | Request::ReadCommunity { community_id } => { |
| 459 | - let me = authenticated(state, &conn).await?; | 423 | + let me = authenticated(client, &conn).await?; |
| 460 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 424 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 461 | ( | 425 | ( |
| 462 | Response::Community(community::read(&community_id, &me.id, &conn).await?), | 426 | Response::Community(community::read(&community_id, &me.id, &conn).await?), |
| @@ -464,7 +428,7 @@ async fn dispatch( | |||
| 464 | ) | 428 | ) |
| 465 | } | 429 | } |
| 466 | Request::UpdateCommunity { community_id, name } => { | 430 | Request::UpdateCommunity { community_id, name } => { |
| 467 | - let me = authenticated(state, &conn).await?; | 431 | + let me = authenticated(client, &conn).await?; |
| 468 | ensure_editable(&community_id, &conn).await?; | 432 | ensure_editable(&community_id, &conn).await?; |
| 469 | allowed(&me, &community_id, &conn, permission::can_rename_community).await?; | 433 | allowed(&me, &community_id, &conn, permission::can_rename_community).await?; |
| 470 | let updated = community::update(&community_id, &name, &me.id, &conn).await?; | 434 | let updated = community::update(&community_id, &name, &me.id, &conn).await?; |
| @@ -472,18 +436,17 @@ async fn dispatch( | |||
| 472 | name: updated.name.clone(), | 436 | name: updated.name.clone(), |
| 473 | }; | 437 | }; |
| 474 | log::record(&community_id, Some(&me.id), None, &action, &conn).await?; | 438 | log::record(&community_id, Some(&me.id), None, &action, &conn).await?; |
| 475 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 476 | let event = Event::CommunityUpdated(updated.clone()); | 439 | let event = Event::CommunityUpdated(updated.clone()); |
| 477 | ( | 440 | ( |
| 478 | Response::Community(updated), | 441 | Response::Community(updated), |
| 479 | - vec![broadcast(event, &members)], | 442 | + vec![Broadcast::new(To::Community(community_id), event)], |
| 480 | ) | 443 | ) |
| 481 | } | 444 | } |
| 482 | Request::UpdateCommunityAvatar { | 445 | Request::UpdateCommunityAvatar { |
| 483 | community_id, | 446 | community_id, |
| 484 | image, | 447 | image, |
| 485 | } => { | 448 | } => { |
| 486 | - let me = authenticated(state, &conn).await?; | 449 | + let me = authenticated(client, &conn).await?; |
| 487 | ensure_editable(&community_id, &conn).await?; | 450 | ensure_editable(&community_id, &conn).await?; |
| 488 | allowed(&me, &community_id, &conn, permission::can_rename_community).await?; | 451 | allowed(&me, &community_id, &conn, permission::can_rename_community).await?; |
| 489 | if let Some(bytes) = &image { | 452 | if let Some(bytes) = &image { |
| @@ -497,19 +460,18 @@ async fn dispatch( | |||
| 497 | LogAction::AvatarRemoved | 460 | LogAction::AvatarRemoved |
| 498 | }; | 461 | }; |
| 499 | log::record(&community_id, Some(&me.id), None, &action, &conn).await?; | 462 | log::record(&community_id, Some(&me.id), None, &action, &conn).await?; |
| 500 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 501 | let event = Event::CommunityUpdated(updated.clone()); | 463 | let event = Event::CommunityUpdated(updated.clone()); |
| 502 | ( | 464 | ( |
| 503 | Response::Community(updated), | 465 | Response::Community(updated), |
| 504 | - vec![broadcast(event, &members)], | 466 | + vec![Broadcast::new(To::Community(community_id), event)], |
| 505 | ) | 467 | ) |
| 506 | } | 468 | } |
| 507 | Request::DeleteCommunity { community_id } => { | 469 | Request::DeleteCommunity { community_id } => { |
| 508 | - let me = authenticated(state, &conn).await?; | 470 | + let me = authenticated(client, &conn).await?; |
| 509 | ensure_editable(&community_id, &conn).await?; | 471 | ensure_editable(&community_id, &conn).await?; |
| 510 | allowed(&me, &community_id, &conn, permission::can_delete_community).await?; | 472 | allowed(&me, &community_id, &conn, permission::can_delete_community).await?; |
| 511 | let tx = conn.transaction().await?; | 473 | let tx = conn.transaction().await?; |
| 512 | - let members = user_community::members(&community_id, &tx).await?; | 474 | + let member_ids = user_community::member_ids(&community_id, &tx).await?; |
| 513 | let owned = | 475 | let owned = |
| 514 | user_community::rank(&me.id, &community_id, &tx).await? == Some(Rank::Owner); | 476 | user_community::rank(&me.id, &community_id, &tx).await? == Some(Rank::Owner); |
| 515 | let deleted = community::delete(&community_id, &me.id, &tx).await?; | 477 | let deleted = community::delete(&community_id, &me.id, &tx).await?; |
| @@ -524,43 +486,44 @@ async fn dispatch( | |||
| 524 | .await?; | 486 | .await?; |
| 525 | } | 487 | } |
| 526 | tx.commit().await?; | 488 | tx.commit().await?; |
| 527 | - let mut broadcasts = voice_closed(voice, share, &community_id, &conn).await?; | 489 | + let mut broadcasts = voice_closed(rooms, &community_id, &conn).await?; |
| 528 | let event = Event::CommunityDeleted { | 490 | let event = Event::CommunityDeleted { |
| 529 | community_id: deleted.id.clone(), | 491 | community_id: deleted.id.clone(), |
| 530 | }; | 492 | }; |
| 531 | - broadcasts.push(broadcast(event, &members)); | 493 | + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); |
| 532 | (Response::Community(deleted), broadcasts) | 494 | (Response::Community(deleted), broadcasts) |
| 533 | } | 495 | } |
| 534 | Request::LeaveCommunity { community_id } => { | 496 | Request::LeaveCommunity { community_id } => { |
| 535 | - let me = authenticated(state, &conn).await?; | 497 | + let me = authenticated(client, &conn).await?; |
| 536 | ensure_editable(&community_id, &conn).await?; | 498 | ensure_editable(&community_id, &conn).await?; |
| 537 | allowed(&me, &community_id, &conn, permission::can_leave).await?; | 499 | allowed(&me, &community_id, &conn, permission::can_leave).await?; |
| 538 | let tx = conn.transaction().await?; | 500 | let tx = conn.transaction().await?; |
| 539 | user_community::leave(&me.id, &community_id, &tx).await?; | 501 | user_community::leave(&me.id, &community_id, &tx).await?; |
| 540 | log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?; | 502 | log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?; |
| 541 | - let members = user_community::members(&community_id, &tx).await?; | 503 | + if user_community::member_ids(&community_id, &tx) |
| 542 | - if members.is_empty() { | 504 | + .await? |
| 505 | + .is_empty() | ||
| 506 | + { | ||
| 543 | community::delete(&community_id, &me.id, &tx).await?; | 507 | community::delete(&community_id, &me.id, &tx).await?; |
| 544 | } | 508 | } |
| 545 | tx.commit().await?; | 509 | tx.commit().await?; |
| 546 | - let mut broadcasts = | 510 | + let mut broadcasts = leave_room_voice(rooms, &community_id, &me.id, &conn).await?; |
| 547 | - leave_room_voice(voice, share, &community_id, &me.id, &conn).await?; | ||
| 548 | let event = Event::MemberLeft { | 511 | let event = Event::MemberLeft { |
| 549 | - community_id, | 512 | + community_id: community_id.clone(), |
| 550 | user_id: me.id, | 513 | user_id: me.id, |
| 551 | }; | 514 | }; |
| 552 | - broadcasts.push(broadcast(event, &members)); | 515 | + broadcasts.push(Broadcast::new(To::Community(community_id), event)); |
| 553 | (Response::Done, broadcasts) | 516 | (Response::Done, broadcasts) |
| 554 | } | 517 | } |
| 555 | Request::Communities => { | 518 | Request::Communities => { |
| 556 | - let me = authenticated(state, &conn).await?; | 519 | + let me = authenticated(client, &conn).await?; |
| 557 | ( | 520 | ( |
| 558 | Response::Communities(community::communities_of(&me.id, &conn).await?), | 521 | Response::Communities(community::communities_of(&me.id, &conn).await?), |
| 559 | Vec::new(), | 522 | Vec::new(), |
| 560 | ) | 523 | ) |
| 561 | } | 524 | } |
| 562 | Request::Members { community_id } => { | 525 | Request::Members { community_id } => { |
| 563 | - let me = authenticated(state, &conn).await?; | 526 | + let me = authenticated(client, &conn).await?; |
| 564 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 527 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 565 | ( | 528 | ( |
| 566 | Response::Members(user_community::members(&community_id, &conn).await?), | 529 | Response::Members(user_community::members(&community_id, &conn).await?), |
| @@ -572,7 +535,7 @@ async fn dispatch( | |||
| 572 | user_id, | 535 | user_id, |
| 573 | reason, | 536 | reason, |
| 574 | } => { | 537 | } => { |
| 575 | - let me = authenticated(state, &conn).await?; | 538 | + let me = authenticated(client, &conn).await?; |
| 576 | remove_member( | 539 | remove_member( |
| 577 | &me, | 540 | &me, |
| 578 | Removal { | 541 | Removal { |
| @@ -581,8 +544,7 @@ async fn dispatch( | |||
| 581 | reason, | 544 | reason, |
| 582 | sanction: Sanction::Kick, | 545 | sanction: Sanction::Kick, |
| 583 | }, | 546 | }, |
| 584 | - voice, | 547 | + rooms, |
| 585 | - share, | ||
| 586 | &mut conn, | 548 | &mut conn, |
| 587 | ) | 549 | ) |
| 588 | .await? | 550 | .await? |
| @@ -592,7 +554,7 @@ async fn dispatch( | |||
| 592 | user_id, | 554 | user_id, |
| 593 | reason, | 555 | reason, |
| 594 | } => { | 556 | } => { |
| 595 | - let me = authenticated(state, &conn).await?; | 557 | + let me = authenticated(client, &conn).await?; |
| 596 | remove_member( | 558 | remove_member( |
| 597 | &me, | 559 | &me, |
| 598 | Removal { | 560 | Removal { |
| @@ -601,8 +563,7 @@ async fn dispatch( | |||
| 601 | reason, | 563 | reason, |
| 602 | sanction: Sanction::Ban, | 564 | sanction: Sanction::Ban, |
| 603 | }, | 565 | }, |
| 604 | - voice, | 566 | + rooms, |
| 605 | - share, | ||
| 606 | &mut conn, | 567 | &mut conn, |
| 607 | ) | 568 | ) |
| 608 | .await? | 569 | .await? |
| @@ -611,7 +572,7 @@ async fn dispatch( | |||
| 611 | community_id, | 572 | community_id, |
| 612 | user_id, | 573 | user_id, |
| 613 | } => { | 574 | } => { |
| 614 | - let me = authenticated(state, &conn).await?; | 575 | + let me = authenticated(client, &conn).await?; |
| 615 | allowed(&me, &community_id, &conn, permission::can_unban).await?; | 576 | allowed(&me, &community_id, &conn, permission::can_unban).await?; |
| 616 | user_community::unban(&user_id, &community_id, &conn).await?; | 577 | user_community::unban(&user_id, &community_id, &conn).await?; |
| 617 | log::record( | 578 | log::record( |
| @@ -625,7 +586,7 @@ async fn dispatch( | |||
| 625 | (Response::Done, Vec::new()) | 586 | (Response::Done, Vec::new()) |
| 626 | } | 587 | } |
| 627 | Request::Bans { community_id } => { | 588 | Request::Bans { community_id } => { |
| 628 | - let me = authenticated(state, &conn).await?; | 589 | + let me = authenticated(client, &conn).await?; |
| 629 | allowed(&me, &community_id, &conn, permission::can_unban).await?; | 590 | allowed(&me, &community_id, &conn, permission::can_unban).await?; |
| 630 | ( | 591 | ( |
| 631 | Response::Bans(user_community::bans(&community_id, &conn).await?), | 592 | Response::Bans(user_community::bans(&community_id, &conn).await?), |
| @@ -637,7 +598,7 @@ async fn dispatch( | |||
| 637 | user_id, | 598 | user_id, |
| 638 | rank, | 599 | rank, |
| 639 | } => { | 600 | } => { |
| 640 | - let me = authenticated(state, &conn).await?; | 601 | + let me = authenticated(client, &conn).await?; |
| 641 | ensure_editable(&community_id, &conn).await?; | 602 | ensure_editable(&community_id, &conn).await?; |
| 642 | let target = user::read(&user_id, &conn).await?; | 603 | let target = user::read(&user_id, &conn).await?; |
| 643 | ensure(permission::can_set_rank( | 604 | ensure(permission::can_set_rank( |
| @@ -654,13 +615,15 @@ async fn dispatch( | |||
| 654 | &conn, | 615 | &conn, |
| 655 | ) | 616 | ) |
| 656 | .await?; | 617 | .await?; |
| 657 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 658 | let event = Event::RankChanged { | 618 | let event = Event::RankChanged { |
| 659 | - community_id, | 619 | + community_id: community_id.clone(), |
| 660 | user_id, | 620 | user_id, |
| 661 | rank, | 621 | rank, |
| 662 | }; | 622 | }; |
| 663 | - (Response::Done, vec![broadcast(event, &members)]) | 623 | + ( |
| 624 | + Response::Done, | ||
| 625 | + vec![Broadcast::new(To::Community(community_id), event)], | ||
| 626 | + ) | ||
| 664 | } | 627 | } |
| 665 | Request::CreateMessage { | 628 | Request::CreateMessage { |
| 666 | community_id, | 629 | community_id, |
| @@ -668,7 +631,7 @@ async fn dispatch( | |||
| 668 | attachments, | 631 | attachments, |
| 669 | reply_to, | 632 | reply_to, |
| 670 | } => { | 633 | } => { |
| 671 | - let me = authenticated(state, &conn).await?; | 634 | + let me = authenticated(client, &conn).await?; |
| 672 | let settings = server_settings::read(&conn).await?; | 635 | let settings = server_settings::read(&conn).await?; |
| 673 | limit_messages(&me, rate_limit, &settings)?; | 636 | limit_messages(&me, rate_limit, &settings)?; |
| 674 | validate_new_message( | 637 | validate_new_message( |
| @@ -689,8 +652,7 @@ async fn dispatch( | |||
| 689 | .await?; | 652 | .await?; |
| 690 | stats::mark_active(&me.id, &tx).await?; | 653 | stats::mark_active(&me.id, &tx).await?; |
| 691 | tx.commit().await?; | 654 | tx.commit().await?; |
| 692 | - let broadcast = | 655 | + let broadcast = message_event(&created, Event::MessageCreated); |
| 693 | - message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; | ||
| 694 | (Response::Message(created), vec![broadcast]) | 656 | (Response::Message(created), vec![broadcast]) |
| 695 | } | 657 | } |
| 696 | Request::ForwardMessages { | 658 | Request::ForwardMessages { |
| @@ -698,7 +660,7 @@ async fn dispatch( | |||
| 698 | community_id, | 660 | community_id, |
| 699 | snippet, | 661 | snippet, |
| 700 | } => { | 662 | } => { |
| 701 | - let me = authenticated(state, &conn).await?; | 663 | + let me = authenticated(client, &conn).await?; |
| 702 | limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?; | 664 | limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?; |
| 703 | validate_forward(message_ids.len())?; | 665 | validate_forward(message_ids.len())?; |
| 704 | ensure(permission::can_post( | 666 | ensure(permission::can_post( |
| @@ -721,16 +683,14 @@ async fn dispatch( | |||
| 721 | let created = | 683 | let created = |
| 722 | message::forward(&me, &community_id, &sources, mode, directory, &tx).await?; | 684 | message::forward(&me, &community_id, &sources, mode, directory, &tx).await?; |
| 723 | tx.commit().await?; | 685 | tx.commit().await?; |
| 724 | - let members = user_community::members(&community_id, &conn).await?; | 686 | + let broadcasts = created |
| 725 | - let mut broadcasts = Vec::new(); | 687 | + .iter() |
| 726 | - for message in &created { | 688 | + .map(|message| message_event(message, Event::MessageCreated)) |
| 727 | - let event = Event::MessageCreated(message.clone()); | 689 | + .collect(); |
| 728 | - broadcasts.push(broadcast_with(event, &members, &me.id)); | ||
| 729 | - } | ||
| 730 | (Response::Messages(created), broadcasts) | 690 | (Response::Messages(created), broadcasts) |
| 731 | } | 691 | } |
| 732 | Request::UpdateMessage { message_id, body } => { | 692 | Request::UpdateMessage { message_id, body } => { |
| 733 | - let me = authenticated(state, &conn).await?; | 693 | + let me = authenticated(client, &conn).await?; |
| 734 | let existing = message::read(&message_id, &conn).await?; | 694 | let existing = message::read(&message_id, &conn).await?; |
| 735 | allowed(&me, &existing.community_id, &conn, permission::can_post).await?; | 695 | allowed(&me, &existing.community_id, &conn, permission::can_post).await?; |
| 736 | ensure(existing.user_id == me.id)?; | 696 | ensure(existing.user_id == me.id)?; |
| @@ -740,8 +700,7 @@ async fn dispatch( | |||
| 740 | server_settings::read(&conn).await?.max_message_length as usize, | 700 | server_settings::read(&conn).await?.max_message_length as usize, |
| 741 | )?; | 701 | )?; |
| 742 | let updated = message::update(&message_id, &body, &conn).await?; | 702 | let updated = message::update(&message_id, &body, &conn).await?; |
| 743 | - let broadcast = | 703 | + let broadcast = message_event(&updated, Event::MessageUpdated); |
| 744 | - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; | ||
| 745 | (Response::Message(updated), vec![broadcast]) | 704 | (Response::Message(updated), vec![broadcast]) |
| 746 | } | 705 | } |
| 747 | Request::CreatePoll { | 706 | Request::CreatePoll { |
| @@ -750,7 +709,7 @@ async fn dispatch( | |||
| 750 | options, | 709 | options, |
| 751 | multiple, | 710 | multiple, |
| 752 | } => { | 711 | } => { |
| 753 | - let me = authenticated(state, &conn).await?; | 712 | + let me = authenticated(client, &conn).await?; |
| 754 | let settings = server_settings::read(&conn).await?; | 713 | let settings = server_settings::read(&conn).await?; |
| 755 | limit_messages(&me, rate_limit, &settings)?; | 714 | limit_messages(&me, rate_limit, &settings)?; |
| 756 | validate_poll(&question, &options)?; | 715 | validate_poll(&question, &options)?; |
| @@ -761,15 +720,14 @@ async fn dispatch( | |||
| 761 | .await?; | 720 | .await?; |
| 762 | stats::mark_active(&me.id, &tx).await?; | 721 | stats::mark_active(&me.id, &tx).await?; |
| 763 | tx.commit().await?; | 722 | tx.commit().await?; |
| 764 | - let broadcast = | 723 | + let broadcast = message_event(&created, Event::MessageCreated); |
| 765 | - message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; | ||
| 766 | (Response::Message(created), vec![broadcast]) | 724 | (Response::Message(created), vec![broadcast]) |
| 767 | } | 725 | } |
| 768 | Request::Vote { | 726 | Request::Vote { |
| 769 | message_id, | 727 | message_id, |
| 770 | positions, | 728 | positions, |
| 771 | } => { | 729 | } => { |
| 772 | - let me = authenticated(state, &conn).await?; | 730 | + let me = authenticated(client, &conn).await?; |
| 773 | let existing = message::read(&message_id, &conn).await?; | 731 | let existing = message::read(&message_id, &conn).await?; |
| 774 | ensure(permission::can_read( | 732 | ensure(permission::can_read( |
| 775 | actor_rank(&me, &existing.community_id, &conn).await?, | 733 | actor_rank(&me, &existing.community_id, &conn).await?, |
| @@ -777,36 +735,33 @@ async fn dispatch( | |||
| 777 | let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?; | 735 | let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?; |
| 778 | validate_vote(poll, &positions)?; | 736 | validate_vote(poll, &positions)?; |
| 779 | let updated = message::vote(&message_id, &me.id, &positions, &conn).await?; | 737 | let updated = message::vote(&message_id, &me.id, &positions, &conn).await?; |
| 780 | - let broadcast = | 738 | + let broadcast = message_event(&updated, Event::MessageUpdated); |
| 781 | - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; | ||
| 782 | (Response::Done, vec![broadcast]) | 739 | (Response::Done, vec![broadcast]) |
| 783 | } | 740 | } |
| 784 | Request::ClosePoll { message_id } => { | 741 | Request::ClosePoll { message_id } => { |
| 785 | - let me = authenticated(state, &conn).await?; | 742 | + let me = authenticated(client, &conn).await?; |
| 786 | let existing = message::read(&message_id, &conn).await?; | 743 | let existing = message::read(&message_id, &conn).await?; |
| 787 | ensure(permission::can_close_poll( | 744 | ensure(permission::can_close_poll( |
| 788 | actor_rank(&me, &existing.community_id, &conn).await?, | 745 | actor_rank(&me, &existing.community_id, &conn).await?, |
| 789 | existing.user_id == me.id, | 746 | existing.user_id == me.id, |
| 790 | ))?; | 747 | ))?; |
| 791 | let updated = message::close_poll(&message_id, &conn).await?; | 748 | let updated = message::close_poll(&message_id, &conn).await?; |
| 792 | - let broadcast = | 749 | + let broadcast = message_event(&updated, Event::MessageUpdated); |
| 793 | - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; | ||
| 794 | (Response::Done, vec![broadcast]) | 750 | (Response::Done, vec![broadcast]) |
| 795 | } | 751 | } |
| 796 | Request::React { message_id, emoji } => { | 752 | Request::React { message_id, emoji } => { |
| 797 | - let me = authenticated(state, &conn).await?; | 753 | + let me = authenticated(client, &conn).await?; |
| 798 | validate_reaction(&emoji)?; | 754 | validate_reaction(&emoji)?; |
| 799 | let existing = message::read(&message_id, &conn).await?; | 755 | let existing = message::read(&message_id, &conn).await?; |
| 800 | ensure(permission::can_read( | 756 | ensure(permission::can_read( |
| 801 | actor_rank(&me, &existing.community_id, &conn).await?, | 757 | actor_rank(&me, &existing.community_id, &conn).await?, |
| 802 | ))?; | 758 | ))?; |
| 803 | let updated = message::react(&message_id, &me.id, &emoji, &conn).await?; | 759 | let updated = message::react(&message_id, &me.id, &emoji, &conn).await?; |
| 804 | - let broadcast = | 760 | + let broadcast = message_event(&updated, Event::MessageUpdated); |
| 805 | - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; | ||
| 806 | (Response::Done, vec![broadcast]) | 761 | (Response::Done, vec![broadcast]) |
| 807 | } | 762 | } |
| 808 | Request::Pin { message_id, pinned } => { | 763 | Request::Pin { message_id, pinned } => { |
| 809 | - let me = authenticated(state, &conn).await?; | 764 | + let me = authenticated(client, &conn).await?; |
| 810 | let existing = message::read(&message_id, &conn).await?; | 765 | let existing = message::read(&message_id, &conn).await?; |
| 811 | let direct = community::is_direct(&existing.community_id, &conn).await?; | 766 | let direct = community::is_direct(&existing.community_id, &conn).await?; |
| 812 | ensure(permission::can_pin( | 767 | ensure(permission::can_pin( |
| @@ -814,12 +769,11 @@ async fn dispatch( | |||
| 814 | direct, | 769 | direct, |
| 815 | ))?; | 770 | ))?; |
| 816 | let updated = message::pin(&message_id, pinned, &conn).await?; | 771 | let updated = message::pin(&message_id, pinned, &conn).await?; |
| 817 | - let broadcast = | 772 | + let broadcast = message_event(&updated, Event::MessageUpdated); |
| 818 | - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; | ||
| 819 | (Response::Done, vec![broadcast]) | 773 | (Response::Done, vec![broadcast]) |
| 820 | } | 774 | } |
| 821 | Request::Unreads => { | 775 | Request::Unreads => { |
| 822 | - let me = authenticated(state, &conn).await?; | 776 | + let me = authenticated(client, &conn).await?; |
| 823 | ( | 777 | ( |
| 824 | Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), | 778 | Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), |
| 825 | Vec::new(), | 779 | Vec::new(), |
| @@ -829,14 +783,14 @@ async fn dispatch( | |||
| 829 | community_id, | 783 | community_id, |
| 830 | message_id, | 784 | message_id, |
| 831 | } => { | 785 | } => { |
| 832 | - let me = authenticated(state, &conn).await?; | 786 | + let me = authenticated(client, &conn).await?; |
| 833 | ensure(!is_outsider(&me.id, &community_id, &conn).await?)?; | 787 | ensure(!is_outsider(&me.id, &community_id, &conn).await?)?; |
| 834 | message::ensure_in_community(&message_id, &community_id, &conn).await?; | 788 | message::ensure_in_community(&message_id, &community_id, &conn).await?; |
| 835 | user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?; | 789 | user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?; |
| 836 | (Response::Done, Vec::new()) | 790 | (Response::Done, Vec::new()) |
| 837 | } | 791 | } |
| 838 | Request::Pins { community_id } => { | 792 | Request::Pins { community_id } => { |
| 839 | - let me = authenticated(state, &conn).await?; | 793 | + let me = authenticated(client, &conn).await?; |
| 840 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 794 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 841 | ( | 795 | ( |
| 842 | Response::Messages(message::pinned(&community_id, &conn).await?), | 796 | Response::Messages(message::pinned(&community_id, &conn).await?), |
| @@ -844,7 +798,7 @@ async fn dispatch( | |||
| 844 | ) | 798 | ) |
| 845 | } | 799 | } |
| 846 | Request::DeleteMessage { message_id } => { | 800 | Request::DeleteMessage { message_id } => { |
| 847 | - let me = authenticated(state, &conn).await?; | 801 | + let me = authenticated(client, &conn).await?; |
| 848 | let existing = message::read(&message_id, &conn).await?; | 802 | let existing = message::read(&message_id, &conn).await?; |
| 849 | let author = user::read(&existing.user_id, &conn).await?; | 803 | let author = user::read(&existing.user_id, &conn).await?; |
| 850 | ensure(permission::can_delete_message( | 804 | ensure(permission::can_delete_message( |
| @@ -874,33 +828,26 @@ async fn dispatch( | |||
| 874 | ) | 828 | ) |
| 875 | .await?; | 829 | .await?; |
| 876 | } | 830 | } |
| 877 | - let broadcast = | 831 | + let event = Event::MessagesDeleted { |
| 878 | - message_broadcast(&deleted, Event::MessageDeleted, &me.id, &conn).await?; | 832 | + community_id: deleted.community_id.clone(), |
| 833 | + ids: vec![deleted.id.clone()], | ||
| 834 | + }; | ||
| 835 | + let broadcast = Broadcast::new(To::Community(deleted.community_id.clone()), event); | ||
| 879 | (Response::Message(deleted), vec![broadcast]) | 836 | (Response::Message(deleted), vec![broadcast]) |
| 880 | } | 837 | } |
| 881 | - Request::ReadMessages { | 838 | + Request::WatchCommunity { community_id } => { |
| 882 | - community_id, | 839 | + let me = authenticated(client, &conn).await?; |
| 883 | - before, | 840 | + let Some(community_id) = community_id else { |
| 884 | - } => { | 841 | + client.watch(None); |
| 885 | - let me = authenticated(state, &conn).await?; | 842 | + return Ok((Response::Done, Vec::new())); |
| 843 | + }; | ||
| 886 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 844 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 887 | let outsider = is_outsider(&me.id, &community_id, &conn).await?; | 845 | let outsider = is_outsider(&me.id, &community_id, &conn).await?; |
| 888 | - if before.is_none() | 846 | + client.watch(outsider.then_some(community_id.as_str())); |
| 889 | - && let Some(connection) = connection | 847 | + let visit = permission::is_builder(me.role) |
| 890 | - { | ||
| 891 | - visits.watch( | ||
| 892 | - connection.stable_id(), | ||
| 893 | - outsider.then_some(community_id.as_str()), | ||
| 894 | - ); | ||
| 895 | - } | ||
| 896 | - let visit = before.is_none() | ||
| 897 | - && permission::is_builder(me.role) | ||
| 898 | && outsider | 848 | && outsider |
| 899 | && user::is_ghost(&me.id, &conn).await?; | 849 | && user::is_ghost(&me.id, &conn).await?; |
| 900 | - if visit | 850 | + if visit && client.first_visit(&community_id) { |
| 901 | - && connection | ||
| 902 | - .is_some_and(|connection| visits.first(connection.stable_id(), &community_id)) | ||
| 903 | - { | ||
| 904 | let community = community::label(&community_id, &conn).await?; | 851 | let community = community::label(&community_id, &conn).await?; |
| 905 | admin_log::record( | 852 | admin_log::record( |
| 906 | Some(&me.id), | 853 | Some(&me.id), |
| @@ -911,84 +858,85 @@ async fn dispatch( | |||
| 911 | ) | 858 | ) |
| 912 | .await?; | 859 | .await?; |
| 913 | } | 860 | } |
| 861 | + (Response::Done, Vec::new()) | ||
| 862 | + } | ||
| 863 | + Request::ReadMessages { | ||
| 864 | + community_id, | ||
| 865 | + before, | ||
| 866 | + } => { | ||
| 867 | + let me = authenticated(client, &conn).await?; | ||
| 868 | + allowed(&me, &community_id, &conn, permission::can_read).await?; | ||
| 914 | let messages = message::read_page(&community_id, before.as_deref(), &conn).await?; | 869 | let messages = message::read_page(&community_id, before.as_deref(), &conn).await?; |
| 915 | (Response::Messages(messages), Vec::new()) | 870 | (Response::Messages(messages), Vec::new()) |
| 916 | } | 871 | } |
| 917 | Request::JoinVoice { community_id } => { | 872 | Request::JoinVoice { community_id } => { |
| 918 | - let me = authenticated(state, &conn).await?; | 873 | + let me = authenticated(client, &conn).await?; |
| 919 | allowed(&me, &community_id, &conn, permission::can_join_voice).await?; | 874 | allowed(&me, &community_id, &conn, permission::can_join_voice).await?; |
| 920 | ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?; | 875 | ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?; |
| 921 | ensure( | 876 | ensure( |
| 922 | permission::is_builder(me.role) | 877 | permission::is_builder(me.role) |
| 923 | || community::voice_enabled(&community_id, &conn).await?, | 878 | || community::voice_enabled(&community_id, &conn).await?, |
| 924 | )?; | 879 | )?; |
| 925 | - let Some(connection) = connection else { | ||
| 926 | - return Err(CommonError::Server.into()); | ||
| 927 | - }; | ||
| 928 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 929 | let muted = user::voice_muted(&me.id, &conn).await?; | 880 | let muted = user::voice_muted(&me.id, &conn).await?; |
| 930 | let outsider = is_outsider(&me.id, &community_id, &conn).await?; | 881 | let outsider = is_outsider(&me.id, &community_id, &conn).await?; |
| 931 | let ghost = outsider || user::is_ghost(&me.id, &conn).await?; | 882 | let ghost = outsider || user::is_ghost(&me.id, &conn).await?; |
| 932 | let starts_call = !ghost | 883 | let starts_call = !ghost |
| 933 | && community::is_direct(&community_id, &conn).await? | 884 | && community::is_direct(&community_id, &conn).await? |
| 934 | - && voice.participants(&community_id).is_empty(); | 885 | + && rooms.participants(&community_id).is_empty(); |
| 935 | - let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost); | 886 | + let joined = rooms.join(client, &community_id, muted, ghost)?; |
| 936 | - let mut broadcasts = match joined { | 887 | + let mut broadcasts = match joined.departure { |
| 937 | - Some(previous) => voice_left(share, previous, &conn).await?, | 888 | + Some(departure) => departed(departure, &conn).await?, |
| 938 | None => Vec::new(), | 889 | None => Vec::new(), |
| 939 | }; | 890 | }; |
| 940 | if starts_call { | 891 | if starts_call { |
| 941 | let created = | 892 | let created = |
| 942 | message::create_call_log(&community_id, &me.id, CallLog::Started, &conn) | 893 | message::create_call_log(&community_id, &me.id, CallLog::Started, &conn) |
| 943 | .await?; | 894 | .await?; |
| 944 | - broadcasts.push(broadcast(Event::MessageCreated(created), &members)); | 895 | + broadcasts.push(message_event(&created, Event::MessageCreated)); |
| 945 | } | 896 | } |
| 946 | - if !ghost { | 897 | + if !ghost && !joined.transferred { |
| 947 | - broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); | 898 | + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); |
| 948 | } | 899 | } |
| 949 | ( | 900 | ( |
| 950 | - Response::Voice(voice.participants(&community_id)), | 901 | + Response::Voice(rooms.participants(&community_id)), |
| 951 | broadcasts, | 902 | broadcasts, |
| 952 | ) | 903 | ) |
| 953 | } | 904 | } |
| 954 | Request::Typing { community_id } => { | 905 | Request::Typing { community_id } => { |
| 955 | - let me = authenticated(state, &conn).await?; | 906 | + let me = authenticated(client, &conn).await?; |
| 956 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 907 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 957 | let broadcasts = if user::is_ghost(&me.id, &conn).await? { | 908 | let broadcasts = if user::is_ghost(&me.id, &conn).await? { |
| 958 | Vec::new() | 909 | Vec::new() |
| 959 | } else { | 910 | } else { |
| 960 | - let members: Vec<Member> = user_community::members(&community_id, &conn) | 911 | + let others: Vec<String> = user_community::member_ids(&community_id, &conn) |
| 961 | .await? | 912 | .await? |
| 962 | .into_iter() | 913 | .into_iter() |
| 963 | - .filter(|member| member.user.id != me.id) | 914 | + .filter(|user_id| *user_id != me.id) |
| 964 | .collect(); | 915 | .collect(); |
| 965 | let event = Event::Typing { | 916 | let event = Event::Typing { |
| 966 | community_id, | 917 | community_id, |
| 967 | user_id: me.id.clone(), | 918 | user_id: me.id.clone(), |
| 968 | }; | 919 | }; |
| 969 | - vec![broadcast(event, &members)] | 920 | + vec![Broadcast::new(To::Users(others), event)] |
| 970 | }; | 921 | }; |
| 971 | (Response::Done, broadcasts) | 922 | (Response::Done, broadcasts) |
| 972 | } | 923 | } |
| 973 | Request::LeaveVoice => { | 924 | Request::LeaveVoice => { |
| 974 | - authenticated(state, &conn).await?; | 925 | + authenticated(client, &conn).await?; |
| 975 | - ( | 926 | + let broadcasts = match rooms.leave(client.id) { |
| 976 | - Response::Done, | 927 | + Some(departure) => departed(departure, &conn).await?, |
| 977 | - leave_connection_voice(voice, share, connection, &conn).await?, | 928 | + None => Vec::new(), |
| 978 | - ) | 929 | + }; |
| 930 | + (Response::Done, broadcasts) | ||
| 979 | } | 931 | } |
| 980 | Request::StartShare { kind, source } => { | 932 | Request::StartShare { kind, source } => { |
| 981 | - let me = authenticated(state, &conn).await?; | 933 | + let me = authenticated(client, &conn).await?; |
| 982 | - let Some(community_id) = voice.room_of(&me.id) else { | 934 | + let Some(community_id) = rooms.room_of_conn(client.id) else { |
| 983 | return Err(CommonError::NotFound.into()); | 935 | return Err(CommonError::NotFound.into()); |
| 984 | }; | 936 | }; |
| 985 | allowed(&me, &community_id, &conn, permission::can_share).await?; | 937 | allowed(&me, &community_id, &conn, permission::can_share).await?; |
| 986 | ensure(!source.encode.is_empty())?; | 938 | ensure(!source.encode.is_empty())?; |
| 987 | ensure(!user::is_ghost(&me.id, &conn).await?)?; | 939 | ensure(!user::is_ghost(&me.id, &conn).await?)?; |
| 988 | - let Some(connection) = connection else { | ||
| 989 | - return Err(CommonError::Server.into()); | ||
| 990 | - }; | ||
| 991 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 992 | let event = Event::ShareStarted { | 940 | let event = Event::ShareStarted { |
| 993 | community_id: community_id.clone(), | 941 | community_id: community_id.clone(), |
| 994 | share: Share { | 942 | share: Share { |
| @@ -997,22 +945,27 @@ async fn dispatch( | |||
| 997 | source: source.clone(), | 945 | source: source.clone(), |
| 998 | }, | 946 | }, |
| 999 | }; | 947 | }; |
| 1000 | - let mut broadcasts = vec![broadcast(event, &members)]; | 948 | + let mut broadcasts = vec![Broadcast::new(To::Community(community_id.clone()), event)]; |
| 1001 | - broadcasts.extend(share.start(&community_id, &me.id, kind, connection.clone(), source)); | 949 | + broadcasts.extend( |
| 950 | + rooms | ||
| 951 | + .start_share(client.id, kind, source) | ||
| 952 | + .ok_or(CommonError::NotFound)?, | ||
| 953 | + ); | ||
| 1002 | 954 | ||
| 1003 | (Response::Done, broadcasts) | 955 | (Response::Done, broadcasts) |
| 1004 | } | 956 | } |
| 1005 | Request::StopShare { kind } => { | 957 | Request::StopShare { kind } => { |
| 1006 | - let me = authenticated(state, &conn).await?; | 958 | + let me = authenticated(client, &conn).await?; |
| 1007 | - ( | 959 | + let broadcasts = match rooms.stop_share(client.id, kind) { |
| 1008 | - Response::Done, | 960 | + Some(community_id) => vec![share_ended(&community_id, &me.id, kind)], |
| 1009 | - share_stopped(share, &me.id, kind, &conn).await?, | 961 | + None => Vec::new(), |
| 1010 | - ) | 962 | + }; |
| 963 | + (Response::Done, broadcasts) | ||
| 1011 | } | 964 | } |
| 1012 | Request::Shares { community_id } => { | 965 | Request::Shares { community_id } => { |
| 1013 | - let me = authenticated(state, &conn).await?; | 966 | + let me = authenticated(client, &conn).await?; |
| 1014 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 967 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 1015 | - (Response::Shares(share.list(&community_id)), Vec::new()) | 968 | + (Response::Shares(rooms.shares(&community_id)), Vec::new()) |
| 1016 | } | 969 | } |
| 1017 | Request::WatchShare { | 970 | Request::WatchShare { |
| 1018 | user_id, | 971 | user_id, |
| @@ -1020,56 +973,50 @@ async fn dispatch( | |||
| 1020 | quality, | 973 | quality, |
| 1021 | decode, | 974 | decode, |
| 1022 | } => { | 975 | } => { |
| 1023 | - let me = authenticated(state, &conn).await?; | 976 | + authenticated(client, &conn).await?; |
| 1024 | - let Some(connection) = connection else { | 977 | + let broadcasts = rooms |
| 1025 | - return Err(CommonError::Server.into()); | 978 | + .watch(client.id, &user_id, kind, quality, &decode) |
| 1026 | - }; | ||
| 1027 | - let room = voice.room_of(&me.id); | ||
| 1028 | - ensure(room.is_some() && room == voice.room_of(&user_id))?; | ||
| 1029 | - let broadcasts = share | ||
| 1030 | - .watch(&user_id, kind, &me.id, connection.clone(), quality, &decode) | ||
| 1031 | .ok_or(CommonError::NotFound)?; | 979 | .ok_or(CommonError::NotFound)?; |
| 1032 | 980 | ||
| 1033 | (Response::Done, broadcasts) | 981 | (Response::Done, broadcasts) |
| 1034 | } | 982 | } |
| 1035 | Request::UnwatchShare { user_id, kind } => { | 983 | Request::UnwatchShare { user_id, kind } => { |
| 1036 | - let me = authenticated(state, &conn).await?; | 984 | + authenticated(client, &conn).await?; |
| 1037 | 985 | ||
| 1038 | - (Response::Done, share.unwatch(&user_id, kind, &me.id)) | 986 | + (Response::Done, rooms.unwatch(client.id, &user_id, kind)) |
| 1039 | } | 987 | } |
| 1040 | Request::RequestKeyframe { user_id, kind } => { | 988 | Request::RequestKeyframe { user_id, kind } => { |
| 1041 | - let me = authenticated(state, &conn).await?; | 989 | + authenticated(client, &conn).await?; |
| 1042 | - let keyframe = share | 990 | + let keyframe = rooms |
| 1043 | - .keyframe(&user_id, kind, &me.id) | 991 | + .keyframe(client.id, &user_id, kind) |
| 1044 | .ok_or(CommonError::NotFound)?; | 992 | .ok_or(CommonError::NotFound)?; |
| 1045 | 993 | ||
| 1046 | (Response::Done, vec![keyframe]) | 994 | (Response::Done, vec![keyframe]) |
| 1047 | } | 995 | } |
| 1048 | Request::DeclineCall { community_id } => { | 996 | Request::DeclineCall { community_id } => { |
| 1049 | - let me = authenticated(state, &conn).await?; | 997 | + let me = authenticated(client, &conn).await?; |
| 1050 | ensure(community::is_direct(&community_id, &conn).await?)?; | 998 | ensure(community::is_direct(&community_id, &conn).await?)?; |
| 1051 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 999 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 1052 | - let participants = voice.participants(&community_id); | 1000 | + let participants = rooms.participants(&community_id); |
| 1053 | ensure(!participants.is_empty() && !participants.contains(&me.id))?; | 1001 | ensure(!participants.is_empty() && !participants.contains(&me.id))?; |
| 1054 | - voice.decline(&community_id); | 1002 | + rooms.decline(&community_id); |
| 1055 | let created = | 1003 | let created = |
| 1056 | message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?; | 1004 | message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?; |
| 1057 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 1058 | ( | 1005 | ( |
| 1059 | Response::Done, | 1006 | Response::Done, |
| 1060 | - vec![broadcast(Event::MessageCreated(created), &members)], | 1007 | + vec![message_event(&created, Event::MessageCreated)], |
| 1061 | ) | 1008 | ) |
| 1062 | } | 1009 | } |
| 1063 | Request::VoiceParticipants { community_id } => { | 1010 | Request::VoiceParticipants { community_id } => { |
| 1064 | - let me = authenticated(state, &conn).await?; | 1011 | + let me = authenticated(client, &conn).await?; |
| 1065 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 1012 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 1066 | ( | 1013 | ( |
| 1067 | - Response::Voice(voice.participants(&community_id)), | 1014 | + Response::Voice(rooms.participants(&community_id)), |
| 1068 | Vec::new(), | 1015 | Vec::new(), |
| 1069 | ) | 1016 | ) |
| 1070 | } | 1017 | } |
| 1071 | Request::FindUser { username } => { | 1018 | Request::FindUser { username } => { |
| 1072 | - let me = authenticated(state, &conn).await?; | 1019 | + let me = authenticated(client, &conn).await?; |
| 1073 | let found = user::by_username(&username, &conn) | 1020 | let found = user::by_username(&username, &conn) |
| 1074 | .await? | 1021 | .await? |
| 1075 | .filter(|found| found.id != me.id) | 1022 | .filter(|found| found.id != me.id) |
| @@ -1077,16 +1024,16 @@ async fn dispatch( | |||
| 1077 | (Response::User(found), Vec::new()) | 1024 | (Response::User(found), Vec::new()) |
| 1078 | } | 1025 | } |
| 1079 | Request::OpenDirect { user_id } => { | 1026 | Request::OpenDirect { user_id } => { |
| 1080 | - let me = authenticated(state, &conn).await?; | 1027 | + let me = authenticated(client, &conn).await?; |
| 1081 | match direct::open(&me.id, &user_id, &mut conn).await? { | 1028 | match direct::open(&me.id, &user_id, &mut conn).await? { |
| 1082 | direct::Opening::Created(community) => { | 1029 | direct::Opening::Created(community) => { |
| 1083 | let peer_view = community::read(&community.id, &user_id, &conn).await?; | 1030 | let peer_view = community::read(&community.id, &user_id, &conn).await?; |
| 1084 | ( | 1031 | ( |
| 1085 | Response::Community(community), | 1032 | Response::Community(community), |
| 1086 | - vec![Broadcast { | 1033 | + vec![Broadcast::new( |
| 1087 | - event: Event::CommunityAdded(peer_view), | 1034 | + To::User(user_id), |
| 1088 | - user_ids: vec![user_id], | 1035 | + Event::CommunityAdded(peer_view), |
| 1089 | - }], | 1036 | + )], |
| 1090 | ) | 1037 | ) |
| 1091 | } | 1038 | } |
| 1092 | direct::Opening::Existing(community) => { | 1039 | direct::Opening::Existing(community) => { |
| @@ -1095,33 +1042,33 @@ async fn dispatch( | |||
| 1095 | } | 1042 | } |
| 1096 | } | 1043 | } |
| 1097 | Request::OpenNotes => { | 1044 | Request::OpenNotes => { |
| 1098 | - let me = authenticated(state, &conn).await?; | 1045 | + let me = authenticated(client, &conn).await?; |
| 1099 | ( | 1046 | ( |
| 1100 | Response::Community(notes::open(&me.id, &mut conn).await?), | 1047 | Response::Community(notes::open(&me.id, &mut conn).await?), |
| 1101 | Vec::new(), | 1048 | Vec::new(), |
| 1102 | ) | 1049 | ) |
| 1103 | } | 1050 | } |
| 1104 | Request::Friends => { | 1051 | Request::Friends => { |
| 1105 | - let me = authenticated(state, &conn).await?; | 1052 | + let me = authenticated(client, &conn).await?; |
| 1106 | ( | 1053 | ( |
| 1107 | Response::Friends(friend::state(&me.id, &conn).await?), | 1054 | Response::Friends(friend::state(&me.id, &conn).await?), |
| 1108 | Vec::new(), | 1055 | Vec::new(), |
| 1109 | ) | 1056 | ) |
| 1110 | } | 1057 | } |
| 1111 | Request::AddFriend { user_id } => { | 1058 | Request::AddFriend { user_id } => { |
| 1112 | - let me = authenticated(state, &conn).await?; | 1059 | + let me = authenticated(client, &conn).await?; |
| 1113 | friend::add(&me.id, &user_id, &mut conn).await?; | 1060 | friend::add(&me.id, &user_id, &mut conn).await?; |
| 1114 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; | 1061 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; |
| 1115 | (Response::Done, broadcasts) | 1062 | (Response::Done, broadcasts) |
| 1116 | } | 1063 | } |
| 1117 | Request::AcceptFriend { user_id } => { | 1064 | Request::AcceptFriend { user_id } => { |
| 1118 | - let me = authenticated(state, &conn).await?; | 1065 | + let me = authenticated(client, &conn).await?; |
| 1119 | friend::accept(&me.id, &user_id, &mut conn).await?; | 1066 | friend::accept(&me.id, &user_id, &mut conn).await?; |
| 1120 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; | 1067 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; |
| 1121 | (Response::Done, broadcasts) | 1068 | (Response::Done, broadcasts) |
| 1122 | } | 1069 | } |
| 1123 | Request::RemoveFriend { user_id } => { | 1070 | Request::RemoveFriend { user_id } => { |
| 1124 | - let me = authenticated(state, &conn).await?; | 1071 | + let me = authenticated(client, &conn).await?; |
| 1125 | friend::remove(&me.id, &user_id, &mut conn).await?; | 1072 | friend::remove(&me.id, &user_id, &mut conn).await?; |
| 1126 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; | 1073 | let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; |
| 1127 | (Response::Done, broadcasts) | 1074 | (Response::Done, broadcasts) |
| @@ -1130,7 +1077,7 @@ async fn dispatch( | |||
| 1130 | community_id, | 1077 | community_id, |
| 1131 | user_id, | 1078 | user_id, |
| 1132 | } => { | 1079 | } => { |
| 1133 | - let me = authenticated(state, &conn).await?; | 1080 | + let me = authenticated(client, &conn).await?; |
| 1134 | ensure_editable(&community_id, &conn).await?; | 1081 | ensure_editable(&community_id, &conn).await?; |
| 1135 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 1082 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 1136 | let target = user::read(&user_id, &conn).await?; | 1083 | let target = user::read(&user_id, &conn).await?; |
| @@ -1158,14 +1105,14 @@ async fn dispatch( | |||
| 1158 | (Response::Done, vec![broadcast]) | 1105 | (Response::Done, vec![broadcast]) |
| 1159 | } | 1106 | } |
| 1160 | Request::Invitations => { | 1107 | Request::Invitations => { |
| 1161 | - let me = authenticated(state, &conn).await?; | 1108 | + let me = authenticated(client, &conn).await?; |
| 1162 | ( | 1109 | ( |
| 1163 | Response::Invitations(invitation::of(&me.id, &conn).await?), | 1110 | Response::Invitations(invitation::of(&me.id, &conn).await?), |
| 1164 | Vec::new(), | 1111 | Vec::new(), |
| 1165 | ) | 1112 | ) |
| 1166 | } | 1113 | } |
| 1167 | Request::AcceptInvitation { community_id } => { | 1114 | Request::AcceptInvitation { community_id } => { |
| 1168 | - let me = authenticated(state, &conn).await?; | 1115 | + let me = authenticated(client, &conn).await?; |
| 1169 | let tx = conn.transaction().await?; | 1116 | let tx = conn.transaction().await?; |
| 1170 | invitation::take(&community_id, &me.id, &tx).await?; | 1117 | invitation::take(&community_id, &me.id, &tx).await?; |
| 1171 | let banned = user_community::is_banned(&me.id, &community_id, &tx).await?; | 1118 | let banned = user_community::is_banned(&me.id, &community_id, &tx).await?; |
| @@ -1173,21 +1120,20 @@ async fn dispatch( | |||
| 1173 | user_community::join(&me.id, &community_id, Rank::Member, &tx).await?; | 1120 | user_community::join(&me.id, &community_id, Rank::Member, &tx).await?; |
| 1174 | log::record(&community_id, Some(&me.id), None, &LogAction::Joined, &tx).await?; | 1121 | log::record(&community_id, Some(&me.id), None, &LogAction::Joined, &tx).await?; |
| 1175 | let community = community::read(&community_id, &me.id, &tx).await?; | 1122 | let community = community::read(&community_id, &me.id, &tx).await?; |
| 1176 | - let members = user_community::members(&community_id, &tx).await?; | ||
| 1177 | tx.commit().await?; | 1123 | tx.commit().await?; |
| 1178 | let event = Event::MemberJoined { | 1124 | let event = Event::MemberJoined { |
| 1179 | - community_id, | 1125 | + community_id: community_id.clone(), |
| 1180 | member: Member { | 1126 | member: Member { |
| 1181 | user: me.clone(), | 1127 | user: me.clone(), |
| 1182 | rank: Rank::Member, | 1128 | rank: Rank::Member, |
| 1183 | }, | 1129 | }, |
| 1184 | }; | 1130 | }; |
| 1185 | - let mut broadcasts = vec![broadcast(event, &members)]; | 1131 | + let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)]; |
| 1186 | broadcasts.push(invitations_updated(&me.id, &conn).await?); | 1132 | broadcasts.push(invitations_updated(&me.id, &conn).await?); |
| 1187 | (Response::Community(community), broadcasts) | 1133 | (Response::Community(community), broadcasts) |
| 1188 | } | 1134 | } |
| 1189 | Request::DeclineInvitation { community_id } => { | 1135 | Request::DeclineInvitation { community_id } => { |
| 1190 | - let me = authenticated(state, &conn).await?; | 1136 | + let me = authenticated(client, &conn).await?; |
| 1191 | invitation::take(&community_id, &me.id, &conn).await?; | 1137 | invitation::take(&community_id, &me.id, &conn).await?; |
| 1192 | ( | 1138 | ( |
| 1193 | Response::Done, | 1139 | Response::Done, |
| @@ -1195,7 +1141,7 @@ async fn dispatch( | |||
| 1195 | ) | 1141 | ) |
| 1196 | } | 1142 | } |
| 1197 | Request::Logs { community_id } => { | 1143 | Request::Logs { community_id } => { |
| 1198 | - let me = authenticated(state, &conn).await?; | 1144 | + let me = authenticated(client, &conn).await?; |
| 1199 | allowed(&me, &community_id, &conn, permission::can_read_logs).await?; | 1145 | allowed(&me, &community_id, &conn, permission::can_read_logs).await?; |
| 1200 | ( | 1146 | ( |
| 1201 | Response::Logs(log::list(&community_id, &conn).await?), | 1147 | Response::Logs(log::list(&community_id, &conn).await?), |
| @@ -1203,7 +1149,7 @@ async fn dispatch( | |||
| 1203 | ) | 1149 | ) |
| 1204 | } | 1150 | } |
| 1205 | Request::AllCommunities => { | 1151 | Request::AllCommunities => { |
| 1206 | - builder(state, &conn).await?; | 1152 | + builder(client, &conn).await?; |
| 1207 | let mut summaries = Vec::new(); | 1153 | let mut summaries = Vec::new(); |
| 1208 | for community in community::groups(&conn).await? { | 1154 | for community in community::groups(&conn).await? { |
| 1209 | let members = user_community::members(&community.id, &conn).await?; | 1155 | let members = user_community::members(&community.id, &conn).await?; |
| @@ -1223,7 +1169,7 @@ async fn dispatch( | |||
| 1223 | community_id, | 1169 | community_id, |
| 1224 | user_id, | 1170 | user_id, |
| 1225 | } => { | 1171 | } => { |
| 1226 | - let me = authenticated(state, &conn).await?; | 1172 | + let me = authenticated(client, &conn).await?; |
| 1227 | ensure_editable(&community_id, &conn).await?; | 1173 | ensure_editable(&community_id, &conn).await?; |
| 1228 | allowed( | 1174 | allowed( |
| 1229 | &me, | 1175 | &me, |
| @@ -1281,18 +1227,17 @@ async fn dispatch( | |||
| 1281 | user_id: changed_id, | 1227 | user_id: changed_id, |
| 1282 | rank, | 1228 | rank, |
| 1283 | }; | 1229 | }; |
| 1284 | - broadcasts.push(broadcast(event, &members)); | 1230 | + broadcasts.push(Broadcast::new(To::Community(community_id.clone()), event)); |
| 1285 | } | 1231 | } |
| 1286 | (Response::Done, broadcasts) | 1232 | (Response::Done, broadcasts) |
| 1287 | } | 1233 | } |
| 1288 | Request::TimeoutUser { user_id, minutes } => { | 1234 | Request::TimeoutUser { user_id, minutes } => { |
| 1289 | - let me = authenticated(state, &conn).await?; | 1235 | + let me = authenticated(client, &conn).await?; |
| 1290 | managed(&me, &user_id, &conn).await?; | 1236 | managed(&me, &user_id, &conn).await?; |
| 1291 | let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); | 1237 | let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); |
| 1292 | user::set_timeout(&user_id, until, &conn).await?; | 1238 | user::set_timeout(&user_id, until, &conn).await?; |
| 1293 | if until.is_some() { | 1239 | if until.is_some() { |
| 1294 | - authentication::revoke_sessions(&user_id, &conn).await?; | 1240 | + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; |
| 1295 | - presence.disconnect(&user_id, Close::Revoked); | ||
| 1296 | } | 1241 | } |
| 1297 | admin_log::record( | 1242 | admin_log::record( |
| 1298 | Some(&me.id), | 1243 | Some(&me.id), |
| @@ -1309,7 +1254,7 @@ async fn dispatch( | |||
| 1309 | reason, | 1254 | reason, |
| 1310 | scope, | 1255 | scope, |
| 1311 | } => { | 1256 | } => { |
| 1312 | - let me = authenticated(state, &conn).await?; | 1257 | + let me = authenticated(client, &conn).await?; |
| 1313 | let target = managed(&me, &user_id, &conn).await?; | 1258 | let target = managed(&me, &user_id, &conn).await?; |
| 1314 | validate_reason(reason.as_deref())?; | 1259 | validate_reason(reason.as_deref())?; |
| 1315 | let tx = conn.transaction().await?; | 1260 | let tx = conn.transaction().await?; |
| @@ -1338,44 +1283,44 @@ async fn dispatch( | |||
| 1338 | ) | 1283 | ) |
| 1339 | .await?; | 1284 | .await?; |
| 1340 | tx.commit().await?; | 1285 | tx.commit().await?; |
| 1341 | - presence.disconnect(&user_id, Close::Banned); | 1286 | + hub.kick_user(&user_id, Close::Banned); |
| 1342 | (Response::Done, Vec::new()) | 1287 | (Response::Done, Vec::new()) |
| 1343 | } | 1288 | } |
| 1344 | Request::ServerBans => { | 1289 | Request::ServerBans => { |
| 1345 | - builder(state, &conn).await?; | 1290 | + builder(client, &conn).await?; |
| 1346 | ( | 1291 | ( |
| 1347 | Response::ServerBans(server_ban::list(&conn).await?), | 1292 | Response::ServerBans(server_ban::list(&conn).await?), |
| 1348 | Vec::new(), | 1293 | Vec::new(), |
| 1349 | ) | 1294 | ) |
| 1350 | } | 1295 | } |
| 1351 | Request::RemoveServerBan { id } => { | 1296 | Request::RemoveServerBan { id } => { |
| 1352 | - let me = builder(state, &conn).await?; | 1297 | + let me = builder(client, &conn).await?; |
| 1353 | server_ban::remove(&id, &conn).await?; | 1298 | server_ban::remove(&id, &conn).await?; |
| 1354 | admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?; | 1299 | admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?; |
| 1355 | (Response::Done, Vec::new()) | 1300 | (Response::Done, Vec::new()) |
| 1356 | } | 1301 | } |
| 1357 | Request::CreateInviteCode { uses, hours } => { | 1302 | Request::CreateInviteCode { uses, hours } => { |
| 1358 | - let me = authenticated(state, &conn).await?; | 1303 | + let me = authenticated(client, &conn).await?; |
| 1359 | ensure(permission::is_builder(me.role) && uses > 0)?; | 1304 | ensure(permission::is_builder(me.role) && uses > 0)?; |
| 1360 | let code = invite::create(uses, hours, &me, &conn).await?; | 1305 | let code = invite::create(uses, hours, &me, &conn).await?; |
| 1361 | admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?; | 1306 | admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?; |
| 1362 | (Response::InviteCode(code), Vec::new()) | 1307 | (Response::InviteCode(code), Vec::new()) |
| 1363 | } | 1308 | } |
| 1364 | Request::InviteCodes => { | 1309 | Request::InviteCodes => { |
| 1365 | - builder(state, &conn).await?; | 1310 | + builder(client, &conn).await?; |
| 1366 | ( | 1311 | ( |
| 1367 | Response::InviteCodes(invite::list(&conn).await?), | 1312 | Response::InviteCodes(invite::list(&conn).await?), |
| 1368 | Vec::new(), | 1313 | Vec::new(), |
| 1369 | ) | 1314 | ) |
| 1370 | } | 1315 | } |
| 1371 | Request::DeleteInviteCode { code } => { | 1316 | Request::DeleteInviteCode { code } => { |
| 1372 | - let me = builder(state, &conn).await?; | 1317 | + let me = builder(client, &conn).await?; |
| 1373 | invite::delete(&code, &conn).await?; | 1318 | invite::delete(&code, &conn).await?; |
| 1374 | admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?; | 1319 | admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?; |
| 1375 | (Response::Done, Vec::new()) | 1320 | (Response::Done, Vec::new()) |
| 1376 | } | 1321 | } |
| 1377 | Request::ReportMessage { message_id, reason } => { | 1322 | Request::ReportMessage { message_id, reason } => { |
| 1378 | - let me = authenticated(state, &conn).await?; | 1323 | + let me = authenticated(client, &conn).await?; |
| 1379 | let message = message::read(&message_id, &conn).await?; | 1324 | let message = message::read(&message_id, &conn).await?; |
| 1380 | let actor = actor_rank(&me, &message.community_id, &conn).await?; | 1325 | let actor = actor_rank(&me, &message.community_id, &conn).await?; |
| 1381 | ensure(permission::can_read(actor) && me.id != message.user_id)?; | 1326 | ensure(permission::can_read(actor) && me.id != message.user_id)?; |
| @@ -1394,10 +1339,10 @@ async fn dispatch( | |||
| 1394 | &conn, | 1339 | &conn, |
| 1395 | ) | 1340 | ) |
| 1396 | .await?; | 1341 | .await?; |
| 1397 | - (Response::Done, vec![report_created(&conn).await?]) | 1342 | + (Response::Done, vec![report_created()]) |
| 1398 | } | 1343 | } |
| 1399 | Request::ReportUser { user_id, reason } => { | 1344 | Request::ReportUser { user_id, reason } => { |
| 1400 | - let me = authenticated(state, &conn).await?; | 1345 | + let me = authenticated(client, &conn).await?; |
| 1401 | user::read(&user_id, &conn).await?; | 1346 | user::read(&user_id, &conn).await?; |
| 1402 | ensure(me.id != user_id)?; | 1347 | ensure(me.id != user_id)?; |
| 1403 | validate_reason(Some(&reason))?; | 1348 | validate_reason(Some(&reason))?; |
| @@ -1406,17 +1351,17 @@ async fn dispatch( | |||
| 1406 | CommonError::Taken, | 1351 | CommonError::Taken, |
| 1407 | )?; | 1352 | )?; |
| 1408 | report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?; | 1353 | report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?; |
| 1409 | - (Response::Done, vec![report_created(&conn).await?]) | 1354 | + (Response::Done, vec![report_created()]) |
| 1410 | } | 1355 | } |
| 1411 | Request::Reports { status } => { | 1356 | Request::Reports { status } => { |
| 1412 | - builder(state, &conn).await?; | 1357 | + builder(client, &conn).await?; |
| 1413 | ( | 1358 | ( |
| 1414 | Response::Reports(report::list(status, &conn).await?), | 1359 | Response::Reports(report::list(status, &conn).await?), |
| 1415 | Vec::new(), | 1360 | Vec::new(), |
| 1416 | ) | 1361 | ) |
| 1417 | } | 1362 | } |
| 1418 | Request::HandleReport { report_id, status } => { | 1363 | Request::HandleReport { report_id, status } => { |
| 1419 | - let me = authenticated(state, &conn).await?; | 1364 | + let me = authenticated(client, &conn).await?; |
| 1420 | ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?; | 1365 | ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?; |
| 1421 | let target = report::handle(&report_id, status, &me.id, &conn).await?; | 1366 | let target = report::handle(&report_id, status, &me.id, &conn).await?; |
| 1422 | admin_log::record( | 1367 | admin_log::record( |
| @@ -1436,7 +1381,7 @@ async fn dispatch( | |||
| 1436 | after_ms, | 1381 | after_ms, |
| 1437 | before_ms, | 1382 | before_ms, |
| 1438 | } => { | 1383 | } => { |
| 1439 | - builder(state, &conn).await?; | 1384 | + builder(client, &conn).await?; |
| 1440 | let hits = message::search( | 1385 | let hits = message::search( |
| 1441 | text.as_deref(), | 1386 | text.as_deref(), |
| 1442 | user_id.as_deref(), | 1387 | user_id.as_deref(), |
| @@ -1449,31 +1394,36 @@ async fn dispatch( | |||
| 1449 | (Response::MessageHits(hits), Vec::new()) | 1394 | (Response::MessageHits(hits), Vec::new()) |
| 1450 | } | 1395 | } |
| 1451 | Request::SearchCommunity { community_id, text } => { | 1396 | Request::SearchCommunity { community_id, text } => { |
| 1452 | - let me = authenticated(state, &conn).await?; | 1397 | + let me = authenticated(client, &conn).await?; |
| 1453 | allowed(&me, &community_id, &conn, permission::can_read).await?; | 1398 | allowed(&me, &community_id, &conn, permission::can_read).await?; |
| 1454 | let hits = | 1399 | let hits = |
| 1455 | message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?; | 1400 | message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?; |
| 1456 | (Response::MessageHits(hits), Vec::new()) | 1401 | (Response::MessageHits(hits), Vec::new()) |
| 1457 | } | 1402 | } |
| 1458 | Request::PurgeUser { user_id } => { | 1403 | Request::PurgeUser { user_id } => { |
| 1459 | - let me = authenticated(state, &conn).await?; | 1404 | + let me = authenticated(client, &conn).await?; |
| 1460 | managed(&me, &user_id, &conn).await?; | 1405 | managed(&me, &user_id, &conn).await?; |
| 1461 | let tx = conn.transaction().await?; | 1406 | let tx = conn.transaction().await?; |
| 1462 | let upload_ids = attachment::uploads_of(&user_id, &tx).await?; | 1407 | let upload_ids = attachment::uploads_of(&user_id, &tx).await?; |
| 1463 | let message_ids = message::ids_of_user(&user_id, &tx).await?; | 1408 | let message_ids = message::ids_of_user(&user_id, &tx).await?; |
| 1464 | - let mut members = BTreeMap::new(); | 1409 | + let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 1465 | - let mut broadcasts = Vec::new(); | ||
| 1466 | for message_id in &message_ids { | 1410 | for message_id in &message_ids { |
| 1467 | - let deleted = message::delete(message_id, &tx).await?; | 1411 | + let message = message::delete(message_id, &tx).await?; |
| 1468 | - if !members.contains_key(&deleted.community_id) { | 1412 | + deleted |
| 1469 | - let community_members = | 1413 | + .entry(message.community_id) |
| 1470 | - user_community::members(&deleted.community_id, &tx).await?; | 1414 | + .or_default() |
| 1471 | - members.insert(deleted.community_id.clone(), community_members); | 1415 | + .push(message.id); |
| 1472 | - } | ||
| 1473 | - let community_members = &members[&deleted.community_id]; | ||
| 1474 | - let event = Event::MessageDeleted(deleted); | ||
| 1475 | - broadcasts.push(broadcast(event, community_members)); | ||
| 1476 | } | 1416 | } |
| 1417 | + let broadcasts = deleted | ||
| 1418 | + .into_iter() | ||
| 1419 | + .map(|(community_id, ids)| { | ||
| 1420 | + let event = Event::MessagesDeleted { | ||
| 1421 | + community_id: community_id.clone(), | ||
| 1422 | + ids, | ||
| 1423 | + }; | ||
| 1424 | + Broadcast::new(To::Community(community_id), event) | ||
| 1425 | + }) | ||
| 1426 | + .collect(); | ||
| 1477 | attachment::delete_uploads(&user_id, &tx).await?; | 1427 | attachment::delete_uploads(&user_id, &tx).await?; |
| 1478 | admin_log::record( | 1428 | admin_log::record( |
| 1479 | Some(&me.id), | 1429 | Some(&me.id), |
| @@ -1493,7 +1443,7 @@ async fn dispatch( | |||
| 1493 | user_id, | 1443 | user_id, |
| 1494 | community_id, | 1444 | community_id, |
| 1495 | } => { | 1445 | } => { |
| 1496 | - builder(state, &conn).await?; | 1446 | + builder(client, &conn).await?; |
| 1497 | ( | 1447 | ( |
| 1498 | Response::AttachmentInfos( | 1448 | Response::AttachmentInfos( |
| 1499 | attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, | 1449 | attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, |
| @@ -1502,7 +1452,7 @@ async fn dispatch( | |||
| 1502 | ) | 1452 | ) |
| 1503 | } | 1453 | } |
| 1504 | Request::DeleteAttachment { attachment_id } => { | 1454 | Request::DeleteAttachment { attachment_id } => { |
| 1505 | - let me = builder(state, &conn).await?; | 1455 | + let me = builder(client, &conn).await?; |
| 1506 | let stored = attachment::read(&attachment_id, &conn).await?; | 1456 | let stored = attachment::read(&attachment_id, &conn).await?; |
| 1507 | let community = community::label(&stored.community_id, &conn).await?; | 1457 | let community = community::label(&stored.community_id, &conn).await?; |
| 1508 | let tx = conn.transaction().await?; | 1458 | let tx = conn.transaction().await?; |
| @@ -1518,20 +1468,19 @@ async fn dispatch( | |||
| 1518 | let mut broadcasts = Vec::new(); | 1468 | let mut broadcasts = Vec::new(); |
| 1519 | if let Some(message_id) = &stored.message_id { | 1469 | if let Some(message_id) = &stored.message_id { |
| 1520 | let updated = message::read(message_id, &tx).await?; | 1470 | let updated = message::read(message_id, &tx).await?; |
| 1521 | - let members = user_community::members(&updated.community_id, &tx).await?; | 1471 | + broadcasts = vec![message_event(&updated, Event::MessageUpdated)]; |
| 1522 | - broadcasts = vec![broadcast(Event::MessageUpdated(updated), &members)]; | ||
| 1523 | } | 1472 | } |
| 1524 | tx.commit().await?; | 1473 | tx.commit().await?; |
| 1525 | attachment::remove_files(&[attachment_id], directory); | 1474 | attachment::remove_files(&[attachment_id], directory); |
| 1526 | (Response::Done, broadcasts) | 1475 | (Response::Done, broadcasts) |
| 1527 | } | 1476 | } |
| 1528 | Request::StorageUsage => { | 1477 | Request::StorageUsage => { |
| 1529 | - builder(state, &conn).await?; | 1478 | + builder(client, &conn).await?; |
| 1530 | let (users, communities) = attachment::usage(&conn).await?; | 1479 | let (users, communities) = attachment::usage(&conn).await?; |
| 1531 | (Response::StorageUsage { users, communities }, Vec::new()) | 1480 | (Response::StorageUsage { users, communities }, Vec::new()) |
| 1532 | } | 1481 | } |
| 1533 | Request::CreateBackup => { | 1482 | Request::CreateBackup => { |
| 1534 | - let me = builder(state, &conn).await?; | 1483 | + let me = builder(client, &conn).await?; |
| 1535 | let backup = backup::create(&conn, backups).await?; | 1484 | let backup = backup::create(&conn, backups).await?; |
| 1536 | let action = AdminAction::BackupCreated { | 1485 | let action = AdminAction::BackupCreated { |
| 1537 | name: backup.name.clone(), | 1486 | name: backup.name.clone(), |
| @@ -1540,27 +1489,27 @@ async fn dispatch( | |||
| 1540 | (Response::Backup(backup), Vec::new()) | 1489 | (Response::Backup(backup), Vec::new()) |
| 1541 | } | 1490 | } |
| 1542 | Request::Backups => { | 1491 | Request::Backups => { |
| 1543 | - builder(state, &conn).await?; | 1492 | + builder(client, &conn).await?; |
| 1544 | (Response::Backups(backup::list(backups)?), Vec::new()) | 1493 | (Response::Backups(backup::list(backups)?), Vec::new()) |
| 1545 | } | 1494 | } |
| 1546 | Request::DeleteBackup { name } => { | 1495 | Request::DeleteBackup { name } => { |
| 1547 | - let me = builder(state, &conn).await?; | 1496 | + let me = builder(client, &conn).await?; |
| 1548 | backup::delete(&name, backups)?; | 1497 | backup::delete(&name, backups)?; |
| 1549 | let action = AdminAction::BackupDeleted { name }; | 1498 | let action = AdminAction::BackupDeleted { name }; |
| 1550 | admin_log::record(Some(&me.id), None, None, &action, &conn).await?; | 1499 | admin_log::record(Some(&me.id), None, None, &action, &conn).await?; |
| 1551 | (Response::Done, Vec::new()) | 1500 | (Response::Done, Vec::new()) |
| 1552 | } | 1501 | } |
| 1553 | Request::VoiceRooms => { | 1502 | Request::VoiceRooms => { |
| 1554 | - builder(state, &conn).await?; | 1503 | + builder(client, &conn).await?; |
| 1555 | ( | 1504 | ( |
| 1556 | - Response::VoiceRooms(voice_rooms(voice, &conn).await?), | 1505 | + Response::VoiceRooms(voice_rooms(rooms, &conn).await?), |
| 1557 | Vec::new(), | 1506 | Vec::new(), |
| 1558 | ) | 1507 | ) |
| 1559 | } | 1508 | } |
| 1560 | Request::KickFromVoice { user_id } => { | 1509 | Request::KickFromVoice { user_id } => { |
| 1561 | - let me = authenticated(state, &conn).await?; | 1510 | + let me = authenticated(client, &conn).await?; |
| 1562 | managed(&me, &user_id, &conn).await?; | 1511 | managed(&me, &user_id, &conn).await?; |
| 1563 | - let broadcasts = leave_user_voice(voice, share, &user_id, &conn).await?; | 1512 | + let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?; |
| 1564 | if !broadcasts.is_empty() { | 1513 | if !broadcasts.is_empty() { |
| 1565 | admin_log::record( | 1514 | admin_log::record( |
| 1566 | Some(&me.id), | 1515 | Some(&me.id), |
| @@ -1574,7 +1523,7 @@ async fn dispatch( | |||
| 1574 | (Response::Done, broadcasts) | 1523 | (Response::Done, broadcasts) |
| 1575 | } | 1524 | } |
| 1576 | Request::ServerMute { user_id, muted } => { | 1525 | Request::ServerMute { user_id, muted } => { |
| 1577 | - let me = authenticated(state, &conn).await?; | 1526 | + let me = authenticated(client, &conn).await?; |
| 1578 | managed(&me, &user_id, &conn).await?; | 1527 | managed(&me, &user_id, &conn).await?; |
| 1579 | user::set_voice_muted(&user_id, muted, &conn).await?; | 1528 | user::set_voice_muted(&user_id, muted, &conn).await?; |
| 1580 | admin_log::record( | 1529 | admin_log::record( |
| @@ -1585,28 +1534,15 @@ async fn dispatch( | |||
| 1585 | &conn, | 1534 | &conn, |
| 1586 | ) | 1535 | ) |
| 1587 | .await?; | 1536 | .await?; |
| 1588 | - let mut user_ids = BTreeSet::from([user_id.clone()]); | 1537 | + let community_id = rooms.set_muted(&user_id, muted); |
| 1589 | - if let Some(community_id) = voice.set_muted(&user_id, muted) | 1538 | + let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?; |
| 1590 | - && !user::is_ghost(&user_id, &conn).await? | 1539 | + (Response::Done, vec![broadcast]) |
| 1591 | - { | ||
| 1592 | - for member in user_community::members(&community_id, &conn).await? { | ||
| 1593 | - user_ids.insert(member.user.id); | ||
| 1594 | - } | ||
| 1595 | - } | ||
| 1596 | - let event = Event::VoiceMuted { user_id, muted }; | ||
| 1597 | - ( | ||
| 1598 | - Response::Done, | ||
| 1599 | - vec![Broadcast { | ||
| 1600 | - event, | ||
| 1601 | - user_ids: user_ids.into_iter().collect(), | ||
| 1602 | - }], | ||
| 1603 | - ) | ||
| 1604 | } | 1540 | } |
| 1605 | Request::SetCommunityVoice { | 1541 | Request::SetCommunityVoice { |
| 1606 | community_id, | 1542 | community_id, |
| 1607 | enabled, | 1543 | enabled, |
| 1608 | } => { | 1544 | } => { |
| 1609 | - let me = authenticated(state, &conn).await?; | 1545 | + let me = authenticated(client, &conn).await?; |
| 1610 | allowed(&me, &community_id, &conn, permission::can_manage_voice).await?; | 1546 | allowed(&me, &community_id, &conn, permission::can_manage_voice).await?; |
| 1611 | let tx = conn.transaction().await?; | 1547 | let tx = conn.transaction().await?; |
| 1612 | community::set_voice_enabled(&community_id, enabled, &tx).await?; | 1548 | community::set_voice_enabled(&community_id, enabled, &tx).await?; |
| @@ -1621,19 +1557,18 @@ async fn dispatch( | |||
| 1621 | ) | 1557 | ) |
| 1622 | .await?; | 1558 | .await?; |
| 1623 | } | 1559 | } |
| 1624 | - let members = user_community::members(&community_id, &tx).await?; | ||
| 1625 | tx.commit().await?; | 1560 | tx.commit().await?; |
| 1626 | let mut broadcasts = Vec::new(); | 1561 | let mut broadcasts = Vec::new(); |
| 1627 | if !enabled { | 1562 | if !enabled { |
| 1628 | - broadcasts.extend(voice_silenced(voice, share, &community_id, &conn).await?); | 1563 | + broadcasts.extend(voice_silenced(rooms, &community_id, &conn).await?); |
| 1629 | } | 1564 | } |
| 1630 | let event = Event::CommunityUpdated(updated.clone()); | 1565 | let event = Event::CommunityUpdated(updated.clone()); |
| 1631 | - broadcasts.push(broadcast(event, &members)); | 1566 | + broadcasts.push(Broadcast::new(To::Community(community_id), event)); |
| 1632 | 1567 | ||
| 1633 | (Response::Community(updated), broadcasts) | 1568 | (Response::Community(updated), broadcasts) |
| 1634 | } | 1569 | } |
| 1635 | Request::SetGhost { enabled } => { | 1570 | Request::SetGhost { enabled } => { |
| 1636 | - let me = builder(state, &conn).await?; | 1571 | + let me = builder(client, &conn).await?; |
| 1637 | user::set_ghost(&me.id, enabled, &conn).await?; | 1572 | user::set_ghost(&me.id, enabled, &conn).await?; |
| 1638 | let action = if enabled { | 1573 | let action = if enabled { |
| 1639 | AdminAction::GhostEnabled | 1574 | AdminAction::GhostEnabled |
| @@ -1642,38 +1577,29 @@ async fn dispatch( | |||
| 1642 | }; | 1577 | }; |
| 1643 | admin_log::record(Some(&me.id), None, None, &action, &conn).await?; | 1578 | admin_log::record(Some(&me.id), None, None, &action, &conn).await?; |
| 1644 | let mut broadcasts = Vec::new(); | 1579 | let mut broadcasts = Vec::new(); |
| 1645 | - let outsider = match voice.room_of(&me.id) { | 1580 | + let outsider = match rooms.room_of(&me.id) { |
| 1646 | Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?, | 1581 | Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?, |
| 1647 | None => false, | 1582 | None => false, |
| 1648 | }; | 1583 | }; |
| 1649 | - if !outsider | 1584 | + if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) { |
| 1650 | - && let Some(Left { | 1585 | + let community_id = departure.community_id.clone(); |
| 1651 | - community_id, | ||
| 1652 | - ghost_seconds: seconds, | ||
| 1653 | - call, | ||
| 1654 | - .. | ||
| 1655 | - }) = voice.set_ghost(&me.id, enabled) | ||
| 1656 | - { | ||
| 1657 | - let members = user_community::members(&community_id, &conn).await?; | ||
| 1658 | if enabled { | 1586 | if enabled { |
| 1659 | - broadcasts.extend(share_left(share, &me.id, &conn).await?); | 1587 | + broadcasts.extend(shares_ended(&mut departure)); |
| 1660 | - broadcasts | 1588 | + broadcasts.extend( |
| 1661 | - .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?); | 1589 | + call_ended(&community_id, &me.id, departure.call_log, &conn).await?, |
| 1662 | - broadcasts.push(Broadcast { | 1590 | + ); |
| 1663 | - event: Event::VoiceLeft { | 1591 | + let event = Event::VoiceLeft { |
| 1664 | - community_id, | 1592 | + community_id: community_id.clone(), |
| 1665 | - user_id: me.id.clone(), | 1593 | + user_id: me.id.clone(), |
| 1666 | - }, | 1594 | + }; |
| 1667 | - user_ids: members | 1595 | + broadcasts.push(Broadcast::new( |
| 1668 | - .iter() | 1596 | + To::CommunityExcept(community_id, me.id.clone()), |
| 1669 | - .map(|member| member.user.id.clone()) | 1597 | + event, |
| 1670 | - .filter(|user_id| *user_id != me.id) | 1598 | + )); |
| 1671 | - .collect(), | ||
| 1672 | - }); | ||
| 1673 | } else { | 1599 | } else { |
| 1674 | let muted = user::voice_muted(&me.id, &conn).await?; | 1600 | let muted = user::voice_muted(&me.id, &conn).await?; |
| 1675 | - broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); | 1601 | + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); |
| 1676 | - if let Some(seconds) = seconds { | 1602 | + if let Some(seconds) = departure.ghost_seconds { |
| 1677 | record_ghost_voice(&me.id, &community_id, seconds, &conn).await?; | 1603 | record_ghost_voice(&me.id, &community_id, seconds, &conn).await?; |
| 1678 | } | 1604 | } |
| 1679 | } | 1605 | } |
| @@ -1685,9 +1611,9 @@ async fn dispatch( | |||
| 1685 | Ok(outcome) | 1611 | Ok(outcome) |
| 1686 | } | 1612 | } |
| 1687 | 1613 | ||
| 1688 | -async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>, ServerError> { | 1614 | +async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result<Vec<VoiceRoom>, ServerError> { |
| 1689 | let mut rooms = Vec::new(); | 1615 | let mut rooms = Vec::new(); |
| 1690 | - for (community_id, user_ids, ghosts) in voice.rooms() { | 1616 | + for (community_id, user_ids, ghosts) in occupied.list() { |
| 1691 | let community = community::label(&community_id, conn).await?; | 1617 | let community = community::label(&community_id, conn).await?; |
| 1692 | let mut users = Vec::new(); | 1618 | let mut users = Vec::new(); |
| 1693 | let mut muted = Vec::new(); | 1619 | let mut muted = Vec::new(); |
| @@ -1711,11 +1637,8 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>, | |||
| 1711 | Ok(rooms) | 1637 | Ok(rooms) |
| 1712 | } | 1638 | } |
| 1713 | 1639 | ||
| 1714 | -async fn report_created(conn: &Connection) -> Result<Broadcast, ServerError> { | 1640 | +fn report_created() -> Broadcast { |
| 1715 | - Ok(Broadcast { | 1641 | + Broadcast::new(To::Builders, Event::ReportCreated) |
| 1716 | - event: Event::ReportCreated, | ||
| 1717 | - user_ids: user::builder_ids(conn).await?, | ||
| 1718 | - }) | ||
| 1719 | } | 1642 | } |
| 1720 | 1643 | ||
| 1721 | fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> { | 1644 | fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> { |
| @@ -1744,7 +1667,7 @@ fn limit_messages( | |||
| 1744 | Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) | 1667 | Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) |
| 1745 | } | 1668 | } |
| 1746 | 1669 | ||
| 1747 | -async fn record_address( | 1670 | +pub(crate) async fn record_address( |
| 1748 | user: &User, | 1671 | user: &User, |
| 1749 | connection: Option<&quinn::Connection>, | 1672 | connection: Option<&quinn::Connection>, |
| 1750 | conn: &Connection, | 1673 | conn: &Connection, |
| @@ -1766,8 +1689,7 @@ struct Removal { | |||
| 1766 | async fn remove_member( | 1689 | async fn remove_member( |
| 1767 | me: &User, | 1690 | me: &User, |
| 1768 | removal: Removal, | 1691 | removal: Removal, |
| 1769 | - voice: &Voice, | 1692 | + rooms: &Rooms, |
| 1770 | - share: &Shares, | ||
| 1771 | conn: &mut Connection, | 1693 | conn: &mut Connection, |
| 1772 | ) -> Result<Outcome, ServerError> { | 1694 | ) -> Result<Outcome, ServerError> { |
| 1773 | let Removal { | 1695 | let Removal { |
| @@ -1785,7 +1707,6 @@ async fn remove_member( | |||
| 1785 | ))?; | 1707 | ))?; |
| 1786 | let community = community::read(&community_id, &me.id, conn).await?; | 1708 | let community = community::read(&community_id, &me.id, conn).await?; |
| 1787 | let tx = conn.transaction().await?; | 1709 | let tx = conn.transaction().await?; |
| 1788 | - let members = user_community::members(&community_id, &tx).await?; | ||
| 1789 | user_community::leave(&user_id, &community_id, &tx).await?; | 1710 | user_community::leave(&user_id, &community_id, &tx).await?; |
| 1790 | let action = match sanction { | 1711 | let action = match sanction { |
| 1791 | Sanction::Ban => { | 1712 | Sanction::Ban => { |
| @@ -1800,52 +1721,36 @@ async fn remove_member( | |||
| 1800 | }; | 1721 | }; |
| 1801 | log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; | 1722 | log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; |
| 1802 | tx.commit().await?; | 1723 | tx.commit().await?; |
| 1803 | - let mut broadcasts = leave_room_voice(voice, share, &community_id, &user_id, conn).await?; | 1724 | + let mut broadcasts = leave_room_voice(rooms, &community_id, &user_id, conn).await?; |
| 1804 | - broadcasts.push(Broadcast { | 1725 | + let removed = Event::Removed { |
| 1805 | - event: Event::Removed { | 1726 | + community_id: community_id.clone(), |
| 1806 | - community_id: community_id.clone(), | 1727 | + community_name: community.name, |
| 1807 | - community_name: community.name, | 1728 | + sanction, |
| 1808 | - sanction, | 1729 | + reason, |
| 1809 | - reason, | 1730 | + }; |
| 1810 | - }, | 1731 | + broadcasts.push(Broadcast::new(To::User(user_id.clone()), removed)); |
| 1811 | - user_ids: vec![user_id.clone()], | ||
| 1812 | - }); | ||
| 1813 | let event = Event::MemberLeft { | 1732 | let event = Event::MemberLeft { |
| 1814 | - community_id, | 1733 | + community_id: community_id.clone(), |
| 1815 | user_id, | 1734 | user_id, |
| 1816 | }; | 1735 | }; |
| 1817 | - broadcasts.push(broadcast(event, &members)); | 1736 | + broadcasts.push(Broadcast::new(To::Community(community_id), event)); |
| 1818 | 1737 | ||
| 1819 | Ok((Response::Done, broadcasts)) | 1738 | Ok((Response::Done, broadcasts)) |
| 1820 | } | 1739 | } |
| 1821 | 1740 | ||
| 1822 | -async fn related_user_ids(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | 1741 | +fn user_updated(user: &User) -> Vec<Broadcast> { |
| 1823 | - let mut user_ids = BTreeSet::from([user_id.to_string()]); | 1742 | + vec![Broadcast::new( |
| 1824 | - for community in community::communities_of(user_id, conn).await? { | 1743 | + To::Related(user.id.clone()), |
| 1825 | - for member in user_community::members(&community.id, conn).await? { | 1744 | + Event::UserUpdated(user.clone()), |
| 1826 | - user_ids.insert(member.user.id); | 1745 | + )] |
| 1827 | - } | ||
| 1828 | - } | ||
| 1829 | - for friend in friend::state(user_id, conn).await?.friends { | ||
| 1830 | - user_ids.insert(friend.id); | ||
| 1831 | - } | ||
| 1832 | - | ||
| 1833 | - Ok(user_ids.into_iter().collect()) | ||
| 1834 | -} | ||
| 1835 | - | ||
| 1836 | -async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, ServerError> { | ||
| 1837 | - Ok(vec![Broadcast { | ||
| 1838 | - event: Event::UserUpdated(user.clone()), | ||
| 1839 | - user_ids: related_user_ids(&user.id, conn).await?, | ||
| 1840 | - }]) | ||
| 1841 | } | 1746 | } |
| 1842 | 1747 | ||
| 1843 | async fn effective_presence( | 1748 | async fn effective_presence( |
| 1844 | - presence: &network::Presence, | 1749 | + hub: &Hub, |
| 1845 | user_id: &str, | 1750 | user_id: &str, |
| 1846 | conn: &Connection, | 1751 | conn: &Connection, |
| 1847 | ) -> Result<Presence, ServerError> { | 1752 | ) -> Result<Presence, ServerError> { |
| 1848 | - if !presence.is_online(user_id) { | 1753 | + if !hub.is_online(user_id) { |
| 1849 | return Ok(Presence::Offline); | 1754 | return Ok(Presence::Offline); |
| 1850 | } | 1755 | } |
| 1851 | 1756 | ||
| @@ -1853,19 +1758,21 @@ async fn effective_presence( | |||
| 1853 | } | 1758 | } |
| 1854 | 1759 | ||
| 1855 | pub async fn presence_changed( | 1760 | pub async fn presence_changed( |
| 1856 | - presence: &network::Presence, | 1761 | + hub: &Hub, |
| 1857 | user_id: &str, | 1762 | user_id: &str, |
| 1858 | conn: &Connection, | 1763 | conn: &Connection, |
| 1859 | ) -> Result<Vec<Broadcast>, ServerError> { | 1764 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1860 | - let presence = effective_presence(presence, user_id, conn).await?; | 1765 | + let presence = effective_presence(hub, user_id, conn).await?; |
| 1861 | 1766 | ||
| 1862 | - Ok(vec![Broadcast { | 1767 | + let event = Event::PresenceChanged { |
| 1863 | - event: Event::PresenceChanged { | 1768 | + user_id: user_id.to_string(), |
| 1864 | - user_id: user_id.to_string(), | 1769 | + presence, |
| 1865 | - presence, | 1770 | + }; |
| 1866 | - }, | 1771 | + |
| 1867 | - user_ids: related_user_ids(user_id, conn).await?, | 1772 | + Ok(vec![Broadcast::new( |
| 1868 | - }]) | 1773 | + To::Related(user_id.to_string()), |
| 1774 | + event, | ||
| 1775 | + )]) | ||
| 1869 | } | 1776 | } |
| 1870 | 1777 | ||
| 1871 | async fn friends_updated( | 1778 | async fn friends_updated( |
| @@ -1874,132 +1781,110 @@ async fn friends_updated( | |||
| 1874 | ) -> Result<Vec<Broadcast>, ServerError> { | 1781 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1875 | let mut broadcasts = Vec::new(); | 1782 | let mut broadcasts = Vec::new(); |
| 1876 | for user_id in user_ids { | 1783 | for user_id in user_ids { |
| 1877 | - broadcasts.push(Broadcast { | 1784 | + let event = Event::FriendsUpdated(friend::state(user_id, conn).await?); |
| 1878 | - event: Event::FriendsUpdated(friend::state(user_id, conn).await?), | 1785 | + broadcasts.push(Broadcast::new(To::User(user_id.to_string()), event)); |
| 1879 | - user_ids: vec![user_id.to_string()], | ||
| 1880 | - }); | ||
| 1881 | } | 1786 | } |
| 1882 | 1787 | ||
| 1883 | Ok(broadcasts) | 1788 | Ok(broadcasts) |
| 1884 | } | 1789 | } |
| 1885 | 1790 | ||
| 1886 | async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, ServerError> { | 1791 | async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, ServerError> { |
| 1887 | - Ok(Broadcast { | 1792 | + let event = Event::InvitationsUpdated(invitation::of(user_id, conn).await?); |
| 1888 | - event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?), | 1793 | + |
| 1889 | - user_ids: vec![user_id.to_string()], | 1794 | + Ok(Broadcast::new(To::User(user_id.to_string()), event)) |
| 1890 | - }) | ||
| 1891 | } | 1795 | } |
| 1892 | 1796 | ||
| 1893 | async fn leave_user_voice( | 1797 | async fn leave_user_voice( |
| 1894 | - voice: &Voice, | 1798 | + rooms: &Rooms, |
| 1895 | - share: &Shares, | ||
| 1896 | user_id: &str, | 1799 | user_id: &str, |
| 1897 | conn: &Connection, | 1800 | conn: &Connection, |
| 1898 | ) -> Result<Vec<Broadcast>, ServerError> { | 1801 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1899 | - match voice.leave(user_id) { | 1802 | + match rooms.leave_user(user_id) { |
| 1900 | - Some(left) => voice_left(share, left, conn).await, | 1803 | + Some(departure) => departed(departure, conn).await, |
| 1901 | - None => Ok(Vec::new()), | ||
| 1902 | - } | ||
| 1903 | -} | ||
| 1904 | - | ||
| 1905 | -pub async fn leave_connection_voice( | ||
| 1906 | - voice: &Voice, | ||
| 1907 | - share: &Shares, | ||
| 1908 | - connection: Option<&quinn::Connection>, | ||
| 1909 | - conn: &Connection, | ||
| 1910 | -) -> Result<Vec<Broadcast>, ServerError> { | ||
| 1911 | - match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { | ||
| 1912 | - Some(left) => voice_left(share, left, conn).await, | ||
| 1913 | None => Ok(Vec::new()), | 1804 | None => Ok(Vec::new()), |
| 1914 | } | 1805 | } |
| 1915 | } | 1806 | } |
| 1916 | 1807 | ||
| 1917 | async fn leave_room_voice( | 1808 | async fn leave_room_voice( |
| 1918 | - voice: &Voice, | 1809 | + rooms: &Rooms, |
| 1919 | - share: &Shares, | ||
| 1920 | community_id: &str, | 1810 | community_id: &str, |
| 1921 | user_id: &str, | 1811 | user_id: &str, |
| 1922 | conn: &Connection, | 1812 | conn: &Connection, |
| 1923 | ) -> Result<Vec<Broadcast>, ServerError> { | 1813 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1924 | - match voice.leave_room(community_id, user_id) { | 1814 | + match rooms.leave_room(community_id, user_id) { |
| 1925 | - Some(left) => voice_left(share, left, conn).await, | 1815 | + Some(departure) => departed(departure, conn).await, |
| 1926 | None => Ok(Vec::new()), | 1816 | None => Ok(Vec::new()), |
| 1927 | } | 1817 | } |
| 1928 | } | 1818 | } |
| 1929 | 1819 | ||
| 1930 | async fn voice_unmuted( | 1820 | async fn voice_unmuted( |
| 1931 | - voice: &Voice, | 1821 | + rooms: &Rooms, |
| 1932 | user_id: &str, | 1822 | user_id: &str, |
| 1933 | conn: &Connection, | 1823 | conn: &Connection, |
| 1934 | ) -> Result<Vec<Broadcast>, ServerError> { | 1824 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1935 | - let Some(community_id) = voice.set_muted(user_id, false) else { | 1825 | + let Some(community_id) = rooms.set_muted(user_id, false) else { |
| 1936 | return Ok(Vec::new()); | 1826 | return Ok(Vec::new()); |
| 1937 | }; | 1827 | }; |
| 1828 | + | ||
| 1829 | + Ok(vec![ | ||
| 1830 | + voice_muted(Some(community_id), user_id, false, conn).await?, | ||
| 1831 | + ]) | ||
| 1832 | +} | ||
| 1833 | + | ||
| 1834 | +async fn voice_muted( | ||
| 1835 | + community_id: Option<String>, | ||
| 1836 | + user_id: &str, | ||
| 1837 | + muted: bool, | ||
| 1838 | + conn: &Connection, | ||
| 1839 | +) -> Result<Broadcast, ServerError> { | ||
| 1938 | let mut user_ids = vec![user_id.to_string()]; | 1840 | let mut user_ids = vec![user_id.to_string()]; |
| 1939 | - if !user::is_ghost(user_id, conn).await? { | 1841 | + if let Some(community_id) = &community_id |
| 1940 | - user_ids.extend( | 1842 | + && !user::is_ghost(user_id, conn).await? |
| 1941 | - user_community::members(&community_id, conn) | 1843 | + { |
| 1942 | - .await? | 1844 | + user_ids.extend(user_community::member_ids(community_id, conn).await?); |
| 1943 | - .into_iter() | ||
| 1944 | - .map(|member| member.user.id), | ||
| 1945 | - ); | ||
| 1946 | } | 1845 | } |
| 1846 | + let event = Event::VoiceMuted { | ||
| 1847 | + community_id, | ||
| 1848 | + user_id: user_id.to_string(), | ||
| 1849 | + muted, | ||
| 1850 | + }; | ||
| 1947 | 1851 | ||
| 1948 | - Ok(vec![Broadcast { | 1852 | + Ok(Broadcast::new(To::Users(user_ids), event)) |
| 1949 | - event: Event::VoiceMuted { | ||
| 1950 | - user_id: user_id.to_string(), | ||
| 1951 | - muted: false, | ||
| 1952 | - }, | ||
| 1953 | - user_ids, | ||
| 1954 | - }]) | ||
| 1955 | } | 1853 | } |
| 1956 | 1854 | ||
| 1957 | async fn voice_silenced( | 1855 | async fn voice_silenced( |
| 1958 | - voice: &Voice, | 1856 | + rooms: &Rooms, |
| 1959 | - share: &Shares, | ||
| 1960 | community_id: &str, | 1857 | community_id: &str, |
| 1961 | conn: &Connection, | 1858 | conn: &Connection, |
| 1962 | ) -> Result<Vec<Broadcast>, ServerError> { | 1859 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1963 | let mut broadcasts = Vec::new(); | 1860 | let mut broadcasts = Vec::new(); |
| 1964 | - for user_id in voice.room_users(community_id) { | 1861 | + for user_id in rooms.room_users(community_id) { |
| 1965 | if permission::is_builder(user::read(&user_id, conn).await?.role) { | 1862 | if permission::is_builder(user::read(&user_id, conn).await?.role) { |
| 1966 | continue; | 1863 | continue; |
| 1967 | } | 1864 | } |
| 1968 | - if let Some(left) = voice.leave_room(community_id, &user_id) { | 1865 | + broadcasts.extend(leave_room_voice(rooms, community_id, &user_id, conn).await?); |
| 1969 | - broadcasts.extend(voice_left(share, left, conn).await?); | ||
| 1970 | - } | ||
| 1971 | } | 1866 | } |
| 1972 | 1867 | ||
| 1973 | Ok(broadcasts) | 1868 | Ok(broadcasts) |
| 1974 | } | 1869 | } |
| 1975 | 1870 | ||
| 1976 | async fn voice_closed( | 1871 | async fn voice_closed( |
| 1977 | - voice: &Voice, | 1872 | + rooms: &Rooms, |
| 1978 | - share: &Shares, | ||
| 1979 | community_id: &str, | 1873 | community_id: &str, |
| 1980 | conn: &Connection, | 1874 | conn: &Connection, |
| 1981 | ) -> Result<Vec<Broadcast>, ServerError> { | 1875 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 1982 | let mut broadcasts = Vec::new(); | 1876 | let mut broadcasts = Vec::new(); |
| 1983 | - for left in voice.remove_room(community_id) { | 1877 | + for departure in rooms.close_room(community_id) { |
| 1984 | - broadcasts.extend(voice_left(share, left, conn).await?); | 1878 | + broadcasts.extend(departed(departure, conn).await?); |
| 1985 | } | 1879 | } |
| 1986 | 1880 | ||
| 1987 | Ok(broadcasts) | 1881 | Ok(broadcasts) |
| 1988 | } | 1882 | } |
| 1989 | 1883 | ||
| 1990 | -fn call_log_of(end: CallEnd) -> Option<CallLog> { | ||
| 1991 | - match end { | ||
| 1992 | - CallEnd::Answered { seconds } => Some(CallLog::Ended { seconds }), | ||
| 1993 | - CallEnd::Unanswered => Some(CallLog::Missed), | ||
| 1994 | - CallEnd::Declined => None, | ||
| 1995 | - } | ||
| 1996 | -} | ||
| 1997 | - | ||
| 1998 | async fn call_ended( | 1884 | async fn call_ended( |
| 1999 | community_id: &str, | 1885 | community_id: &str, |
| 2000 | user_id: &str, | 1886 | user_id: &str, |
| 2001 | - call: Option<CallEnd>, | 1887 | + call: Option<CallLog>, |
| 2002 | - members: &[Member], | ||
| 2003 | conn: &Connection, | 1888 | conn: &Connection, |
| 2004 | ) -> Result<Vec<Broadcast>, ServerError> { | 1889 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 2005 | let Some(call) = call else { | 1890 | let Some(call) = call else { |
| @@ -2008,140 +1893,70 @@ async fn call_ended( | |||
| 2008 | if !community::is_direct(community_id, conn).await? { | 1893 | if !community::is_direct(community_id, conn).await? { |
| 2009 | return Ok(Vec::new()); | 1894 | return Ok(Vec::new()); |
| 2010 | } | 1895 | } |
| 2011 | - let Some(call) = call_log_of(call) else { | ||
| 2012 | - return Ok(Vec::new()); | ||
| 2013 | - }; | ||
| 2014 | let created = message::create_call_log(community_id, user_id, call, conn).await?; | 1896 | let created = message::create_call_log(community_id, user_id, call, conn).await?; |
| 2015 | 1897 | ||
| 2016 | - Ok(vec![broadcast(Event::MessageCreated(created), members)]) | 1898 | + Ok(vec![message_event(&created, Event::MessageCreated)]) |
| 2017 | } | 1899 | } |
| 2018 | 1900 | ||
| 2019 | -async fn voice_left( | 1901 | +pub async fn departed( |
| 2020 | - share: &Shares, | 1902 | + mut departure: Departure, |
| 2021 | - left: Left, | ||
| 2022 | conn: &Connection, | 1903 | conn: &Connection, |
| 2023 | ) -> Result<Vec<Broadcast>, ServerError> { | 1904 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 2024 | - let mut broadcasts = share_left(share, &left.user_id, conn).await?; | 1905 | + let mut broadcasts = shares_ended(&mut departure); |
| 2025 | - let Some(seconds) = left.ghost_seconds else { | 1906 | + if departure.quiet { |
| 2026 | - let members = user_community::members(&left.community_id, conn).await?; | 1907 | + return Ok(broadcasts); |
| 2027 | - broadcasts.extend( | 1908 | + } |
| 2028 | - call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?, | 1909 | + let Departure { |
| 2029 | - ); | 1910 | + community_id, |
| 1911 | + user_id, | ||
| 1912 | + ghost_seconds, | ||
| 1913 | + call_log, | ||
| 1914 | + .. | ||
| 1915 | + } = departure; | ||
| 1916 | + let Some(seconds) = ghost_seconds else { | ||
| 1917 | + broadcasts.extend(call_ended(&community_id, &user_id, call_log, conn).await?); | ||
| 2030 | let event = Event::VoiceLeft { | 1918 | let event = Event::VoiceLeft { |
| 2031 | - community_id: left.community_id, | 1919 | + community_id: community_id.clone(), |
| 2032 | - user_id: left.user_id, | 1920 | + user_id, |
| 2033 | }; | 1921 | }; |
| 2034 | - broadcasts.push(broadcast(event, &members)); | 1922 | + broadcasts.push(Broadcast::new(To::Community(community_id), event)); |
| 2035 | 1923 | ||
| 2036 | return Ok(broadcasts); | 1924 | return Ok(broadcasts); |
| 2037 | }; | 1925 | }; |
| 2038 | - record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?; | 1926 | + record_ghost_voice(&user_id, &community_id, seconds, conn).await?; |
| 2039 | 1927 | ||
| 2040 | Ok(broadcasts) | 1928 | Ok(broadcasts) |
| 2041 | } | 1929 | } |
| 2042 | 1930 | ||
| 2043 | -async fn share_ended( | 1931 | +fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { |
| 2044 | - community_id: &str, | ||
| 2045 | - user_id: &str, | ||
| 2046 | - kind: Kind, | ||
| 2047 | - conn: &Connection, | ||
| 2048 | -) -> Result<Broadcast, ServerError> { | ||
| 2049 | - let members = user_community::members(community_id, conn).await?; | ||
| 2050 | let event = Event::ShareStopped { | 1932 | let event = Event::ShareStopped { |
| 2051 | community_id: community_id.to_string(), | 1933 | community_id: community_id.to_string(), |
| 2052 | user_id: user_id.to_string(), | 1934 | user_id: user_id.to_string(), |
| 2053 | kind, | 1935 | kind, |
| 2054 | }; | 1936 | }; |
| 2055 | 1937 | ||
| 2056 | - Ok(broadcast(event, &members)) | 1938 | + Broadcast::new(To::Community(community_id.to_string()), event) |
| 2057 | -} | ||
| 2058 | - | ||
| 2059 | -async fn share_stopped( | ||
| 2060 | - share: &Shares, | ||
| 2061 | - user_id: &str, | ||
| 2062 | - kind: Kind, | ||
| 2063 | - conn: &Connection, | ||
| 2064 | -) -> Result<Vec<Broadcast>, ServerError> { | ||
| 2065 | - let Some(community_id) = share.stop(user_id, kind) else { | ||
| 2066 | - return Ok(Vec::new()); | ||
| 2067 | - }; | ||
| 2068 | - | ||
| 2069 | - Ok(vec![share_ended(&community_id, user_id, kind, conn).await?]) | ||
| 2070 | -} | ||
| 2071 | - | ||
| 2072 | -async fn share_left( | ||
| 2073 | - share: &Shares, | ||
| 2074 | - user_id: &str, | ||
| 2075 | - conn: &Connection, | ||
| 2076 | -) -> Result<Vec<Broadcast>, ServerError> { | ||
| 2077 | - let mut broadcasts = Vec::new(); | ||
| 2078 | - for (community_id, kind) in share.stop_all(user_id) { | ||
| 2079 | - broadcasts.push(share_ended(&community_id, user_id, kind, conn).await?); | ||
| 2080 | - } | ||
| 2081 | - broadcasts.extend(share.leave_viewer(user_id)); | ||
| 2082 | - | ||
| 2083 | - Ok(broadcasts) | ||
| 2084 | } | 1939 | } |
| 2085 | 1940 | ||
| 2086 | -async fn enter( | 1941 | +fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> { |
| 2087 | - state: &Mutex<State>, | 1942 | + let mut broadcasts: Vec<Broadcast> = departure |
| 2088 | - user: User, | 1943 | + .shares |
| 2089 | - token: String, | 1944 | + .iter() |
| 2090 | - voice: &Voice, | 1945 | + .map(|kind| share_ended(&departure.community_id, &departure.user_id, *kind)) |
| 2091 | - share: &Shares, | 1946 | + .collect(); |
| 2092 | - connection: Option<&quinn::Connection>, | 1947 | + broadcasts.append(&mut departure.media); |
| 2093 | - conn: &Connection, | ||
| 2094 | -) -> Result<Outcome, ServerError> { | ||
| 2095 | - stats::mark_active(&user.id, conn).await?; | ||
| 2096 | - record_address(&user, connection, conn).await?; | ||
| 2097 | - let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; | ||
| 2098 | 1948 | ||
| 2099 | - Ok(sign_in(state, user, token, broadcasts)) | 1949 | + broadcasts |
| 2100 | -} | ||
| 2101 | - | ||
| 2102 | -fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome { | ||
| 2103 | - set_state( | ||
| 2104 | - state, | ||
| 2105 | - State::Authenticated { | ||
| 2106 | - user: user.clone(), | ||
| 2107 | - token: token.clone(), | ||
| 2108 | - }, | ||
| 2109 | - ); | ||
| 2110 | - | ||
| 2111 | - (Response::Session { user, token }, broadcasts) | ||
| 2112 | -} | ||
| 2113 | - | ||
| 2114 | -fn set_state(state: &Mutex<State>, new_state: State) { | ||
| 2115 | - *state.lock().unwrap() = new_state; | ||
| 2116 | -} | ||
| 2117 | - | ||
| 2118 | -fn session(state: &Mutex<State>) -> Result<(User, String), ServerError> { | ||
| 2119 | - match state.lock().unwrap().clone() { | ||
| 2120 | - State::Anonymous => Err(CommonError::Unauthenticated.into()), | ||
| 2121 | - State::Authenticated { user, token } => Ok((user, token)), | ||
| 2122 | - } | ||
| 2123 | } | 1950 | } |
| 2124 | 1951 | ||
| 2125 | -fn session_token(state: &Mutex<State>) -> Result<String, ServerError> { | ||
crates/server/src/retention.rsmodified+32 -16
| @@ -1,27 +1,26 @@ | |||
| 1 | -use std::{ | 1 | +use std::{collections::BTreeMap, path::Path, time::Duration}; |
| 2 | - path::{Path, PathBuf}, | ||
| 3 | - time::Duration, | ||
| 4 | -}; | ||
| 5 | 2 | ||
| 6 | -use common::time; | 3 | +use common::{event::Event, time}; |
| 7 | use tracing::{error, info}; | 4 | use tracing::{error, info}; |
| 8 | use turso::Connection; | 5 | use turso::Connection; |
| 9 | 6 | ||
| 10 | use crate::{ | 7 | use crate::{ |
| 11 | - attachment, | 8 | + attachment, database, |
| 12 | - database::{self, DB}, | ||
| 13 | error::ServerError, | 9 | error::ServerError, |
| 14 | - message, server_settings, | 10 | + message, |
| 11 | + network::Shared, | ||
| 12 | + publish::{Broadcast, To, publish}, | ||
| 13 | + server_settings, | ||
| 15 | }; | 14 | }; |
| 16 | 15 | ||
| 17 | const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); | 16 | const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); |
| 18 | const BATCH_SIZE: i64 = 500; | 17 | const BATCH_SIZE: i64 = 500; |
| 19 | 18 | ||
| 20 | -pub async fn collect(db: DB, directory: PathBuf) { | 19 | +pub(crate) async fn collect(shared: Shared) { |
| 21 | let mut interval = tokio::time::interval(SWEEP_INTERVAL); | 20 | let mut interval = tokio::time::interval(SWEEP_INTERVAL); |
| 22 | loop { | 21 | loop { |
| 23 | interval.tick().await; | 22 | interval.tick().await; |
| 24 | - if let Err(error) = sweep(&db, &directory).await { | 23 | + if let Err(error) = sweep(&shared).await { |
| 25 | error!("retention sweep: {error}"); | 24 | error!("retention sweep: {error}"); |
| 26 | } | 25 | } |
| 27 | } | 26 | } |
| @@ -50,7 +49,7 @@ async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result<Vec<Str | |||
| 50 | async fn purge_messages( | 49 | async fn purge_messages( |
| 51 | cutoff: &str, | 50 | cutoff: &str, |
| 52 | conn: &mut Connection, | 51 | conn: &mut Connection, |
| 53 | - directory: &Path, | 52 | + shared: &Shared, |
| 54 | ) -> Result<u64, ServerError> { | 53 | ) -> Result<u64, ServerError> { |
| 55 | let mut purged = 0; | 54 | let mut purged = 0; |
| 56 | loop { | 55 | loop { |
| @@ -61,12 +60,28 @@ async fn purge_messages( | |||
| 61 | 60 | ||
| 62 | let tx = conn.transaction().await?; | 61 | let tx = conn.transaction().await?; |
| 63 | let mut files = Vec::new(); | 62 | let mut files = Vec::new(); |
| 63 | + let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new(); | ||
| 64 | for id in &ids { | 64 | for id in &ids { |
| 65 | files.extend(attachment::ids_of_message(id, &tx).await?); | 65 | files.extend(attachment::ids_of_message(id, &tx).await?); |
| 66 | - message::delete(id, &tx).await?; | 66 | + let message = message::delete(id, &tx).await?; |
| 67 | + deleted | ||
| 68 | + .entry(message.community_id) | ||
| 69 | + .or_default() | ||
| 70 | + .push(message.id); | ||
| 67 | } | 71 | } |
| 68 | tx.commit().await?; | 72 | tx.commit().await?; |
| 69 | - attachment::remove_files(&files, directory); | 73 | + attachment::remove_files(&files, &shared.directory); |
| 74 | + let broadcasts = deleted | ||
| 75 | + .into_iter() | ||
| 76 | + .map(|(community_id, ids)| { | ||
| 77 | + let event = Event::MessagesDeleted { | ||
| 78 | + community_id: community_id.clone(), | ||
| 79 | + ids, | ||
| 80 | + }; | ||
| 81 | + Broadcast::new(To::Community(community_id), event) | ||
| 82 | + }) | ||
| 83 | + .collect(); | ||
| 84 | + publish(shared, broadcasts).await; | ||
| 70 | purged += ids.len() as u64; | 85 | purged += ids.len() as u64; |
| 71 | } | 86 | } |
| 72 | } | 87 | } |
| @@ -91,14 +106,15 @@ async fn purge_attachments( | |||
| 91 | } | 106 | } |
| 92 | } | 107 | } |
| 93 | 108 | ||
| 94 | -async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { | 109 | +async fn sweep(shared: &Shared) -> Result<(), ServerError> { |
| 95 | - let mut conn = database::connect(db).await?; | 110 | + let directory = &shared.directory; |
| 111 | + let mut conn = database::connect(&shared.db).await?; | ||
| 96 | let settings = server_settings::read(&conn).await?; | 112 | let settings = server_settings::read(&conn).await?; |
| 97 | let now = time::now_ms(); | 113 | let now = time::now_ms(); |
| 98 | 114 | ||
| 99 | let messages = match settings.message_retention_days { | 115 | let messages = match settings.message_retention_days { |
| 100 | 0 => 0, | 116 | 0 => 0, |
| 101 | - days => purge_messages(&cutoff(now, days), &mut conn, directory).await?, | 117 | + days => purge_messages(&cutoff(now, days), &mut conn, shared).await?, |
| 102 | }; | 118 | }; |
| 103 | let attachments = match settings.attachment_retention_days { | 119 | let attachments = match settings.attachment_retention_days { |
| 104 | 0 => 0, | 120 | 0 => 0, |
crates/server/src/rooms.rsadded+748 -0
| @@ -0,0 +1,748 @@ | |||
| 1 | +use std::{ | ||
| 2 | + collections::{BTreeMap, BTreeSet, HashMap}, | ||
| 3 | + sync::{Arc, Mutex, atomic::Ordering}, | ||
| 4 | + time::Instant, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use bytes::Bytes; | ||
| 8 | +use common::{ | ||
| 9 | + datagram::{Datagram, Fragment, encode_relay}, | ||
| 10 | + error::Error, | ||
| 11 | + event::{Event, Media}, | ||
| 12 | + model::CallLog, | ||
| 13 | + share::{Codec, Kind, Layer, Quality, Share, Source, choose}, | ||
| 14 | + time, | ||
| 15 | +}; | ||
| 16 | +use quinn::Connection; | ||
| 17 | + | ||
| 18 | +use crate::{ | ||
| 19 | + hub::{Client, ConnId}, | ||
| 20 | + publish::{Broadcast, To}, | ||
| 21 | +}; | ||
| 22 | + | ||
| 23 | +#[derive(Clone, Copy)] | ||
| 24 | +enum Forward { | ||
| 25 | + Waiting(Layer), | ||
| 26 | + Live(Layer), | ||
| 27 | + Switching { live: Layer, next: Layer }, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl Forward { | ||
| 31 | + fn target(self) -> Layer { | ||
| 32 | + match self { | ||
| 33 | + Self::Waiting(layer) | Self::Live(layer) => layer, | ||
| 34 | + Self::Switching { next, .. } => next, | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + fn layers(self) -> Vec<Layer> { | ||
| 39 | + match self { | ||
| 40 | + Self::Waiting(layer) | Self::Live(layer) => vec![layer], | ||
| 41 | + Self::Switching { live, next } => vec![live, next], | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + fn live(self) -> Option<Layer> { | ||
| 46 | + match self { | ||
| 47 | + Self::Waiting(_) => None, | ||
| 48 | + Self::Live(layer) | Self::Switching { live: layer, .. } => Some(layer), | ||
| 49 | + } | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + fn retarget(self, next: Layer) -> Self { | ||
| 53 | + match self { | ||
| 54 | + Self::Waiting(_) => Self::Waiting(next), | ||
| 55 | + Self::Live(live) | Self::Switching { live, .. } if live == next => Self::Live(live), | ||
| 56 | + Self::Live(live) | Self::Switching { live, .. } => Self::Switching { live, next }, | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + fn on_keyframe(self, layer: Layer) -> Self { | ||
| 61 | + match self { | ||
| 62 | + Self::Waiting(next) | Self::Switching { next, .. } if next == layer => { | ||
| 63 | + Self::Live(layer) | ||
| 64 | + } | ||
| 65 | + _ => self, | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +struct Viewer { | ||
| 71 | + user_id: String, | ||
| 72 | + connection: Connection, | ||
| 73 | + quality: Quality, | ||
| 74 | + decode: Vec<Codec>, | ||
| 75 | + forward: Forward, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +struct Sharing { | ||
| 79 | + source: Source, | ||
| 80 | + viewers: Vec<Viewer>, | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +impl Sharing { | ||
| 84 | + fn layers(&self) -> BTreeSet<Layer> { | ||
| 85 | + self.viewers | ||
| 86 | + .iter() | ||
| 87 | + .flat_map(|viewer| viewer.forward.layers()) | ||
| 88 | + .collect() | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + fn viewer(&self, user_id: &str) -> Option<&Viewer> { | ||
| 92 | + self.viewers.iter().find(|viewer| viewer.user_id == user_id) | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +fn layers_changed( | ||
| 97 | + sharer: ConnId, | ||
| 98 | + kind: Kind, | ||
| 99 | + sharing: &Sharing, | ||
| 100 | + before: BTreeSet<Layer>, | ||
| 101 | +) -> Option<Broadcast> { | ||
| 102 | + let after = sharing.layers(); | ||
| 103 | + | ||
| 104 | + (after != before).then(|| { | ||
| 105 | + Broadcast::media( | ||
| 106 | + sharer, | ||
| 107 | + Media::Layers { | ||
| 108 | + kind, | ||
| 109 | + layers: after.into_iter().collect(), | ||
| 110 | + }, | ||
| 111 | + ) | ||
| 112 | + }) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +struct Sharer<'a> { | ||
| 116 | + conn: ConnId, | ||
| 117 | + user_id: &'a str, | ||
| 118 | + community_id: &'a str, | ||
| 119 | + kind: Kind, | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> { | ||
| 123 | + let before = sharing.layers(); | ||
| 124 | + let Sharing { source, viewers } = sharing; | ||
| 125 | + let mut used: Vec<Layer> = Vec::new(); | ||
| 126 | + let mut keyframes = Vec::new(); | ||
| 127 | + let mut stopped = Vec::new(); | ||
| 128 | + viewers.retain_mut(|viewer| { | ||
| 129 | + let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { | ||
| 130 | + stopped.push(Broadcast::new( | ||
| 131 | + To::User(viewer.user_id.clone()), | ||
| 132 | + Event::ShareStopped { | ||
| 133 | + community_id: sharer.community_id.to_string(), | ||
| 134 | + user_id: sharer.user_id.to_string(), | ||
| 135 | + kind: sharer.kind, | ||
| 136 | + }, | ||
| 137 | + )); | ||
| 138 | + return false; | ||
| 139 | + }; | ||
| 140 | + if !used.contains(&layer) { | ||
| 141 | + used.push(layer); | ||
| 142 | + } | ||
| 143 | + if viewer.forward.target() != layer { | ||
| 144 | + keyframes.push(Broadcast::media( | ||
| 145 | + sharer.conn, | ||
| 146 | + Media::Keyframe { | ||
| 147 | + kind: sharer.kind, | ||
| 148 | + layer, | ||
| 149 | + }, | ||
| 150 | + )); | ||
| 151 | + } | ||
| 152 | + viewer.forward = viewer.forward.retarget(layer); | ||
| 153 | + | ||
| 154 | + true | ||
| 155 | + }); | ||
| 156 | + | ||
| 157 | + let mut broadcasts: Vec<Broadcast> = layers_changed(sharer.conn, sharer.kind, sharing, before) | ||
| 158 | + .into_iter() | ||
| 159 | + .collect(); | ||
| 160 | + broadcasts.extend(keyframes); | ||
| 161 | + broadcasts.extend(stopped); | ||
| 162 | + | ||
| 163 | + broadcasts | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +fn remove_viewer( | ||
| 167 | + sharer: ConnId, | ||
| 168 | + kind: Kind, | ||
| 169 | + sharing: &mut Sharing, | ||
| 170 | + viewer_id: &str, | ||
| 171 | +) -> Option<Broadcast> { | ||
| 172 | + let before = sharing.layers(); | ||
| 173 | + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 174 | + | ||
| 175 | + layers_changed(sharer, kind, sharing, before) | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +struct Seat { | ||
| 179 | + user_id: String, | ||
| 180 | + connection: Connection, | ||
| 181 | + muted: bool, | ||
| 182 | + ghost: bool, | ||
| 183 | + joined_at: Instant, | ||
| 184 | + shares: BTreeMap<Kind, Sharing>, | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +enum Outcome { | ||
| 188 | + Ringing, | ||
| 189 | + Declined, | ||
| 190 | + Answered, | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +struct Room { | ||
| 194 | + seats: HashMap<ConnId, Seat>, | ||
| 195 | + started_ms: u64, | ||
| 196 | + outcome: Outcome, | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +impl Room { | ||
| 200 | + fn new() -> Self { | ||
| 201 | + Self { | ||
| 202 | + seats: HashMap::new(), | ||
| 203 | + started_ms: time::now_ms(), | ||
| 204 | + outcome: Outcome::Ringing, | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + fn occupied(&self) -> bool { | ||
| 209 | + self.seats.values().any(|seat| !seat.ghost) | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec<String> { | ||
| 213 | + self.seats | ||
| 214 | + .values() | ||
| 215 | + .filter(|seat| keep(seat)) | ||
| 216 | + .map(|seat| seat.user_id.clone()) | ||
| 217 | + .collect() | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + fn admit(&mut self) { | ||
| 221 | + if self.occupied() { | ||
| 222 | + self.outcome = Outcome::Answered; | ||
| 223 | + } else { | ||
| 224 | + self.started_ms = time::now_ms(); | ||
| 225 | + self.outcome = Outcome::Ringing; | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + fn call_log(&self) -> Option<CallLog> { | ||
| 230 | + match self.outcome { | ||
| 231 | + Outcome::Answered => Some(CallLog::Ended { | ||
| 232 | + seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, | ||
| 233 | + }), | ||
| 234 | + Outcome::Declined => None, | ||
| 235 | + Outcome::Ringing => Some(CallLog::Missed), | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + fn drop_viewer(&mut self, user_id: &str) -> Vec<Broadcast> { | ||
| 240 | + let mut broadcasts = Vec::new(); | ||
| 241 | + for (conn, seat) in &mut self.seats { | ||
| 242 | + for (kind, sharing) in &mut seat.shares { | ||
| 243 | + broadcasts.extend(remove_viewer(*conn, *kind, sharing, user_id)); | ||
| 244 | + } | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + broadcasts | ||
| 248 | + } | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +pub struct Departure { | ||
| 252 | + pub community_id: String, | ||
| 253 | + pub user_id: String, | ||
| 254 | + pub ghost_seconds: Option<u64>, | ||
| 255 | + pub call_log: Option<CallLog>, | ||
| 256 | + pub shares: Vec<Kind>, | ||
| 257 | + pub media: Vec<Broadcast>, | ||
| 258 | + pub quiet: bool, | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +pub struct Joined { | ||
| 262 | + pub departure: Option<Departure>, | ||
| 263 | + pub transferred: bool, | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +#[derive(Default)] | ||
| 267 | +struct Inner { | ||
| 268 | + rooms: HashMap<String, Room>, | ||
| 269 | + seat_of: HashMap<ConnId, String>, | ||
| 270 | + conn_of_user: HashMap<String, ConnId>, | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +impl Inner { | ||
| 274 | + fn seat_conn(&self, user_id: &str) -> Option<ConnId> { | ||
| 275 | + self.conn_of_user.get(user_id).copied() | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + fn seat_mut(&mut self, id: ConnId) -> Option<(&str, &mut Room)> { | ||
| 279 | + let community_id = self.seat_of.get(&id)?; | ||
| 280 | + | ||
| 281 | + Some((community_id.as_str(), self.rooms.get_mut(community_id)?)) | ||
| 282 | + } | ||
| 283 | + | ||
| 284 | + fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option<Departure> { | ||
| 285 | + let community_id = self.seat_of.remove(&id)?; | ||
| 286 | + let room = self.rooms.get_mut(&community_id)?; | ||
| 287 | + let seat = room.seats.remove(&id)?; | ||
| 288 | + if self.conn_of_user.get(&seat.user_id) == Some(&id) { | ||
| 289 | + self.conn_of_user.remove(&seat.user_id); | ||
| 290 | + } | ||
| 291 | + let mut media = room.drop_viewer(&seat.user_id); | ||
| 292 | + let call_log = (!quiet && !seat.ghost && !room.occupied()) | ||
| 293 | + .then(|| room.call_log()) | ||
| 294 | + .flatten(); | ||
| 295 | + if !quiet && room.seats.is_empty() { | ||
| 296 | + self.rooms.remove(&community_id); | ||
| 297 | + } | ||
| 298 | + if notify { | ||
| 299 | + media.push(Broadcast::media(id, Media::VoiceEnded)); | ||
| 300 | + } | ||
| 301 | + | ||
| 302 | + Some(Departure { | ||
| 303 | + community_id, | ||
| 304 | + ghost_seconds: seat.ghost.then(|| seat.joined_at.elapsed().as_secs()), | ||
| 305 | + user_id: seat.user_id, | ||
| 306 | + call_log, | ||
| 307 | + shares: seat.shares.keys().copied().collect(), | ||
| 308 | + media, | ||
| 309 | + quiet, | ||
| 310 | + }) | ||
| 311 | + } | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +#[derive(Clone, Default)] | ||
| 315 | +pub struct Rooms(Arc<Mutex<Inner>>); | ||
| 316 | + | ||
| 317 | +impl Rooms { | ||
| 318 | + pub fn join( | ||
| 319 | + &self, | ||
| 320 | + client: &Client, | ||
| 321 | + community_id: &str, | ||
| 322 | + muted: bool, | ||
| 323 | + ghost: bool, | ||
| 324 | + ) -> Result<Joined, Error> { | ||
| 325 | + let connection = client.conn.clone().ok_or(Error::Server)?; | ||
| 326 | + let user_id = client.user_id().ok_or(Error::Unauthenticated)?; | ||
| 327 | + let mut inner = self.0.lock().unwrap(); | ||
| 328 | + if client.closed.load(Ordering::Acquire) { | ||
| 329 | + return Err(Error::Server); | ||
| 330 | + } | ||
| 331 | + let mut departure = None; | ||
| 332 | + let mut transferred = false; | ||
| 333 | + let mut joined_at = Instant::now(); | ||
| 334 | + if let Some(previous) = inner.seat_conn(user_id) { | ||
| 335 | + let same_room = inner.seat_of.get(&previous).map(String::as_str) == Some(community_id); | ||
| 336 | + let kept_ghost = inner | ||
| 337 | + .rooms | ||
| 338 | + .get(community_id) | ||
| 339 | + .and_then(|room| room.seats.get(&previous)) | ||
| 340 | + .map(|seat| (seat.ghost, seat.joined_at)); | ||
| 341 | + transferred = same_room && kept_ghost.is_some_and(|(was, _)| was == ghost); | ||
| 342 | + if let (true, Some((_, at))) = (transferred, kept_ghost) { | ||
| 343 | + joined_at = at; | ||
| 344 | + } | ||
| 345 | + departure = inner.take(previous, previous != client.id, transferred); | ||
| 346 | + } | ||
| 347 | + let room = inner | ||
| 348 | + .rooms | ||
| 349 | + .entry(community_id.to_string()) | ||
| 350 | + .or_insert_with(Room::new); | ||
| 351 | + if !ghost && !transferred { | ||
| 352 | + room.admit(); | ||
| 353 | + } | ||
| 354 | + room.seats.insert( | ||
| 355 | + client.id, | ||
| 356 | + Seat { | ||
| 357 | + user_id: user_id.to_string(), | ||
| 358 | + connection, | ||
| 359 | + muted, | ||
| 360 | + ghost, | ||
| 361 | + joined_at, | ||
| 362 | + shares: BTreeMap::new(), | ||
| 363 | + }, | ||
| 364 | + ); | ||
| 365 | + inner.seat_of.insert(client.id, community_id.to_string()); | ||
| 366 | + inner.conn_of_user.insert(user_id.to_string(), client.id); | ||
| 367 | + | ||
| 368 | + Ok(Joined { | ||
| 369 | + departure, | ||
| 370 | + transferred, | ||
| 371 | + }) | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + pub fn leave(&self, id: ConnId) -> Option<Departure> { | ||
| 375 | + self.0.lock().unwrap().take(id, false, false) | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + pub fn leave_user(&self, user_id: &str) -> Option<Departure> { | ||
| 379 | + let mut inner = self.0.lock().unwrap(); | ||
| 380 | + let id = inner.seat_conn(user_id)?; | ||
| 381 | + | ||
| 382 | + inner.take(id, true, false) | ||
| 383 | + } | ||
| 384 | + | ||
| 385 | + pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option<Departure> { | ||
| 386 | + let mut inner = self.0.lock().unwrap(); | ||
| 387 | + let id = inner.seat_conn(user_id)?; | ||
| 388 | + if inner.seat_of.get(&id).map(String::as_str) != Some(community_id) { | ||
| 389 | + return None; | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + inner.take(id, true, false) | ||
| 393 | + } | ||
| 394 | + | ||
| 395 | + pub fn close_room(&self, community_id: &str) -> Vec<Departure> { | ||
| 396 | + let mut inner = self.0.lock().unwrap(); | ||
| 397 | + let Some(room) = inner.rooms.get(community_id) else { | ||
| 398 | + return Vec::new(); | ||
| 399 | + }; | ||
| 400 | + let ids: Vec<ConnId> = room.seats.keys().copied().collect(); | ||
| 401 | + let mut departures: Vec<Departure> = ids | ||
| 402 | + .into_iter() | ||
| 403 | + .filter_map(|id| inner.take(id, true, false)) | ||
| 404 | + .collect(); | ||
| 405 | + for departure in &mut departures { | ||
| 406 | + departure.call_log = None; | ||
| 407 | + } | ||
| 408 | + | ||
| 409 | + departures | ||
| 410 | + } | ||
| 411 | + | ||
| 412 | + pub fn decline(&self, community_id: &str) { | ||
| 413 | + if let Some(room) = self.0.lock().unwrap().rooms.get_mut(community_id) | ||
| 414 | + && matches!(room.outcome, Outcome::Ringing) | ||
| 415 | + { | ||
| 416 | + room.outcome = Outcome::Declined; | ||
| 417 | + } | ||
| 418 | + } | ||
| 419 | + | ||
| 420 | + pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> { | ||
| 421 | + let mut inner = self.0.lock().unwrap(); | ||
| 422 | + let id = inner.seat_conn(user_id)?; | ||
| 423 | + let (community_id, room) = inner.seat_mut(id)?; | ||
| 424 | + let community_id = community_id.to_string(); | ||
| 425 | + room.seats.get_mut(&id)?.muted = muted; | ||
| 426 | + | ||
| 427 | + Some(community_id) | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Departure> { | ||
| 431 | + let mut inner = self.0.lock().unwrap(); | ||
| 432 | + let id = inner.seat_conn(user_id)?; | ||
| 433 | + let (community_id, room) = inner.seat_mut(id)?; | ||
| 434 | + let community_id = community_id.to_string(); | ||
| 435 | + if room.seats.get(&id)?.ghost == ghost { | ||
| 436 | + return None; | ||
| 437 | + } | ||
| 438 | + if !ghost { | ||
| 439 | + room.admit(); | ||
| 440 | + } | ||
| 441 | + let seat = room.seats.get_mut(&id)?; | ||
| 442 | + let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs()); | ||
| 443 | + seat.ghost = ghost; | ||
| 444 | + seat.joined_at = Instant::now(); | ||
| 445 | + let shares: Vec<Kind> = if ghost { | ||
| 446 | + std::mem::take(&mut seat.shares).into_keys().collect() | ||
| 447 | + } else { | ||
| 448 | + Vec::new() | ||
| 449 | + }; | ||
| 450 | + let media = if ghost { | ||
| 451 | + room.drop_viewer(user_id) | ||
| 452 | + } else { | ||
| 453 | + Vec::new() | ||
| 454 | + }; | ||
| 455 | + let call_log = (ghost && !room.occupied()) | ||
| 456 | + .then(|| room.call_log()) | ||
| 457 | + .flatten(); | ||
| 458 | + | ||
| 459 | + Some(Departure { | ||
| 460 | + community_id, | ||
| 461 | + user_id: user_id.to_string(), | ||
| 462 | + ghost_seconds, | ||
| 463 | + call_log, | ||
| 464 | + shares, | ||
| 465 | + media, | ||
| 466 | + quiet: false, | ||
| 467 | + }) | ||
| 468 | + } | ||
| 469 | + | ||
| 470 | + pub fn room_of(&self, user_id: &str) -> Option<String> { | ||
| 471 | + let inner = self.0.lock().unwrap(); | ||
| 472 | + | ||
| 473 | + inner.seat_of.get(&inner.seat_conn(user_id)?).cloned() | ||
| 474 | + } | ||
| 475 | + | ||
| 476 | + pub fn room_of_conn(&self, id: ConnId) -> Option<String> { | ||
| 477 | + self.0.lock().unwrap().seat_of.get(&id).cloned() | ||
| 478 | + } | ||
| 479 | + | ||
| 480 | + pub fn room_users(&self, community_id: &str) -> Vec<String> { | ||
| 481 | + self.0 | ||
| 482 | + .lock() | ||
| 483 | + .unwrap() | ||
| 484 | + .rooms | ||
| 485 | + .get(community_id) | ||
| 486 | + .map(|room| room.user_ids(|_| true)) | ||
| 487 | + .unwrap_or_default() | ||
| 488 | + } | ||
| 489 | + | ||
| 490 | + pub fn participants(&self, community_id: &str) -> Vec<String> { | ||
| 491 | + self.0 | ||
| 492 | + .lock() | ||
| 493 | + .unwrap() | ||
| 494 | + .rooms | ||
| 495 | + .get(community_id) | ||
| 496 | + .map(|room| room.user_ids(|seat| !seat.ghost)) | ||
| 497 | + .unwrap_or_default() | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + pub fn count(&self) -> usize { | ||
| 501 | + self.0.lock().unwrap().seat_of.len() | ||
| 502 | + } | ||
| 503 | + | ||
| 504 | + pub fn list(&self) -> Vec<(String, Vec<String>, Vec<String>)> { | ||
| 505 | + self.0 | ||
| 506 | + .lock() | ||
| 507 | + .unwrap() | ||
| 508 | + .rooms | ||
| 509 | + .iter() | ||
| 510 | + .map(|(community_id, room)| { | ||
| 511 | + ( | ||
| 512 | + community_id.clone(), | ||
| 513 | + room.user_ids(|_| true), | ||
| 514 | + room.user_ids(|seat| seat.ghost), | ||
| 515 | + ) | ||
| 516 | + }) | ||
| 517 | + .collect() | ||
| 518 | + } | ||
| 519 | + | ||
| 520 | + pub fn shares(&self, community_id: &str) -> Vec<Share> { | ||
| 521 | + let inner = self.0.lock().unwrap(); | ||
| 522 | + let Some(room) = inner.rooms.get(community_id) else { | ||
| 523 | + return Vec::new(); | ||
| 524 | + }; | ||
| 525 | + | ||
| 526 | + room.seats | ||
| 527 | + .values() | ||
| 528 | + .flat_map(|seat| { | ||
| 529 | + seat.shares.iter().map(|(kind, sharing)| Share { | ||
| 530 | + user_id: seat.user_id.clone(), | ||
| 531 | + kind: *kind, | ||
| 532 | + source: sharing.source.clone(), | ||
| 533 | + }) | ||
| 534 | + }) | ||
| 535 | + .collect() | ||
| 536 | + } | ||
| 537 | + | ||
| 538 | + pub fn start_share(&self, id: ConnId, kind: Kind, source: Source) -> Option<Vec<Broadcast>> { | ||
| 539 | + let mut inner = self.0.lock().unwrap(); | ||
| 540 | + let (community_id, room) = inner.seat_mut(id)?; | ||
| 541 | + let community_id = community_id.to_string(); | ||
| 542 | + let seat = room.seats.get_mut(&id)?; | ||
| 543 | + let user_id = seat.user_id.clone(); | ||
| 544 | + let sharer = Sharer { | ||
| 545 | + conn: id, | ||
| 546 | + user_id: &user_id, | ||
| 547 | + community_id: &community_id, | ||
| 548 | + kind, | ||
| 549 | + }; | ||
| 550 | + if let Some(sharing) = seat.shares.get_mut(&kind) { | ||
| 551 | + sharing.source = source; | ||
| 552 | + return Some(reroute(&sharer, sharing)); | ||
| 553 | + } | ||
| 554 | + seat.shares.insert( | ||
| 555 | + kind, | ||
| 556 | + Sharing { | ||
| 557 | + source, | ||
| 558 | + viewers: Vec::new(), | ||
| 559 | + }, | ||
| 560 | + ); | ||
| 561 | + | ||
| 562 | + Some(Vec::new()) | ||
| 563 | + } | ||
| 564 | + | ||
| 565 | + pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option<String> { | ||
| 566 | + let mut inner = self.0.lock().unwrap(); | ||
| 567 | + let (community_id, room) = inner.seat_mut(id)?; | ||
| 568 | + let community_id = community_id.to_string(); | ||
| 569 | + room.seats.get_mut(&id)?.shares.remove(&kind)?; | ||
| 570 | + | ||
| 571 | + Some(community_id) | ||
| 572 | + } | ||
| 573 | + | ||
| 574 | + pub fn watch( | ||
| 575 | + &self, | ||
| 576 | + id: ConnId, | ||
| 577 | + sharer_id: &str, | ||
| 578 | + kind: Kind, | ||
| 579 | + quality: Quality, | ||
| 580 | + decode: &[Codec], | ||
| 581 | + ) -> Option<Vec<Broadcast>> { | ||
| 582 | + let mut inner = self.0.lock().unwrap(); | ||
| 583 | + let sharer_conn = inner.seat_conn(sharer_id)?; | ||
| 584 | + let (_, room) = inner.seat_mut(id)?; | ||
| 585 | + let viewer_seat = room.seats.get(&id)?; | ||
| 586 | + let (viewer_id, connection) = (viewer_seat.user_id.clone(), viewer_seat.connection.clone()); | ||
| 587 | + let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; | ||
| 588 | + let before = sharing.layers(); | ||
| 589 | + let used: Vec<Layer> = before.iter().copied().collect(); | ||
| 590 | + let layer = choose(&sharing.source, quality, decode, &used)?; | ||
| 591 | + let forward = sharing | ||
| 592 | + .viewer(&viewer_id) | ||
| 593 | + .map_or(Forward::Waiting(layer), |viewer| { | ||
| 594 | + viewer.forward.retarget(layer) | ||
| 595 | + }); | ||
| 596 | + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 597 | + sharing.viewers.push(Viewer { | ||
| 598 | + user_id: viewer_id, | ||
| 599 | + connection, | ||
| 600 | + quality, | ||
| 601 | + decode: decode.to_vec(), | ||
| 602 | + forward, | ||
| 603 | + }); | ||
| 604 | + let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_conn, kind, sharing, before) | ||
| 605 | + .into_iter() | ||
| 606 | + .collect(); | ||
| 607 | + broadcasts.push(Broadcast::media( | ||
| 608 | + sharer_conn, | ||
| 609 | + Media::Keyframe { kind, layer }, | ||
| 610 | + )); | ||
| 611 | + | ||
| 612 | + Some(broadcasts) | ||
| 613 | + } | ||
| 614 | + | ||
| 615 | + pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Vec<Broadcast> { | ||
| 616 | + let mut inner = self.0.lock().unwrap(); | ||
| 617 | + let Some(sharer_conn) = inner.seat_conn(sharer_id) else { | ||
| 618 | + return Vec::new(); | ||
| 619 | + }; | ||
| 620 | + let Some((_, room)) = inner.seat_mut(id) else { | ||
| 621 | + return Vec::new(); | ||
| 622 | + }; | ||
| 623 | + let Some(viewer_id) = room.seats.get(&id).map(|seat| seat.user_id.clone()) else { | ||
| 624 | + return Vec::new(); | ||
| 625 | + }; | ||
| 626 | + | ||
| 627 | + room.seats | ||
| 628 | + .get_mut(&sharer_conn) | ||
| 629 | + .and_then(|seat| seat.shares.get_mut(&kind)) | ||
| 630 | + .and_then(|sharing| remove_viewer(sharer_conn, kind, sharing, &viewer_id)) | ||
| 631 | + .into_iter() | ||
| 632 | + .collect() | ||
| 633 | + } | ||
| 634 | + | ||
| 635 | + pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> { | ||
| 636 | + let mut inner = self.0.lock().unwrap(); | ||
| 637 | + let sharer_conn = inner.seat_conn(sharer_id)?; | ||
| 638 | + let (_, room) = inner.seat_mut(id)?; | ||
| 639 | + let viewer_id = room.seats.get(&id)?.user_id.clone(); | ||
| 640 | + let viewer = room | ||
| 641 | + .seats | ||
| 642 | + .get(&sharer_conn)? | ||
| 643 | + .shares | ||
| 644 | + .get(&kind)? | ||
| 645 | + .viewer(&viewer_id)?; | ||
| 646 | + | ||
| 647 | + Some(Broadcast::media( | ||
| 648 | + sharer_conn, | ||
| 649 | + Media::Keyframe { | ||
| 650 | + kind, | ||
| 651 | + layer: viewer.forward.target(), | ||
| 652 | + }, | ||
| 653 | + )) | ||
| 654 | + } | ||
| 655 | + | ||
| 656 | + pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec<Broadcast> { | ||
| 657 | + if from.me.is_none() { | ||
| 658 | + return Vec::new(); | ||
| 659 | + } | ||
| 660 | + let Some(datagram) = Datagram::decode(packet) else { | ||
| 661 | + return Vec::new(); | ||
| 662 | + }; | ||
| 663 | + let mut inner = self.0.lock().unwrap(); | ||
| 664 | + let Some((_, room)) = inner.seat_mut(from.id) else { | ||
| 665 | + return Vec::new(); | ||
| 666 | + }; | ||
| 667 | + match datagram { | ||
| 668 | + Datagram::Voice { sequence, .. } => relay_voice(room, from.id, sequence, packet), | ||
| 669 | + Datagram::ShareAudio { .. } => relay_share_audio(room, from.id, packet), | ||
| 670 | + Datagram::Video(fragment) => relay_video(room, from.id, &fragment, packet), | ||
| 671 | + } | ||
| 672 | + } | ||
| 673 | +} | ||
| 674 | + | ||
| 675 | +fn relay_voice(room: &Room, id: ConnId, sequence: u32, packet: &[u8]) -> Vec<Broadcast> { | ||
| 676 | + let Some(sender) = room.seats.get(&id) else { | ||
| 677 | + return Vec::new(); | ||
| 678 | + }; | ||
| 679 | + if sender.muted { | ||
| 680 | + return Vec::new(); | ||
| 681 | + } | ||
| 682 | + let (Some(relay), Some(echo)) = ( | ||
| 683 | + encode_relay(&sender.user_id, packet), | ||
| 684 | + encode_relay( | ||
| 685 | + &sender.user_id, | ||
| 686 | + &Datagram::Voice { | ||
| 687 | + sequence, | ||
| 688 | + payload: &[], | ||
| 689 | + } | ||
| 690 | + .encode(), | ||
| 691 | + ), | ||
| 692 | + ) else { | ||
| 693 | + return Vec::new(); | ||
| 694 | + }; | ||
| 695 | + let _ = sender.connection.send_datagram(Bytes::from(echo)); | ||
| 696 | + let bytes = Bytes::from(relay); | ||
| 697 | + for (other_id, seat) in &room.seats { | ||
| 698 | + if *other_id != id { | ||
| 699 | + let _ = seat.connection.send_datagram(bytes.clone()); | ||
| 700 | + } | ||
| 701 | + } | ||
| 702 | + | ||
| 703 | + Vec::new() | ||
| 704 | +} | ||
| 705 | + | ||
| 706 | +fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) -> Vec<Broadcast> { | ||
| 707 | + let Some(seat) = room.seats.get(&id) else { | ||
| 708 | + return Vec::new(); | ||
| 709 | + }; | ||
| 710 | + let Some(sharing) = seat.shares.get(&Kind::Screen) else { | ||
| 711 | + return Vec::new(); | ||
| 712 | + }; | ||
| 713 | + let Some(relay) = encode_relay(&seat.user_id, packet) else { | ||
| 714 | + return Vec::new(); | ||
| 715 | + }; | ||
| 716 | + let bytes = Bytes::from(relay); | ||
| 717 | + for viewer in &sharing.viewers { | ||
| 718 | + let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 719 | + } | ||
| 720 | + | ||
| 721 | + Vec::new() | ||
| 722 | +} | ||
| 723 | + | ||
| 724 | +fn relay_video(room: &mut Room, id: ConnId, fragment: &Fragment, packet: &[u8]) -> Vec<Broadcast> { | ||
| 725 | + let Some(seat) = room.seats.get_mut(&id) else { | ||
| 726 | + return Vec::new(); | ||
| 727 | + }; | ||
| 728 | + let Some(sharing) = seat.shares.get_mut(&fragment.kind) else { | ||
| 729 | + return Vec::new(); | ||
| 730 | + }; | ||
| 731 | + let Some(relay) = encode_relay(&seat.user_id, packet) else { | ||
| 732 | + return Vec::new(); | ||
| 733 | + }; | ||
| 734 | + let bytes = Bytes::from(relay); | ||
| 735 | + let before = sharing.layers(); | ||
| 736 | + for viewer in &mut sharing.viewers { | ||
| 737 | + if fragment.keyframe { | ||
| 738 | + viewer.forward = viewer.forward.on_keyframe(fragment.layer); | ||
| 739 | + } | ||
| 740 | + if viewer.forward.live() == Some(fragment.layer) { | ||
| 741 | + let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 742 | + } | ||
| 743 | + } | ||
| 744 | + | ||
| 745 | + layers_changed(id, fragment.kind, sharing, before) | ||
| 746 | + .into_iter() | ||
| 747 | + .collect() | ||
| 748 | +} | ||
crates/server/src/share.rsdeleted+0 -347
| @@ -1,347 +0,0 @@ | |||
| 1 | -use std::{ | ||
| 2 | - collections::{BTreeMap, BTreeSet}, | ||
| 3 | - sync::{Arc, Mutex}, | ||
| 4 | -}; | ||
| 5 | - | ||
| 6 | -use bytes::Bytes; | ||
| 7 | -use common::{ | ||
| 8 | - datagram::{Datagram, encode_relay}, | ||
| 9 | - event::Event, | ||
| 10 | - share::{Codec, Kind, Layer, Quality, Share, Source, choose}, | ||
| 11 | -}; | ||
| 12 | -use quinn::Connection; | ||
| 13 | - | ||
| 14 | -use crate::request::Broadcast; | ||
| 15 | - | ||
| 16 | -#[derive(Clone, Copy)] | ||
| 17 | -enum Forward { | ||
| 18 | - Waiting(Layer), | ||
| 19 | - Live(Layer), | ||
| 20 | - Switching { live: Layer, next: Layer }, | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -impl Forward { | ||
| 24 | - fn target(self) -> Layer { | ||
| 25 | - match self { | ||
| 26 | - Self::Waiting(layer) | Self::Live(layer) => layer, | ||
| 27 | - Self::Switching { next, .. } => next, | ||
| 28 | - } | ||
| 29 | - } | ||
| 30 | - | ||
| 31 | - fn layers(self) -> Vec<Layer> { | ||
| 32 | - match self { | ||
| 33 | - Self::Waiting(layer) | Self::Live(layer) => vec![layer], | ||
| 34 | - Self::Switching { live, next } => vec![live, next], | ||
| 35 | - } | ||
| 36 | - } | ||
| 37 | - | ||
| 38 | - fn live(self) -> Option<Layer> { | ||
| 39 | - match self { | ||
| 40 | - Self::Waiting(_) => None, | ||
| 41 | - Self::Live(layer) | Self::Switching { live: layer, .. } => Some(layer), | ||
| 42 | - } | ||
| 43 | - } | ||
| 44 | - | ||
| 45 | - fn retarget(self, next: Layer) -> Self { | ||
| 46 | - match self { | ||
| 47 | - Self::Waiting(_) => Self::Waiting(next), | ||
| 48 | - Self::Live(live) | Self::Switching { live, .. } if live == next => Self::Live(live), | ||
| 49 | - Self::Live(live) | Self::Switching { live, .. } => Self::Switching { live, next }, | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - | ||
| 53 | - fn on_keyframe(self, layer: Layer) -> Self { | ||
| 54 | - match self { | ||
| 55 | - Self::Waiting(next) | Self::Switching { next, .. } if next == layer => { | ||
| 56 | - Self::Live(layer) | ||
| 57 | - } | ||
| 58 | - _ => self, | ||
| 59 | - } | ||
| 60 | - } | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -struct Viewer { | ||
| 64 | - user_id: String, | ||
| 65 | - connection: Connection, | ||
| 66 | - quality: Quality, | ||
| 67 | - decode: Vec<Codec>, | ||
| 68 | - forward: Forward, | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -struct Sharing { | ||
| 72 | - community_id: String, | ||
| 73 | - connection: Connection, | ||
| 74 | - source: Source, | ||
| 75 | - viewers: Vec<Viewer>, | ||
| 76 | -} | ||
| 77 | - | ||
| 78 | -impl Sharing { | ||
| 79 | - fn layers(&self) -> BTreeSet<Layer> { | ||
| 80 | - self.viewers | ||
| 81 | - .iter() | ||
| 82 | - .flat_map(|viewer| viewer.forward.layers()) | ||
| 83 | - .collect() | ||
| 84 | - } | ||
| 85 | - | ||
| 86 | - fn viewer(&self, user_id: &str) -> Option<&Viewer> { | ||
| 87 | - self.viewers.iter().find(|viewer| viewer.user_id == user_id) | ||
| 88 | - } | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -fn to(user_id: &str, event: Event) -> Broadcast { | ||
| 92 | - Broadcast { | ||
| 93 | - event, | ||
| 94 | - user_ids: vec![user_id.to_string()], | ||
| 95 | - } | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -fn slot(user_id: &str, kind: Kind) -> (String, Kind) { | ||
| 99 | - (user_id.to_string(), kind) | ||
| 100 | -} | ||
| 101 | - | ||
| 102 | -fn layers_changed( | ||
| 103 | - sharer_id: &str, | ||
| 104 | - kind: Kind, | ||
| 105 | - sharing: &Sharing, | ||
| 106 | - before: BTreeSet<Layer>, | ||
| 107 | -) -> Option<Broadcast> { | ||
| 108 | - let after = sharing.layers(); | ||
| 109 | - | ||
| 110 | - (after != before).then(|| { | ||
| 111 | - to( | ||
| 112 | - sharer_id, | ||
| 113 | - Event::ShareLayers { | ||
| 114 | - kind, | ||
| 115 | - layers: after.into_iter().collect(), | ||
| 116 | - }, | ||
| 117 | - ) | ||
| 118 | - }) | ||
| 119 | -} | ||
| 120 | - | ||
| 121 | -fn reroute(sharer_id: &str, kind: Kind, sharing: &mut Sharing) -> Vec<Broadcast> { | ||
| 122 | - let before = sharing.layers(); | ||
| 123 | - let community_id = sharing.community_id.clone(); | ||
| 124 | - let Sharing { | ||
| 125 | - source, viewers, .. | ||
| 126 | - } = sharing; | ||
| 127 | - let mut used: Vec<Layer> = Vec::new(); | ||
| 128 | - let mut keyframes = Vec::new(); | ||
| 129 | - let mut stopped = Vec::new(); | ||
| 130 | - viewers.retain_mut(|viewer| { | ||
| 131 | - let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { | ||
| 132 | - stopped.push(to( | ||
| 133 | - &viewer.user_id, | ||
| 134 | - Event::ShareStopped { | ||
| 135 | - community_id: community_id.clone(), | ||
| 136 | - user_id: sharer_id.to_string(), | ||
| 137 | - kind, | ||
| 138 | - }, | ||
| 139 | - )); | ||
| 140 | - return false; | ||
| 141 | - }; | ||
| 142 | - if !used.contains(&layer) { | ||
| 143 | - used.push(layer); | ||
| 144 | - } | ||
| 145 | - if viewer.forward.target() != layer { | ||
| 146 | - keyframes.push(to(sharer_id, Event::KeyframeWanted { kind, layer })); | ||
| 147 | - } | ||
| 148 | - viewer.forward = viewer.forward.retarget(layer); | ||
| 149 | - | ||
| 150 | - true | ||
| 151 | - }); | ||
| 152 | - | ||
| 153 | - let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_id, kind, sharing, before) | ||
| 154 | - .into_iter() | ||
| 155 | - .collect(); | ||
| 156 | - broadcasts.extend(keyframes); | ||
| 157 | - broadcasts.extend(stopped); | ||
| 158 | - | ||
| 159 | - broadcasts | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -fn remove_viewer( | ||
| 163 | - sharer_id: &str, | ||
| 164 | - kind: Kind, | ||
| 165 | - sharing: &mut Sharing, | ||
| 166 | - viewer_id: &str, | ||
| 167 | -) -> Option<Broadcast> { | ||
| 168 | - let before = sharing.layers(); | ||
| 169 | - sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 170 | - | ||
| 171 | - layers_changed(sharer_id, kind, sharing, before) | ||
| 172 | -} | ||
| 173 | - | ||
| 174 | -#[derive(Clone, Default)] | ||
| 175 | -pub struct Shares(Arc<Mutex<BTreeMap<(String, Kind), Sharing>>>); | ||
| 176 | - | ||
| 177 | -impl Shares { | ||
| 178 | - pub fn start( | ||
| 179 | - &self, | ||
| 180 | - community_id: &str, | ||
| 181 | - user_id: &str, | ||
| 182 | - kind: Kind, | ||
| 183 | - connection: Connection, | ||
| 184 | - source: Source, | ||
| 185 | - ) -> Vec<Broadcast> { | ||
| 186 | - let mut sharings = self.0.lock().unwrap(); | ||
| 187 | - let key = slot(user_id, kind); | ||
| 188 | - if let Some(sharing) = sharings | ||
| 189 | - .get_mut(&key) | ||
| 190 | - .filter(|sharing| sharing.community_id == community_id) | ||
| 191 | - { | ||
| 192 | - sharing.connection = connection; | ||
| 193 | - sharing.source = source; | ||
| 194 | - return reroute(user_id, kind, sharing); | ||
| 195 | - } | ||
| 196 | - sharings.insert( | ||
| 197 | - key, | ||
| 198 | - Sharing { | ||
| 199 | - community_id: community_id.to_string(), | ||
| 200 | - connection, | ||
| 201 | - source, | ||
| 202 | - viewers: Vec::new(), | ||
| 203 | - }, | ||
| 204 | - ); | ||
| 205 | - | ||
| 206 | - Vec::new() | ||
| 207 | - } | ||
| 208 | - | ||
| 209 | - pub fn stop(&self, user_id: &str, kind: Kind) -> Option<String> { | ||
| 210 | - self.0 | ||
| 211 | - .lock() | ||
| 212 | - .unwrap() | ||
| 213 | - .remove(&slot(user_id, kind)) | ||
| 214 | - .map(|sharing| sharing.community_id) | ||
| 215 | - } | ||
| 216 | - | ||
| 217 | - pub fn stop_all(&self, user_id: &str) -> Vec<(String, Kind)> { | ||
| 218 | - Kind::ALL | ||
| 219 | - .into_iter() | ||
| 220 | - .filter_map(|kind| { | ||
| 221 | - self.stop(user_id, kind) | ||
| 222 | - .map(|community_id| (community_id, kind)) | ||
| 223 | - }) | ||
| 224 | - .collect() | ||
| 225 | - } | ||
| 226 | - | ||
| 227 | - pub fn list(&self, community_id: &str) -> Vec<Share> { | ||
| 228 | - self.0 | ||
| 229 | - .lock() | ||
| 230 | - .unwrap() | ||
| 231 | - .iter() | ||
| 232 | - .filter(|(_, sharing)| sharing.community_id == community_id) | ||
| 233 | - .map(|((user_id, kind), sharing)| Share { | ||
| 234 | - user_id: user_id.clone(), | ||
| 235 | - kind: *kind, | ||
| 236 | - source: sharing.source.clone(), | ||
| 237 | - }) | ||
| 238 | - .collect() | ||
| 239 | - } | ||
| 240 | - | ||
| 241 | - pub fn watch( | ||
| 242 | - &self, | ||
| 243 | - sharer_id: &str, | ||
| 244 | - kind: Kind, | ||
| 245 | - viewer_id: &str, | ||
| 246 | - connection: Connection, | ||
| 247 | - quality: Quality, | ||
| 248 | - decode: &[Codec], | ||
| 249 | - ) -> Option<Vec<Broadcast>> { | ||
| 250 | - let mut sharings = self.0.lock().unwrap(); | ||
| 251 | - let sharing = sharings.get_mut(&slot(sharer_id, kind))?; | ||
| 252 | - let before = sharing.layers(); | ||
| 253 | - let used: Vec<Layer> = before.iter().copied().collect(); | ||
| 254 | - let layer = choose(&sharing.source, quality, decode, &used)?; | ||
| 255 | - let forward = sharing | ||
| 256 | - .viewer(viewer_id) | ||
| 257 | - .map_or(Forward::Waiting(layer), |viewer| { | ||
| 258 | - viewer.forward.retarget(layer) | ||
| 259 | - }); | ||
| 260 | - sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 261 | - sharing.viewers.push(Viewer { | ||
| 262 | - user_id: viewer_id.to_string(), | ||
| 263 | - connection, | ||
| 264 | - quality, | ||
| 265 | - decode: decode.to_vec(), | ||
| 266 | - forward, | ||
| 267 | - }); | ||
| 268 | - let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_id, kind, sharing, before) | ||
| 269 | - .into_iter() | ||
| 270 | - .collect(); | ||
| 271 | - broadcasts.push(to(sharer_id, Event::KeyframeWanted { kind, layer })); | ||
| 272 | - | ||
| 273 | - Some(broadcasts) | ||
| 274 | - } | ||
| 275 | - | ||
| 276 | - pub fn unwatch(&self, sharer_id: &str, kind: Kind, viewer_id: &str) -> Vec<Broadcast> { | ||
| 277 | - self.0 | ||
| 278 | - .lock() | ||
| 279 | - .unwrap() | ||
| 280 | - .get_mut(&slot(sharer_id, kind)) | ||
| 281 | - .and_then(|sharing| remove_viewer(sharer_id, kind, sharing, viewer_id)) | ||
| 282 | - .into_iter() | ||
| 283 | - .collect() | ||
| 284 | - } | ||
| 285 | - | ||
| 286 | - pub fn leave_viewer(&self, viewer_id: &str) -> Vec<Broadcast> { | ||
| 287 | - self.0 | ||
| 288 | - .lock() | ||
| 289 | - .unwrap() | ||
| 290 | - .iter_mut() | ||
| 291 | - .filter_map(|((sharer_id, kind), sharing)| { | ||
| 292 | - remove_viewer(sharer_id, *kind, sharing, viewer_id) | ||
| 293 | - }) | ||
| 294 | - .collect() | ||
| 295 | - } | ||
| 296 | - | ||
| 297 | - pub fn keyframe(&self, sharer_id: &str, kind: Kind, viewer_id: &str) -> Option<Broadcast> { | ||
| 298 | - let sharings = self.0.lock().unwrap(); | ||
| 299 | - let viewer = sharings.get(&slot(sharer_id, kind))?.viewer(viewer_id)?; | ||
| 300 | - | ||
| 301 | - Some(to( | ||
| 302 | - sharer_id, | ||
| 303 | - Event::KeyframeWanted { | ||
| 304 | - kind, | ||
| 305 | - layer: viewer.forward.target(), | ||
| 306 | - }, | ||
| 307 | - )) | ||
| 308 | - } | ||
| 309 | - | ||
| 310 | - pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec<Broadcast> { | ||
| 311 | - let (kind, fragment) = match Datagram::decode(packet) { | ||
| 312 | - Some(Datagram::Video(fragment)) => (fragment.kind, Some(fragment)), | ||
| 313 | - Some(Datagram::ShareAudio { .. }) => (Kind::Screen, None), | ||
| 314 | - _ => return Vec::new(), | ||
| 315 | - }; | ||
| 316 | - let mut sharings = self.0.lock().unwrap(); | ||
| 317 | - let Some((key, sharing)) = sharings.iter_mut().find(|(key, sharing)| { | ||
| 318 | - key.1 == kind && sharing.connection.stable_id() == connection_id | ||
| 319 | - }) else { | ||
| 320 | - return Vec::new(); | ||
| 321 | - }; | ||
| 322 | - let sharer_id = &key.0; | ||
| 323 | - let Some(relay) = encode_relay(sharer_id, packet) else { | ||
| 324 | - return Vec::new(); | ||
| 325 | - }; | ||
| 326 | - let bytes = Bytes::from(relay); | ||
| 327 | - let Some(fragment) = fragment else { | ||
| 328 | - for viewer in &sharing.viewers { | ||
| 329 | - let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 330 | - } | ||
| 331 | - return Vec::new(); | ||
| 332 | - }; | ||
| 333 | - let before = sharing.layers(); | ||
| 334 | - for viewer in &mut sharing.viewers { | ||
| 335 | - if fragment.keyframe { | ||
| 336 | - viewer.forward = viewer.forward.on_keyframe(fragment.layer); | ||
| 337 | - } | ||
| 338 | - if viewer.forward.live() == Some(fragment.layer) { | ||
| 339 | - let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 340 | - } | ||
| 341 | - } | ||
| 342 | - | ||
| 343 | - layers_changed(sharer_id, kind, sharing, before) | ||
| 344 | - .into_iter() | ||
| 345 | - .collect() | ||
| 346 | - } | ||
| 347 | -} | ||
crates/server/src/user_community.rsmodified+9 -0
| @@ -141,6 +141,15 @@ pub async fn unreads( | |||
| 141 | Ok(unreads) | 141 | Ok(unreads) |
| 142 | } | 142 | } |
| 143 | 143 | ||
| 144 | +pub async fn member_ids(community_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 145 | + database::ids( | ||
| 146 | + conn, | ||
| 147 | + "SELECT user_id FROM user_community WHERE community_id = ?1", | ||
| 148 | + (community_id,), | ||
| 149 | + ) | ||
| 150 | + .await | ||
| 151 | +} | ||
| 152 | + | ||
| 144 | pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, ServerError> { | 153 | pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, ServerError> { |
| 145 | let mut rows = conn | 154 | let mut rows = conn |
| 146 | .query( | 155 | .query( |
crates/server/src/voice.rsdeleted+0 -323
| @@ -1,323 +0,0 @@ | |||
| 1 | -use std::{ | ||
| 2 | - collections::HashMap, | ||
| 3 | - sync::{Arc, Mutex}, | ||
| 4 | - time::Instant, | ||
| 5 | -}; | ||
| 6 | - | ||
| 7 | -use bytes::Bytes; | ||
| 8 | -use common::{ | ||
| 9 | - datagram::{Datagram, encode_relay}, | ||
| 10 | - time, | ||
| 11 | -}; | ||
| 12 | -use quinn::Connection; | ||
| 13 | - | ||
| 14 | -struct Participant { | ||
| 15 | - user_id: String, | ||
| 16 | - connection: Connection, | ||
| 17 | - muted: bool, | ||
| 18 | - ghost: bool, | ||
| 19 | - joined_at: Instant, | ||
| 20 | -} | ||
| 21 | - | ||
| 22 | -pub enum CallEnd { | ||
| 23 | - Answered { seconds: u64 }, | ||
| 24 | - Unanswered, | ||
| 25 | - Declined, | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -pub struct Left { | ||
| 29 | - pub community_id: String, | ||
| 30 | - pub user_id: String, | ||
| 31 | - pub ghost_seconds: Option<u64>, | ||
| 32 | - pub call: Option<CallEnd>, | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -enum Outcome { | ||
| 36 | - Ringing, | ||
| 37 | - Declined, | ||
| 38 | - Answered, | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | -struct Room { | ||
| 42 | - participants: Vec<Participant>, | ||
| 43 | - started_ms: u64, | ||
| 44 | - outcome: Outcome, | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -impl Room { | ||
| 48 | - fn new() -> Self { | ||
| 49 | - Self { | ||
| 50 | - participants: Vec::new(), | ||
| 51 | - started_ms: time::now_ms(), | ||
| 52 | - outcome: Outcome::Ringing, | ||
| 53 | - } | ||
| 54 | - } | ||
| 55 | - | ||
| 56 | - fn occupied(&self) -> bool { | ||
| 57 | - self.participants | ||
| 58 | - .iter() | ||
| 59 | - .any(|participant| !participant.ghost) | ||
| 60 | - } | ||
| 61 | - | ||
| 62 | - fn user_ids(&self, keep: impl Fn(&Participant) -> bool) -> Vec<String> { | ||
| 63 | - self.participants | ||
| 64 | - .iter() | ||
| 65 | - .filter(|participant| keep(participant)) | ||
| 66 | - .map(|participant| participant.user_id.clone()) | ||
| 67 | - .collect() | ||
| 68 | - } | ||
| 69 | - | ||
| 70 | - fn admit(&mut self) { | ||
| 71 | - if self.occupied() { | ||
| 72 | - self.outcome = Outcome::Answered; | ||
| 73 | - } else { | ||
| 74 | - self.started_ms = time::now_ms(); | ||
| 75 | - self.outcome = Outcome::Ringing; | ||
| 76 | - } | ||
| 77 | - } | ||
| 78 | - | ||
| 79 | - fn end(&self) -> CallEnd { | ||
| 80 | - match self.outcome { | ||
| 81 | - Outcome::Answered => CallEnd::Answered { | ||
| 82 | - seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, | ||
| 83 | - }, | ||
| 84 | - Outcome::Declined => CallEnd::Declined, | ||
| 85 | - Outcome::Ringing => CallEnd::Unanswered, | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -type Rooms = HashMap<String, Room>; | ||
| 91 | - | ||
| 92 | -#[derive(Clone, Default)] | ||
| 93 | -pub struct Voice(Arc<Mutex<Rooms>>); | ||
| 94 | - | ||
| 95 | -impl Voice { | ||
| 96 | - pub fn join( | ||
| 97 | - &self, | ||
| 98 | - community_id: &str, | ||
| 99 | - user_id: &str, | ||
| 100 | - connection: Connection, | ||
| 101 | - muted: bool, | ||
| 102 | - ghost: bool, | ||
| 103 | - ) -> Option<Left> { | ||
| 104 | - let mut rooms = self.0.lock().unwrap(); | ||
| 105 | - let previous = leave_locked(&mut rooms, user_id); | ||
| 106 | - let room = rooms | ||
| 107 | - .entry(community_id.to_string()) | ||
| 108 | - .or_insert_with(Room::new); | ||
| 109 | - if !ghost { | ||
| 110 | - room.admit(); | ||
| 111 | - } | ||
| 112 | - room.participants.push(Participant { | ||
| 113 | - user_id: user_id.to_string(), | ||
| 114 | - connection, | ||
| 115 | - muted, | ||
| 116 | - ghost, | ||
| 117 | - joined_at: Instant::now(), | ||
| 118 | - }); | ||
| 119 | - | ||
| 120 | - previous | ||
| 121 | - } | ||
| 122 | - | ||
| 123 | - pub fn decline(&self, community_id: &str) { | ||
| 124 | - if let Some(room) = self.0.lock().unwrap().get_mut(community_id) | ||
| 125 | - && matches!(room.outcome, Outcome::Ringing) | ||
| 126 | - { | ||
| 127 | - room.outcome = Outcome::Declined; | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | - | ||
| 131 | - pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> { | ||
| 132 | - let mut rooms = self.0.lock().unwrap(); | ||
| 133 | - let (community_id, index) = locate(&rooms, user_id)?; | ||
| 134 | - rooms.get_mut(&community_id)?.participants[index].muted = muted; | ||
| 135 | - | ||
| 136 | - Some(community_id) | ||
| 137 | - } | ||
| 138 | - | ||
| 139 | - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Left> { | ||
| 140 | - let mut rooms = self.0.lock().unwrap(); | ||
| 141 | - let (community_id, index) = locate(&rooms, user_id)?; | ||
| 142 | - let room = rooms.get_mut(&community_id)?; | ||
| 143 | - if room.participants[index].ghost == ghost { | ||
| 144 | - return None; | ||
| 145 | - } | ||
| 146 | - if !ghost { | ||
| 147 | - room.admit(); | ||
| 148 | - } | ||
| 149 | - let participant = &mut room.participants[index]; | ||
| 150 | - let seconds = participant | ||
| 151 | - .ghost | ||
| 152 | - .then(|| participant.joined_at.elapsed().as_secs()); | ||
| 153 | - participant.ghost = ghost; | ||
| 154 | - participant.joined_at = Instant::now(); | ||
| 155 | - let call = (ghost && !room.occupied()).then(|| room.end()); | ||
| 156 | - | ||
| 157 | - Some(Left { | ||
| 158 | - community_id, | ||
| 159 | - user_id: user_id.to_string(), | ||
| 160 | - ghost_seconds: seconds, | ||
| 161 | - call, | ||
| 162 | - }) | ||
| 163 | - } | ||
| 164 | - | ||
| 165 | - pub fn room_users(&self, community_id: &str) -> Vec<String> { | ||
| 166 | - self.0 | ||
| 167 | - .lock() | ||
| 168 | - .unwrap() | ||
| 169 | - .get(community_id) | ||
| 170 | - .map(|room| room.user_ids(|_| true)) | ||
| 171 | - .unwrap_or_default() | ||
| 172 | - } | ||
| 173 | - | ||
| 174 | - pub fn room_of(&self, user_id: &str) -> Option<String> { | ||
| 175 | - locate(&self.0.lock().unwrap(), user_id).map(|(community_id, _)| community_id) | ||
| 176 | - } | ||
| 177 | - | ||
| 178 | - pub fn leave(&self, user_id: &str) -> Option<Left> { | ||
| 179 | - leave_locked(&mut self.0.lock().unwrap(), user_id) | ||
| 180 | - } | ||
| 181 | - | ||
| 182 | - pub fn leave_connection(&self, connection_id: usize) -> Option<Left> { | ||
| 183 | - let mut rooms = self.0.lock().unwrap(); | ||
| 184 | - let user_id = find(&rooms, connection_id)?.1.user_id.clone(); | ||
| 185 | - | ||
| 186 | - leave_locked(&mut rooms, &user_id) | ||
| 187 | - } | ||
| 188 | - | ||
| 189 | - pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option<Left> { | ||
| 190 | - remove(&mut self.0.lock().unwrap(), community_id, user_id) | ||
| 191 | - } | ||
| 192 | - | ||
| 193 | - pub fn count(&self) -> usize { | ||
| 194 | - self.0 | ||
| 195 | - .lock() | ||
| 196 | - .unwrap() | ||
| 197 | - .values() | ||
| 198 | - .map(|room| room.participants.len()) | ||
| 199 | - .sum() | ||
| 200 | - } | ||
| 201 | - | ||
| 202 | - pub fn participants(&self, community_id: &str) -> Vec<String> { | ||
| 203 | - self.0 | ||
| 204 | - .lock() | ||
| 205 | - .unwrap() | ||
| 206 | - .get(community_id) | ||
| 207 | - .map(|room| room.user_ids(|participant| !participant.ghost)) | ||
| 208 | - .unwrap_or_default() | ||
| 209 | - } | ||
| 210 | - | ||
| 211 | - pub fn rooms(&self) -> Vec<(String, Vec<String>, Vec<String>)> { | ||
| 212 | - self.0 | ||
| 213 | - .lock() | ||
| 214 | - .unwrap() | ||
| 215 | - .iter() | ||
| 216 | - .map(|(community_id, room)| { | ||
| 217 | - ( | ||
| 218 | - community_id.clone(), | ||
| 219 | - room.user_ids(|_| true), | ||
| 220 | - room.user_ids(|participant| participant.ghost), | ||
| 221 | - ) | ||
| 222 | - }) | ||
| 223 | - .collect() | ||
| 224 | - } | ||
| 225 | - | ||
| 226 | - pub fn remove_room(&self, community_id: &str) -> Vec<Left> { | ||
| 227 | - self.0 | ||
| 228 | - .lock() | ||
| 229 | - .unwrap() | ||
| 230 | - .remove(community_id) | ||
| 231 | - .map(|room| room.participants) | ||
| 232 | - .unwrap_or_default() | ||
| 233 | - .into_iter() | ||
| 234 | - .map(|participant| left(community_id, participant, None)) | ||
| 235 | - .collect() | ||
| 236 | - } | ||
| 237 | - | ||
| 238 | - pub fn relay(&self, connection_id: usize, packet: &[u8]) { | ||
| 239 | - let Some(Datagram::Voice { sequence, .. }) = Datagram::decode(packet) else { | ||
| 240 | - return; | ||
| 241 | - }; | ||
| 242 | - let rooms = self.0.lock().unwrap(); | ||
| 243 | - let Some((room, sender)) = find(&rooms, connection_id) else { | ||
| 244 | - return; | ||
| 245 | - }; | ||
| 246 | - if sender.muted { | ||
| 247 | - return; | ||
| 248 | - } | ||
| 249 | - let (Some(relay), Some(echo)) = ( | ||
| 250 | - encode_relay(&sender.user_id, packet), | ||
| 251 | - encode_relay( | ||
| 252 | - &sender.user_id, | ||
| 253 | - &Datagram::Voice { | ||
| 254 | - sequence, | ||
| 255 | - payload: &[], | ||
| 256 | - } | ||
| 257 | - .encode(), | ||
| 258 | - ), | ||
| 259 | - ) else { | ||
| 260 | - return; | ||
| 261 | - }; | ||
| 262 | - let _ = sender.connection.send_datagram(Bytes::from(echo)); | ||
| 263 | - let bytes = Bytes::from(relay); | ||
| 264 | - | ||
| 265 | - for participant in room | ||
| 266 | - .participants | ||
| 267 | - .iter() | ||
| 268 | - .filter(|participant| participant.user_id != sender.user_id) | ||
| 269 | - { | ||
| 270 | - let _ = participant.connection.send_datagram(bytes.clone()); | ||
| 271 | - } | ||
| 272 | - } | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -fn find(rooms: &Rooms, connection_id: usize) -> Option<(&Room, &Participant)> { | ||
| 276 | - rooms.values().find_map(|room| { | ||
| 277 | - room.participants | ||
| 278 | - .iter() | ||
| 279 | - .find(|participant| participant.connection.stable_id() == connection_id) | ||
| 280 | - .map(|sender| (room, sender)) | ||
| 281 | - }) | ||
| 282 | -} | ||
| 283 | - | ||
| 284 | -fn left(community_id: &str, participant: Participant, call: Option<CallEnd>) -> Left { | ||
| 285 | - Left { | ||
| 286 | - community_id: community_id.to_string(), | ||
| 287 | - user_id: participant.user_id, | ||
| 288 | - ghost_seconds: participant | ||
| 289 | - .ghost | ||
| 290 | - .then(|| participant.joined_at.elapsed().as_secs()), | ||
| 291 | - call, | ||
| 292 | - } | ||
| 293 | -} | ||
| 294 | - | ||
| 295 | -fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option<Left> { | ||
| 296 | - let room = rooms.get_mut(community_id)?; | ||
| 297 | - let index = room | ||
| 298 | - .participants | ||
| 299 | - .iter() | ||
| 300 | - .position(|participant| participant.user_id == user_id)?; | ||
| 301 | - let participant = room.participants.remove(index); | ||
| 302 | - let call = (!participant.ghost && !room.occupied()).then(|| room.end()); | ||
| 303 | - if room.participants.is_empty() { | ||
| 304 | - rooms.remove(community_id); | ||
| 305 | - } | ||
| 306 | - | ||
| 307 | - Some(left(community_id, participant, call)) | ||
| 308 | -} | ||
| 309 | - | ||
| 310 | -fn locate(rooms: &Rooms, user_id: &str) -> Option<(String, usize)> { | ||
| 311 | - rooms.iter().find_map(|(community_id, room)| { | ||
| 312 | - room.participants | ||
| 313 | - .iter() | ||
| 314 | - .position(|participant| participant.user_id == user_id) | ||
| 315 | - .map(|index| (community_id.clone(), index)) | ||
| 316 | - }) | ||
| 317 | -} | ||
| 318 | - | ||
| 319 | -fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<Left> { | ||
| 320 | - let (community_id, _) = locate(rooms, user_id)?; | ||
| 321 | - | ||
| 322 | - remove(rooms, &community_id, user_id) | ||
| 323 | -} | ||