forge
Explore
Log in

Don't you dare go Hollow

One client media owner, datagram v2 and typed calls

Browse files at this commit

c69c3caf6b5ea194d426e0ba5348a2814dc2c783Ahmet Kaan GümüşParent: 700e2a4
  • refactor
    • one client media owner, datagram v2 and typed calls
Show full message
♻️ refactor: one client media owner, datagram v2 and typed calls

Voice, shares and the mic test live in one client Media owner guarded by
the link epoch, so a stale join never installs after a reconnect and a
blip keeps the capture source. Datagrams become a Packet enum with fixed
little endian headers, derived fragment layout and bounds checked decode;
the server peeks three bytes to route video. Calls start moving to typed
Call structs whose reply type and gate come from the type, beginning
with the user domain. Share throughput unchanged at 59.4 fps.

34 changed files +1985 -1378

crates/client/Cargo.tomlmodified+1 -0
@@ -25,6 +25,7 @@ ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d9
25 ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" }25 ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" }
26 ureq = "3.5.2"26 ureq = "3.5.2"
27 bytes = "1.12.2"27 bytes = "1.12.2"
28+uuid = "1.29.3"
28 tracing = "0.1.44"29 tracing = "0.1.44"
29 tracing-subscriber = "0.3.23"30 tracing-subscriber = "0.3.23"
30 jiff = "1.0.2"31 jiff = "1.0.2"
crates/client/src/gui.rsmodified+5 -5
@@ -602,9 +602,6 @@ impl Yumush {
602 window: &mut Window,602 window: &mut Window,
603 cx: &mut Context<Self>,603 cx: &mut Context<Self>,
604 ) -> Self {604 ) -> Self {
605- network.set_voice_settings(settings.voice.clone());
606- network.set_share_settings(settings.share.clone());
607-
608 cx.spawn(async move |this, cx| {605 cx.spawn(async move |this, cx| {
609 while let Some(event) = network_event_receiver.recv().await {606 while let Some(event) = network_event_receiver.recv().await {
610 let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else {607 let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else {
@@ -1141,12 +1138,13 @@ impl Yumush {
1141 self.load_server_settings(window, cx);1138 self.load_server_settings(window, cx);
1142 if self.user.is_some() {1139 if self.user.is_some() {
1143 self.reload(window, cx);1140 self.reload(window, cx);
1144- self.rejoin_voice(window, cx);
1145 } else if let Some(active) = self.accounts.active.clone() {1141 } else if let Some(active) = self.accounts.active.clone() {
1146 self.switch_account(active, window, cx);1142 self.switch_account(active, window, cx);
1147 }1143 }
1148 }1144 }
1149 NetworkEvent::Disconnected(error) => self.connection.lost(&error),1145 NetworkEvent::Disconnected(error) => self.connection.lost(&error),
1146+ NetworkEvent::VoiceRejoined => self.refresh_voice(cx),
1147+ NetworkEvent::VoiceEnded => self.chat.set_voice_off(),
1150 NetworkEvent::SessionLost => {1148 NetworkEvent::SessionLost => {
1151 if let Some(user) = &self.user {1149 if let Some(user) = &self.user {
1152 self.accounts.forget(&user.id);1150 self.accounts.forget(&user.id);
@@ -1208,7 +1206,7 @@ impl Yumush {
1208 match event {1206 match event {
1209 Event::MessageCreated(message) => {1207 Event::MessageCreated(message) => {
1210 if self.should_notify(message, active) {1208 if self.should_notify(message, active) {
1211- self.network.play_notification();1209+ self.network.play_notification(&self.settings.voice);
1212 }1210 }
1213 self.count_message(message, active, cx);1211 self.count_message(message, active, cx);
1214 if message.call == Some(CallLog::Declined)1212 if message.call == Some(CallLog::Declined)
@@ -1240,6 +1238,8 @@ impl Yumush {
1240 self.deferred.push(NetworkEvent::Connected);1238 self.deferred.push(NetworkEvent::Connected);
1241 }1239 }
1242 NetworkEvent::Disconnected(error) => self.connection.lost(&error),1240 NetworkEvent::Disconnected(error) => self.connection.lost(&error),
1241+ NetworkEvent::VoiceRejoined => self.refresh_voice(cx),
1242+ NetworkEvent::VoiceEnded => self.chat.set_voice_off(),
1243 NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost),1243 NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost),
1244 NetworkEvent::Pushed(event) => match *event {1244 NetworkEvent::Pushed(event) => match *event {
1245 Event::MemberLeft { .. }1245 Event::MemberLeft { .. }
crates/client/src/gui/camera_view.rsmodified+5 -2
@@ -59,9 +59,11 @@ impl Yumush {
59 );59 );
60 let network = self.network.clone();60 let network = self.network.clone();
61 let user_id = user_id.clone();61 let user_id = user_id.clone();
62+ let volume = self.settings.share.volume;
63+ let choice = self.settings.voice.choice.clone();
62 spawn_warn(cx, "camera watch", async move {64 spawn_warn(cx, "camera watch", async move {
63 network65 network
64- .watch_share(&user_id, Kind::Camera, CAMERA_TILE)66+ .watch_share(&user_id, Kind::Camera, CAMERA_TILE, volume, choice)
65 .await67 .await
66 });68 });
67 changed = true;69 changed = true;
@@ -116,11 +118,12 @@ impl Yumush {
116 pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context<Self>) {118 pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context<Self>) {
117 let network = self.network.clone();119 let network = self.network.clone();
118 let on = network.camera_on();120 let on = network.camera_on();
121+ let settings = self.settings.share.clone();
119 122
120 cx.spawn_in(window, async move |this, cx| {123 cx.spawn_in(window, async move |this, cx| {
121 if on {124 if on {
122 let _ = network.stop_camera().await;125 let _ = network.stop_camera().await;
123- } else if let Err(error) = network.start_camera().await {126+ } else if let Err(error) = network.start_camera(&settings).await {
124 notify_error(&this, cx, error);127 notify_error(&this, cx, error);
125 }128 }
126 let _ = this.update(cx, |_, cx| cx.notify());129 let _ = this.update(cx, |_, cx| cx.notify());
crates/client/src/gui/chat.rsmodified+11 -16
@@ -1598,7 +1598,7 @@ impl Yumush {
1598 self.chat.focus(window, cx);1598 self.chat.focus(window, cx);
1599 self.load_members(window, cx);1599 self.load_members(window, cx);
1600 self.load_pins(window, cx);1600 self.load_pins(window, cx);
1601- self.load_voice(window, cx);1601+ self.load_voice(community_id.clone(), cx);
1602 self.load_shares(community_id, cx);1602 self.load_shares(community_id, cx);
1603 self.load_messages(None, window, cx);1603 self.load_messages(None, window, cx);
1604 cx.notify();1604 cx.notify();
@@ -1626,7 +1626,7 @@ impl Yumush {
1626 self.load_members(window, cx);1626 self.load_members(window, cx);
1627 self.chat.messages.clear();1627 self.chat.messages.clear();
1628 self.load_messages(None, window, cx);1628 self.load_messages(None, window, cx);
1629- self.load_voice(window, cx);1629+ self.load_voice(community_id.clone(), cx);
1630 self.load_shares(community_id, cx);1630 self.load_shares(community_id, cx);
1631 }1631 }
1632 }1632 }
@@ -1937,16 +1937,11 @@ impl Yumush {
1937 .detach();1937 .detach();
1938 }1938 }
1939 1939
1940- fn load_voice(&self, window: &mut Window, cx: &mut Context<Self>) {1940+ fn load_voice(&self, community_id: String, cx: &mut Context<Self>) {
1941- let Some(community_id) = self.chat.selected_community_id.clone() else {
1942- return;
1943- };
1944 let network = self.network.clone();1941 let network = self.network.clone();
1945 1942
1946- cx.spawn_in(window, async move |this, cx| {1943+ cx.spawn(async move |this, cx| {
1947- let Some(participants) =1944+ let Ok(participants) = network.voice_participants(&community_id).await else {
1948- ok_or_notify(network.voice_participants(&community_id).await, &this, cx)
1949- else {
1950 return;1945 return;
1951 };1946 };
1952 1947
@@ -1986,13 +1981,14 @@ impl Yumush {
1986 cx: &mut Context<Self>,1981 cx: &mut Context<Self>,
1987 ) {1982 ) {
1988 let network = self.network.clone();1983 let network = self.network.clone();
1984+ let voice_settings = self.settings.voice.clone();
1989 1985
1990 cx.spawn_in(window, async move |this, cx| {1986 cx.spawn_in(window, async move |this, cx| {
1991 if was_in {1987 if was_in {
1992 let _ = network.leave_voice().await;1988 let _ = network.leave_voice().await;
1993 }1989 }
1994 1990
1995- match network.join_voice(&community_id).await {1991+ match network.join_voice(&community_id, &voice_settings).await {
1996 Ok(participants) => {1992 Ok(participants) => {
1997 network.set_deafened(deafened);1993 network.set_deafened(deafened);
1998 let _ = this.update_in(cx, |yumush, _, cx| {1994 let _ = this.update_in(cx, |yumush, _, cx| {
@@ -2035,13 +2031,12 @@ impl Yumush {
2035 .detach();2031 .detach();
2036 }2032 }
2037 2033
2038- pub(super) fn rejoin_voice(&mut self, window: &mut Window, cx: &mut Context<Self>) {2034+ pub(super) fn refresh_voice(&mut self, cx: &mut Context<Self>) {
2039 let Some(community_id) = self.chat.voice_community().map(str::to_string) else {2035 let Some(community_id) = self.chat.voice_community().map(str::to_string) else {
2040 return;2036 return;
2041 };2037 };
2042- let flags = self.chat.voice_flags().unwrap_or((false, false));2038+ self.load_voice(community_id.clone(), cx);
2043- self.chat.set_voice_off();2039+ self.load_shares(community_id, cx);
2044- self.join_voice(community_id, flags, false, window, cx);
2045 }2040 }
2046 2041
2047 pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) {2042 pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) {
@@ -2400,7 +2395,7 @@ impl Yumush {
2400 let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() {2395 let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() {
2401 Some((community_id, _)) => {2396 Some((community_id, _)) => {
2402 if yumush.ring_allowed(&community_id) {2397 if yumush.ring_allowed(&community_id) {
2403- yumush.network.play_ring();2398+ yumush.network.play_ring(&yumush.settings.voice);
2404 }2399 }
2405 true2400 true
2406 }2401 }
crates/client/src/gui/settings_page.rsmodified+1 -1
@@ -254,7 +254,7 @@ impl Yumush {
254 254
255 pub(super) fn commit_settings(&mut self, cx: &mut Context<Self>) {255 pub(super) fn commit_settings(&mut self, cx: &mut Context<Self>) {
256 settings::save(&self.settings);256 settings::save(&self.settings);
257- self.network.set_voice_settings(self.settings.voice.clone());257+ self.network.set_voice_settings(&self.settings.voice);
258 cx.notify();258 cx.notify();
259 }259 }
260 }260 }
crates/client/src/gui/share_view.rsmodified+15 -8
@@ -106,11 +106,12 @@ impl Yumush {
106 pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context<Self>) {106 pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context<Self>) {
107 let network = self.network.clone();107 let network = self.network.clone();
108 let sharing = network.sharing();108 let sharing = network.sharing();
109+ let settings = self.settings.share.clone();
109 110
110 cx.spawn_in(window, async move |this, cx| {111 cx.spawn_in(window, async move |this, cx| {
111 if sharing {112 if sharing {
112 let _ = network.stop_share().await;113 let _ = network.stop_share().await;
113- } else if let Err(error) = network.start_share().await {114+ } else if let Err(error) = network.start_share(&settings).await {
114 notify_error(&this, cx, error);115 notify_error(&this, cx, error);
115 }116 }
116 let _ = this.update(cx, |_, cx| cx.notify());117 let _ = this.update(cx, |_, cx| cx.notify());
@@ -119,15 +120,16 @@ impl Yumush {
119 }120 }
120 121
121 fn update_share(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut ShareSettings)) {122 fn update_share(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut ShareSettings)) {
123+ let before = self.settings.share.clone();
122 change(&mut self.settings.share);124 change(&mut self.settings.share);
123 settings::save(&self.settings);125 settings::save(&self.settings);
124- if self.network.set_share_settings(self.settings.share.clone()) {126+ self.network.set_share_settings(&self.settings.share);
127+ if self.network.sharing() && before.encoding_differs(&self.settings.share) {
125 let network = self.network.clone();128 let network = self.network.clone();
126- spawn_warn(129+ let settings = self.settings.share.clone();
127- cx,130+ spawn_warn(cx, "share update", async move {
128- "share update",131+ network.update_share(&settings).await
129- async move { network.update_share().await },132+ });
130- );
131 }133 }
132 cx.notify();134 cx.notify();
133 }135 }
@@ -259,11 +261,16 @@ impl Yumush {
259 261
260 let network = self.network.clone();262 let network = self.network.clone();
261 let watch = self.settings.share.watch;263 let watch = self.settings.share.watch;
264+ let volume = self.settings.share.volume;
265+ let choice = self.settings.voice.choice.clone();
262 if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) {266 if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) {
263 network.set_watch_quality(&user_id, kind, watch);267 network.set_watch_quality(&user_id, kind, watch);
264 } else {268 } else {
265 cx.spawn_in(window, async move |this, cx| {269 cx.spawn_in(window, async move |this, cx| {
266- if let Err(error) = network.watch_share(&user_id, kind, watch).await {270+ if let Err(error) = network
271+ .watch_share(&user_id, kind, watch, volume, choice)
272+ .await
273+ {
267 let _ = this.update(cx, |yumush, cx| {274 let _ = this.update(cx, |yumush, cx| {
268 if yumush.is_watching(&user_id, kind) {275 if yumush.is_watching(&user_id, kind) {
269 yumush.close_viewer(cx);276 yumush.close_viewer(cx);
crates/client/src/gui/voice_settings.rsmodified+4 -2
@@ -289,7 +289,9 @@ impl Yumush {
289 )289 )
290 .child(290 .child(
291 test_button("speaker_test_button", palette, false, move |_, cx| {291 test_button("speaker_test_button", palette, false, move |_, cx| {
292- speaker.update(cx, |yumush, _| yumush.network.play_chime());292+ speaker.update(cx, |yumush, _| {
293+ yumush.network.play_chime(&yumush.settings.voice)
294+ });
293 })295 })
294 .child(Icon::new(IconName::Volume2).w(px(14.)).h(px(14.)))296 .child(Icon::new(IconName::Volume2).w(px(14.)).h(px(14.)))
295 .child("Play sound"),297 .child("Play sound"),
@@ -455,7 +457,7 @@ impl Yumush {
455 match self.voice.mic_test {457 match self.voice.mic_test {
456 MicTest::On => self.stop_mic_test(),458 MicTest::On => self.stop_mic_test(),
457 MicTest::Off => {459 MicTest::Off => {
458- self.network.start_mic_test();460+ self.network.start_mic_test(&self.settings.voice);
459 self.voice.mic_test = MicTest::On;461 self.voice.mic_test = MicTest::On;
460 self.start_level_poll(cx);462 self.start_level_poll(cx);
461 }463 }
crates/client/src/net/datagram.rsmodified+10 -21
@@ -1,34 +1,23 @@
1-use common::{1+use common::datagram::{Packet, split};
2- datagram::{Datagram, decode_relay},
3- share::Kind,
4-};
5 2
6 use super::*;3 use super::*;
7 4
8-pub(super) async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) {5+pub(super) async fn datagram_receive_loop(connection: quinn::Connection, media: Arc<Media>) {
9 let loss: u64 = std::env::var("YUMUSH_TEST_LOSS")6 let loss: u64 = std::env::var("YUMUSH_TEST_LOSS")
10 .ok()7 .ok()
11 .and_then(|value| value.parse().ok())8 .and_then(|value| value.parse().ok())
12 .unwrap_or(0);9 .unwrap_or(0);
13 let mut received: u64 = 0;10 let mut received: u64 = 0;
14 while let Ok(datagram) = connection.read_datagram().await {11 while let Ok(datagram) = connection.read_datagram().await {
15- if let Some(voice) = shared.voice.lock().unwrap().as_ref() {12+ let Some((from, packet)) = split(&datagram) else {
16- voice.receive(&datagram);13+ continue;
17- }14+ };
18- if let Some((user_id, packet)) = decode_relay(&datagram) {15+ if matches!(packet, Packet::Video { .. }) {
19- if let Datagram::Video(_) = packet {16+ received += 1;
20- received += 1;17+ if received * 37 % 100 < loss {
21- if received * 37 % 100 < loss {18+ continue;
22- continue;
23- }
24- }
25- let kind = match &packet {
26- Datagram::Video(fragment) => fragment.kind,
27- _ => Kind::Screen,
28- };
29- if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) {
30- watching.receive(packet);
31 }19 }
32 }20 }
21+ media.receive(&datagram, from, packet);
33 }22 }
34 }23 }
crates/client/src/net/events.rsmodified+7 -3
@@ -9,7 +9,7 @@ use super::*;
9 pub(super) async fn event_receive_loop(9 pub(super) async fn event_receive_loop(
10 connection: quinn::Connection,10 connection: quinn::Connection,
11 event_sender: mpsc::Sender<NetworkEvent>,11 event_sender: mpsc::Sender<NetworkEvent>,
12- share: SharedShare,12+ media: Arc<Media>,
13 ) {13 ) {
14 let Ok(mut receive_stream) = connection.accept_uni().await else {14 let Ok(mut receive_stream) = connection.accept_uni().await else {
15 return;15 return;
@@ -18,7 +18,7 @@ pub(super) async fn event_receive_loop(
18 while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await {18 while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await {
19 match down {19 match down {
20 Down::Event(event) => {20 Down::Event(event) => {
21- share.lock().unwrap().event(&event);21+ media.pushed(&event);
22 if event_sender22 if event_sender
23 .send(NetworkEvent::Pushed(event))23 .send(NetworkEvent::Pushed(event))
24 .await24 .await
@@ -27,7 +27,11 @@ pub(super) async fn event_receive_loop(
27 return;27 return;
28 }28 }
29 }29 }
30- Down::Media(media) => share.lock().unwrap().media(&media),30+ Down::Media(down) => {
31+ if media.down(&down) && event_sender.send(NetworkEvent::VoiceEnded).await.is_err() {
32+ return;
33+ }
34+ }
31 }35 }
32 }36 }
33 }37 }
crates/client/src/net/link.rsmodified+39 -81
@@ -1,12 +1,13 @@
1 use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};1 use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};
2 2
3 use common::{3 use common::{
4+ call::{Call, Legacy},
4 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},5 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},
5 error::Error,6 error::Error,
6 frame::{self, DOWN_MAX, Sending, UP_MAX},7 frame::{self, DOWN_MAX, Sending, UP_MAX},
7 model::{Attachment, User},8 model::{Attachment, User},
8 open::{Blob, Open, Upload},9 open::{Blob, Open, Upload},
9- request::Request,10+ request::LegacyRequest,
10 response::Response,11 response::Response,
11 session::{Hello, Welcome},12 session::{Hello, Welcome},
12 transport::{Close, alpn, transport},13 transport::{Close, alpn, transport},
@@ -27,40 +28,31 @@ use rustls_platform_verifier as _;
27 use tokio::sync::{mpsc, oneshot};28 use tokio::sync::{mpsc, oneshot};
28 use tracing::{info, warn};29 use tracing::{info, warn};
29 30
30-use crate::{31+use crate::ClientConfig;
31- ClientConfig,
32- voice::{self},
33-};
34 32
35-use super::{33+use super::{datagram::datagram_receive_loop, events::event_receive_loop, *};
36- datagram::datagram_receive_loop,
37- events::event_receive_loop,
38- share::{start_share, update_share},
39- *,
40-};
41 34
42 const CHANNEL_SIZE: usize = 32;35 const CHANNEL_SIZE: usize = 32;
43 const BACKOFF_BASE_MILLIS: u64 = 250;36 const BACKOFF_BASE_MILLIS: u64 = 250;
44 const BACKOFF_CAP_MILLIS: u64 = 8_000;37 const BACKOFF_CAP_MILLIS: u64 = 8_000;
45 38
46-const SHARE_TICK: Duration = Duration::from_secs(1);
47-
48 pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {39 pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {
49 let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);40 let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);
50 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);41 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);
51- let shared = Shared::default();42+ let runtime = tokio::runtime::Builder::new_current_thread()
43+ .enable_all()
44+ .build()
45+ .expect("network runtime");
46+ let shared = Shared {
47+ media: Media::new(runtime.handle().clone()),
48+ fetches: Arc::default(),
49+ };
52 50
53 std::thread::Builder::new()51 std::thread::Builder::new()
54 .name("network".to_string())52 .name("network".to_string())
55 .spawn({53 .spawn({
56 let shared = shared.clone();54 let shared = shared.clone();
57- move || {55+ move || runtime.block_on(actor(client_config, command_receiver, event_sender, shared))
58- tokio::runtime::Builder::new_current_thread()
59- .enable_all()
60- .build()
61- .expect("network runtime")
62- .block_on(actor(client_config, command_receiver, event_sender, shared));
63- }
64 })56 })
65 .expect("network thread");57 .expect("network thread");
66 58
@@ -261,16 +253,23 @@ fn config() -> Result<quinn::ClientConfig, LinkError> {
261 Ok(client_config)253 Ok(client_config)
262 }254 }
263 255
264-pub(super) async fn send(256+pub(super) async fn call<C: Call>(
265 connection: &quinn::Connection,257 connection: &quinn::Connection,
266- request: &Request,258+ call: C,
267-) -> Result<Response, Fail> {259+) -> Result<C::Reply, Fail> {
268 let (send_stream, mut receive_stream) = connection.open_bi().await?;260 let (send_stream, mut receive_stream) = connection.open_bi().await?;
269 let mut send_stream = Sending::new(send_stream);261 let mut send_stream = Sending::new(send_stream);
270- frame::write(&mut send_stream, &Open::Call(request.clone()), UP_MAX).await?;262+ frame::write(&mut send_stream, &Open::Call(call.into_request()), UP_MAX).await?;
271 send_stream.finish()?;263 send_stream.finish()?;
272 264
273- Ok(frame::read::<Result<Response, Error>>(&mut receive_stream, DOWN_MAX).await??)265+ Ok(frame::read::<Result<C::Reply, Error>>(&mut receive_stream, DOWN_MAX).await??)
266+}
267+
268+pub(super) async fn send(
269+ connection: &quinn::Connection,
270+ request: &LegacyRequest,
271+) -> Result<Response, Fail> {
272+ call(connection, Legacy(request.clone())).await
274 }273 }
275 274
276 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {275 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {
@@ -286,7 +285,10 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<
286 Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)285 Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)
287 }286 }
288 287
289-pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> {288+pub(super) async fn done(
289+ connection: &quinn::Connection,
290+ request: LegacyRequest,
291+) -> Result<(), Fail> {
290 match send(connection, &request).await? {292 match send(connection, &request).await? {
291 Response::Done => Ok(()),293 Response::Done => Ok(()),
292 _ => Err(Fail::Protocol),294 _ => Err(Fail::Protocol),
@@ -471,6 +473,7 @@ async fn actor(
471 let _ = reply.send(Err(Fail::Server(error)));473 let _ = reply.send(Err(Fail::Server(error)));
472 }474 }
473 None => {475 None => {
476+ shared.media.reset();
474 if event_sender.send(NetworkEvent::SessionLost).await.is_err() {477 if event_sender.send(NetworkEvent::SessionLost).await.is_err() {
475 return;478 return;
476 }479 }
@@ -496,6 +499,7 @@ async fn actor(
496 499
497 attempt = 0;500 attempt = 0;
498 info!("connected");501 info!("connected");
502+ shared.media.ready(connection.clone(), event_sender.clone());
499 if event_sender.send(NetworkEvent::Connected).await.is_err() {503 if event_sender.send(NetworkEvent::Connected).await.is_err() {
500 return;504 return;
501 }505 }
@@ -506,60 +510,24 @@ async fn actor(
506 tokio::spawn(event_receive_loop(510 tokio::spawn(event_receive_loop(
507 connection.clone(),511 connection.clone(),
508 event_sender.clone(),512 event_sender.clone(),
509- shared.share.clone(),513+ shared.media.clone(),
514+ ));
515+ tokio::spawn(datagram_receive_loop(
516+ connection.clone(),
517+ shared.media.clone(),
510 ));518 ));
511- tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone()));
512- let mut ticker = tokio::time::interval(SHARE_TICK);
513 519
514 loop {520 loop {
515 tokio::select! {521 tokio::select! {
516 command = command_receiver.recv() => match command {522 command = command_receiver.recv() => match command {
517- Some(Command::Request { request, reply }) => match &request {523+ Some(Command::Call(run)) => run(connection.clone()),
518- Request::JoinVoice { .. } => {
519- let shared = shared.clone();
520- let settings = shared.voice_settings.lock().unwrap().clone();
521- let connection = connection.clone();
522-
523- answer(reply, async move {
524- let response = send(&connection, &request).await;
525- if let Ok(Response::Voice(_)) = &response {
526- shared.mic_test.lock().unwrap().take();
527- *shared.voice.lock().unwrap() =
528- Some(voice::start(Some(connection), &settings));
529- }
530- response
531- });
532- }
533- Request::LeaveVoice => {
534- hang_up(&shared);
535-
536- let connection = connection.clone();
537- answer(reply, async move { send(&connection, &request).await });
538- }
539- _ => {
540- let connection = connection.clone();
541- answer(reply, async move { send(&connection, &request).await });
542- }
543- },
544 Some(Command::SignIn { token: next, reply }) => {524 Some(Command::SignIn { token: next, reply }) => {
545 token = next;525 token = next;
546 pending = Some(reply);526 pending = Some(reply);
547- hang_up(&shared);527+ shared.media.reset();
548 connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes());528 connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes());
549 break;529 break;
550 }530 }
551- Some(Command::StartShare { kind, settings, reply }) => {
552- let connection = connection.clone();
553- let share = shared.share.clone();
554-
555- answer(reply, async move { start_share(&connection, &share, kind, &settings).await });
556- }
557- Some(Command::UpdateShare { settings, reply }) => {
558- let connection = connection.clone();
559- let share = shared.share.clone();
560-
561- answer(reply, async move { update_share(&connection, &share, &settings).await });
562- }
563 Some(Command::Upload { community_id, path, maximum, reply }) => {531 Some(Command::Upload { community_id, path, maximum, reply }) => {
564 let connection = connection.clone();532 let connection = connection.clone();
565 533
@@ -583,19 +551,9 @@ async fn actor(
583 None => break 'session,551 None => break 'session,
584 },552 },
585 553
586- _ = ticker.tick() => {
587- let requests = shared.share.lock().unwrap().ticks();
588- for request in requests {
589- let connection = connection.clone();
590- tokio::spawn(async move {
591- let _ = send(&connection, &request).await;
592- });
593- }
594- }
595-
596 error = connection.closed() => {554 error = connection.closed() => {
597 warn!("disconnected: {error}");555 warn!("disconnected: {error}");
598- hang_up(&shared);556+ shared.media.lost();
599 557
600 let event = LinkError::from(error);558 let event = LinkError::from(error);
601 let banned = event == LinkError::Closed(Close::Banned);559 let banned = event == LinkError::Closed(Close::Banned);
crates/client/src/net/media.rsadded+778 -0
@@ -0,0 +1,778 @@
1+use std::{
2+ collections::HashMap,
3+ sync::{Arc, Mutex, MutexGuard},
4+ time::Duration,
5+};
6+
7+use bytes::Bytes;
8+use common::{
9+ datagram::{Packet, RELAY_PREFIX},
10+ event::{Event, Media as Down},
11+ request::LegacyRequest,
12+ response::Response,
13+ share::{Fps, Kind, Quality, Resolution, Source},
14+};
15+use quinn::Connection;
16+use tokio::{runtime::Handle, sync::mpsc};
17+use tracing::warn;
18+use uuid::Uuid;
19+
20+use crate::{
21+ settings::{ShareSettings, VoiceSettings},
22+ share::{
23+ audio::AudioApp,
24+ audio_capture,
25+ encode::capabilities,
26+ session::{ShareSample, Sharing, Tick, WatchQuality, Watching},
27+ },
28+ voice::{self, Voice, VoiceSample, audio::Choice},
29+};
30+
31+use super::{
32+ link::{done, send},
33+ *,
34+};
35+
36+const TICK: Duration = Duration::from_secs(1);
37+const WAIT_STEP: Duration = Duration::from_millis(100);
38+const WAIT_STEPS: u32 = 50;
39+
40+const CAMERA_TOP: Quality = Quality {
41+ resolution: Resolution::P2160,
42+ fps: Fps::F60,
43+};
44+
45+#[derive(Clone)]
46+struct Want {
47+ community_id: String,
48+ settings: VoiceSettings,
49+ muted: bool,
50+ deafened: bool,
51+}
52+
53+struct Inner {
54+ epoch: u64,
55+ connection: Option<Connection>,
56+ want_voice: Option<Want>,
57+ voice: Option<Voice>,
58+ joining: u32,
59+ mic_test: Option<Voice>,
60+ sharing: HashMap<Kind, Sharing>,
61+ watching: HashMap<(String, Kind), Watching>,
62+}
63+
64+impl Inner {
65+ fn current(&self, epoch: u64) -> bool {
66+ self.connection.is_some() && self.epoch == epoch
67+ }
68+
69+ fn drop_calls(&mut self) {
70+ self.voice = None;
71+ self.sharing.clear();
72+ }
73+
74+ fn install_voice(&mut self, mut voice: Voice, want: Want) {
75+ voice.apply(&want.settings);
76+ voice.set_muted(want.muted);
77+ voice.set_deafened(want.deafened);
78+ self.mic_test = None;
79+ self.voice = Some(voice);
80+ self.want_voice = Some(want);
81+ }
82+}
83+
84+pub(super) struct Media {
85+ handle: Handle,
86+ inner: Mutex<Inner>,
87+}
88+
89+impl Media {
90+ pub(super) fn new(handle: Handle) -> Arc<Media> {
91+ let media = Arc::new(Media {
92+ handle: handle.clone(),
93+ inner: Mutex::new(Inner {
94+ epoch: 0,
95+ connection: None,
96+ want_voice: None,
97+ voice: None,
98+ joining: 0,
99+ mic_test: None,
100+ sharing: HashMap::new(),
101+ watching: HashMap::new(),
102+ }),
103+ });
104+ handle.spawn(tick_loop(media.clone()));
105+
106+ media
107+ }
108+
109+ fn lock(&self) -> MutexGuard<'_, Inner> {
110+ self.inner.lock().unwrap()
111+ }
112+
113+ fn current(&self) -> Result<(Connection, u64), Fail> {
114+ let inner = self.lock();
115+ let connection = inner.connection.clone().ok_or(Fail::Offline)?;
116+
117+ Ok((connection, inner.epoch))
118+ }
119+
120+ async fn current_wait(&self) -> Result<(Connection, u64), Fail> {
121+ for _ in 0..WAIT_STEPS {
122+ if let Ok(current) = self.current() {
123+ return Ok(current);
124+ }
125+ tokio::time::sleep(WAIT_STEP).await;
126+ }
127+
128+ self.current()
129+ }
130+
131+ async fn run<T: Send + 'static>(
132+ &self,
133+ work: impl Future<Output = Result<T, Fail>> + Send + 'static,
134+ ) -> Result<T, Fail> {
135+ self.handle.spawn(work).await.map_err(|_| Fail::Offline)?
136+ }
137+
138+ pub(super) fn ready(
139+ self: &Arc<Self>,
140+ connection: Connection,
141+ events: mpsc::Sender<NetworkEvent>,
142+ ) {
143+ let (epoch, want) = {
144+ let mut inner = self.lock();
145+ inner.epoch += 1;
146+ inner.connection = Some(connection.clone());
147+ (inner.epoch, inner.want_voice.clone())
148+ };
149+ if let Some(want) = want {
150+ tokio::spawn(self.clone().rejoin(connection, epoch, want, events));
151+ }
152+ }
153+
154+ pub(super) fn lost(&self) {
155+ let mut inner = self.lock();
156+ inner.connection = None;
157+ inner.drop_calls();
158+ }
159+
160+ pub(super) fn reset(&self) {
161+ let mut inner = self.lock();
162+ inner.connection = None;
163+ inner.drop_calls();
164+ inner.want_voice = None;
165+ inner.watching.clear();
166+ }
167+
168+ async fn rejoin(
169+ self: Arc<Self>,
170+ connection: Connection,
171+ epoch: u64,
172+ want: Want,
173+ events: mpsc::Sender<NetworkEvent>,
174+ ) {
175+ let joined = join(&connection, &want.community_id).await;
176+ let next = {
177+ let mut inner = self.lock();
178+ if !inner.current(epoch) {
179+ return;
180+ }
181+ let ours = inner
182+ .want_voice
183+ .as_ref()
184+ .is_some_and(|wanted| wanted.community_id == want.community_id)
185+ && inner.voice.is_none();
186+ match joined {
187+ Ok(_) if ours => Rejoin::Install,
188+ Ok(_) => {
189+ if inner.want_voice.is_none() && inner.joining == 0 {
190+ tokio::spawn(send_quietly(connection.clone(), LegacyRequest::LeaveVoice));
191+ }
192+ Rejoin::Skip
193+ }
194+ Err(error) if ours => {
195+ warn!("voice rejoin failed: {error}");
196+ inner.want_voice = None;
197+ inner.watching.clear();
198+ Rejoin::Ended
199+ }
200+ Err(_) => Rejoin::Skip,
201+ }
202+ };
203+
204+ let watches = match next {
205+ Rejoin::Skip => return,
206+ Rejoin::Ended => None,
207+ Rejoin::Install => {
208+ let voice = voice::start(Some(connection.clone()), &want.settings);
209+ let mut inner = self.lock();
210+ let wanted = inner.want_voice.clone();
211+ match wanted {
212+ Some(wanted)
213+ if inner.current(epoch)
214+ && wanted.community_id == want.community_id
215+ && inner.voice.is_none() =>
216+ {
217+ inner.install_voice(voice, wanted);
218+ Some(inner.watch_requests())
219+ }
220+ _ => return,
221+ }
222+ }
223+ };
224+
225+ let event = match watches {
226+ Some(requests) => {
227+ for (key, request) in requests {
228+ let media = self.clone();
229+ let connection = connection.clone();
230+ tokio::spawn(async move {
231+ if send(&connection, &request).await.is_err() {
232+ media.lock().watching.remove(&key);
233+ }
234+ });
235+ }
236+ NetworkEvent::VoiceRejoined
237+ }
238+ None => NetworkEvent::VoiceEnded,
239+ };
240+ let _ = events.send(event).await;
241+ }
242+
243+ pub(super) fn pushed(&self, event: &Event) {
244+ if let Event::ShareStopped { user_id, kind, .. } = event {
245+ self.lock().watching.remove(&(user_id.clone(), *kind));
246+ }
247+ }
248+
249+ pub(super) fn down(&self, media: &Down) -> bool {
250+ let mut inner = self.lock();
251+ match media {
252+ Down::Layers { kind, layers } => {
253+ if let Some(sharing) = inner.sharing.get_mut(kind) {
254+ sharing.set_layers(layers);
255+ }
256+ }
257+ Down::Keyframe { kind, layer } => {
258+ if let Some(sharing) = inner.sharing.get(kind) {
259+ sharing.keyframe(*layer);
260+ }
261+ }
262+ Down::VoiceEnded => {
263+ inner.drop_calls();
264+ inner.want_voice = None;
265+ inner.watching.clear();
266+ return true;
267+ }
268+ }
269+
270+ false
271+ }
272+
273+ pub(super) fn receive(&self, datagram: &Bytes, from: &[u8; RELAY_PREFIX], packet: Packet<'_>) {
274+ let inner = self.lock();
275+ let kind = match packet {
276+ Packet::Voice { seq, opus } => {
277+ if let Some(voice) = &inner.voice {
278+ voice.receive(from, seq, opus);
279+ }
280+ return;
281+ }
282+ Packet::ScreenAudio { .. } => Kind::Screen,
283+ Packet::Video { kind, .. } => kind,
284+ };
285+ let key = (Uuid::from_bytes(*from).to_string(), kind);
286+ if let Some(watching) = inner.watching.get(&key) {
287+ watching.receive(datagram, &packet);
288+ }
289+ }
290+
291+ async fn join_voice(
292+ &self,
293+ community_id: String,
294+ settings: VoiceSettings,
295+ ) -> Result<Vec<String>, Fail> {
296+ self.lock().joining += 1;
297+ let result = self.join_voice_inner(community_id, settings).await;
298+ self.lock().joining -= 1;
299+
300+ result
301+ }
302+
303+ async fn join_voice_inner(
304+ &self,
305+ community_id: String,
306+ settings: VoiceSettings,
307+ ) -> Result<Vec<String>, Fail> {
308+ let (connection, epoch) = self.current_wait().await?;
309+ let participants = join(&connection, &community_id).await?;
310+ let voice = voice::start(Some(connection), &settings);
311+ let mut inner = self.lock();
312+ if !inner.current(epoch) {
313+ return Err(Fail::Offline);
314+ }
315+ let want = Want {
316+ community_id,
317+ settings,
318+ muted: false,
319+ deafened: false,
320+ };
321+ inner.install_voice(voice, want);
322+
323+ Ok(participants)
324+ }
325+
326+ async fn leave_voice(&self) -> Result<(), Fail> {
327+ let connection = {
328+ let mut inner = self.lock();
329+ inner.drop_calls();
330+ inner.want_voice = None;
331+ inner.watching.clear();
332+ inner.connection.clone().ok_or(Fail::Offline)?
333+ };
334+
335+ done(&connection, LegacyRequest::LeaveVoice).await
336+ }
337+
338+ async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {
339+ let (connection, epoch) = self.current_wait().await?;
340+ let top = match kind {
341+ Kind::Screen => settings.top,
342+ Kind::Camera => CAMERA_TOP,
343+ };
344+ let sharing = Sharing::start(
345+ connection.clone(),
346+ kind,
347+ top,
348+ settings.encode(),
349+ settings.audio_mode(),
350+ )
351+ .await
352+ .map_err(Fail::Io)?;
353+ let source = sharing.source();
354+ {
355+ let mut inner = self.lock();
356+ if !inner.current(epoch) {
357+ return Err(Fail::Offline);
358+ }
359+ inner.sharing.insert(kind, sharing);
360+ }
361+
362+ let result = done(&connection, LegacyRequest::StartShare { kind, source }).await;
363+ if result.is_err() {
364+ self.lock().sharing.remove(&kind);
365+ }
366+
367+ result
368+ }
369+
370+ async fn update_share(&self, settings: ShareSettings) -> Result<(), Fail> {
371+ let (connection, _) = self.current_wait().await?;
372+ let source = {
373+ let mut inner = self.lock();
374+ let Some(sharing) = inner.sharing.get_mut(&Kind::Screen) else {
375+ return Ok(());
376+ };
377+ sharing
378+ .update(
379+ &connection,
380+ settings.top,
381+ settings.encode(),
382+ settings.audio_mode(),
383+ )
384+ .map_err(Fail::Io)?
385+ };
386+
387+ done(
388+ &connection,
389+ LegacyRequest::StartShare {
390+ kind: Kind::Screen,
391+ source,
392+ },
393+ )
394+ .await
395+ }
396+
397+ async fn stop_share(&self, kind: Kind) -> Result<(), Fail> {
398+ self.lock().sharing.remove(&kind);
399+ let (connection, _) = self.current_wait().await?;
400+
401+ done(&connection, LegacyRequest::StopShare { kind }).await
402+ }
403+}
404+
405+impl Inner {
406+ fn watch_requests(&self) -> Vec<((String, Kind), LegacyRequest)> {
407+ self.watching
408+ .iter()
409+ .map(|((user_id, kind), watching)| {
410+ let request = LegacyRequest::WatchShare {
411+ user_id: user_id.clone(),
412+ kind: *kind,
413+ quality: watching.wanted(),
414+ decode: capabilities().decode.clone(),
415+ };
416+ ((user_id.clone(), *kind), request)
417+ })
418+ .collect()
419+ }
420+}
421+
422+enum Rejoin {
423+ Install,
424+ Ended,
425+ Skip,
426+}
427+
428+async fn join(connection: &Connection, community_id: &str) -> Result<Vec<String>, Fail> {
429+ let request = LegacyRequest::JoinVoice {
430+ community_id: community_id.to_string(),
431+ };
432+ match send(connection, &request).await? {
433+ Response::Voice(participants) => Ok(participants),
434+ _ => Err(Fail::Protocol),
435+ }
436+}
437+
438+async fn send_quietly(connection: Connection, request: LegacyRequest) {
439+ if let Err(error) = send(&connection, &request).await {
440+ warn!("media request failed: {error}");
441+ }
442+}
443+
444+async fn tick_loop(media: Arc<Media>) {
445+ let mut ticker = tokio::time::interval(TICK);
446+ loop {
447+ ticker.tick().await;
448+ let (connection, requests) = {
449+ let mut inner = media.lock();
450+ (inner.connection.clone(), watch_ticks(&mut inner.watching))
451+ };
452+ let Some(connection) = connection else {
453+ continue;
454+ };
455+ for request in requests {
456+ tokio::spawn(send_quietly(connection.clone(), request));
457+ }
458+ }
459+}
460+
461+fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<LegacyRequest> {
462+ watching
463+ .iter_mut()
464+ .flat_map(|((user_id, kind), watching)| {
465+ let (user_id, kind) = (user_id.clone(), *kind);
466+ watching
467+ .tick()
468+ .into_iter()
469+ .map(|tick| match tick {
470+ Tick::Quality(quality) => LegacyRequest::WatchShare {
471+ user_id: user_id.clone(),
472+ kind,
473+ quality,
474+ decode: capabilities().decode.clone(),
475+ },
476+ Tick::Keyframe => LegacyRequest::RequestKeyframe {
477+ user_id: user_id.clone(),
478+ kind,
479+ },
480+ })
481+ .collect::<Vec<_>>()
482+ })
483+ .collect()
484+}
485+
486+impl NetworkHandle {
487+ fn media(&self) -> &Arc<Media> {
488+ &self.shared.media
489+ }
490+
491+ pub async fn join_voice(
492+ &self,
493+ community_id: &str,
494+ settings: &VoiceSettings,
495+ ) -> Result<Vec<String>, Fail> {
496+ let media = self.media().clone();
497+ let community_id = community_id.to_string();
498+ let settings = settings.clone();
499+
500+ self.media()
501+ .run(async move { media.join_voice(community_id, settings).await })
502+ .await
503+ }
504+
505+ pub async fn leave_voice(&self) -> Result<(), Fail> {
506+ let media = self.media().clone();
507+
508+ self.media()
509+ .run(async move { media.leave_voice().await })
510+ .await
511+ }
512+
513+ pub fn set_voice_settings(&self, settings: &VoiceSettings) {
514+ let mut inner = self.media().lock();
515+ if let Some(want) = inner.want_voice.as_mut() {
516+ want.settings = settings.clone();
517+ }
518+ if let Some(voice) = inner.voice.as_mut() {
519+ voice.apply(settings);
520+ }
521+ if let Some(voice) = inner.mic_test.as_mut() {
522+ voice.apply(settings);
523+ }
524+ }
525+
526+ pub fn start_mic_test(&self, settings: &VoiceSettings) {
527+ if self.media().lock().voice.is_some() {
528+ return;
529+ }
530+ let voice = voice::start(None, settings);
531+ let mut inner = self.media().lock();
532+ if inner.voice.is_none() {
533+ inner.mic_test = Some(voice);
534+ }
535+ }
536+
537+ pub fn stop_mic_test(&self) {
538+ self.media().lock().mic_test = None;
539+ }
540+
541+ pub fn play_chime(&self, settings: &VoiceSettings) {
542+ voice::play_chime(settings);
543+ }
544+
545+ pub fn play_notification(&self, settings: &VoiceSettings) {
546+ voice::play_yumush(settings);
547+ }
548+
549+ pub fn play_ring(&self, settings: &VoiceSettings) {
550+ voice::play_ring(settings);
551+ }
552+
553+ pub fn voice_level_db(&self) -> Option<f32> {
554+ let inner = self.media().lock();
555+
556+ inner
557+ .voice
558+ .as_ref()
559+ .or(inner.mic_test.as_ref())
560+ .map(Voice::level_db)
561+ }
562+
563+ pub fn voice_sample(&self) -> Option<VoiceSample> {
564+ self.media().lock().voice.as_ref().map(Voice::sample)
565+ }
566+
567+ pub fn set_talking(&self, talking: bool) {
568+ if let Some(voice) = &self.media().lock().voice {
569+ voice.set_talking(talking);
570+ }
571+ }
572+
573+ pub fn set_muted(&self, muted: bool) {
574+ let mut inner = self.media().lock();
575+ if let Some(want) = inner.want_voice.as_mut() {
576+ want.muted = muted;
577+ }
578+ if let Some(voice) = &inner.voice {
579+ voice.set_muted(muted);
580+ }
581+ }
582+
583+ pub fn set_deafened(&self, deafened: bool) {
584+ let mut inner = self.media().lock();
585+ if let Some(want) = inner.want_voice.as_mut() {
586+ want.deafened = deafened;
587+ }
588+ if let Some(voice) = &inner.voice {
589+ voice.set_deafened(deafened);
590+ }
591+ }
592+
593+ pub fn levels(&self) -> Levels {
594+ let inner = self.media().lock();
595+ Levels {
596+ voice: inner.voice.as_ref().map(Voice::levels).unwrap_or_default(),
597+ watching: inner
598+ .watching
599+ .iter()
600+ .filter(|((_, kind), _)| *kind == Kind::Screen)
601+ .map(|((user_id, _), watching)| (user_id.clone(), watching.level()))
602+ .collect(),
603+ sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level),
604+ }
605+ }
606+
607+ pub async fn start_share(&self, settings: &ShareSettings) -> Result<(), Fail> {
608+ self.start(Kind::Screen, settings).await
609+ }
610+
611+ pub async fn start_camera(&self, settings: &ShareSettings) -> Result<(), Fail> {
612+ self.start(Kind::Camera, settings).await
613+ }
614+
615+ async fn start(&self, kind: Kind, settings: &ShareSettings) -> Result<(), Fail> {
616+ let media = self.media().clone();
617+ let settings = settings.clone();
618+
619+ self.media()
620+ .run(async move { media.start_share(kind, settings).await })
621+ .await
622+ }
623+
624+ pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> {
625+ let media = self.media().clone();
626+ let settings = settings.clone();
627+
628+ self.media()
629+ .run(async move { media.update_share(settings).await })
630+ .await
631+ }
632+
633+ pub async fn stop_share(&self) -> Result<(), Fail> {
634+ self.stop(Kind::Screen).await
635+ }
636+
637+ pub async fn stop_camera(&self) -> Result<(), Fail> {
638+ self.stop(Kind::Camera).await
639+ }
640+
641+ async fn stop(&self, kind: Kind) -> Result<(), Fail> {
642+ let media = self.media().clone();
643+
644+ self.media()
645+ .run(async move { media.stop_share(kind).await })
646+ .await
647+ }
648+
649+ pub fn sharing(&self) -> bool {
650+ self.media().lock().sharing.contains_key(&Kind::Screen)
651+ }
652+
653+ pub fn camera_on(&self) -> bool {
654+ self.media().lock().sharing.contains_key(&Kind::Camera)
655+ }
656+
657+ pub fn share_source(&self) -> Option<Source> {
658+ self.media()
659+ .lock()
660+ .sharing
661+ .get(&Kind::Screen)
662+ .map(Sharing::source)
663+ }
664+
665+ pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {
666+ expect!(
667+ self.request(LegacyRequest::Shares {
668+ community_id: community_id.to_string(),
669+ })
670+ .await?,
671+ Response::Shares
672+ )
673+ }
674+
675+ pub async fn watch_share(
676+ &self,
677+ user_id: &str,
678+ kind: Kind,
679+ watch: WatchQuality,
680+ volume: f32,
681+ choice: Choice,
682+ ) -> Result<(), Fail> {
683+ let media = self.media().clone();
684+ let key = (user_id.to_string(), kind);
685+ let watching = Watching::new(kind, watch, volume, choice);
686+ let quality = watching.wanted();
687+
688+ self.media()
689+ .run(async move {
690+ let (connection, epoch) = media.current_wait().await?;
691+ {
692+ let mut inner = media.lock();
693+ if !inner.current(epoch) {
694+ return Err(Fail::Offline);
695+ }
696+ inner.watching.insert(key.clone(), watching);
697+ }
698+ let result = done(
699+ &connection,
700+ LegacyRequest::WatchShare {
701+ user_id: key.0.clone(),
702+ kind,
703+ quality,
704+ decode: capabilities().decode.clone(),
705+ },
706+ )
707+ .await;
708+ if result.is_err() {
709+ media.lock().watching.remove(&key);
710+ }
711+
712+ result
713+ })
714+ .await
715+ }
716+
717+ pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> {
718+ self.media()
719+ .lock()
720+ .watching
721+ .remove(&(user_id.to_string(), kind));
722+
723+ self.done(LegacyRequest::UnwatchShare {
724+ user_id: user_id.to_string(),
725+ kind,
726+ })
727+ .await
728+ }
729+
730+ pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) {
731+ if let Some(watching) = self
732+ .media()
733+ .lock()
734+ .watching
735+ .get_mut(&(user_id.to_string(), kind))
736+ {
737+ watching.set_quality(quality);
738+ }
739+ }
740+
741+ pub fn set_share_settings(&self, settings: &ShareSettings) {
742+ for ((_, kind), watching) in self.media().lock().watching.iter_mut() {
743+ if *kind == Kind::Screen {
744+ watching.set_volume(settings.volume);
745+ watching.set_quality(settings.watch);
746+ }
747+ }
748+ }
749+
750+ pub fn share_sample(&self) -> ShareSample {
751+ let mut inner = self.media().lock();
752+ ShareSample {
753+ sending: inner
754+ .sharing
755+ .get(&Kind::Screen)
756+ .map(Sharing::stats)
757+ .unwrap_or_default(),
758+ watching: inner
759+ .watching
760+ .iter_mut()
761+ .filter(|((_, kind), _)| *kind == Kind::Screen)
762+ .map(|((user_id, _), watching)| (user_id.clone(), watching.stats()))
763+ .collect(),
764+ }
765+ }
766+
767+ pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> {
768+ self.media()
769+ .lock()
770+ .watching
771+ .get(&(user_id.to_string(), kind))?
772+ .frame()
773+ }
774+
775+ pub fn audio_apps(&self) -> Vec<AudioApp> {
776+ audio_capture::apps()
777+ }
778+}
crates/client/src/net/mod.rsmodified+153 -199
@@ -1,9 +1,10 @@
1-use std::{1+use std::{path::PathBuf, sync::Arc};
2- path::PathBuf,
3- sync::{Arc, Mutex},
4-};
5 2
6 use common::{3 use common::{
4+ call::{
5+ Call, GetAvatar, GetSettings, GetUser, Legacy, ListPresences, ListSessions, RemoveAvatar,
6+ RevokeSession, UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser,
7+ },
7 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},8 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
8 event::Event,9 event::Event,
9 model::{10 model::{
@@ -13,9 +14,8 @@ use common::{
13 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,14 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
14 },15 },
15 open::Blob,16 open::Blob,
16- request::Request,17+ request::LegacyRequest,
17 response::Response,18 response::Response,
18- share::Kind,
19 validate::{19 validate::{
20 validate_avatar_size, validate_community_name, validate_forward, validate_new_message,20 validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
21 validate_password, validate_poll, validate_reason, validate_server_settings,21 validate_password, validate_poll, validate_reason, validate_server_settings,
@@ -24,11 +24,6 @@ use common::{
24 };24 };
25 use tokio::sync::{mpsc, oneshot};25 use tokio::sync::{mpsc, oneshot};
26 26
27-use crate::{
28- settings::{ShareSettings, VoiceSettings},
29- voice::Voice,
30-};
31-
32 macro_rules! expect {27 macro_rules! expect {
33 ($response:expr, $variant:path) => {28 ($response:expr, $variant:path) => {
34 match $response {29 match $response {
@@ -43,12 +38,11 @@ mod events;
43 mod fail;38 mod fail;
44 mod fetch;39 mod fetch;
45 mod link;40 mod link;
46-mod share;41+mod media;
47-mod voice;
48 42
49 pub use fail::{Fail, LinkError};43 pub use fail::{Fail, LinkError};
50 pub use link::start;44 pub use link::start;
51-use share::Share;45+use media::Media;
52 46
53 fn device_name() -> String {47 fn device_name() -> String {
54 let host = gethostname::gethostname()48 let host = gethostname::gethostname()
@@ -64,26 +58,12 @@ fn device_name() -> String {
64 format!("{host} {}", std::env::consts::OS)58 format!("{host} {}", std::env::consts::OS)
65 }59 }
66 60
67-type SharedVoice = Arc<Mutex<Option<Voice>>>;61+#[derive(Clone)]
68-type SharedSettings = Arc<Mutex<VoiceSettings>>;
69-type SharedShare = Arc<Mutex<Share>>;
70-type SharedShareSettings = Arc<Mutex<ShareSettings>>;
71-
72-#[derive(Clone, Default)]
73 struct Shared {62 struct Shared {
74- voice: SharedVoice,63+ media: Arc<Media>,
75- mic_test: SharedVoice,
76- voice_settings: SharedSettings,
77- share: SharedShare,
78- share_settings: SharedShareSettings,
79 fetches: Arc<fetch::Fetches>,64 fetches: Arc<fetch::Fetches>,
80 }65 }
81 66
82-fn hang_up(shared: &Shared) {
83- shared.voice.lock().unwrap().take();
84- *shared.share.lock().unwrap() = Share::default();
85-}
86-
87 #[derive(Default)]67 #[derive(Default)]
88 pub struct Levels {68 pub struct Levels {
89 pub voice: Vec<(String, Vec<f32>)>,69 pub voice: Vec<(String, Vec<f32>)>,
@@ -94,17 +74,15 @@ pub struct Levels {
94 #[derive(Debug)]74 #[derive(Debug)]
95 pub enum NetworkEvent {75 pub enum NetworkEvent {
96 Connected,76 Connected,
77+ VoiceRejoined,
78+ VoiceEnded,
97 Disconnected(LinkError),79 Disconnected(LinkError),
98 SessionLost,80 SessionLost,
99 Pushed(Box<Event>),81 Pushed(Box<Event>),
100 }82 }
101 83
102-#[derive(Debug)]
103 enum Command {84 enum Command {
104- Request {85+ Call(Box<dyn FnOnce(quinn::Connection) + Send>),
105- request: Request,
106- reply: oneshot::Sender<Result<Response, Fail>>,
107- },
108 SignIn {86 SignIn {
109 token: Option<String>,87 token: Option<String>,
110 reply: oneshot::Sender<Result<Option<User>, Fail>>,88 reply: oneshot::Sender<Result<Option<User>, Fail>>,
@@ -124,15 +102,6 @@ enum Command {
124 path: PathBuf,102 path: PathBuf,
125 reply: oneshot::Sender<Result<(), Fail>>,103 reply: oneshot::Sender<Result<(), Fail>>,
126 },104 },
127- StartShare {
128- kind: Kind,
129- settings: ShareSettings,
130- reply: oneshot::Sender<Result<(), Fail>>,
131- },
132- UpdateShare {
133- settings: ShareSettings,
134- reply: oneshot::Sender<Result<(), Fail>>,
135- },
136 }105 }
137 106
138 #[derive(Clone)]107 #[derive(Clone)]
@@ -156,19 +125,24 @@ impl NetworkHandle {
156 response.await.map_err(|_| Fail::Offline)?125 response.await.map_err(|_| Fail::Offline)?
157 }126 }
158 127
159- fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> {128+ async fn call<C: Call>(&self, call: C) -> Result<C::Reply, Fail> {
160- self.shared.voice.lock().unwrap().as_ref().map(f)129+ self.ask(|reply| {
130+ Command::Call(Box::new(move |connection| {
131+ link::answer(reply, async move { link::call(&connection, call).await });
132+ }))
133+ })
134+ .await
161 }135 }
162 136
163- async fn request(&self, request: Request) -> Result<Response, Fail> {137+ async fn request(&self, request: LegacyRequest) -> Result<Response, Fail> {
164- self.ask(|reply| Command::Request { request, reply }).await138+ self.call(Legacy(request)).await
165 }139 }
166 140
167 async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> {141 async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> {
168 self.ask(|reply| Command::SignIn { token, reply }).await142 self.ask(|reply| Command::SignIn { token, reply }).await
169 }143 }
170 144
171- async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> {145+ async fn sign_in(&self, request: LegacyRequest) -> Result<(User, String), Fail> {
172 let (user, token) = match self.request(request).await? {146 let (user, token) = match self.request(request).await? {
173 Response::Session { user, token } => (user, token),147 Response::Session { user, token } => (user, token),
174 _ => return Err(Fail::Protocol),148 _ => return Err(Fail::Protocol),
@@ -179,17 +153,14 @@ impl NetworkHandle {
179 }153 }
180 154
181 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {155 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {
182- expect!(156+ self.call(ListSessions {
183- self.request(Request::Sessions {157+ user_id: user_id.to_string(),
184- user_id: user_id.to_string(),158+ })
185- })159+ .await
186- .await?,
187- Response::Sessions
188- )
189 }160 }
190 161
191 pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> {162 pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> {
192- self.done(Request::RevokeSession {163+ self.call(RevokeSession {
193 user_id: user_id.to_string(),164 user_id: user_id.to_string(),
194 session_id: session_id.to_string(),165 session_id: session_id.to_string(),
195 })166 })
@@ -200,7 +171,7 @@ impl NetworkHandle {
200 validate_username(username)?;171 validate_username(username)?;
201 172
202 expect!(173 expect!(
203- self.request(Request::RenameUser {174+ self.request(LegacyRequest::RenameUser {
204 user_id: user_id.to_string(),175 user_id: user_id.to_string(),
205 username: username.to_string(),176 username: username.to_string(),
206 })177 })
@@ -231,7 +202,7 @@ impl NetworkHandle {
231 validate_username(username)?;202 validate_username(username)?;
232 validate_password(password)?;203 validate_password(password)?;
233 204
234- self.sign_in(Request::Register {205+ self.sign_in(LegacyRequest::Register {
235 username: username.to_string(),206 username: username.to_string(),
236 password: password.to_string(),207 password: password.to_string(),
237 invite: invite.map(str::to_string),208 invite: invite.map(str::to_string),
@@ -242,7 +213,7 @@ impl NetworkHandle {
242 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {213 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {
243 validate_password(password)?;214 validate_password(password)?;
244 215
245- self.sign_in(Request::Login {216+ self.sign_in(LegacyRequest::Login {
246 username: username.to_string(),217 username: username.to_string(),
247 password: password.to_string(),218 password: password.to_string(),
248 })219 })
@@ -250,7 +221,7 @@ impl NetworkHandle {
250 }221 }
251 222
252 pub async fn logout(&self) -> Result<(), Fail> {223 pub async fn logout(&self) -> Result<(), Fail> {
253- let result = self.done(Request::Logout).await;224+ let result = self.done(LegacyRequest::Logout).await;
254 self.detach().await?;225 self.detach().await?;
255 result226 result
256 }227 }
@@ -258,18 +229,15 @@ impl NetworkHandle {
258 pub async fn update_user(&self, username: &str) -> Result<User, Fail> {229 pub async fn update_user(&self, username: &str) -> Result<User, Fail> {
259 validate_username(username)?;230 validate_username(username)?;
260 231
261- expect!(232+ self.call(UpdateUser {
262- self.request(Request::UpdateUser {233+ username: username.to_string(),
263- username: username.to_string(),234+ })
264- })235+ .await
265- .await?,
266- Response::User
267- )
268 }236 }
269 237
270 pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {238 pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {
271 expect!(239 expect!(
272- self.request(Request::DeleteUser {240+ self.request(LegacyRequest::DeleteUser {
273 user_id: user_id.to_string(),241 user_id: user_id.to_string(),
274 })242 })
275 .await?,243 .await?,
@@ -279,11 +247,11 @@ impl NetworkHandle {
279 }247 }
280 248
281 pub async fn users(&self) -> Result<Vec<Account>, Fail> {249 pub async fn users(&self) -> Result<Vec<Account>, Fail> {
282- expect!(self.request(Request::Users).await?, Response::Users)250+ expect!(self.request(LegacyRequest::Users).await?, Response::Users)
283 }251 }
284 252
285 pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {253 pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {
286- self.done(Request::SuspendUser {254+ self.done(LegacyRequest::SuspendUser {
287 user_id: user_id.to_string(),255 user_id: user_id.to_string(),
288 suspended,256 suspended,
289 })257 })
@@ -291,7 +259,7 @@ impl NetworkHandle {
291 }259 }
292 260
293 pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {261 pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {
294- self.done(Request::TimeoutUser {262+ self.done(LegacyRequest::TimeoutUser {
295 user_id: user_id.to_string(),263 user_id: user_id.to_string(),
296 minutes,264 minutes,
297 })265 })
@@ -306,7 +274,7 @@ impl NetworkHandle {
306 ) -> Result<(), Fail> {274 ) -> Result<(), Fail> {
307 validate_reason(reason)?;275 validate_reason(reason)?;
308 276
309- self.done(Request::BanUser {277+ self.done(LegacyRequest::BanUser {
310 user_id: user_id.to_string(),278 user_id: user_id.to_string(),
311 reason: reason.map(str::to_string),279 reason: reason.map(str::to_string),
312 scope,280 scope,
@@ -316,13 +284,13 @@ impl NetworkHandle {
316 284
317 pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {285 pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {
318 expect!(286 expect!(
319- self.request(Request::ServerBans).await?,287+ self.request(LegacyRequest::ServerBans).await?,
320 Response::ServerBans288 Response::ServerBans
321 )289 )
322 }290 }
323 291
324 pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {292 pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {
325- self.done(Request::RemoveServerBan { id: id.to_string() })293+ self.done(LegacyRequest::RemoveServerBan { id: id.to_string() })
326 .await294 .await
327 }295 }
328 296
@@ -332,7 +300,7 @@ impl NetworkHandle {
332 hours: Option<u32>,300 hours: Option<u32>,
333 ) -> Result<InviteCode, Fail> {301 ) -> Result<InviteCode, Fail> {
334 expect!(302 expect!(
335- self.request(Request::CreateInviteCode { uses, hours })303+ self.request(LegacyRequest::CreateInviteCode { uses, hours })
336 .await?,304 .await?,
337 Response::InviteCode305 Response::InviteCode
338 )306 )
@@ -340,20 +308,20 @@ impl NetworkHandle {
340 308
341 pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {309 pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {
342 expect!(310 expect!(
343- self.request(Request::InviteCodes).await?,311+ self.request(LegacyRequest::InviteCodes).await?,
344 Response::InviteCodes312 Response::InviteCodes
345 )313 )
346 }314 }
347 315
348 pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {316 pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {
349- self.done(Request::DeleteInviteCode {317+ self.done(LegacyRequest::DeleteInviteCode {
350 code: code.to_string(),318 code: code.to_string(),
351 })319 })
352 .await320 .await
353 }321 }
354 322
355 pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {323 pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {
356- self.done(Request::RevokeSessions {324+ self.done(LegacyRequest::RevokeSessions {
357 user_id: user_id.to_string(),325 user_id: user_id.to_string(),
358 })326 })
359 .await327 .await
@@ -362,7 +330,7 @@ impl NetworkHandle {
362 pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {330 pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {
363 validate_password(password)?;331 validate_password(password)?;
364 332
365- self.done(Request::ResetPassword {333+ self.done(LegacyRequest::ResetPassword {
366 user_id: user_id.to_string(),334 user_id: user_id.to_string(),
367 password: password.to_string(),335 password: password.to_string(),
368 })336 })
@@ -371,7 +339,7 @@ impl NetworkHandle {
371 339
372 pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {340 pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {
373 expect!(341 expect!(
374- self.request(Request::ClearProfile {342+ self.request(LegacyRequest::ClearProfile {
375 user_id: user_id.to_string(),343 user_id: user_id.to_string(),
376 })344 })
377 .await?,345 .await?,
@@ -381,7 +349,7 @@ impl NetworkHandle {
381 349
382 pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {350 pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {
383 expect!(351 expect!(
384- self.request(Request::SetRole {352+ self.request(LegacyRequest::SetRole {
385 user_id: user_id.to_string(),353 user_id: user_id.to_string(),
386 role,354 role,
387 })355 })
@@ -398,7 +366,7 @@ impl NetworkHandle {
398 after_ms: Option<u64>,366 after_ms: Option<u64>,
399 before_ms: Option<u64>,367 before_ms: Option<u64>,
400 ) -> Result<Vec<AdminLogEntry>, Fail> {368 ) -> Result<Vec<AdminLogEntry>, Fail> {
401- let request = Request::AdminLogs {369+ let request = LegacyRequest::AdminLogs {
402 actor_id,370 actor_id,
403 target_id,371 target_id,
404 action,372 action,
@@ -410,16 +378,13 @@ impl NetworkHandle {
410 378
411 pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {379 pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {
412 expect!(380 expect!(
413- self.request(Request::DailyStats { days }).await?,381+ self.request(LegacyRequest::DailyStats { days }).await?,
414 Response::DailyStats382 Response::DailyStats
415 )383 )
416 }384 }
417 385
418 pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {386 pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {
419- expect!(387+ self.call(GetSettings).await
420- self.request(Request::ServerSettings).await?,
421- Response::ServerSettings
422- )
423 }388 }
424 389
425 pub async fn update_server_settings(390 pub async fn update_server_settings(
@@ -429,7 +394,7 @@ impl NetworkHandle {
429 validate_server_settings(&settings)?;394 validate_server_settings(&settings)?;
430 395
431 expect!(396 expect!(
432- self.request(Request::UpdateServerSettings { settings })397+ self.request(LegacyRequest::UpdateServerSettings { settings })
433 .await?,398 .await?,
434 Response::ServerSettings399 Response::ServerSettings
435 )400 )
@@ -440,7 +405,7 @@ impl NetworkHandle {
440 validate_password(password)?;405 validate_password(password)?;
441 406
442 expect!(407 expect!(
443- self.request(Request::CreateUser {408+ self.request(LegacyRequest::CreateUser {
444 username: username.to_string(),409 username: username.to_string(),
445 password: password.to_string(),410 password: password.to_string(),
446 })411 })
@@ -450,18 +415,21 @@ impl NetworkHandle {
450 }415 }
451 416
452 pub async fn overview(&self) -> Result<Overview, Fail> {417 pub async fn overview(&self) -> Result<Overview, Fail> {
453- expect!(self.request(Request::Overview).await?, Response::Overview)418+ expect!(
419+ self.request(LegacyRequest::Overview).await?,
420+ Response::Overview
421+ )
454 }422 }
455 423
456 pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {424 pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {
457 expect!(425 expect!(
458- self.request(Request::AllCommunities).await?,426+ self.request(LegacyRequest::AllCommunities).await?,
459 Response::AllCommunities427 Response::AllCommunities
460 )428 )
461 }429 }
462 430
463 pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {431 pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
464- self.done(Request::TransferOwnership {432+ self.done(LegacyRequest::TransferOwnership {
465 community_id: community_id.to_string(),433 community_id: community_id.to_string(),
466 user_id: user_id.to_string(),434 user_id: user_id.to_string(),
467 })435 })
@@ -469,20 +437,17 @@ impl NetworkHandle {
469 }437 }
470 438
471 pub async fn read_user(&self, user_id: &str) -> Result<User, Fail> {439 pub async fn read_user(&self, user_id: &str) -> Result<User, Fail> {
472- expect!(440+ self.call(GetUser {
473- self.request(Request::ReadUser {441+ user_id: user_id.to_string(),
474- user_id: user_id.to_string(),442+ })
475- })443+ .await
476- .await?,
477- Response::User
478- )
479 }444 }
480 445
481 pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {446 pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {
482 validate_community_name(name)?;447 validate_community_name(name)?;
483 448
484 expect!(449 expect!(
485- self.request(Request::CreateCommunity {450+ self.request(LegacyRequest::CreateCommunity {
486 name: name.to_string(),451 name: name.to_string(),
487 })452 })
488 .await?,453 .await?,
@@ -498,7 +463,7 @@ impl NetworkHandle {
498 validate_community_name(name)?;463 validate_community_name(name)?;
499 464
500 expect!(465 expect!(
501- self.request(Request::UpdateCommunity {466+ self.request(LegacyRequest::UpdateCommunity {
502 community_id: community_id.to_string(),467 community_id: community_id.to_string(),
503 name: name.to_string(),468 name: name.to_string(),
504 })469 })
@@ -509,7 +474,7 @@ impl NetworkHandle {
509 474
510 pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {475 pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {
511 expect!(476 expect!(
512- self.request(Request::DeleteCommunity {477+ self.request(LegacyRequest::DeleteCommunity {
513 community_id: community_id.to_string(),478 community_id: community_id.to_string(),
514 })479 })
515 .await?,480 .await?,
@@ -519,7 +484,7 @@ impl NetworkHandle {
519 }484 }
520 485
521 pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {486 pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {
522- self.done(Request::LeaveCommunity {487+ self.done(LegacyRequest::LeaveCommunity {
523 community_id: community_id.to_string(),488 community_id: community_id.to_string(),
524 })489 })
525 .await490 .await
@@ -527,14 +492,14 @@ impl NetworkHandle {
527 492
528 pub async fn communities(&self) -> Result<Vec<Community>, Fail> {493 pub async fn communities(&self) -> Result<Vec<Community>, Fail> {
529 expect!(494 expect!(
530- self.request(Request::Communities).await?,495+ self.request(LegacyRequest::Communities).await?,
531 Response::Communities496 Response::Communities
532 )497 )
533 }498 }
534 499
535 pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {500 pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {
536 expect!(501 expect!(
537- self.request(Request::Members {502+ self.request(LegacyRequest::Members {
538 community_id: community_id.to_string(),503 community_id: community_id.to_string(),
539 })504 })
540 .await?,505 .await?,
@@ -549,7 +514,7 @@ impl NetworkHandle {
549 reason: Option<&str>,514 reason: Option<&str>,
550 ) -> Result<(), Fail> {515 ) -> Result<(), Fail> {
551 validate_reason(reason)?;516 validate_reason(reason)?;
552- self.done(Request::Kick {517+ self.done(LegacyRequest::Kick {
553 community_id: community_id.to_string(),518 community_id: community_id.to_string(),
554 user_id: user_id.to_string(),519 user_id: user_id.to_string(),
555 reason: reason.map(str::to_string),520 reason: reason.map(str::to_string),
@@ -564,7 +529,7 @@ impl NetworkHandle {
564 reason: Option<&str>,529 reason: Option<&str>,
565 ) -> Result<(), Fail> {530 ) -> Result<(), Fail> {
566 validate_reason(reason)?;531 validate_reason(reason)?;
567- self.done(Request::Ban {532+ self.done(LegacyRequest::Ban {
568 community_id: community_id.to_string(),533 community_id: community_id.to_string(),
569 user_id: user_id.to_string(),534 user_id: user_id.to_string(),
570 reason: reason.map(str::to_string),535 reason: reason.map(str::to_string),
@@ -573,7 +538,7 @@ impl NetworkHandle {
573 }538 }
574 539
575 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {540 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
576- self.done(Request::Unban {541+ self.done(LegacyRequest::Unban {
577 community_id: community_id.to_string(),542 community_id: community_id.to_string(),
578 user_id: user_id.to_string(),543 user_id: user_id.to_string(),
579 })544 })
@@ -582,7 +547,7 @@ impl NetworkHandle {
582 547
583 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {548 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {
584 expect!(549 expect!(
585- self.request(Request::Bans {550+ self.request(LegacyRequest::Bans {
586 community_id: community_id.to_string(),551 community_id: community_id.to_string(),
587 })552 })
588 .await?,553 .await?,
@@ -592,7 +557,7 @@ impl NetworkHandle {
592 557
593 pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {558 pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {
594 expect!(559 expect!(
595- self.request(Request::Logs {560+ self.request(LegacyRequest::Logs {
596 community_id: community_id.to_string(),561 community_id: community_id.to_string(),
597 })562 })
598 .await?,563 .await?,
@@ -606,7 +571,7 @@ impl NetworkHandle {
606 user_id: &str,571 user_id: &str,
607 rank: Rank,572 rank: Rank,
608 ) -> Result<(), Fail> {573 ) -> Result<(), Fail> {
609- self.done(Request::SetRank {574+ self.done(LegacyRequest::SetRank {
610 community_id: community_id.to_string(),575 community_id: community_id.to_string(),
611 user_id: user_id.to_string(),576 user_id: user_id.to_string(),
612 rank,577 rank,
@@ -616,7 +581,7 @@ impl NetworkHandle {
616 581
617 pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {582 pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {
618 expect!(583 expect!(
619- self.request(Request::DeleteMessage {584+ self.request(LegacyRequest::DeleteMessage {
620 message_id: message_id.to_string(),585 message_id: message_id.to_string(),
621 })586 })
622 .await?,587 .await?,
@@ -635,7 +600,7 @@ impl NetworkHandle {
635 validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;600 validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
636 601
637 expect!(602 expect!(
638- self.request(Request::CreateMessage {603+ self.request(LegacyRequest::CreateMessage {
639 community_id: community_id.to_string(),604 community_id: community_id.to_string(),
640 body: body.to_string(),605 body: body.to_string(),
641 attachments,606 attachments,
@@ -650,7 +615,7 @@ impl NetworkHandle {
650 validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;615 validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
651 616
652 expect!(617 expect!(
653- self.request(Request::UpdateMessage {618+ self.request(LegacyRequest::UpdateMessage {
654 message_id: message_id.to_string(),619 message_id: message_id.to_string(),
655 body: body.to_string(),620 body: body.to_string(),
656 })621 })
@@ -668,7 +633,7 @@ impl NetworkHandle {
668 validate_forward(message_ids.len())?;633 validate_forward(message_ids.len())?;
669 634
670 expect!(635 expect!(
671- self.request(Request::ForwardMessages {636+ self.request(LegacyRequest::ForwardMessages {
672 message_ids,637 message_ids,
673 community_id: community_id.to_string(),638 community_id: community_id.to_string(),
674 snippet,639 snippet,
@@ -680,7 +645,7 @@ impl NetworkHandle {
680 645
681 pub async fn find_user(&self, username: &str) -> Result<User, Fail> {646 pub async fn find_user(&self, username: &str) -> Result<User, Fail> {
682 expect!(647 expect!(
683- self.request(Request::FindUser {648+ self.request(LegacyRequest::FindUser {
684 username: username.to_string(),649 username: username.to_string(),
685 })650 })
686 .await?,651 .await?,
@@ -689,12 +654,15 @@ impl NetworkHandle {
689 }654 }
690 655
691 pub async fn open_notes(&self) -> Result<Community, Fail> {656 pub async fn open_notes(&self) -> Result<Community, Fail> {
692- expect!(self.request(Request::OpenNotes).await?, Response::Community)657+ expect!(
658+ self.request(LegacyRequest::OpenNotes).await?,
659+ Response::Community
660+ )
693 }661 }
694 662
695 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {663 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {
696 expect!(664 expect!(
697- self.request(Request::OpenDirect {665+ self.request(LegacyRequest::OpenDirect {
698 user_id: user_id.to_string(),666 user_id: user_id.to_string(),
699 })667 })
700 .await?,668 .await?,
@@ -703,43 +671,43 @@ impl NetworkHandle {
703 }671 }
704 672
705 pub async fn friends(&self) -> Result<Friends, Fail> {673 pub async fn friends(&self) -> Result<Friends, Fail> {
706- expect!(self.request(Request::Friends).await?, Response::Friends)674+ expect!(
675+ self.request(LegacyRequest::Friends).await?,
676+ Response::Friends
677+ )
707 }678 }
708 679
709 pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {680 pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {
710- expect!(681+ self.call(ListPresences).await
711- self.request(Request::ReadPresences).await?,
712- Response::Presences
713- )
714 }682 }
715 683
716 pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> {684 pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> {
717- self.done(Request::UpdatePresence { presence }).await685+ self.call(UpdatePresence { presence }).await
718 }686 }
719 687
720 pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {688 pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {
721- self.done(Request::AddFriend {689+ self.done(LegacyRequest::AddFriend {
722 user_id: user_id.to_string(),690 user_id: user_id.to_string(),
723 })691 })
724 .await692 .await
725 }693 }
726 694
727 pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {695 pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {
728- self.done(Request::AcceptFriend {696+ self.done(LegacyRequest::AcceptFriend {
729 user_id: user_id.to_string(),697 user_id: user_id.to_string(),
730 })698 })
731 .await699 .await
732 }700 }
733 701
734 pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {702 pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {
735- self.done(Request::RemoveFriend {703+ self.done(LegacyRequest::RemoveFriend {
736 user_id: user_id.to_string(),704 user_id: user_id.to_string(),
737 })705 })
738 .await706 .await
739 }707 }
740 708
741 pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {709 pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
742- self.done(Request::Invite {710+ self.done(LegacyRequest::Invite {
743 community_id: community_id.to_string(),711 community_id: community_id.to_string(),
744 user_id: user_id.to_string(),712 user_id: user_id.to_string(),
745 })713 })
@@ -748,14 +716,14 @@ impl NetworkHandle {
748 716
749 pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {717 pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {
750 expect!(718 expect!(
751- self.request(Request::Invitations).await?,719+ self.request(LegacyRequest::Invitations).await?,
752 Response::Invitations720 Response::Invitations
753 )721 )
754 }722 }
755 723
756 pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {724 pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {
757 expect!(725 expect!(
758- self.request(Request::AcceptInvitation {726+ self.request(LegacyRequest::AcceptInvitation {
759 community_id: community_id.to_string(),727 community_id: community_id.to_string(),
760 })728 })
761 .await?,729 .await?,
@@ -764,21 +732,21 @@ impl NetworkHandle {
764 }732 }
765 733
766 pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {734 pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {
767- self.done(Request::DeclineInvitation {735+ self.done(LegacyRequest::DeclineInvitation {
768 community_id: community_id.to_string(),736 community_id: community_id.to_string(),
769 })737 })
770 .await738 .await
771 }739 }
772 740
773 pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {741 pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {
774- self.done(Request::DeclineCall {742+ self.done(LegacyRequest::DeclineCall {
775 community_id: community_id.to_string(),743 community_id: community_id.to_string(),
776 })744 })
777 .await745 .await
778 }746 }
779 747
780 pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {748 pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {
781- self.done(Request::React {749+ self.done(LegacyRequest::React {
782 message_id: message_id.to_string(),750 message_id: message_id.to_string(),
783 emoji: emoji.to_string(),751 emoji: emoji.to_string(),
784 })752 })
@@ -786,7 +754,7 @@ impl NetworkHandle {
786 }754 }
787 755
788 pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {756 pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {
789- self.done(Request::Pin {757+ self.done(LegacyRequest::Pin {
790 message_id: message_id.to_string(),758 message_id: message_id.to_string(),
791 pinned,759 pinned,
792 })760 })
@@ -795,7 +763,7 @@ impl NetworkHandle {
795 763
796 pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {764 pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {
797 expect!(765 expect!(
798- self.request(Request::Pins {766+ self.request(LegacyRequest::Pins {
799 community_id: community_id.to_string(),767 community_id: community_id.to_string(),
800 })768 })
801 .await?,769 .await?,
@@ -813,7 +781,7 @@ impl NetworkHandle {
813 validate_poll(question, &options)?;781 validate_poll(question, &options)?;
814 782
815 expect!(783 expect!(
816- self.request(Request::CreatePoll {784+ self.request(LegacyRequest::CreatePoll {
817 community_id: community_id.to_string(),785 community_id: community_id.to_string(),
818 question: question.to_string(),786 question: question.to_string(),
819 options,787 options,
@@ -825,7 +793,7 @@ impl NetworkHandle {
825 }793 }
826 794
827 pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {795 pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {
828- self.done(Request::Vote {796+ self.done(LegacyRequest::Vote {
829 message_id: message_id.to_string(),797 message_id: message_id.to_string(),
830 positions,798 positions,
831 })799 })
@@ -833,7 +801,7 @@ impl NetworkHandle {
833 }801 }
834 802
835 pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {803 pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {
836- self.done(Request::ClosePoll {804+ self.done(LegacyRequest::ClosePoll {
837 message_id: message_id.to_string(),805 message_id: message_id.to_string(),
838 })806 })
839 .await807 .await
@@ -842,7 +810,7 @@ impl NetworkHandle {
842 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {810 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {
843 validate_reason(Some(reason))?;811 validate_reason(Some(reason))?;
844 812
845- self.done(Request::ReportMessage {813+ self.done(LegacyRequest::ReportMessage {
846 message_id: message_id.to_string(),814 message_id: message_id.to_string(),
847 reason: reason.to_string(),815 reason: reason.to_string(),
848 })816 })
@@ -852,7 +820,7 @@ impl NetworkHandle {
852 pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {820 pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {
853 validate_reason(Some(reason))?;821 validate_reason(Some(reason))?;
854 822
855- self.done(Request::ReportUser {823+ self.done(LegacyRequest::ReportUser {
856 user_id: user_id.to_string(),824 user_id: user_id.to_string(),
857 reason: reason.to_string(),825 reason: reason.to_string(),
858 })826 })
@@ -861,13 +829,13 @@ impl NetworkHandle {
861 829
862 pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {830 pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {
863 expect!(831 expect!(
864- self.request(Request::Reports { status }).await?,832+ self.request(LegacyRequest::Reports { status }).await?,
865 Response::Reports833 Response::Reports
866 )834 )
867 }835 }
868 836
869 pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {837 pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {
870- self.done(Request::HandleReport {838+ self.done(LegacyRequest::HandleReport {
871 report_id: report_id.to_string(),839 report_id: report_id.to_string(),
872 status,840 status,
873 })841 })
@@ -883,7 +851,7 @@ impl NetworkHandle {
883 before_ms: Option<u64>,851 before_ms: Option<u64>,
884 ) -> Result<Vec<MessageHit>, Fail> {852 ) -> Result<Vec<MessageHit>, Fail> {
885 expect!(853 expect!(
886- self.request(Request::SearchMessages {854+ self.request(LegacyRequest::SearchMessages {
887 text,855 text,
888 user_id,856 user_id,
889 community_id,857 community_id,
@@ -901,29 +869,35 @@ impl NetworkHandle {
901 text: String,869 text: String,
902 ) -> Result<Vec<MessageHit>, Fail> {870 ) -> Result<Vec<MessageHit>, Fail> {
903 expect!(871 expect!(
904- self.request(Request::SearchCommunity { community_id, text })872+ self.request(LegacyRequest::SearchCommunity { community_id, text })
905 .await?,873 .await?,
906 Response::MessageHits874 Response::MessageHits
907 )875 )
908 }876 }
909 877
910 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {878 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {
911- match self.request(Request::StorageUsage).await? {879+ match self.request(LegacyRequest::StorageUsage).await? {
912 Response::StorageUsage { users, communities } => Ok((users, communities)),880 Response::StorageUsage { users, communities } => Ok((users, communities)),
913 _ => Err(Fail::Protocol),881 _ => Err(Fail::Protocol),
914 }882 }
915 }883 }
916 884
917 pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {885 pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {
918- expect!(self.request(Request::CreateBackup).await?, Response::Backup)886+ expect!(
887+ self.request(LegacyRequest::CreateBackup).await?,
888+ Response::Backup
889+ )
919 }890 }
920 891
921 pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {892 pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {
922- expect!(self.request(Request::Backups).await?, Response::Backups)893+ expect!(
894+ self.request(LegacyRequest::Backups).await?,
895+ Response::Backups
896+ )
923 }897 }
924 898
925 pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {899 pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {
926- self.done(Request::DeleteBackup {900+ self.done(LegacyRequest::DeleteBackup {
927 name: name.to_string(),901 name: name.to_string(),
928 })902 })
929 .await903 .await
@@ -935,7 +909,7 @@ impl NetworkHandle {
935 community_id: Option<String>,909 community_id: Option<String>,
936 ) -> Result<Vec<AttachmentInfo>, Fail> {910 ) -> Result<Vec<AttachmentInfo>, Fail> {
937 expect!(911 expect!(
938- self.request(Request::AllAttachments {912+ self.request(LegacyRequest::AllAttachments {
939 user_id,913 user_id,
940 community_id,914 community_id,
941 })915 })
@@ -945,20 +919,20 @@ impl NetworkHandle {
945 }919 }
946 920
947 pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {921 pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {
948- self.done(Request::DeleteAttachment {922+ self.done(LegacyRequest::DeleteAttachment {
949 attachment_id: attachment_id.to_string(),923 attachment_id: attachment_id.to_string(),
950 })924 })
951 .await925 .await
952 }926 }
953 927
954 pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {928 pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {
955- self.done(Request::PurgeUser {929+ self.done(LegacyRequest::PurgeUser {
956 user_id: user_id.to_string(),930 user_id: user_id.to_string(),
957 })931 })
958 .await932 .await
959 }933 }
960 934
961- async fn done(&self, request: Request) -> Result<(), Fail> {935+ async fn done(&self, request: LegacyRequest) -> Result<(), Fail> {
962 match self.request(request).await? {936 match self.request(request).await? {
963 Response::Done => Ok(()),937 Response::Done => Ok(()),
964 _ => Err(Fail::Protocol),938 _ => Err(Fail::Protocol),
@@ -1004,7 +978,7 @@ impl NetworkHandle {
1004 }978 }
1005 979
1006 pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {980 pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {
1007- self.done(Request::WatchCommunity {981+ self.done(LegacyRequest::WatchCommunity {
1008 community_id: community_id.map(str::to_string),982 community_id: community_id.map(str::to_string),
1009 })983 })
1010 .await984 .await
@@ -1016,7 +990,7 @@ impl NetworkHandle {
1016 before: Option<&str>,990 before: Option<&str>,
1017 ) -> Result<Vec<Message>, Fail> {991 ) -> Result<Vec<Message>, Fail> {
1018 expect!(992 expect!(
1019- self.request(Request::ReadMessages {993+ self.request(LegacyRequest::ReadMessages {
1020 community_id: community_id.to_string(),994 community_id: community_id.to_string(),
1021 before: before.map(str::to_string),995 before: before.map(str::to_string),
1022 })996 })
@@ -1026,11 +1000,14 @@ impl NetworkHandle {
1026 }1000 }
1027 1001
1028 pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {1002 pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {
1029- expect!(self.request(Request::Unreads).await?, Response::Unreads)1003+ expect!(
1004+ self.request(LegacyRequest::Unreads).await?,
1005+ Response::Unreads
1006+ )
1030 }1007 }
1031 1008
1032 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {1009 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {
1033- self.done(Request::MarkRead {1010+ self.done(LegacyRequest::MarkRead {
1034 community_id: community_id.to_string(),1011 community_id: community_id.to_string(),
1035 message_id: message_id.to_string(),1012 message_id: message_id.to_string(),
1036 })1013 })
@@ -1040,22 +1017,16 @@ impl NetworkHandle {
1040 pub async fn update_status(&self, status: &str) -> Result<User, Fail> {1017 pub async fn update_status(&self, status: &str) -> Result<User, Fail> {
1041 validate_status(status)?;1018 validate_status(status)?;
1042 1019
1043- expect!(1020+ self.call(UpdateStatus {
1044- self.request(Request::UpdateStatus {1021+ status: status.to_string(),
1045- status: status.to_string(),1022+ })
1046- })1023+ .await
1047- .await?,
1048- Response::User
1049- )
1050 }1024 }
1051 1025
1052 pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Fail> {1026 pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Fail> {
1053 validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?;1027 validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1054 1028
1055- expect!(1029+ self.call(UpdateAvatar { image: bytes }).await
1056- self.request(Request::UpdateAvatar { image: bytes }).await?,
1057- Response::User
1058- )
1059 }1030 }
1060 1031
1061 pub async fn update_community_avatar(1032 pub async fn update_community_avatar(
@@ -1068,7 +1039,7 @@ impl NetworkHandle {
1068 }1039 }
1069 1040
1070 expect!(1041 expect!(
1071- self.request(Request::UpdateCommunityAvatar {1042+ self.request(LegacyRequest::UpdateCommunityAvatar {
1072 community_id: community_id.to_string(),1043 community_id: community_id.to_string(),
1073 image,1044 image,
1074 })1045 })
@@ -1078,43 +1049,26 @@ impl NetworkHandle {
1078 }1049 }
1079 1050
1080 pub async fn remove_avatar(&self) -> Result<User, Fail> {1051 pub async fn remove_avatar(&self) -> Result<User, Fail> {
1081- expect!(self.request(Request::RemoveAvatar).await?, Response::User)1052+ self.call(RemoveAvatar).await
1082 }1053 }
1083 1054
1084 pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Fail> {1055 pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Fail> {
1085- expect!(1056+ self.call(GetAvatar {
1086- self.request(Request::ReadAvatar {1057+ avatar_id: avatar_id.to_string(),
1087- avatar_id: avatar_id.to_string(),1058+ })
1088- })1059+ .await
1089- .await?,
1090- Response::Avatar
1091- )
1092- }
1093-
1094- pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1095- expect!(
1096- self.request(Request::JoinVoice {
1097- community_id: community_id.to_string(),
1098- })
1099- .await?,
1100- Response::Voice
1101- )
1102 }1060 }
1103 1061
1104 pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {1062 pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {
1105- self.done(Request::Typing {1063+ self.done(LegacyRequest::Typing {
1106 community_id: community_id.to_string(),1064 community_id: community_id.to_string(),
1107 })1065 })
1108 .await1066 .await
1109 }1067 }
1110 1068
1111- pub async fn leave_voice(&self) -> Result<(), Fail> {
1112- self.done(Request::LeaveVoice).await
1113- }
1114-
1115 pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {1069 pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {
1116 expect!(1070 expect!(
1117- self.request(Request::ReadCommunity {1071+ self.request(LegacyRequest::ReadCommunity {
1118 community_id: community_id.to_string(),1072 community_id: community_id.to_string(),
1119 })1073 })
1120 .await?,1074 .await?,
@@ -1124,7 +1078,7 @@ impl NetworkHandle {
1124 1078
1125 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {1079 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1126 expect!(1080 expect!(
1127- self.request(Request::VoiceParticipants {1081+ self.request(LegacyRequest::VoiceParticipants {
1128 community_id: community_id.to_string(),1082 community_id: community_id.to_string(),
1129 })1083 })
1130 .await?,1084 .await?,
@@ -1134,24 +1088,24 @@ impl NetworkHandle {
1134 1088
1135 pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {1089 pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {
1136 expect!(1090 expect!(
1137- self.request(Request::VoiceRooms).await?,1091+ self.request(LegacyRequest::VoiceRooms).await?,
1138 Response::VoiceRooms1092 Response::VoiceRooms
1139 )1093 )
1140 }1094 }
1141 1095
1142 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {1096 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {
1143- self.done(Request::SetGhost { enabled }).await1097+ self.done(LegacyRequest::SetGhost { enabled }).await
1144 }1098 }
1145 1099
1146 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {1100 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {
1147- self.done(Request::KickFromVoice {1101+ self.done(LegacyRequest::KickFromVoice {
1148 user_id: user_id.to_string(),1102 user_id: user_id.to_string(),
1149 })1103 })
1150 .await1104 .await
1151 }1105 }
1152 1106
1153 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {1107 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {
1154- self.done(Request::ServerMute {1108+ self.done(LegacyRequest::ServerMute {
1155 user_id: user_id.to_string(),1109 user_id: user_id.to_string(),
1156 muted,1110 muted,
1157 })1111 })
@@ -1164,7 +1118,7 @@ impl NetworkHandle {
1164 enabled: bool,1118 enabled: bool,
1165 ) -> Result<Community, Fail> {1119 ) -> Result<Community, Fail> {
1166 expect!(1120 expect!(
1167- self.request(Request::SetCommunityVoice {1121+ self.request(LegacyRequest::SetCommunityVoice {
1168 community_id: community_id.to_string(),1122 community_id: community_id.to_string(),
1169 enabled,1123 enabled,
1170 })1124 })
crates/client/src/net/share.rsdeleted+0 -338
@@ -1,338 +0,0 @@
1-use std::collections::HashMap;
2-
3-use common::{
4- event::{Event, Media},
5- request::Request,
6- response::Response,
7- share::{Fps, Kind, Quality, Resolution, Source},
8-};
9-
10-use crate::{
11- settings::ShareSettings,
12- share::{
13- audio::AudioApp,
14- audio_capture,
15- encode::capabilities,
16- session::{ShareSample, Sharing, Tick, WatchQuality, Watching},
17- },
18-};
19-
20-use super::{link::done, *};
21-
22-#[derive(Default)]
23-pub(super) struct Share {
24- pub(super) sharing: HashMap<Kind, Sharing>,
25- pub(super) sources: HashMap<Kind, Source>,
26- pub(super) watching: HashMap<(String, Kind), Watching>,
27-}
28-
29-impl Share {
30- pub(super) fn event(&mut self, event: &Event) {
31- if let Event::ShareStopped { user_id, kind, .. } = event {
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 } => {
39- if let Some(sharing) = self.sharing.get_mut(kind) {
40- sharing.set_layers(layers);
41- }
42- }
43- Media::Keyframe { kind, layer } => {
44- if let Some(sharing) = self.sharing.get(kind) {
45- sharing.keyframe(*layer);
46- }
47- }
48- Media::VoiceEnded => {}
49- }
50- }
51-
52- pub(super) fn ticks(&mut self) -> Vec<Request> {
53- self.watching
54- .iter_mut()
55- .flat_map(|((user_id, kind), watching)| {
56- let (user_id, kind) = (user_id.clone(), *kind);
57- watching
58- .tick()
59- .into_iter()
60- .map(|tick| match tick {
61- Tick::Quality(quality) => Request::WatchShare {
62- user_id: user_id.clone(),
63- kind,
64- quality,
65- decode: capabilities().decode.clone(),
66- },
67- Tick::Keyframe => Request::RequestKeyframe {
68- user_id: user_id.clone(),
69- kind,
70- },
71- })
72- .collect::<Vec<_>>()
73- })
74- .collect()
75- }
76-}
77-
78-const CAMERA_TOP: Quality = Quality {
79- resolution: Resolution::P2160,
80- fps: Fps::F60,
81-};
82-
83-impl NetworkHandle {
84- pub async fn start_share(&self) -> Result<(), Fail> {
85- self.start(Kind::Screen).await
86- }
87-
88- pub async fn start_camera(&self) -> Result<(), Fail> {
89- self.start(Kind::Camera).await
90- }
91-
92- async fn start(&self, kind: Kind) -> Result<(), Fail> {
93- let settings = self.shared.share_settings.lock().unwrap().clone();
94- self.ask(|reply| Command::StartShare {
95- kind,
96- settings,
97- reply,
98- })
99- .await
100- }
101-
102- pub async fn update_share(&self) -> Result<(), Fail> {
103- let settings = self.shared.share_settings.lock().unwrap().clone();
104- self.ask(|reply| Command::UpdateShare { settings, reply })
105- .await
106- }
107-
108- pub async fn stop_share(&self) -> Result<(), Fail> {
109- self.stop(Kind::Screen).await
110- }
111-
112- pub async fn stop_camera(&self) -> Result<(), Fail> {
113- self.stop(Kind::Camera).await
114- }
115-
116- async fn stop(&self, kind: Kind) -> Result<(), Fail> {
117- let result = self.done(Request::StopShare { kind }).await;
118- let mut share = self.shared.share.lock().unwrap();
119- share.sharing.remove(&kind);
120- share.sources.remove(&kind);
121- result
122- }
123-
124- pub fn sharing(&self) -> bool {
125- self.shared
126- .share
127- .lock()
128- .unwrap()
129- .sharing
130- .contains_key(&Kind::Screen)
131- }
132-
133- pub fn camera_on(&self) -> bool {
134- self.shared
135- .share
136- .lock()
137- .unwrap()
138- .sharing
139- .contains_key(&Kind::Camera)
140- }
141-
142- pub fn share_source(&self) -> Option<Source> {
143- self.shared
144- .share
145- .lock()
146- .unwrap()
147- .sources
148- .get(&Kind::Screen)
149- .cloned()
150- }
151-
152- pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {
153- expect!(
154- self.request(Request::Shares {
155- community_id: community_id.to_string(),
156- })
157- .await?,
158- Response::Shares
159- )
160- }
161-
162- pub async fn watch_share(
163- &self,
164- user_id: &str,
165- kind: Kind,
166- watch: WatchQuality,
167- ) -> Result<(), Fail> {
168- let volume = self.shared.share_settings.lock().unwrap().volume;
169- let choice = self.shared.voice_settings.lock().unwrap().choice.clone();
170- let key = (user_id.to_string(), kind);
171- let watching = Watching::new(kind, watch, volume, choice);
172- let quality = watching.wanted();
173- self.shared
174- .share
175- .lock()
176- .unwrap()
177- .watching
178- .insert(key.clone(), watching);
179-
180- let result = self
181- .done(Request::WatchShare {
182- user_id: key.0.clone(),
183- kind,
184- quality,
185- decode: capabilities().decode.clone(),
186- })
187- .await;
188- if result.is_err() {
189- self.shared.share.lock().unwrap().watching.remove(&key);
190- }
191- result
192- }
193-
194- pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> {
195- self.shared
196- .share
197- .lock()
198- .unwrap()
199- .watching
200- .remove(&(user_id.to_string(), kind));
201- self.done(Request::UnwatchShare {
202- user_id: user_id.to_string(),
203- kind,
204- })
205- .await
206- }
207-
208- pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) {
209- if let Some(watching) = self
210- .shared
211- .share
212- .lock()
213- .unwrap()
214- .watching
215- .get_mut(&(user_id.to_string(), kind))
216- {
217- watching.set_quality(quality);
218- }
219- }
220-
221- pub fn share_sample(&self) -> ShareSample {
222- let mut share = self.shared.share.lock().unwrap();
223- ShareSample {
224- sending: share
225- .sharing
226- .get(&Kind::Screen)
227- .map(Sharing::stats)
228- .unwrap_or_default(),
229- watching: share
230- .watching
231- .iter_mut()
232- .filter(|((_, kind), _)| *kind == Kind::Screen)
233- .map(|((user_id, _), watching)| (user_id.clone(), watching.stats()))
234- .collect(),
235- }
236- }
237-
238- pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> {
239- self.shared
240- .share
241- .lock()
242- .unwrap()
243- .watching
244- .get(&(user_id.to_string(), kind))?
245- .frame()
246- }
247-
248- pub fn set_share_settings(&self, settings: ShareSettings) -> bool {
249- let changed = self.sharing()
250- && self
251- .shared
252- .share_settings
253- .lock()
254- .unwrap()
255- .encoding_differs(&settings);
256- *self.shared.share_settings.lock().unwrap() = settings.clone();
257- for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() {
258- if *kind == Kind::Screen {
259- watching.set_volume(settings.volume);
260- watching.set_quality(settings.watch);
261- }
262- }
263- changed
264- }
265-
266- pub fn audio_apps(&self) -> Vec<AudioApp> {
267- audio_capture::apps()
268- }
269-}
270-
271-pub(super) async fn start_share(
272- connection: &quinn::Connection,
273- share: &SharedShare,
274- kind: Kind,
275- settings: &ShareSettings,
276-) -> Result<(), Fail> {
277- let top = match kind {
278- Kind::Screen => settings.top,
279- Kind::Camera => CAMERA_TOP,
280- };
281- let (sharing, source) = Sharing::start(
282- connection.clone(),
283- kind,
284- top,
285- settings.encode(),
286- settings.audio_mode(),
287- )
288- .await
289- .map_err(Fail::Io)?;
290- {
291- let mut share = share.lock().unwrap();
292- share.sharing.insert(kind, sharing);
293- share.sources.insert(kind, source.clone());
294- }
295-
296- let result = done(connection, Request::StartShare { kind, source }).await;
297- if result.is_err() {
298- let mut share = share.lock().unwrap();
299- share.sharing.remove(&kind);
300- share.sources.remove(&kind);
301- }
302- result
303-}
304-
305-pub(super) async fn update_share(
306- connection: &quinn::Connection,
307- share: &SharedShare,
308- settings: &ShareSettings,
309-) -> Result<(), Fail> {
310- let source = {
311- let mut share = share.lock().unwrap();
312- let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else {
313- return Ok(());
314- };
315- sharing
316- .update(
317- connection,
318- settings.top,
319- settings.encode(),
320- settings.audio_mode(),
321- )
322- .map_err(Fail::Io)?
323- };
324- share
325- .lock()
326- .unwrap()
327- .sources
328- .insert(Kind::Screen, source.clone());
329-
330- done(
331- connection,
332- Request::StartShare {
333- kind: Kind::Screen,
334- source,
335- },
336- )
337- .await
338-}
crates/client/src/net/voice.rsdeleted+0 -87
@@ -1,87 +0,0 @@
1-use common::share::Kind;
2-
3-use crate::{
4- settings::VoiceSettings,
5- share::session::Sharing,
6- voice::{self, Voice, VoiceSample},
7-};
8-
9-use super::*;
10-
11-impl NetworkHandle {
12- pub fn set_voice_settings(&self, settings: VoiceSettings) {
13- *self.shared.voice_settings.lock().unwrap() = settings.clone();
14-
15- if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() {
16- voice.apply(&settings);
17- }
18- if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() {
19- voice.apply(&settings);
20- }
21- }
22-
23- pub fn start_mic_test(&self) {
24- if self.shared.voice.lock().unwrap().is_some() {
25- return;
26- }
27- let settings = self.shared.voice_settings.lock().unwrap().clone();
28- *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings));
29- }
30-
31- pub fn play_chime(&self) {
32- voice::play_chime(&self.shared.voice_settings.lock().unwrap());
33- }
34-
35- pub fn play_notification(&self) {
36- voice::play_yumush(&self.shared.voice_settings.lock().unwrap());
37- }
38-
39- pub fn play_ring(&self) {
40- voice::play_ring(&self.shared.voice_settings.lock().unwrap());
41- }
42-
43- pub fn stop_mic_test(&self) {
44- self.shared.mic_test.lock().unwrap().take();
45- }
46-
47- pub fn voice_level_db(&self) -> Option<f32> {
48- self.with_voice(Voice::level_db).or_else(|| {
49- self.shared
50- .mic_test
51- .lock()
52- .unwrap()
53- .as_ref()
54- .map(Voice::level_db)
55- })
56- }
57-
58- pub fn voice_sample(&self) -> Option<VoiceSample> {
59- self.with_voice(Voice::sample)
60- }
61-
62- pub fn set_talking(&self, talking: bool) {
63- self.with_voice(|voice| voice.set_talking(talking));
64- }
65-
66- pub fn set_muted(&self, muted: bool) {
67- self.with_voice(|voice| voice.set_muted(muted));
68- }
69-
70- pub fn set_deafened(&self, deafened: bool) {
71- self.with_voice(|voice| voice.set_deafened(deafened));
72- }
73-
74- pub fn levels(&self) -> Levels {
75- let share = self.shared.share.lock().unwrap();
76- Levels {
77- voice: self.with_voice(Voice::levels).unwrap_or_default(),
78- watching: share
79- .watching
80- .iter()
81- .filter(|((_, kind), _)| *kind == Kind::Screen)
82- .map(|((user_id, _), watching)| (user_id.clone(), watching.level()))
83- .collect(),
84- sharing: share.sharing.get(&Kind::Screen).map(Sharing::level),
85- }
86- }
87-}
crates/client/src/share/reassembly.rsmodified+40 -31
@@ -1,6 +1,9 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 2
3-use common::{datagram::Fragment, share::Layer};3+use common::{
4+ datagram::{Packet, layout, seq_newer},
5+ share::Layer,
6+};
4 7
5 const PENDING_LIMIT: usize = 8;8 const PENDING_LIMIT: usize = 8;
6 9
@@ -29,23 +32,24 @@ struct Pending {
29 }32 }
30 33
31 impl Pending {34 impl Pending {
32- fn new(fragment: Fragment<'_>) -> Pending {35+ fn new(layer: Layer, keyframe: bool, timestamp_ms: u32, length: u32) -> Pending {
36+ let layout = layout(length);
33 Pending {37 Pending {
34- layer: fragment.layer,38+ layer,
35- keyframe: fragment.keyframe,39+ keyframe,
36- timestamp_ms: fragment.timestamp_ms,40+ timestamp_ms,
37- data: usize::from(fragment.data),41+ data: layout.data,
38- length: fragment.length as usize,42+ length: length as usize,
39 present: 0,43 present: 0,
40- shards: vec![None; usize::from(fragment.count)],44+ shards: vec![None; layout.count()],
41 }45 }
42 }46 }
43 47
44- fn insert(&mut self, fragment: Fragment<'_>) {48+ fn insert(&mut self, index: u16, shard: &[u8]) {
45- if let Some(shard) = self.shards.get_mut(usize::from(fragment.index))49+ if let Some(slot) = self.shards.get_mut(usize::from(index))
46- && shard.is_none()50+ && slot.is_none()
47 {51 {
48- *shard = Some(fragment.payload.to_vec());52+ *slot = Some(shard.to_vec());
49 self.present += 1;53 self.present += 1;
50 }54 }
51 }55 }
@@ -78,11 +82,6 @@ impl Pending {
78 }82 }
79 }83 }
80 84
81-fn is_newer(frame: u32, than: u32) -> bool {
82- let distance = frame.wrapping_sub(than);
83- distance != 0 && distance < u32::MAX / 2
84-}
85-
86 pub struct Reassembler {85 pub struct Reassembler {
87 layer: Option<Layer>,86 layer: Option<Layer>,
88 pending: HashMap<u32, Pending>,87 pending: HashMap<u32, Pending>,
@@ -110,33 +109,43 @@ impl Reassembler {
110 }109 }
111 }110 }
112 111
113- pub fn push(&mut self, fragment: Fragment<'_>) -> Option<Assembled> {112+ pub fn push(&mut self, packet: &Packet<'_>) -> Option<Assembled> {
114- if self.layer != Some(fragment.layer) {113+ let &Packet::Video {
115- self.layer = Some(fragment.layer);114+ layer,
115+ keyframe,
116+ frame,
117+ index,
118+ length,
119+ ts_ms,
120+ shard,
121+ ..
122+ } = packet
123+ else {
124+ return None;
125+ };
126+ if self.layer != Some(layer) {
127+ self.layer = Some(layer);
116 self.pending.clear();128 self.pending.clear();
117 self.last = None;129 self.last = None;
118 self.phase = Phase::WaitingKeyframe;130 self.phase = Phase::WaitingKeyframe;
119 }131 }
120- if self132+ if self.last.is_some_and(|last| !seq_newer(frame, last)) {
121- .last
122- .is_some_and(|last| !is_newer(fragment.frame, last))
123- {
124 return None;133 return None;
125 }134 }
126- if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT {135+ if !self.pending.contains_key(&frame) && self.pending.len() >= PENDING_LIMIT {
127 self.pending.clear();136 self.pending.clear();
128 self.phase = Phase::WaitingKeyframe;137 self.phase = Phase::WaitingKeyframe;
129 }138 }
130 let pending = self139 let pending = self
131 .pending140 .pending
132- .entry(fragment.frame)141+ .entry(frame)
133- .or_insert_with(|| Pending::new(fragment));142+ .or_insert_with(|| Pending::new(layer, keyframe, ts_ms, length));
134- pending.insert(fragment);143+ pending.insert(index, shard);
135 if !pending.is_complete() {144 if !pending.is_complete() {
136 return None;145 return None;
137 }146 }
138- let complete = self.pending.remove(&fragment.frame)?;147+ let complete = self.pending.remove(&frame)?;
139- self.deliver(fragment.frame, complete)148+ self.deliver(frame, complete)
140 }149 }
141 150
142 fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> {151 fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> {
@@ -150,7 +159,7 @@ impl Reassembler {
150 if skipped > 0 || data.is_none() {159 if skipped > 0 || data.is_none() {
151 self.lost_frames += skipped + u32::from(data.is_none());160 self.lost_frames += skipped + u32::from(data.is_none());
152 self.phase = Phase::WaitingKeyframe;161 self.phase = Phase::WaitingKeyframe;
153- self.pending.retain(|&older, _| is_newer(older, frame));162+ self.pending.retain(|&older, _| seq_newer(older, frame));
154 }163 }
155 let data = data?;164 let data = data?;
156 self.received_frames += 1;165 self.received_frames += 1;
crates/client/src/share/session.rsmodified+61 -63
@@ -15,7 +15,7 @@ use common::{
15 SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD,15 SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD,
16 VOICE_SAMPLE_RATE,16 VOICE_SAMPLE_RATE,
17 },17 },
18- datagram::{Datagram, fragments},18+ datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small},
19 share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options},19 share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options},
20 };20 };
21 use ec_opus::{Application, Decoder, Encoder};21 use ec_opus::{Application, Decoder, Encoder};
@@ -208,11 +208,12 @@ impl Sharing {
208 top: Quality,208 top: Quality,
209 encode: Vec<Codec>,209 encode: Vec<Codec>,
210 audio: Option<AudioMode>,210 audio: Option<AudioMode>,
211- ) -> Result<(Sharing, Source), String> {211+ ) -> Result<Sharing, String> {
212 if encode.is_empty() {212 if encode.is_empty() {
213 return Err("codec unavailable".into());213 return Err("codec unavailable".into());
214 }214 }
215 let audio = audio.filter(|_| kind == Kind::Screen);215 let audio = audio.filter(|_| kind == Kind::Screen);
216+ warn_if_small(&connection);
216 let mut input = match kind {217 let mut input = match kind {
217 Kind::Screen => Input::Screen(capture::open().await?),218 Kind::Screen => Input::Screen(capture::open().await?),
218 Kind::Camera => Input::Camera(219 Kind::Camera => Input::Camera(
@@ -261,24 +262,25 @@ impl Sharing {
261 })262 })
262 };263 };
263 264
264- Ok((265+ Ok(Sharing {
265- Sharing {266+ encoders,
266- encoders,267+ _feed: feed,
267- _feed: feed,268+ _input: input,
268- _input: input,269+ refresh,
269- refresh,
270- source: source.clone(),
271- started,
272- audio,
273- _audio: audio_capture,
274- _audio_encode: audio_encode,
275- meter,
276- _sender: sender,
277- _congestion: congestion,
278- sent,
279- },
280 source,270 source,
281- ))271+ started,
272+ audio,
273+ _audio: audio_capture,
274+ _audio_encode: audio_encode,
275+ meter,
276+ _sender: sender,
277+ _congestion: congestion,
278+ sent,
279+ })
280+ }
281+
282+ pub fn source(&self) -> Source {
283+ self.source.clone()
282 }284 }
283 285
284 pub fn update(286 pub fn update(
@@ -376,16 +378,15 @@ fn send(
376 let counter = counters.entry(item.layer).or_default();378 let counter = counters.entry(item.layer).or_default();
377 let number = *counter;379 let number = *counter;
378 *counter = counter.wrapping_add(1);380 *counter = counter.wrapping_add(1);
379- for packet in fragments(381+ fragments(
380 kind,382 kind,
381 item.layer,383 item.layer,
382 number,384 number,
383 item.keyframe,385 item.keyframe,
384 item.timestamp_ms,386 item.timestamp_ms,
385 &item.data,387 &item.data,
386- ) {388+ |packet| datagram::send(&connection, Bytes::copy_from_slice(packet)),
387- let _ = connection.send_datagram(Bytes::from(packet));389+ );
388- }
389 }390 }
390 }391 }
391 392
@@ -404,6 +405,7 @@ fn encode_audio(
404 encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32);405 encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32);
405 let mut pcm = vec![0.0; CHUNK_SAMPLES];406 let mut pcm = vec![0.0; CHUNK_SAMPLES];
406 let mut payload = [0u8; VOICE_MAX_PAYLOAD];407 let mut payload = [0u8; VOICE_MAX_PAYLOAD];
408+ let mut packet = Vec::new();
407 let mut sequence = 0u32;409 let mut sequence = 0u32;
408 while !stop.load(Ordering::Relaxed) {410 while !stop.load(Ordering::Relaxed) {
409 if samples.slots() < CHUNK_SAMPLES {411 if samples.slots() < CHUNK_SAMPLES {
@@ -417,13 +419,14 @@ fn encode_audio(
417 let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else {419 let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else {
418 continue;420 continue;
419 };421 };
420- let packet = Datagram::ShareAudio {422+ packet.clear();
421- sequence,423+ Packet::ScreenAudio {
422- timestamp_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS),424+ seq: sequence,
423- payload: &payload[..length],425+ ts_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS),
426+ opus: &payload[..length],
424 }427 }
425- .encode();428+ .encode(&mut packet);
426- let _ = connection.send_datagram(Bytes::from(packet));429+ datagram::send(&connection, Bytes::copy_from_slice(&packet));
427 sequence = sequence.wrapping_add(1);430 sequence = sequence.wrapping_add(1);
428 }431 }
429 }432 }
@@ -470,8 +473,8 @@ pub struct Watching {
470 video: Arc<Mutex<Video>>,473 video: Arc<Mutex<Video>>,
471 health: Arc<Mutex<Health>>,474 health: Arc<Mutex<Health>>,
472 volume: Arc<AtomicU32>,475 volume: Arc<AtomicU32>,
473- video_tx: Sender<Vec<u8>>,476+ video_tx: Sender<Bytes>,
474- audio_tx: Option<Sender<Vec<u8>>>,477+ audio_tx: Option<Sender<Bytes>>,
475 meter: Meter,478 meter: Meter,
476 received: AtomicU64,479 received: AtomicU64,
477 since: Instant,480 since: Instant,
@@ -553,18 +556,17 @@ impl Watching {
553 }556 }
554 }557 }
555 558
556- pub fn receive(&self, datagram: Datagram<'_>) {559+ pub fn receive(&self, datagram: &Bytes, packet: &Packet<'_>) {
557- let (timestamp_ms, tx) = match datagram {560+ let (ts_ms, tx) = match packet {
558- Datagram::Video(fragment) => (fragment.timestamp_ms, Some(&self.video_tx)),561+ Packet::Video { ts_ms, .. } => (*ts_ms, Some(&self.video_tx)),
559- Datagram::ShareAudio { timestamp_ms, .. } => (timestamp_ms, self.audio_tx.as_ref()),562+ Packet::ScreenAudio { ts_ms, .. } => (*ts_ms, self.audio_tx.as_ref()),
560- Datagram::Voice { .. } => return,563+ Packet::Voice { .. } => return,
561 };564 };
562- self.clock.observe(timestamp_ms);565+ self.clock.observe(ts_ms);
563- let bytes = datagram.encode();
564 self.received566 self.received
565- .fetch_add(bytes.len() as u64, Ordering::Relaxed);567+ .fetch_add((datagram.len() - RELAY_PREFIX) as u64, Ordering::Relaxed);
566 if let Some(tx) = tx {568 if let Some(tx) = tx {
567- let _ = tx.send(bytes);569+ let _ = tx.send(datagram.clone());
568 }570 }
569 }571 }
570 572
@@ -685,7 +687,7 @@ fn rungs() -> &'static [Quality] {
685 }687 }
686 688
687 fn watch_video(689 fn watch_video(
688- rx: Receiver<Vec<u8>>,690+ rx: Receiver<Bytes>,
689 clock: &Clock,691 clock: &Clock,
690 video: &Mutex<Video>,692 video: &Mutex<Video>,
691 health: &Mutex<Health>,693 health: &Mutex<Health>,
@@ -697,8 +699,8 @@ fn watch_video(
697 while !stop.load(Ordering::Relaxed) {699 while !stop.load(Ordering::Relaxed) {
698 match rx.recv_timeout(STOP_CHECK) {700 match rx.recv_timeout(STOP_CHECK) {
699 Ok(bytes) => {701 Ok(bytes) => {
700- if let Some(Datagram::Video(fragment)) = Datagram::decode(&bytes)702+ if let Some((_, packet)) = split(&bytes)
701- && let Some(assembled) = reassembler.push(fragment)703+ && let Some(assembled) = reassembler.push(&packet)
702 {704 {
703 {705 {
704 let mut health = lock(health);706 let mut health = lock(health);
@@ -750,7 +752,7 @@ fn decode_video(
750 }752 }
751 753
752 fn play_audio(754 fn play_audio(
753- rx: Receiver<Vec<u8>>,755+ rx: Receiver<Bytes>,
754 clock: &Clock,756 clock: &Clock,
755 mut ring: Producer<f32>,757 mut ring: Producer<f32>,
756 volume: &AtomicU32,758 volume: &AtomicU32,
@@ -766,15 +768,11 @@ fn play_audio(
766 while !stop.load(Ordering::Relaxed) {768 while !stop.load(Ordering::Relaxed) {
767 match rx.recv_timeout(AUDIO_STEP) {769 match rx.recv_timeout(AUDIO_STEP) {
768 Ok(bytes) => {770 Ok(bytes) => {
769- if let Some(Datagram::ShareAudio {771+ if let Some((_, Packet::ScreenAudio { ts_ms, opus, .. })) = split(&bytes)
770- timestamp_ms,772+ && let Ok(count) = decoder.decode_float(opus, &mut scratch)
771- payload,
772- ..
773- }) = Datagram::decode(&bytes)
774- && let Ok(count) = decoder.decode_float(payload, &mut scratch)
775 {773 {
776 let samples = scratch[..count * SHARE_AUDIO_CHANNELS].to_vec();774 let samples = scratch[..count * SHARE_AUDIO_CHANNELS].to_vec();
777- pending.push_back((clock.due(timestamp_ms), samples));775+ pending.push_back((clock.due(ts_ms), samples));
778 }776 }
779 }777 }
780 Err(RecvTimeoutError::Timeout) => {}778 Err(RecvTimeoutError::Timeout) => {}
@@ -809,7 +807,6 @@ fn flush(
809 #[cfg(test)]807 #[cfg(test)]
810 mod tests {808 mod tests {
811 use super::*;809 use super::*;
812- use common::datagram::fragments;
813 810
814 #[test]811 #[test]
815 fn every_codec_round_trips() {812 fn every_codec_round_trips() {
@@ -851,23 +848,24 @@ mod tests {
851 let mut reassembler = Reassembler::new();848 let mut reassembler = Reassembler::new();
852 let mut pictures = Vec::new();849 let mut pictures = Vec::new();
853 for (number, encoded) in encoded.iter().enumerate() {850 for (number, encoded) in encoded.iter().enumerate() {
854- for packet in fragments(851+ fragments(
855 Kind::Screen,852 Kind::Screen,
856 encoded.layer,853 encoded.layer,
857 number as u32,854 number as u32,
858 encoded.keyframe,855 encoded.keyframe,
859 encoded.timestamp_ms,856 encoded.timestamp_ms,
860 &encoded.data,857 &encoded.data,
861- ) {858+ |packet| {
862- let Some(Datagram::Video(fragment)) = Datagram::decode(&packet) else {859+ let Some(packet) = Packet::decode(packet) else {
863- panic!("fragment");860+ panic!("fragment");
864- };861+ };
865- if let Some(assembled) = reassembler.push(fragment) {862+ if let Some(assembled) = reassembler.push(&packet) {
866- pictures.extend(863+ pictures.extend(
867- decoder.decode(&assembled.data, assembled.timestamp_ms),864+ decoder.decode(&assembled.data, assembled.timestamp_ms),
868- );865+ );
869- }866+ }
870- }867+ },
868+ );
871 }869 }
872 assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine());870 assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine());
873 let last = pictures.pop().expect("picture");871 let last = pictures.pop().expect("picture");
crates/client/src/voice/engine.rsmodified+15 -15
@@ -7,9 +7,10 @@ use common::{
7 constant::{7 constant::{
8 MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE,8 MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE,
9 },9 },
10- datagram::{Datagram, decode_relay},10+ datagram::{Packet, RELAY_PREFIX},
11 };11 };
12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13+use uuid::Uuid;
13 14
14 use crate::{15 use crate::{
15 media::meter::{Spectrum, rms},16 media::meter::{Spectrum, rms},
@@ -275,11 +276,12 @@ impl Engine {
275 continue;276 continue;
276 };277 };
277 278
278- let packet = Datagram::Voice {279+ let mut packet = Vec::with_capacity(length + 5);
279- sequence: self.sequence,280+ Packet::Voice {
280- payload: &payload[..length],281+ seq: self.sequence,
282+ opus: &payload[..length],
281 }283 }
282- .encode();284+ .encode(&mut packet);
283 self.sent_bytes += packet.len();285 self.sent_bytes += packet.len();
284 packets.push(packet);286 packets.push(packet);
285 self.sequence = self.sequence.wrapping_add(1);287 self.sequence = self.sequence.wrapping_add(1);
@@ -288,12 +290,10 @@ impl Engine {
288 packets290 packets
289 }291 }
290 292
291- pub fn receive(&mut self, datagram: &[u8]) {293+ pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) {
292- let Some((user_id, Datagram::Voice { sequence, payload })) = decode_relay(datagram) else {294+ let user_id = Uuid::from_bytes(*from).to_string();
293- return;
294- };
295 let now = Instant::now();295 let now = Instant::now();
296- self.received_bytes += datagram.len();296+ self.received_bytes += RELAY_PREFIX + 5 + payload.len();
297 297
298 let speaker = self298 let speaker = self
299 .speakers299 .speakers
@@ -444,15 +444,13 @@ impl Engine {
444 mod tests {444 mod tests {
445 use std::f32::consts::TAU;445 use std::f32::consts::TAU;
446 446
447- use common::datagram::encode_relay;
448-
449 use super::*;447 use super::*;
450 448
451 #[test]449 #[test]
452 fn voice_round_trip() {450 fn voice_round_trip() {
453 let mut sender = Engine::new();451 let mut sender = Engine::new();
454 let mut receiver = Engine::new();452 let mut receiver = Engine::new();
455- let user_id = "0190a3b4-c5d6-7e8f-9a0b-1c2d3e4f5a6b";453+ let user_id = [7u8; RELAY_PREFIX];
456 let frames = 10;454 let frames = 10;
457 455
458 let tone: Vec<f32> = (0..VOICE_FRAME_SAMPLES * frames)456 let tone: Vec<f32> = (0..VOICE_FRAME_SAMPLES * frames)
@@ -460,8 +458,10 @@ mod tests {
460 .collect();458 .collect();
461 459
462 for packet in sender.capture(&tone) {460 for packet in sender.capture(&tone) {
463- let datagram = encode_relay(user_id, &packet).unwrap();461+ let Some(Packet::Voice { seq, opus }) = Packet::decode(&packet) else {
464- receiver.receive(&datagram);462+ panic!("not voice");
463+ };
464+ receiver.receive(&user_id, seq, opus);
465 }465 }
466 466
467 let mut out = vec![0.0; VOICE_FRAME_SAMPLES * frames];467 let mut out = vec![0.0; VOICE_FRAME_SAMPLES * frames];
crates/client/src/voice/mod.rsmodified+7 -7
@@ -9,7 +9,7 @@ use std::{
9 use bytes::Bytes;9 use bytes::Bytes;
10 use common::{10 use common::{
11 constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE},11 constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE},
12- datagram::encode_relay,12+ datagram::{self, Packet, RELAY_PREFIX},
13 };13 };
14 use quinn::Connection;14 use quinn::Connection;
15 use rtrb::{Consumer, Producer, RingBuffer};15 use rtrb::{Consumer, Producer, RingBuffer};
@@ -25,7 +25,7 @@ const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2;
25 const PLAYBACK_RING: usize = RING_SAMPLES * PLAYBACK_CHANNELS;25 const PLAYBACK_RING: usize = RING_SAMPLES * PLAYBACK_CHANNELS;
26 const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2 * PLAYBACK_CHANNELS;26 const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2 * PLAYBACK_CHANNELS;
27 const TICK: Duration = Duration::from_millis(5);27 const TICK: Duration = Duration::from_millis(5);
28-const LOOPBACK: &str = "00000000-0000-0000-0000-000000000000";28+const LOOPBACK: [u8; RELAY_PREFIX] = [0; RELAY_PREFIX];
29 const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)];29 const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)];
30 30
31 pub const PLAYBACK_CHANNELS: usize = 2;31 pub const PLAYBACK_CHANNELS: usize = 2;
@@ -238,11 +238,11 @@ fn work(
238 for packet in locked.capture(&captured) {238 for packet in locked.capture(&captured) {
239 match connection {239 match connection {
240 Some(connection) => {240 Some(connection) => {
241- let _ = connection.send_datagram(Bytes::from(packet));241+ datagram::send(connection, Bytes::from(packet));
242 }242 }
243 None => {243 None => {
244- if let Some(relay) = encode_relay(LOOPBACK, &packet) {244+ if let Some(Packet::Voice { seq, opus }) = Packet::decode(&packet) {
245- locked.receive(&relay);245+ locked.receive(&LOOPBACK, seq, opus);
246 }246 }
247 }247 }
248 }248 }
@@ -289,8 +289,8 @@ impl Voice {
289 .map_or(default, |mut engine| f(&mut engine))289 .map_or(default, |mut engine| f(&mut engine))
290 }290 }
291 291
292- pub fn receive(&self, datagram: &[u8]) {292+ pub fn receive(&self, from: &[u8; RELAY_PREFIX], seq: u32, opus: &[u8]) {
293- self.with_engine((), |engine| engine.receive(datagram));293+ self.with_engine((), |engine| engine.receive(from, seq, opus));
294 }294 }
295 295
296 pub fn levels(&self) -> Vec<(String, Vec<f32>)> {296 pub fn levels(&self) -> Vec<(String, Vec<f32>)> {
crates/common/Cargo.tomlmodified+2 -0
@@ -6,6 +6,8 @@ edition = "2024"
6 [dependencies]6 [dependencies]
7 bitcode.workspace = true7 bitcode.workspace = true
8 quinn.workspace = true8 quinn.workspace = true
9+bytes = "1.12.2"
10+tracing = "0.1.44"
9 thiserror = "2.0.21"11 thiserror = "2.0.21"
10 uuid = { version = "1.29.3", features = ["v7"] }12 uuid = { version = "1.29.3", features = ["v7"] }
11 reed-solomon-simd = "3.1.0"13 reed-solomon-simd = "3.1.0"
crates/common/src/call.rsadded+109 -0
@@ -0,0 +1,109 @@
1+use bitcode::{Decode, DecodeOwned, Encode};
2+
3+use crate::{
4+ model::{Presence, ServerSettings, SessionInfo, User},
5+ request::LegacyRequest,
6+ response::Response,
7+};
8+
9+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10+pub enum Gate {
11+ Guest,
12+ User,
13+ Builder,
14+}
15+
16+pub trait Call: Encode + DecodeOwned + Send + 'static {
17+ type Reply: Encode + DecodeOwned + Send + 'static;
18+ const GATE: Gate;
19+
20+ fn into_request(self) -> Request;
21+}
22+
23+macro_rules! calls {
24+ ($($name:ident: $gate:ident -> $reply:ty;)*) => {
25+ #[derive(Debug, Clone, Encode, Decode)]
26+ pub enum Request {
27+ $($name($name),)*
28+ }
29+
30+ $(
31+ impl Call for $name {
32+ type Reply = $reply;
33+ const GATE: Gate = Gate::$gate;
34+
35+ fn into_request(self) -> Request {
36+ Request::$name(self)
37+ }
38+ }
39+ )*
40+ };
41+}
42+
43+#[derive(Debug, Clone, Encode, Decode)]
44+pub struct Legacy(pub LegacyRequest);
45+
46+#[derive(Debug, Clone, Encode, Decode)]
47+pub struct GetSettings;
48+
49+#[derive(Debug, Clone, Encode, Decode)]
50+pub struct GetUser {
51+ pub user_id: String,
52+}
53+
54+#[derive(Debug, Clone, Encode, Decode)]
55+pub struct UpdateUser {
56+ pub username: String,
57+}
58+
59+#[derive(Debug, Clone, Encode, Decode)]
60+pub struct UpdateStatus {
61+ pub status: String,
62+}
63+
64+#[derive(Debug, Clone, Encode, Decode)]
65+pub struct UpdatePresence {
66+ pub presence: Presence,
67+}
68+
69+#[derive(Debug, Clone, Encode, Decode)]
70+pub struct ListPresences;
71+
72+#[derive(Debug, Clone, Encode, Decode)]
73+pub struct UpdateAvatar {
74+ pub image: Vec<u8>,
75+}
76+
77+#[derive(Debug, Clone, Encode, Decode)]
78+pub struct RemoveAvatar;
79+
80+#[derive(Debug, Clone, Encode, Decode)]
81+pub struct GetAvatar {
82+ pub avatar_id: String,
83+}
84+
85+#[derive(Debug, Clone, Encode, Decode)]
86+pub struct ListSessions {
87+ pub user_id: String,
88+}
89+
90+#[derive(Debug, Clone, Encode, Decode)]
91+pub struct RevokeSession {
92+ pub user_id: String,
93+ pub session_id: String,
94+}
95+
96+calls! {
97+ Legacy: Guest -> Response;
98+ GetSettings: Guest -> ServerSettings;
99+ GetUser: User -> User;
100+ UpdateUser: User -> User;
101+ UpdateStatus: User -> User;
102+ UpdatePresence: User -> ();
103+ ListPresences: User -> Vec<(String, Presence)>;
104+ UpdateAvatar: User -> User;
105+ RemoveAvatar: User -> User;
106+ GetAvatar: User -> Vec<u8>;
107+ ListSessions: User -> Vec<SessionInfo>;
108+ RevokeSession: User -> ();
109+}
crates/common/src/constant.rsmodified+1 -0
@@ -41,3 +41,4 @@ pub const VIDEO_FEC_DATA_PER_PARITY: usize = 4;
41 pub const MAXIMUM_SHARE_LAYERS: usize = 4;41 pub const MAXIMUM_SHARE_LAYERS: usize = 4;
42 pub const SHARE_AUDIO_BITRATE: i32 = 128_000;42 pub const SHARE_AUDIO_BITRATE: i32 = 128_000;
43 pub const SHARE_AUDIO_CHANNELS: usize = 2;43 pub const SHARE_AUDIO_CHANNELS: usize = 2;
44+pub const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
crates/common/src/datagram.rsmodified+262 -178
@@ -1,164 +1,200 @@
1-use uuid::Uuid;1+use std::sync::atomic::{AtomicBool, Ordering};
2+
3+use bytes::Bytes;
4+use quinn::{Connection, SendDatagramError};
5+use tracing::warn;
2 6
3 use crate::{7 use crate::{
4- constant::{VIDEO_FEC_DATA_PER_PARITY, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD},8+ constant::{
9+ MAX_FRAME_BYTES, VIDEO_FEC_DATA_PER_PARITY, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD,
10+ },
5 share::{Kind, Layer},11 share::{Kind, Layer},
6 };12 };
7 13
8-const USER_ID_LENGTH: usize = 16;14+pub const RELAY_PREFIX: usize = 16;
15+pub const MAX_DATAGRAM: usize = 1200 - 48;
16+
17+const VOICE_HEADER: usize = 5;
18+const SHARE_AUDIO_HEADER: usize = 9;
19+const VIDEO_HEADER: usize = 17;
20+const KEYFRAME_FLAG: u8 = 1;
21+
22+const _: () = assert!(RELAY_PREFIX + VIDEO_HEADER + VIDEO_FRAGMENT_BYTES <= MAX_DATAGRAM);
23+const _: () = assert!(RELAY_PREFIX + SHARE_AUDIO_HEADER + VOICE_MAX_PAYLOAD <= MAX_DATAGRAM);
24+
25+const TAG_VOICE: u8 = 0;
26+const TAG_SCREEN_AUDIO: u8 = 1;
27+const TAG_SCREEN: u8 = 2;
28+const TAG_CAMERA: u8 = 3;
29+
30+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31+pub enum Packet<'a> {
32+ Voice {
33+ seq: u32,
34+ opus: &'a [u8],
35+ },
36+ ScreenAudio {
37+ seq: u32,
38+ ts_ms: u32,
39+ opus: &'a [u8],
40+ },
41+ Video {
42+ kind: Kind,
43+ layer: Layer,
44+ keyframe: bool,
45+ frame: u32,
46+ index: u16,
47+ length: u32,
48+ ts_ms: u32,
49+ shard: &'a [u8],
50+ },
51+}
9 52
10-#[repr(u8)]
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12-enum Tag {54+pub struct Layout {
13- Voice = 0,55+ pub shard: usize,
14- Video = 1,56+ pub data: usize,
15- ShareAudio = 2,57+ pub parity: usize,
16 }58 }
17 59
18-impl Tag {60+impl Layout {
19- fn parse(byte: u8) -> Option<Self> {61+ pub fn count(self) -> usize {
20- match byte {62+ self.data + self.parity
21- 0 => Some(Self::Voice),
22- 1 => Some(Self::Video),
23- 2 => Some(Self::ShareAudio),
24- _ => None,
25- }
26 }63 }
27 }64 }
28 65
29-#[derive(Debug, Clone, Copy, PartialEq, Eq)]66+pub fn layout(length: u32) -> Layout {
30-pub struct Fragment<'a> {67+ let length = length as usize;
31- pub kind: Kind,68+ let shard = length.clamp(2, VIDEO_FRAGMENT_BYTES).next_multiple_of(2);
32- pub layer: Layer,69+ let data = length.div_ceil(shard).max(1);
33- pub frame: u32,70+ Layout {
34- pub index: u16,71+ shard,
35- pub count: u16,72+ data,
36- pub data: u16,73+ parity: data.div_ceil(VIDEO_FEC_DATA_PER_PARITY).max(1),
37- pub length: u32,74+ }
38- pub keyframe: bool,
39- pub timestamp_ms: u32,
40- pub payload: &'a [u8],
41 }75 }
42 76
43-#[derive(Debug, Clone, Copy, PartialEq, Eq)]77+pub fn seq_newer(a: u32, b: u32) -> bool {
44-pub enum Datagram<'a> {78+ let distance = a.wrapping_sub(b);
45- Voice {79+ distance != 0 && distance < u32::MAX / 2
46- sequence: u32,80+}
47- payload: &'a [u8],81+
48- },82+fn u32_at(b: &[u8], at: usize) -> u32 {
49- Video(Fragment<'a>),83+ u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
50- ShareAudio {
51- sequence: u32,
52- timestamp_ms: u32,
53- payload: &'a [u8],
54- },
55 }84 }
56 85
57-impl<'a> Datagram<'a> {86+fn video_tag(kind: Kind) -> u8 {
58- pub fn encode(&self) -> Vec<u8> {87+ match kind {
59- let mut bytes = Vec::new();88+ Kind::Screen => TAG_SCREEN,
89+ Kind::Camera => TAG_CAMERA,
90+ }
91+}
92+
93+fn video_kind(tag: u8) -> Option<Kind> {
94+ match tag {
95+ TAG_SCREEN => Some(Kind::Screen),
96+ TAG_CAMERA => Some(Kind::Camera),
97+ _ => None,
98+ }
99+}
100+
101+impl<'a> Packet<'a> {
102+ pub fn encode(&self, out: &mut Vec<u8>) {
60 match self {103 match self {
61- Self::Voice { sequence, payload } => {104+ Self::Voice { seq, opus } => {
62- bytes.push(Tag::Voice as u8);105+ out.push(TAG_VOICE);
63- bytes.extend_from_slice(&sequence.to_be_bytes());106+ out.extend_from_slice(&seq.to_le_bytes());
64- bytes.extend_from_slice(payload);107+ out.extend_from_slice(opus);
65 }108 }
66- Self::Video(fragment) => {109+ Self::ScreenAudio { seq, ts_ms, opus } => {
67- bytes.push(Tag::Video as u8);110+ out.push(TAG_SCREEN_AUDIO);
68- bytes.push(fragment.kind.to_byte());111+ out.extend_from_slice(&seq.to_le_bytes());
69- bytes.push(fragment.layer.to_byte());112+ out.extend_from_slice(&ts_ms.to_le_bytes());
70- bytes.extend_from_slice(&fragment.frame.to_be_bytes());113+ out.extend_from_slice(opus);
71- bytes.extend_from_slice(&fragment.index.to_be_bytes());
72- bytes.extend_from_slice(&fragment.count.to_be_bytes());
73- bytes.extend_from_slice(&fragment.data.to_be_bytes());
74- bytes.extend_from_slice(&fragment.length.to_be_bytes());
75- bytes.push(fragment.keyframe as u8);
76- bytes.extend_from_slice(&fragment.timestamp_ms.to_be_bytes());
77- bytes.extend_from_slice(fragment.payload);
78 }114 }
79- Self::ShareAudio {115+ Self::Video {
80- sequence,116+ kind,
81- timestamp_ms,117+ layer,
82- payload,118+ keyframe,
119+ frame,
120+ index,
121+ length,
122+ ts_ms,
123+ shard,
83 } => {124 } => {
84- bytes.push(Tag::ShareAudio as u8);125+ out.push(video_tag(*kind));
85- bytes.extend_from_slice(&sequence.to_be_bytes());126+ out.push(layer.to_byte());
86- bytes.extend_from_slice(&timestamp_ms.to_be_bytes());127+ out.push(if *keyframe { KEYFRAME_FLAG } else { 0 });
87- bytes.extend_from_slice(payload);128+ out.extend_from_slice(&frame.to_le_bytes());
129+ out.extend_from_slice(&index.to_le_bytes());
130+ out.extend_from_slice(&length.to_le_bytes());
131+ out.extend_from_slice(&ts_ms.to_le_bytes());
132+ out.extend_from_slice(shard);
88 }133 }
89 }134 }
90- bytes
91 }135 }
92 136
93- pub fn decode(bytes: &'a [u8]) -> Option<Self> {137+ pub fn decode(b: &'a [u8]) -> Option<Self> {
94- let (tag, rest) = bytes.split_first()?;138+ match *b.first()? {
95- let datagram = match Tag::parse(*tag)? {139+ TAG_VOICE => {
96- Tag::Voice => {140+ let opus = b.get(VOICE_HEADER..)?;
97- let (sequence, payload) = rest.split_first_chunk::<4>()?;141+ (opus.len() <= VOICE_MAX_PAYLOAD).then(|| Self::Voice {
98- Self::Voice {142+ seq: u32_at(b, 1),
99- sequence: u32::from_be_bytes(*sequence),143+ opus,
100- payload,144+ })
101- }145+ }
146+ TAG_SCREEN_AUDIO => {
147+ let opus = b.get(SHARE_AUDIO_HEADER..)?;
148+ (opus.len() <= VOICE_MAX_PAYLOAD).then(|| Self::ScreenAudio {
149+ seq: u32_at(b, 1),
150+ ts_ms: u32_at(b, 5),
151+ opus,
152+ })
102 }153 }
103- Tag::Video => {154+ tag => {
104- let (kind, rest) = rest.split_first()?;155+ let kind = video_kind(tag)?;
105- let (layer, rest) = rest.split_first()?;156+ let shard = b.get(VIDEO_HEADER..)?;
106- let (frame, rest) = rest.split_first_chunk::<4>()?;157+ let layer = Layer::from_byte(b[1])?;
107- let (index, rest) = rest.split_first_chunk::<2>()?;158+ let index = u16::from_le_bytes([b[7], b[8]]);
108- let (count, rest) = rest.split_first_chunk::<2>()?;159+ let length = u32_at(b, 9);
109- let (data, rest) = rest.split_first_chunk::<2>()?;160+ if length as usize > MAX_FRAME_BYTES {
110- let (length, rest) = rest.split_first_chunk::<4>()?;
111- let (keyframe, rest) = rest.split_first()?;
112- let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?;
113- let fragment = Fragment {
114- kind: Kind::from_byte(*kind)?,
115- layer: Layer::from_byte(*layer)?,
116- frame: u32::from_be_bytes(*frame),
117- index: u16::from_be_bytes(*index),
118- count: u16::from_be_bytes(*count),
119- data: u16::from_be_bytes(*data),
120- length: u32::from_be_bytes(*length),
121- keyframe: *keyframe != 0,
122- timestamp_ms: u32::from_be_bytes(*timestamp_ms),
123- payload,
124- };
125- if fragment.index >= fragment.count
126- || fragment.data == 0
127- || fragment.data > fragment.count
128- {
129 return None;161 return None;
130 }162 }
131- Self::Video(fragment)163+ let layout = layout(length);
132- }164+ if usize::from(index) >= layout.count() || shard.len() != layout.shard {
133- Tag::ShareAudio => {165+ return None;
134- let (sequence, rest) = rest.split_first_chunk::<4>()?;
135- let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?;
136- Self::ShareAudio {
137- sequence: u32::from_be_bytes(*sequence),
138- timestamp_ms: u32::from_be_bytes(*timestamp_ms),
139- payload,
140 }166 }
167+ Some(Self::Video {
168+ kind,
169+ layer,
170+ keyframe: b[2] & KEYFRAME_FLAG != 0,
171+ frame: u32_at(b, 3),
172+ index,
173+ length,
174+ ts_ms: u32_at(b, 13),
175+ shard,
176+ })
141 }177 }
142- };178+ }
143- let limit = match datagram {
144- Self::Voice { .. } | Self::ShareAudio { .. } => VOICE_MAX_PAYLOAD,
145- Self::Video(_) => VIDEO_FRAGMENT_BYTES,
146- };
147- (datagram.payload().len() <= limit).then_some(datagram)
148 }179 }
149 180
150- pub fn payload(&self) -> &'a [u8] {181+ pub fn peek_video(b: &[u8]) -> Option<(Kind, Layer, bool)> {
151- match self {182+ let kind = video_kind(*b.first()?)?;
152- Self::Voice { payload, .. } | Self::ShareAudio { payload, .. } => payload,183+ let layer = Layer::from_byte(*b.get(1)?)?;
153- Self::Video(fragment) => fragment.payload,184+ Some((kind, layer, b.get(2)? & KEYFRAME_FLAG != 0))
154- }
155 }185 }
156 }186 }
157 187
158-fn layout(length: usize) -> (usize, usize, usize) {188+pub fn relayed(from: &[u8; RELAY_PREFIX], uplink: &[u8]) -> Bytes {
159- let shard = length.clamp(2, VIDEO_FRAGMENT_BYTES).next_multiple_of(2);189+ let mut bytes = Vec::with_capacity(RELAY_PREFIX + uplink.len());
160- let data = length.div_ceil(shard).max(1);190+ bytes.extend_from_slice(from);
161- (shard, data, data.div_ceil(VIDEO_FEC_DATA_PER_PARITY).max(1))191+ bytes.extend_from_slice(uplink);
192+ Bytes::from(bytes)
193+}
194+
195+pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> {
196+ let (from, rest) = b.split_first_chunk::<RELAY_PREFIX>()?;
197+ Some((from, Packet::decode(rest)?))
162 }198 }
163 199
164 pub fn fragments(200 pub fn fragments(
@@ -166,52 +202,72 @@ pub fn fragments(
166 layer: Layer,202 layer: Layer,
167 frame: u32,203 frame: u32,
168 keyframe: bool,204 keyframe: bool,
169- timestamp_ms: u32,205+ ts_ms: u32,
170 data: &[u8],206 data: &[u8],
171-) -> Vec<Vec<u8>> {207+ mut emit: impl FnMut(&[u8]),
172- let (shard, data_count, parity_count) = layout(data.len());208+) {
173- let count = (data_count + parity_count) as u16;209+ let length = data.len() as u32;
210+ let Layout {
211+ shard,
212+ data: data_count,
213+ parity: parity_count,
214+ } = layout(length);
174 let mut padded = data.to_vec();215 let mut padded = data.to_vec();
175 padded.resize(data_count * shard, 0);216 padded.resize(data_count * shard, 0);
176- let parity = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard))217+ let Ok(parity) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard))
177- .expect("reed-solomon encode");218+ else {
178- padded219+ return;
220+ };
221+ let mut out = Vec::with_capacity(VIDEO_HEADER + shard);
222+ for (index, shard) in padded
179 .chunks(shard)223 .chunks(shard)
180 .chain(parity.iter().map(Vec::as_slice))224 .chain(parity.iter().map(Vec::as_slice))
181 .enumerate()225 .enumerate()
182- .map(|(index, payload)| {226+ {
183- Datagram::Video(Fragment {227+ out.clear();
184- kind,228+ Packet::Video {
185- layer,229+ kind,
186- frame,230+ layer,
187- index: index as u16,231+ keyframe,
188- count,232+ frame,
189- data: data_count as u16,233+ index: index as u16,
190- length: data.len() as u32,234+ length,
191- keyframe,235+ ts_ms,
192- timestamp_ms,236+ shard,
193- payload,237+ }
194- })238+ .encode(&mut out);
195- .encode()239+ emit(&out);
196- })240+ }
197- .collect()
198 }241 }
199 242
200-pub fn encode_relay(user_id: &str, packet: &[u8]) -> Option<Vec<u8>> {243+static SEND_FAILED: [AtomicBool; 4] = [const { AtomicBool::new(false) }; 4];
201- let user_id = Uuid::parse_str(user_id).ok()?;
202- let mut bytes = user_id.as_bytes().to_vec();
203- bytes.extend_from_slice(packet);
204 244
205- Some(bytes)245+pub fn send(connection: &Connection, bytes: Bytes) {
246+ let Err(error) = connection.send_datagram(bytes) else {
247+ return;
248+ };
249+ let slot = match error {
250+ SendDatagramError::UnsupportedByPeer => 0,
251+ SendDatagramError::Disabled => 1,
252+ SendDatagramError::TooLarge => 2,
253+ SendDatagramError::ConnectionLost(_) => 3,
254+ };
255+ if !SEND_FAILED[slot].swap(true, Ordering::Relaxed) {
256+ warn!(%error, "datagram send failed");
257+ }
206 }258 }
207 259
208-pub fn decode_relay(bytes: &[u8]) -> Option<(String, Datagram<'_>)> {260+pub fn warn_if_small(connection: &Connection) {
209- let user_id = Uuid::from_slice(bytes.get(..USER_ID_LENGTH)?).ok()?;261+ if connection
210-262+ .max_datagram_size()
211- Some((263+ .is_none_or(|size| size < MAX_DATAGRAM)
212- user_id.to_string(),264+ {
213- Datagram::decode(&bytes[USER_ID_LENGTH..])?,265+ warn!(
214- ))266+ max = ?connection.max_datagram_size(),
267+ needed = MAX_DATAGRAM,
268+ "datagram size limit below media packets"
269+ );
270+ }
215 }271 }
216 272
217 #[cfg(test)]273 #[cfg(test)]
@@ -219,9 +275,14 @@ mod tests {
219 use super::*;275 use super::*;
220 use crate::share::{Codec, Fps, Quality, Resolution};276 use crate::share::{Codec, Fps, Quality, Resolution};
221 277
278+ fn round_trip(packet: Packet<'_>) {
279+ let mut out = Vec::new();
280+ packet.encode(&mut out);
281+ assert_eq!(Packet::decode(&out), Some(packet));
282+ }
283+
222 #[test]284 #[test]
223- fn relay_round_trip() {285+ fn every_packet_round_trips() {
224- let user_id = Uuid::now_v7().to_string();
225 let layer = Layer {286 let layer = Layer {
226 quality: Quality {287 quality: Quality {
227 resolution: Resolution::P1080,288 resolution: Resolution::P1080,
@@ -229,20 +290,43 @@ mod tests {
229 },290 },
230 codec: Codec::Av1,291 codec: Codec::Av1,
231 };292 };
293+ round_trip(Packet::Voice {
294+ seq: 7,
295+ opus: &[1, 2, 3],
296+ });
297+ round_trip(Packet::ScreenAudio {
298+ seq: 8,
299+ ts_ms: 99,
300+ opus: &[4, 5],
301+ });
302+
232 let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5];303 let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5];
233- let packets = fragments(Kind::Camera, layer, 3, true, 99, &data);304+ let mut count = 0;
234- assert_eq!(packets.len(), 3);305+ fragments(Kind::Camera, layer, 3, true, 99, &data, |packet| {
235-306+ let Some(Packet::Video {
236- let relay = encode_relay(&user_id, &packets[1]).unwrap();307+ kind,
237- let (decoded_id, datagram) = decode_relay(&relay).unwrap();308+ keyframe,
238- assert_eq!(decoded_id, user_id);309+ index,
239- let Datagram::Video(fragment) = datagram else {310+ length,
240- panic!("not video");311+ ..
241- };312+ }) = Packet::decode(packet)
242- assert_eq!(fragment.kind, Kind::Camera);313+ else {
243- assert_eq!(fragment.layer, layer);314+ panic!("not video");
244- assert_eq!((fragment.index, fragment.count), (1, 3));315+ };
245- assert_eq!((fragment.data, fragment.length), (2, data.len() as u32));316+ assert_eq!(
246- assert_eq!(fragment.payload.len(), VIDEO_FRAGMENT_BYTES);317+ (kind, keyframe, length),
318+ (Kind::Camera, true, data.len() as u32)
319+ );
320+ assert_eq!(usize::from(index), count);
321+ assert_eq!(
322+ Packet::peek_video(packet),
323+ Some((Kind::Camera, layer, true))
324+ );
325+ let relay = relayed(&[9; RELAY_PREFIX], packet);
326+ let (from, _) = split(&relay).unwrap();
327+ assert_eq!(from, &[9; RELAY_PREFIX]);
328+ count += 1;
329+ });
330+ assert_eq!(count, 3);
247 }331 }
248 }332 }
crates/common/src/lib.rsmodified+1 -0
@@ -1,3 +1,4 @@
1+pub mod call;
1 pub mod config;2 pub mod config;
2 pub mod constant;3 pub mod constant;
3 pub mod datagram;4 pub mod datagram;
crates/common/src/open.rsmodified+1 -1
@@ -1,6 +1,6 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::request::Request;3+use crate::call::Request;
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub enum Open {6 pub enum Open {
crates/common/src/request.rsmodified+2 -30
@@ -1,12 +1,12 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3 use crate::{3 use crate::{
4- model::{BanScope, Presence, Rank, ReportStatus, Role, ServerSettings},4+ model::{BanScope, Rank, ReportStatus, Role, ServerSettings},
5 share::{Codec, Kind, Quality, Source},5 share::{Codec, Kind, Quality, Source},
6 };6 };
7 7
8 #[derive(Debug, Clone, Encode, Decode)]8 #[derive(Debug, Clone, Encode, Decode)]
9-pub enum Request {9+pub enum LegacyRequest {
10 Register {10 Register {
11 username: String,11 username: String,
12 password: String,12 password: String,
@@ -17,26 +17,6 @@ pub enum Request {
17 password: String,17 password: String,
18 },18 },
19 Logout,19 Logout,
20- ReadUser {
21- user_id: String,
22- },
23- UpdateUser {
24- username: String,
25- },
26- UpdateStatus {
27- status: String,
28- },
29- UpdatePresence {
30- presence: Presence,
31- },
32- ReadPresences,
33- UpdateAvatar {
34- image: Vec<u8>,
35- },
36- RemoveAvatar,
37- ReadAvatar {
38- avatar_id: String,
39- },
40 DeleteUser {20 DeleteUser {
41 user_id: String,21 user_id: String,
42 },22 },
@@ -240,7 +220,6 @@ pub enum Request {
240 community_id: String,220 community_id: String,
241 user_id: String,221 user_id: String,
242 },222 },
243- ServerSettings,
244 UpdateServerSettings {223 UpdateServerSettings {
245 settings: ServerSettings,224 settings: ServerSettings,
246 },225 },
@@ -248,13 +227,6 @@ pub enum Request {
248 username: String,227 username: String,
249 password: String,228 password: String,
250 },229 },
251- Sessions {
252- user_id: String,
253- },
254- RevokeSession {
255- user_id: String,
256- session_id: String,
257- },
258 RenameUser {230 RenameUser {
259 user_id: String,231 user_id: String,
260 username: String,232 username: String,
crates/common/src/share.rsmodified+0 -12
@@ -145,18 +145,6 @@ pub enum Kind {
145 Camera,145 Camera,
146 }146 }
147 147
148-impl Kind {
149- pub const ALL: [Self; 2] = [Self::Screen, Self::Camera];
150-
151- pub fn to_byte(self) -> u8 {
152- self as u8
153- }
154-
155- pub fn from_byte(byte: u8) -> Option<Self> {
156- Self::ALL.get(byte as usize).copied()
157- }
158-}
159-
160 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]148 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
161 pub struct Share {149 pub struct Share {
162 pub user_id: String,150 pub user_id: String,
crates/common/src/transport.rsmodified+1 -1
@@ -2,7 +2,7 @@ use std::time::Duration;
2 2
3 use quinn::{TransportConfig, VarInt};3 use quinn::{TransportConfig, VarInt};
4 4
5-pub const PROTOCOL: u32 = 1;5+pub const PROTOCOL: u32 = 2;
6 6
7 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);7 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);
8 const KEEP_ALIVE: Duration = Duration::from_secs(2);8 const KEEP_ALIVE: Duration = Duration::from_secs(2);
crates/server/src/attachment.rsmodified+2 -2
@@ -673,7 +673,7 @@ mod tests {
673 use common::{673 use common::{
674 model::{AttachmentKind, Rank},674 model::{AttachmentKind, Rank},
675 open::Upload,675 open::Upload,
676- request::Request,676+ request::LegacyRequest,
677 };677 };
678 use image::{ImageFormat, RgbImage};678 use image::{ImageFormat, RgbImage};
679 679
@@ -717,7 +717,7 @@ mod tests {
717 token: "token".to_string(),717 token: "token".to_string(),
718 }));718 }));
719 let (reply, _) = handle(719 let (reply, _) = handle(
720- Request::CreateMessage {720+ LegacyRequest::CreateMessage {
721 community_id: community.id.clone(),721 community_id: community.id.clone(),
722 body: String::new(),722 body: String::new(),
723 attachments: vec![attachment.id.clone()],723 attachments: vec![attachment.id.clone()],
crates/server/src/call/mod.rsadded+123 -0
@@ -0,0 +1,123 @@
1+mod user;
2+
3+use std::{future::Future, sync::Arc};
4+
5+use common::{
6+ call::{Call, Gate, Legacy, Request},
7+ error::Error,
8+ event::Event,
9+ frame::{self, DOWN_MAX},
10+ model::User,
11+};
12+use turso::Connection;
13+
14+use crate::{
15+ error::ServerError,
16+ hub::Client,
17+ network::Shared,
18+ publish::{Broadcast, To, publish},
19+ request,
20+};
21+
22+pub(crate) struct Cx<'a> {
23+ pub client: &'a Arc<Client>,
24+ pub sh: &'a Shared,
25+ pub db: Connection,
26+ pub out: Vec<Broadcast>,
27+}
28+
29+impl<'a> Cx<'a> {
30+ pub(crate) fn new(client: &'a Arc<Client>, sh: &'a Shared, db: Connection) -> Self {
31+ Self {
32+ client,
33+ sh,
34+ db,
35+ out: Vec::new(),
36+ }
37+ }
38+
39+ pub fn emit(&mut self, to: To, event: Event) {
40+ self.out.push(Broadcast::new(to, event));
41+ }
42+}
43+
44+pub(crate) enum Me {
45+ Guest,
46+ User(User),
47+}
48+
49+impl Me {
50+ pub fn user(self) -> Result<User, ServerError> {
51+ match self {
52+ Me::User(user) => Ok(user),
53+ Me::Guest => Err(Error::Unauthenticated.into()),
54+ }
55+ }
56+}
57+
58+pub(crate) trait Handle: Call {
59+ fn handle(
60+ self,
61+ me: Me,
62+ cx: &mut Cx<'_>,
63+ ) -> impl Future<Output = Result<Self::Reply, ServerError>> + Send;
64+}
65+
66+async fn gate(gate: Gate, cx: &Cx<'_>) -> Result<Me, ServerError> {
67+ match gate {
68+ Gate::Guest => Ok(Me::Guest),
69+ Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)),
70+ Gate::Builder => Ok(Me::User(request::builder(cx.client, &cx.db).await?)),
71+ }
72+}
73+
74+async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {
75+ let reply = async {
76+ let me = gate(C::GATE, cx).await?;
77+ call.handle(me, cx).await
78+ }
79+ .await;
80+ publish(cx.sh, std::mem::take(&mut cx.out)).await;
81+
82+ let reply = reply.map_err(Error::from);
83+ let framed = frame::encode(&reply);
84+ if framed.len() - 4 > DOWN_MAX as usize {
85+ return frame::encode(&Err::<C::Reply, Error>(Error::Server));
86+ }
87+
88+ framed
89+}
90+
91+pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
92+ match request {
93+ Request::Legacy(call) => serve(call, cx).await,
94+ Request::GetSettings(call) => serve(call, cx).await,
95+ Request::GetUser(call) => serve(call, cx).await,
96+ Request::UpdateUser(call) => serve(call, cx).await,
97+ Request::UpdateStatus(call) => serve(call, cx).await,
98+ Request::UpdatePresence(call) => serve(call, cx).await,
99+ Request::ListPresences(call) => serve(call, cx).await,
100+ Request::UpdateAvatar(call) => serve(call, cx).await,
101+ Request::RemoveAvatar(call) => serve(call, cx).await,
102+ Request::GetAvatar(call) => serve(call, cx).await,
103+ Request::ListSessions(call) => serve(call, cx).await,
104+ Request::RevokeSession(call) => serve(call, cx).await,
105+ }
106+}
107+
108+impl Handle for Legacy {
109+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Self::Reply, ServerError> {
110+ let (reply, broadcasts) = request::dispatch(
111+ self.0,
112+ cx.client,
113+ &cx.sh.db,
114+ &cx.sh.services,
115+ &cx.sh.directory,
116+ &cx.sh.backups,
117+ )
118+ .await?;
119+ cx.out.extend(broadcasts);
120+
121+ Ok(reply)
122+ }
123+}
crates/server/src/call/user.rsadded+147 -0
@@ -0,0 +1,147 @@
1+use common::{
2+ call::{
3+ GetAvatar, GetSettings, GetUser, ListPresences, ListSessions, RemoveAvatar, RevokeSession,
4+ UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser,
5+ },
6+ event::Event,
7+ model::{AdminAction, Presence, ServerSettings, SessionInfo, User},
8+ validate::validate_avatar_size,
9+};
10+
11+use crate::{
12+ admin_log, authentication,
13+ call::{Cx, Handle, Me},
14+ error::ServerError,
15+ publish::{To, related_user_ids},
16+ request::{effective_presence, managed, presence_changed},
17+ server_settings, user,
18+};
19+
20+fn user_updated(user: &User, cx: &mut Cx<'_>) {
21+ cx.emit(
22+ To::Related(user.id.clone()),
23+ Event::UserUpdated(user.clone()),
24+ );
25+}
26+
27+impl Handle for GetSettings {
28+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> {
29+ server_settings::read(&cx.db).await
30+ }
31+}
32+
33+impl Handle for GetUser {
34+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
35+ user::read(&self.user_id, &cx.db).await
36+ }
37+}
38+
39+impl Handle for UpdateUser {
40+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
41+ let me = me.user()?;
42+ let user = user::update(&me.id, &self.username, &cx.db).await?;
43+ user_updated(&user, cx);
44+
45+ Ok(user)
46+ }
47+}
48+
49+impl Handle for UpdateStatus {
50+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
51+ let me = me.user()?;
52+ let user = user::update_status(&me.id, &self.status, &cx.db).await?;
53+ user_updated(&user, cx);
54+
55+ Ok(user)
56+ }
57+}
58+
59+impl Handle for UpdatePresence {
60+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
61+ let me = me.user()?;
62+ user::update_presence(&me.id, self.presence, &cx.db).await?;
63+ let broadcasts = presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?;
64+ cx.out.extend(broadcasts);
65+
66+ Ok(())
67+ }
68+}
69+
70+impl Handle for ListPresences {
71+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<(String, Presence)>, ServerError> {
72+ let me = me.user()?;
73+ let hub = &cx.sh.services.hub;
74+ let mut presences = Vec::new();
75+ for user_id in related_user_ids(&me.id, &cx.db).await? {
76+ let effective = effective_presence(hub, &user_id, &cx.db).await?;
77+ if effective != Presence::Offline || user_id == me.id {
78+ presences.push((user_id, effective));
79+ }
80+ }
81+
82+ Ok(presences)
83+ }
84+}
85+
86+impl Handle for UpdateAvatar {
87+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
88+ let me = me.user()?;
89+ let maximum = server_settings::read(&cx.db).await?.max_avatar_bytes;
90+ validate_avatar_size(&self.image, maximum)?;
91+ let user = user::set_avatar(&me.id, Some(&self.image), &mut cx.db).await?;
92+ user_updated(&user, cx);
93+
94+ Ok(user)
95+ }
96+}
97+
98+impl Handle for RemoveAvatar {
99+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
100+ let me = me.user()?;
101+ let user = user::set_avatar(&me.id, None, &mut cx.db).await?;
102+ user_updated(&user, cx);
103+
104+ Ok(user)
105+ }
106+}
107+
108+impl Handle for GetAvatar {
109+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<u8>, ServerError> {
110+ user::avatar(&self.avatar_id, &cx.db).await
111+ }
112+}
113+
114+impl Handle for ListSessions {
115+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<SessionInfo>, ServerError> {
116+ let me = me.user()?;
117+ managed(&me, &self.user_id, &cx.db).await?;
118+
119+ authentication::sessions(&self.user_id, &cx.db).await
120+ }
121+}
122+
123+impl Handle for RevokeSession {
124+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
125+ let me = me.user()?;
126+ managed(&me, &self.user_id, &cx.db).await?;
127+ authentication::revoke(
128+ &cx.sh.services.hub,
129+ authentication::Revoke::Session {
130+ user_id: &self.user_id,
131+ session_id: &self.session_id,
132+ },
133+ &cx.db,
134+ )
135+ .await?;
136+ admin_log::record(
137+ Some(&me.id),
138+ Some(&self.user_id),
139+ None,
140+ &AdminAction::SessionsRevoked,
141+ &cx.db,
142+ )
143+ .await?;
144+
145+ Ok(())
146+ }
147+}
crates/server/src/lib.rsmodified+1 -0
@@ -2,6 +2,7 @@ pub mod admin_log;
2 pub mod attachment;2 pub mod attachment;
3 pub mod authentication;3 pub mod authentication;
4 pub mod backup;4 pub mod backup;
5+pub mod call;
5 pub mod certificate;6 pub mod certificate;
6 pub mod community;7 pub mod community;
7 pub mod database;8 pub mod database;
crates/server/src/network.rsmodified+8 -15
@@ -2,10 +2,10 @@ use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration};
2 2
3 use bytes::Bytes;3 use bytes::Bytes;
4 use common::{4 use common::{
5+ call::Request,
5 frame::{self, DOWN_MAX, Sending, UP_MAX},6 frame::{self, DOWN_MAX, Sending, UP_MAX},
6 model::User,7 model::User,
7 open::Open,8 open::Open,
8- request::Request,
9 session::{Hello, Welcome},9 session::{Hello, Welcome},
10 transport::Close,10 transport::Close,
11 };11 };
@@ -15,6 +15,7 @@ use tracing::{info, warn};
15 15
16 use crate::{16 use crate::{
17 attachment, authentication,17 attachment, authentication,
18+ call::{self, Cx},
18 database::{self, DB},19 database::{self, DB},
19 datagram,20 datagram,
20 error::ServerError,21 error::ServerError,
@@ -40,7 +41,7 @@ pub(crate) struct Shared {
40 pub(crate) db: DB,41 pub(crate) db: DB,
41 pub(crate) services: Services,42 pub(crate) services: Services,
42 pub(crate) directory: PathBuf,43 pub(crate) directory: PathBuf,
43- backups: PathBuf,44+ pub(crate) backups: PathBuf,
44 }45 }
45 46
46 struct Pending {47 struct Pending {
@@ -300,19 +301,11 @@ async fn answer(
300 mut send_stream: Sending,301 mut send_stream: Sending,
301 shared: Shared,302 shared: Shared,
302 ) -> Result<(), ServerError> {303 ) -> Result<(), ServerError> {
303- let (response, broadcasts) = request::handle(304+ let db = database::connect(&shared.db).await?;
304- request,305+ let mut cx = Cx::new(&client, &shared, db);
305- &client,306+ let reply = call::dispatch(request, &mut cx).await;
306- &shared.db,307+
307- &shared.services,308+ send_stream.get().write_all(&reply).await?;
308- &shared.directory,
309- &shared.backups,
310- )
311- .await;
312-
313- publish(&shared, broadcasts).await;
314-
315- frame::write(&mut send_stream, &response, DOWN_MAX).await?;
316 send_stream.finish()?;309 send_stream.finish()?;
317 310
318 Ok(())311 Ok(())
crates/server/src/request.rsmodified+135 -217
@@ -8,7 +8,7 @@ use common::{
8 Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom,8 Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom,
9 },9 },
10 permission,10 permission,
11- request::Request,11+ request::LegacyRequest,
12 response::Response,12 response::Response,
13 share::{Kind, Share},13 share::{Kind, Share},
14 time::{self, MINUTE_MILLIS},14 time::{self, MINUTE_MILLIS},
@@ -30,17 +30,18 @@ use crate::{
30 invitation, invite, log, message,30 invitation, invite, log, message,
31 network::Services,31 network::Services,
32 notes, overview,32 notes, overview,
33- publish::{Broadcast, To, related_user_ids},33+ publish::{Broadcast, To},
34 rate_limit::RateLimit,34 rate_limit::RateLimit,
35 report,35 report,
36 rooms::{Departure, Rooms},36 rooms::{Departure, Rooms},
37 server_ban, server_settings, stats, user, user_community,37 server_ban, server_settings, stats, user, user_community,
38 };38 };
39 39
40-type Outcome = (Response, Vec<Broadcast>);40+pub(crate) type Outcome = (Response, Vec<Broadcast>);
41 41
42+#[cfg(test)]
42 pub async fn handle(43 pub async fn handle(
43- request: Request,44+ request: LegacyRequest,
44 client: &Client,45 client: &Client,
45 db: &DB,46 db: &DB,
46 services: &Services,47 services: &Services,
@@ -53,8 +54,8 @@ pub async fn handle(
53 }54 }
54 }55 }
55 56
56-async fn dispatch(57+pub(crate) async fn dispatch(
57- request: Request,58+ request: LegacyRequest,
58 client: &Client,59 client: &Client,
59 db: &DB,60 db: &DB,
60 services: &Services,61 services: &Services,
@@ -70,7 +71,7 @@ async fn dispatch(
70 let mut conn = database::connect(db).await?;71 let mut conn = database::connect(db).await?;
71 72
72 let outcome = match request {73 let outcome = match request {
73- Request::Register {74+ LegacyRequest::Register {
74 username,75 username,
75 password,76 password,
76 invite,77 invite,
@@ -81,35 +82,18 @@ async fn dispatch(
81 .await?;82 .await?;
82 (Response::Session { user, token }, Vec::new())83 (Response::Session { user, token }, Vec::new())
83 }84 }
84- Request::Login { username, password } => {85+ LegacyRequest::Login { username, password } => {
85 limit_logins(rate_limit, connection, &conn).await?;86 limit_logins(rate_limit, connection, &conn).await?;
86 let (user, token) = authentication::login(&username, &password, &conn).await?;87 let (user, token) = authentication::login(&username, &password, &conn).await?;
87 (Response::Session { user, token }, Vec::new())88 (Response::Session { user, token }, Vec::new())
88 }89 }
89- Request::Logout => {90+ LegacyRequest::Logout => {
90 authenticated(client, &conn).await?;91 authenticated(client, &conn).await?;
91 let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?;92 let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?;
92 authentication::logout(&me.token, &conn).await?;93 authentication::logout(&me.token, &conn).await?;
93 (Response::Done, Vec::new())94 (Response::Done, Vec::new())
94 }95 }
95- Request::ReadUser { user_id } => {96+ LegacyRequest::UpdateServerSettings { settings } => {
96- authenticated(client, &conn).await?;
97- (
98- Response::User(user::read(&user_id, &conn).await?),
99- Vec::new(),
100- )
101- }
102- Request::UpdateUser { username } => {
103- let me = authenticated(client, &conn).await?;
104- let user = user::update(&me.id, &username, &conn).await?;
105- let broadcasts = user_updated(&user);
106- (Response::User(user), broadcasts)
107- }
108- Request::ServerSettings => (
109- Response::ServerSettings(server_settings::read(&conn).await?),
110- Vec::new(),
111- ),
112- Request::UpdateServerSettings { settings } => {
113 let me = builder(client, &conn).await?;97 let me = builder(client, &conn).await?;
114 validate_server_settings(&settings)?;98 validate_server_settings(&settings)?;
115 server_settings::update(&settings, &conn).await?;99 server_settings::update(&settings, &conn).await?;
@@ -131,40 +115,7 @@ async fn dispatch(
131 )];115 )];
132 (Response::ServerSettings(settings), broadcasts)116 (Response::ServerSettings(settings), broadcasts)
133 }117 }
134- Request::Sessions { user_id } => {118+ LegacyRequest::RenameUser { user_id, username } => {
135- let me = authenticated(client, &conn).await?;
136- managed(&me, &user_id, &conn).await?;
137- (
138- Response::Sessions(authentication::sessions(&user_id, &conn).await?),
139- Vec::new(),
140- )
141- }
142- Request::RevokeSession {
143- user_id,
144- session_id,
145- } => {
146- let me = authenticated(client, &conn).await?;
147- managed(&me, &user_id, &conn).await?;
148- authentication::revoke(
149- hub,
150- authentication::Revoke::Session {
151- user_id: &user_id,
152- session_id: &session_id,
153- },
154- &conn,
155- )
156- .await?;
157- admin_log::record(
158- Some(&me.id),
159- Some(&user_id),
160- None,
161- &AdminAction::SessionsRevoked,
162- &conn,
163- )
164- .await?;
165- (Response::Done, Vec::new())
166- }
167- Request::RenameUser { user_id, username } => {
168 let me = authenticated(client, &conn).await?;119 let me = authenticated(client, &conn).await?;
169 let target = managed(&me, &user_id, &conn).await?;120 let target = managed(&me, &user_id, &conn).await?;
170 let user = user::update(&user_id, &username, &conn).await?;121 let user = user::update(&user_id, &username, &conn).await?;
@@ -181,7 +132,7 @@ async fn dispatch(
181 let broadcasts = user_updated(&user);132 let broadcasts = user_updated(&user);
182 (Response::User(user), broadcasts)133 (Response::User(user), broadcasts)
183 }134 }
184- Request::CreateUser { username, password } => {135+ LegacyRequest::CreateUser { username, password } => {
185 let me = builder(client, &conn).await?;136 let me = builder(client, &conn).await?;
186 let user = authentication::create_account(&username, &password, &conn).await?;137 let user = authentication::create_account(&username, &password, &conn).await?;
187 admin_log::record(138 admin_log::record(
@@ -194,11 +145,11 @@ async fn dispatch(
194 .await?;145 .await?;
195 (Response::User(user), Vec::new())146 (Response::User(user), Vec::new())
196 }147 }
197- Request::Users => {148+ LegacyRequest::Users => {
198 builder(client, &conn).await?;149 builder(client, &conn).await?;
199 (Response::Users(user::all(&conn).await?), Vec::new())150 (Response::Users(user::all(&conn).await?), Vec::new())
200 }151 }
201- Request::AdminLogs {152+ LegacyRequest::AdminLogs {
202 actor_id,153 actor_id,
203 target_id,154 target_id,
204 action,155 action,
@@ -221,21 +172,21 @@ async fn dispatch(
221 Vec::new(),172 Vec::new(),
222 )173 )
223 }174 }
224- Request::DailyStats { days } => {175+ LegacyRequest::DailyStats { days } => {
225 builder(client, &conn).await?;176 builder(client, &conn).await?;
226 (177 (
227 Response::DailyStats(stats::daily(days, &conn).await?),178 Response::DailyStats(stats::daily(days, &conn).await?),
228 Vec::new(),179 Vec::new(),
229 )180 )
230 }181 }
231- Request::Overview => {182+ LegacyRequest::Overview => {
232 builder(client, &conn).await?;183 builder(client, &conn).await?;
233 (184 (
234 Response::Overview(overview::read(hub, rooms, &conn).await?),185 Response::Overview(overview::read(hub, rooms, &conn).await?),
235 Vec::new(),186 Vec::new(),
236 )187 )
237 }188 }
238- Request::SuspendUser { user_id, suspended } => {189+ LegacyRequest::SuspendUser { user_id, suspended } => {
239 let me = authenticated(client, &conn).await?;190 let me = authenticated(client, &conn).await?;
240 managed(&me, &user_id, &conn).await?;191 managed(&me, &user_id, &conn).await?;
241 user::set_suspended(&user_id, suspended, &conn).await?;192 user::set_suspended(&user_id, suspended, &conn).await?;
@@ -250,7 +201,7 @@ async fn dispatch(
250 }201 }
251 (Response::Done, Vec::new())202 (Response::Done, Vec::new())
252 }203 }
253- Request::RevokeSessions { user_id } => {204+ LegacyRequest::RevokeSessions { user_id } => {
254 let me = authenticated(client, &conn).await?;205 let me = authenticated(client, &conn).await?;
255 managed(&me, &user_id, &conn).await?;206 managed(&me, &user_id, &conn).await?;
256 authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;207 authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;
@@ -264,7 +215,7 @@ async fn dispatch(
264 .await?;215 .await?;
265 (Response::Done, Vec::new())216 (Response::Done, Vec::new())
266 }217 }
267- Request::ResetPassword { user_id, password } => {218+ LegacyRequest::ResetPassword { user_id, password } => {
268 let me = authenticated(client, &conn).await?;219 let me = authenticated(client, &conn).await?;
269 managed(&me, &user_id, &conn).await?;220 managed(&me, &user_id, &conn).await?;
270 authentication::reset_password(&user_id, &password, &conn).await?;221 authentication::reset_password(&user_id, &password, &conn).await?;
@@ -279,7 +230,7 @@ async fn dispatch(
279 .await?;230 .await?;
280 (Response::Done, Vec::new())231 (Response::Done, Vec::new())
281 }232 }
282- Request::ClearProfile { user_id } => {233+ LegacyRequest::ClearProfile { user_id } => {
283 let me = authenticated(client, &conn).await?;234 let me = authenticated(client, &conn).await?;
284 managed(&me, &user_id, &conn).await?;235 managed(&me, &user_id, &conn).await?;
285 user::set_avatar(&user_id, None, &mut conn).await?;236 user::set_avatar(&user_id, None, &mut conn).await?;
@@ -295,7 +246,7 @@ async fn dispatch(
295 let broadcasts = user_updated(&user);246 let broadcasts = user_updated(&user);
296 (Response::User(user), broadcasts)247 (Response::User(user), broadcasts)
297 }248 }
298- Request::SetRole { user_id, role } => {249+ LegacyRequest::SetRole { user_id, role } => {
299 let me = authenticated(client, &conn).await?;250 let me = authenticated(client, &conn).await?;
300 ensure(permission::can_set_role(me.role, me.id == user_id))?;251 ensure(permission::can_set_role(me.role, me.id == user_id))?;
301 let user = user::set_role_by_id(&user_id, role, &conn).await?;252 let user = user::set_role_by_id(&user_id, role, &conn).await?;
@@ -316,50 +267,7 @@ async fn dispatch(
316 }267 }
317 (Response::User(user), broadcasts)268 (Response::User(user), broadcasts)
318 }269 }
319- Request::UpdateStatus { status } => {270+ LegacyRequest::DeleteUser { user_id } => {
320- let me = authenticated(client, &conn).await?;
321- let user = user::update_status(&me.id, &status, &conn).await?;
322- let broadcasts = user_updated(&user);
323- (Response::User(user), broadcasts)
324- }
325- Request::UpdatePresence { presence: chosen } => {
326- let me = authenticated(client, &conn).await?;
327- user::update_presence(&me.id, chosen, &conn).await?;
328- let broadcasts = presence_changed(hub, &me.id, &conn).await?;
329- (Response::Done, broadcasts)
330- }
331- Request::ReadPresences => {
332- let me = authenticated(client, &conn).await?;
333- let mut presences = Vec::new();
334- for user_id in related_user_ids(&me.id, &conn).await? {
335- let effective = effective_presence(hub, &user_id, &conn).await?;
336- if effective != Presence::Offline || user_id == me.id {
337- presences.push((user_id, effective));
338- }
339- }
340- (Response::Presences(presences), Vec::new())
341- }
342- Request::UpdateAvatar { image } => {
343- let me = authenticated(client, &conn).await?;
344- validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?;
345- let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?;
346- let broadcasts = user_updated(&user);
347- (Response::User(user), broadcasts)
348- }
349- Request::RemoveAvatar => {
350- let me = authenticated(client, &conn).await?;
351- let user = user::set_avatar(&me.id, None, &mut conn).await?;
352- let broadcasts = user_updated(&user);
353- (Response::User(user), broadcasts)
354- }
355- Request::ReadAvatar { avatar_id } => {
356- authenticated(client, &conn).await?;
357- (
358- Response::Avatar(user::avatar(&avatar_id, &conn).await?),
359- Vec::new(),
360- )
361- }
362- Request::DeleteUser { user_id } => {
363 let me = authenticated(client, &conn).await?;271 let me = authenticated(client, &conn).await?;
364 let target = user::read(&user_id, &conn).await?;272 let target = user::read(&user_id, &conn).await?;
365 ensure(permission::can_delete_user(273 ensure(permission::can_delete_user(
@@ -404,7 +312,7 @@ async fn dispatch(
404 }312 }
405 (Response::User(deleted), broadcasts)313 (Response::User(deleted), broadcasts)
406 }314 }
407- Request::CreateCommunity { name } => {315+ LegacyRequest::CreateCommunity { name } => {
408 let me = authenticated(client, &conn).await?;316 let me = authenticated(client, &conn).await?;
409 let limit = server_settings::read(&conn).await?.max_communities_per_user;317 let limit = server_settings::read(&conn).await?.max_communities_per_user;
410 let owned = user_community::owned_groups(&me.id, &conn).await?;318 let owned = user_community::owned_groups(&me.id, &conn).await?;
@@ -419,7 +327,7 @@ async fn dispatch(
419 tx.commit().await?;327 tx.commit().await?;
420 (Response::Community(community), Vec::new())328 (Response::Community(community), Vec::new())
421 }329 }
422- Request::ReadCommunity { community_id } => {330+ LegacyRequest::ReadCommunity { community_id } => {
423 let me = authenticated(client, &conn).await?;331 let me = authenticated(client, &conn).await?;
424 allowed(&me, &community_id, &conn, permission::can_read).await?;332 allowed(&me, &community_id, &conn, permission::can_read).await?;
425 (333 (
@@ -427,7 +335,7 @@ async fn dispatch(
427 Vec::new(),335 Vec::new(),
428 )336 )
429 }337 }
430- Request::UpdateCommunity { community_id, name } => {338+ LegacyRequest::UpdateCommunity { community_id, name } => {
431 let me = authenticated(client, &conn).await?;339 let me = authenticated(client, &conn).await?;
432 ensure_editable(&community_id, &conn).await?;340 ensure_editable(&community_id, &conn).await?;
433 allowed(&me, &community_id, &conn, permission::can_rename_community).await?;341 allowed(&me, &community_id, &conn, permission::can_rename_community).await?;
@@ -442,7 +350,7 @@ async fn dispatch(
442 vec![Broadcast::new(To::Community(community_id), event)],350 vec![Broadcast::new(To::Community(community_id), event)],
443 )351 )
444 }352 }
445- Request::UpdateCommunityAvatar {353+ LegacyRequest::UpdateCommunityAvatar {
446 community_id,354 community_id,
447 image,355 image,
448 } => {356 } => {
@@ -466,7 +374,7 @@ async fn dispatch(
466 vec![Broadcast::new(To::Community(community_id), event)],374 vec![Broadcast::new(To::Community(community_id), event)],
467 )375 )
468 }376 }
469- Request::DeleteCommunity { community_id } => {377+ LegacyRequest::DeleteCommunity { community_id } => {
470 let me = authenticated(client, &conn).await?;378 let me = authenticated(client, &conn).await?;
471 ensure_editable(&community_id, &conn).await?;379 ensure_editable(&community_id, &conn).await?;
472 allowed(&me, &community_id, &conn, permission::can_delete_community).await?;380 allowed(&me, &community_id, &conn, permission::can_delete_community).await?;
@@ -493,7 +401,7 @@ async fn dispatch(
493 broadcasts.push(Broadcast::new(To::Users(member_ids), event));401 broadcasts.push(Broadcast::new(To::Users(member_ids), event));
494 (Response::Community(deleted), broadcasts)402 (Response::Community(deleted), broadcasts)
495 }403 }
496- Request::LeaveCommunity { community_id } => {404+ LegacyRequest::LeaveCommunity { community_id } => {
497 let me = authenticated(client, &conn).await?;405 let me = authenticated(client, &conn).await?;
498 ensure_editable(&community_id, &conn).await?;406 ensure_editable(&community_id, &conn).await?;
499 allowed(&me, &community_id, &conn, permission::can_leave).await?;407 allowed(&me, &community_id, &conn, permission::can_leave).await?;
@@ -515,14 +423,14 @@ async fn dispatch(
515 broadcasts.push(Broadcast::new(To::Community(community_id), event));423 broadcasts.push(Broadcast::new(To::Community(community_id), event));
516 (Response::Done, broadcasts)424 (Response::Done, broadcasts)
517 }425 }
518- Request::Communities => {426+ LegacyRequest::Communities => {
519 let me = authenticated(client, &conn).await?;427 let me = authenticated(client, &conn).await?;
520 (428 (
521 Response::Communities(community::communities_of(&me.id, &conn).await?),429 Response::Communities(community::communities_of(&me.id, &conn).await?),
522 Vec::new(),430 Vec::new(),
523 )431 )
524 }432 }
525- Request::Members { community_id } => {433+ LegacyRequest::Members { community_id } => {
526 let me = authenticated(client, &conn).await?;434 let me = authenticated(client, &conn).await?;
527 allowed(&me, &community_id, &conn, permission::can_read).await?;435 allowed(&me, &community_id, &conn, permission::can_read).await?;
528 (436 (
@@ -530,7 +438,7 @@ async fn dispatch(
530 Vec::new(),438 Vec::new(),
531 )439 )
532 }440 }
533- Request::Kick {441+ LegacyRequest::Kick {
534 community_id,442 community_id,
535 user_id,443 user_id,
536 reason,444 reason,
@@ -549,7 +457,7 @@ async fn dispatch(
549 )457 )
550 .await?458 .await?
551 }459 }
552- Request::Ban {460+ LegacyRequest::Ban {
553 community_id,461 community_id,
554 user_id,462 user_id,
555 reason,463 reason,
@@ -568,7 +476,7 @@ async fn dispatch(
568 )476 )
569 .await?477 .await?
570 }478 }
571- Request::Unban {479+ LegacyRequest::Unban {
572 community_id,480 community_id,
573 user_id,481 user_id,
574 } => {482 } => {
@@ -585,7 +493,7 @@ async fn dispatch(
585 .await?;493 .await?;
586 (Response::Done, Vec::new())494 (Response::Done, Vec::new())
587 }495 }
588- Request::Bans { community_id } => {496+ LegacyRequest::Bans { community_id } => {
589 let me = authenticated(client, &conn).await?;497 let me = authenticated(client, &conn).await?;
590 allowed(&me, &community_id, &conn, permission::can_unban).await?;498 allowed(&me, &community_id, &conn, permission::can_unban).await?;
591 (499 (
@@ -593,7 +501,7 @@ async fn dispatch(
593 Vec::new(),501 Vec::new(),
594 )502 )
595 }503 }
596- Request::SetRank {504+ LegacyRequest::SetRank {
597 community_id,505 community_id,
598 user_id,506 user_id,
599 rank,507 rank,
@@ -625,7 +533,7 @@ async fn dispatch(
625 vec![Broadcast::new(To::Community(community_id), event)],533 vec![Broadcast::new(To::Community(community_id), event)],
626 )534 )
627 }535 }
628- Request::CreateMessage {536+ LegacyRequest::CreateMessage {
629 community_id,537 community_id,
630 body,538 body,
631 attachments,539 attachments,
@@ -655,7 +563,7 @@ async fn dispatch(
655 let broadcast = message_event(&created, Event::MessageCreated);563 let broadcast = message_event(&created, Event::MessageCreated);
656 (Response::Message(created), vec![broadcast])564 (Response::Message(created), vec![broadcast])
657 }565 }
658- Request::ForwardMessages {566+ LegacyRequest::ForwardMessages {
659 message_ids,567 message_ids,
660 community_id,568 community_id,
661 snippet,569 snippet,
@@ -689,7 +597,7 @@ async fn dispatch(
689 .collect();597 .collect();
690 (Response::Messages(created), broadcasts)598 (Response::Messages(created), broadcasts)
691 }599 }
692- Request::UpdateMessage { message_id, body } => {600+ LegacyRequest::UpdateMessage { message_id, body } => {
693 let me = authenticated(client, &conn).await?;601 let me = authenticated(client, &conn).await?;
694 let existing = message::read(&message_id, &conn).await?;602 let existing = message::read(&message_id, &conn).await?;
695 allowed(&me, &existing.community_id, &conn, permission::can_post).await?;603 allowed(&me, &existing.community_id, &conn, permission::can_post).await?;
@@ -703,7 +611,7 @@ async fn dispatch(
703 let broadcast = message_event(&updated, Event::MessageUpdated);611 let broadcast = message_event(&updated, Event::MessageUpdated);
704 (Response::Message(updated), vec![broadcast])612 (Response::Message(updated), vec![broadcast])
705 }613 }
706- Request::CreatePoll {614+ LegacyRequest::CreatePoll {
707 community_id,615 community_id,
708 question,616 question,
709 options,617 options,
@@ -723,7 +631,7 @@ async fn dispatch(
723 let broadcast = message_event(&created, Event::MessageCreated);631 let broadcast = message_event(&created, Event::MessageCreated);
724 (Response::Message(created), vec![broadcast])632 (Response::Message(created), vec![broadcast])
725 }633 }
726- Request::Vote {634+ LegacyRequest::Vote {
727 message_id,635 message_id,
728 positions,636 positions,
729 } => {637 } => {
@@ -738,7 +646,7 @@ async fn dispatch(
738 let broadcast = message_event(&updated, Event::MessageUpdated);646 let broadcast = message_event(&updated, Event::MessageUpdated);
739 (Response::Done, vec![broadcast])647 (Response::Done, vec![broadcast])
740 }648 }
741- Request::ClosePoll { message_id } => {649+ LegacyRequest::ClosePoll { message_id } => {
742 let me = authenticated(client, &conn).await?;650 let me = authenticated(client, &conn).await?;
743 let existing = message::read(&message_id, &conn).await?;651 let existing = message::read(&message_id, &conn).await?;
744 ensure(permission::can_close_poll(652 ensure(permission::can_close_poll(
@@ -749,7 +657,7 @@ async fn dispatch(
749 let broadcast = message_event(&updated, Event::MessageUpdated);657 let broadcast = message_event(&updated, Event::MessageUpdated);
750 (Response::Done, vec![broadcast])658 (Response::Done, vec![broadcast])
751 }659 }
752- Request::React { message_id, emoji } => {660+ LegacyRequest::React { message_id, emoji } => {
753 let me = authenticated(client, &conn).await?;661 let me = authenticated(client, &conn).await?;
754 validate_reaction(&emoji)?;662 validate_reaction(&emoji)?;
755 let existing = message::read(&message_id, &conn).await?;663 let existing = message::read(&message_id, &conn).await?;
@@ -760,7 +668,7 @@ async fn dispatch(
760 let broadcast = message_event(&updated, Event::MessageUpdated);668 let broadcast = message_event(&updated, Event::MessageUpdated);
761 (Response::Done, vec![broadcast])669 (Response::Done, vec![broadcast])
762 }670 }
763- Request::Pin { message_id, pinned } => {671+ LegacyRequest::Pin { message_id, pinned } => {
764 let me = authenticated(client, &conn).await?;672 let me = authenticated(client, &conn).await?;
765 let existing = message::read(&message_id, &conn).await?;673 let existing = message::read(&message_id, &conn).await?;
766 let direct = community::is_direct(&existing.community_id, &conn).await?;674 let direct = community::is_direct(&existing.community_id, &conn).await?;
@@ -772,14 +680,14 @@ async fn dispatch(
772 let broadcast = message_event(&updated, Event::MessageUpdated);680 let broadcast = message_event(&updated, Event::MessageUpdated);
773 (Response::Done, vec![broadcast])681 (Response::Done, vec![broadcast])
774 }682 }
775- Request::Unreads => {683+ LegacyRequest::Unreads => {
776 let me = authenticated(client, &conn).await?;684 let me = authenticated(client, &conn).await?;
777 (685 (
778 Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),686 Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),
779 Vec::new(),687 Vec::new(),
780 )688 )
781 }689 }
782- Request::MarkRead {690+ LegacyRequest::MarkRead {
783 community_id,691 community_id,
784 message_id,692 message_id,
785 } => {693 } => {
@@ -789,7 +697,7 @@ async fn dispatch(
789 user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;697 user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;
790 (Response::Done, Vec::new())698 (Response::Done, Vec::new())
791 }699 }
792- Request::Pins { community_id } => {700+ LegacyRequest::Pins { community_id } => {
793 let me = authenticated(client, &conn).await?;701 let me = authenticated(client, &conn).await?;
794 allowed(&me, &community_id, &conn, permission::can_read).await?;702 allowed(&me, &community_id, &conn, permission::can_read).await?;
795 (703 (
@@ -797,7 +705,7 @@ async fn dispatch(
797 Vec::new(),705 Vec::new(),
798 )706 )
799 }707 }
800- Request::DeleteMessage { message_id } => {708+ LegacyRequest::DeleteMessage { message_id } => {
801 let me = authenticated(client, &conn).await?;709 let me = authenticated(client, &conn).await?;
802 let existing = message::read(&message_id, &conn).await?;710 let existing = message::read(&message_id, &conn).await?;
803 let author = user::read(&existing.user_id, &conn).await?;711 let author = user::read(&existing.user_id, &conn).await?;
@@ -835,7 +743,7 @@ async fn dispatch(
835 let broadcast = Broadcast::new(To::Community(deleted.community_id.clone()), event);743 let broadcast = Broadcast::new(To::Community(deleted.community_id.clone()), event);
836 (Response::Message(deleted), vec![broadcast])744 (Response::Message(deleted), vec![broadcast])
837 }745 }
838- Request::WatchCommunity { community_id } => {746+ LegacyRequest::WatchCommunity { community_id } => {
839 let me = authenticated(client, &conn).await?;747 let me = authenticated(client, &conn).await?;
840 let Some(community_id) = community_id else {748 let Some(community_id) = community_id else {
841 client.watch(None);749 client.watch(None);
@@ -860,7 +768,7 @@ async fn dispatch(
860 }768 }
861 (Response::Done, Vec::new())769 (Response::Done, Vec::new())
862 }770 }
863- Request::ReadMessages {771+ LegacyRequest::ReadMessages {
864 community_id,772 community_id,
865 before,773 before,
866 } => {774 } => {
@@ -869,7 +777,7 @@ async fn dispatch(
869 let messages = message::read_page(&community_id, before.as_deref(), &conn).await?;777 let messages = message::read_page(&community_id, before.as_deref(), &conn).await?;
870 (Response::Messages(messages), Vec::new())778 (Response::Messages(messages), Vec::new())
871 }779 }
872- Request::JoinVoice { community_id } => {780+ LegacyRequest::JoinVoice { community_id } => {
873 let me = authenticated(client, &conn).await?;781 let me = authenticated(client, &conn).await?;
874 allowed(&me, &community_id, &conn, permission::can_join_voice).await?;782 allowed(&me, &community_id, &conn, permission::can_join_voice).await?;
875 ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;783 ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;
@@ -902,7 +810,7 @@ async fn dispatch(
902 broadcasts,810 broadcasts,
903 )811 )
904 }812 }
905- Request::Typing { community_id } => {813+ LegacyRequest::Typing { community_id } => {
906 let me = authenticated(client, &conn).await?;814 let me = authenticated(client, &conn).await?;
907 allowed(&me, &community_id, &conn, permission::can_read).await?;815 allowed(&me, &community_id, &conn, permission::can_read).await?;
908 let broadcasts = if user::is_ghost(&me.id, &conn).await? {816 let broadcasts = if user::is_ghost(&me.id, &conn).await? {
@@ -921,7 +829,7 @@ async fn dispatch(
921 };829 };
922 (Response::Done, broadcasts)830 (Response::Done, broadcasts)
923 }831 }
924- Request::LeaveVoice => {832+ LegacyRequest::LeaveVoice => {
925 authenticated(client, &conn).await?;833 authenticated(client, &conn).await?;
926 let broadcasts = match rooms.leave(client.id) {834 let broadcasts = match rooms.leave(client.id) {
927 Some(departure) => departed(departure, &conn).await?,835 Some(departure) => departed(departure, &conn).await?,
@@ -929,7 +837,7 @@ async fn dispatch(
929 };837 };
930 (Response::Done, broadcasts)838 (Response::Done, broadcasts)
931 }839 }
932- Request::StartShare { kind, source } => {840+ LegacyRequest::StartShare { kind, source } => {
933 let me = authenticated(client, &conn).await?;841 let me = authenticated(client, &conn).await?;
934 let Some(community_id) = rooms.room_of_conn(client.id) else {842 let Some(community_id) = rooms.room_of_conn(client.id) else {
935 return Err(CommonError::NotFound.into());843 return Err(CommonError::NotFound.into());
@@ -954,7 +862,7 @@ async fn dispatch(
954 862
955 (Response::Done, broadcasts)863 (Response::Done, broadcasts)
956 }864 }
957- Request::StopShare { kind } => {865+ LegacyRequest::StopShare { kind } => {
958 let me = authenticated(client, &conn).await?;866 let me = authenticated(client, &conn).await?;
959 let broadcasts = match rooms.stop_share(client.id, kind) {867 let broadcasts = match rooms.stop_share(client.id, kind) {
960 Some(community_id) => vec![share_ended(&community_id, &me.id, kind)],868 Some(community_id) => vec![share_ended(&community_id, &me.id, kind)],
@@ -962,12 +870,12 @@ async fn dispatch(
962 };870 };
963 (Response::Done, broadcasts)871 (Response::Done, broadcasts)
964 }872 }
965- Request::Shares { community_id } => {873+ LegacyRequest::Shares { community_id } => {
966 let me = authenticated(client, &conn).await?;874 let me = authenticated(client, &conn).await?;
967 allowed(&me, &community_id, &conn, permission::can_read).await?;875 allowed(&me, &community_id, &conn, permission::can_read).await?;
968 (Response::Shares(rooms.shares(&community_id)), Vec::new())876 (Response::Shares(rooms.shares(&community_id)), Vec::new())
969 }877 }
970- Request::WatchShare {878+ LegacyRequest::WatchShare {
971 user_id,879 user_id,
972 kind,880 kind,
973 quality,881 quality,
@@ -980,12 +888,12 @@ async fn dispatch(
980 888
981 (Response::Done, broadcasts)889 (Response::Done, broadcasts)
982 }890 }
983- Request::UnwatchShare { user_id, kind } => {891+ LegacyRequest::UnwatchShare { user_id, kind } => {
984 authenticated(client, &conn).await?;892 authenticated(client, &conn).await?;
985 893
986 (Response::Done, rooms.unwatch(client.id, &user_id, kind))894 (Response::Done, rooms.unwatch(client.id, &user_id, kind))
987 }895 }
988- Request::RequestKeyframe { user_id, kind } => {896+ LegacyRequest::RequestKeyframe { user_id, kind } => {
989 authenticated(client, &conn).await?;897 authenticated(client, &conn).await?;
990 let keyframe = rooms898 let keyframe = rooms
991 .keyframe(client.id, &user_id, kind)899 .keyframe(client.id, &user_id, kind)
@@ -993,7 +901,7 @@ async fn dispatch(
993 901
994 (Response::Done, vec![keyframe])902 (Response::Done, vec![keyframe])
995 }903 }
996- Request::DeclineCall { community_id } => {904+ LegacyRequest::DeclineCall { community_id } => {
997 let me = authenticated(client, &conn).await?;905 let me = authenticated(client, &conn).await?;
998 ensure(community::is_direct(&community_id, &conn).await?)?;906 ensure(community::is_direct(&community_id, &conn).await?)?;
999 allowed(&me, &community_id, &conn, permission::can_read).await?;907 allowed(&me, &community_id, &conn, permission::can_read).await?;
@@ -1007,7 +915,7 @@ async fn dispatch(
1007 vec![message_event(&created, Event::MessageCreated)],915 vec![message_event(&created, Event::MessageCreated)],
1008 )916 )
1009 }917 }
1010- Request::VoiceParticipants { community_id } => {918+ LegacyRequest::VoiceParticipants { community_id } => {
1011 let me = authenticated(client, &conn).await?;919 let me = authenticated(client, &conn).await?;
1012 allowed(&me, &community_id, &conn, permission::can_read).await?;920 allowed(&me, &community_id, &conn, permission::can_read).await?;
1013 (921 (
@@ -1015,7 +923,7 @@ async fn dispatch(
1015 Vec::new(),923 Vec::new(),
1016 )924 )
1017 }925 }
1018- Request::FindUser { username } => {926+ LegacyRequest::FindUser { username } => {
1019 let me = authenticated(client, &conn).await?;927 let me = authenticated(client, &conn).await?;
1020 let found = user::by_username(&username, &conn)928 let found = user::by_username(&username, &conn)
1021 .await?929 .await?
@@ -1023,7 +931,7 @@ async fn dispatch(
1023 .ok_or(CommonError::NotFound)?;931 .ok_or(CommonError::NotFound)?;
1024 (Response::User(found), Vec::new())932 (Response::User(found), Vec::new())
1025 }933 }
1026- Request::OpenDirect { user_id } => {934+ LegacyRequest::OpenDirect { user_id } => {
1027 let me = authenticated(client, &conn).await?;935 let me = authenticated(client, &conn).await?;
1028 match direct::open(&me.id, &user_id, &mut conn).await? {936 match direct::open(&me.id, &user_id, &mut conn).await? {
1029 direct::Opening::Created(community) => {937 direct::Opening::Created(community) => {
@@ -1041,39 +949,39 @@ async fn dispatch(
1041 }949 }
1042 }950 }
1043 }951 }
1044- Request::OpenNotes => {952+ LegacyRequest::OpenNotes => {
1045 let me = authenticated(client, &conn).await?;953 let me = authenticated(client, &conn).await?;
1046 (954 (
1047 Response::Community(notes::open(&me.id, &mut conn).await?),955 Response::Community(notes::open(&me.id, &mut conn).await?),
1048 Vec::new(),956 Vec::new(),
1049 )957 )
1050 }958 }
1051- Request::Friends => {959+ LegacyRequest::Friends => {
1052 let me = authenticated(client, &conn).await?;960 let me = authenticated(client, &conn).await?;
1053 (961 (
1054 Response::Friends(friend::state(&me.id, &conn).await?),962 Response::Friends(friend::state(&me.id, &conn).await?),
1055 Vec::new(),963 Vec::new(),
1056 )964 )
1057 }965 }
1058- Request::AddFriend { user_id } => {966+ LegacyRequest::AddFriend { user_id } => {
1059 let me = authenticated(client, &conn).await?;967 let me = authenticated(client, &conn).await?;
1060 friend::add(&me.id, &user_id, &mut conn).await?;968 friend::add(&me.id, &user_id, &mut conn).await?;
1061 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;969 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1062 (Response::Done, broadcasts)970 (Response::Done, broadcasts)
1063 }971 }
1064- Request::AcceptFriend { user_id } => {972+ LegacyRequest::AcceptFriend { user_id } => {
1065 let me = authenticated(client, &conn).await?;973 let me = authenticated(client, &conn).await?;
1066 friend::accept(&me.id, &user_id, &mut conn).await?;974 friend::accept(&me.id, &user_id, &mut conn).await?;
1067 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;975 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1068 (Response::Done, broadcasts)976 (Response::Done, broadcasts)
1069 }977 }
1070- Request::RemoveFriend { user_id } => {978+ LegacyRequest::RemoveFriend { user_id } => {
1071 let me = authenticated(client, &conn).await?;979 let me = authenticated(client, &conn).await?;
1072 friend::remove(&me.id, &user_id, &mut conn).await?;980 friend::remove(&me.id, &user_id, &mut conn).await?;
1073 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;981 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1074 (Response::Done, broadcasts)982 (Response::Done, broadcasts)
1075 }983 }
1076- Request::Invite {984+ LegacyRequest::Invite {
1077 community_id,985 community_id,
1078 user_id,986 user_id,
1079 } => {987 } => {
@@ -1104,14 +1012,14 @@ async fn dispatch(
1104 let broadcast = invitations_updated(&user_id, &conn).await?;1012 let broadcast = invitations_updated(&user_id, &conn).await?;
1105 (Response::Done, vec![broadcast])1013 (Response::Done, vec![broadcast])
1106 }1014 }
1107- Request::Invitations => {1015+ LegacyRequest::Invitations => {
1108 let me = authenticated(client, &conn).await?;1016 let me = authenticated(client, &conn).await?;
1109 (1017 (
1110 Response::Invitations(invitation::of(&me.id, &conn).await?),1018 Response::Invitations(invitation::of(&me.id, &conn).await?),
1111 Vec::new(),1019 Vec::new(),
1112 )1020 )
1113 }1021 }
1114- Request::AcceptInvitation { community_id } => {1022+ LegacyRequest::AcceptInvitation { community_id } => {
1115 let me = authenticated(client, &conn).await?;1023 let me = authenticated(client, &conn).await?;
1116 let tx = conn.transaction().await?;1024 let tx = conn.transaction().await?;
1117 invitation::take(&community_id, &me.id, &tx).await?;1025 invitation::take(&community_id, &me.id, &tx).await?;
@@ -1132,7 +1040,7 @@ async fn dispatch(
1132 broadcasts.push(invitations_updated(&me.id, &conn).await?);1040 broadcasts.push(invitations_updated(&me.id, &conn).await?);
1133 (Response::Community(community), broadcasts)1041 (Response::Community(community), broadcasts)
1134 }1042 }
1135- Request::DeclineInvitation { community_id } => {1043+ LegacyRequest::DeclineInvitation { community_id } => {
1136 let me = authenticated(client, &conn).await?;1044 let me = authenticated(client, &conn).await?;
1137 invitation::take(&community_id, &me.id, &conn).await?;1045 invitation::take(&community_id, &me.id, &conn).await?;
1138 (1046 (
@@ -1140,7 +1048,7 @@ async fn dispatch(
1140 vec![invitations_updated(&me.id, &conn).await?],1048 vec![invitations_updated(&me.id, &conn).await?],
1141 )1049 )
1142 }1050 }
1143- Request::Logs { community_id } => {1051+ LegacyRequest::Logs { community_id } => {
1144 let me = authenticated(client, &conn).await?;1052 let me = authenticated(client, &conn).await?;
1145 allowed(&me, &community_id, &conn, permission::can_read_logs).await?;1053 allowed(&me, &community_id, &conn, permission::can_read_logs).await?;
1146 (1054 (
@@ -1148,7 +1056,7 @@ async fn dispatch(
1148 Vec::new(),1056 Vec::new(),
1149 )1057 )
1150 }1058 }
1151- Request::AllCommunities => {1059+ LegacyRequest::AllCommunities => {
1152 builder(client, &conn).await?;1060 builder(client, &conn).await?;
1153 let mut summaries = Vec::new();1061 let mut summaries = Vec::new();
1154 for community in community::groups(&conn).await? {1062 for community in community::groups(&conn).await? {
@@ -1165,7 +1073,7 @@ async fn dispatch(
1165 }1073 }
1166 (Response::AllCommunities(summaries), Vec::new())1074 (Response::AllCommunities(summaries), Vec::new())
1167 }1075 }
1168- Request::TransferOwnership {1076+ LegacyRequest::TransferOwnership {
1169 community_id,1077 community_id,
1170 user_id,1078 user_id,
1171 } => {1079 } => {
@@ -1231,7 +1139,7 @@ async fn dispatch(
1231 }1139 }
1232 (Response::Done, broadcasts)1140 (Response::Done, broadcasts)
1233 }1141 }
1234- Request::TimeoutUser { user_id, minutes } => {1142+ LegacyRequest::TimeoutUser { user_id, minutes } => {
1235 let me = authenticated(client, &conn).await?;1143 let me = authenticated(client, &conn).await?;
1236 managed(&me, &user_id, &conn).await?;1144 managed(&me, &user_id, &conn).await?;
1237 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);1145 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);
@@ -1249,7 +1157,7 @@ async fn dispatch(
1249 .await?;1157 .await?;
1250 (Response::Done, Vec::new())1158 (Response::Done, Vec::new())
1251 }1159 }
1252- Request::BanUser {1160+ LegacyRequest::BanUser {
1253 user_id,1161 user_id,
1254 reason,1162 reason,
1255 scope,1163 scope,
@@ -1286,40 +1194,40 @@ async fn dispatch(
1286 hub.kick_user(&user_id, Close::Banned);1194 hub.kick_user(&user_id, Close::Banned);
1287 (Response::Done, Vec::new())1195 (Response::Done, Vec::new())
1288 }1196 }
1289- Request::ServerBans => {1197+ LegacyRequest::ServerBans => {
1290 builder(client, &conn).await?;1198 builder(client, &conn).await?;
1291 (1199 (
1292 Response::ServerBans(server_ban::list(&conn).await?),1200 Response::ServerBans(server_ban::list(&conn).await?),
1293 Vec::new(),1201 Vec::new(),
1294 )1202 )
1295 }1203 }
1296- Request::RemoveServerBan { id } => {1204+ LegacyRequest::RemoveServerBan { id } => {
1297 let me = builder(client, &conn).await?;1205 let me = builder(client, &conn).await?;
1298 server_ban::remove(&id, &conn).await?;1206 server_ban::remove(&id, &conn).await?;
1299 admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?;1207 admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?;
1300 (Response::Done, Vec::new())1208 (Response::Done, Vec::new())
1301 }1209 }
1302- Request::CreateInviteCode { uses, hours } => {1210+ LegacyRequest::CreateInviteCode { uses, hours } => {
1303 let me = authenticated(client, &conn).await?;1211 let me = authenticated(client, &conn).await?;
1304 ensure(permission::is_builder(me.role) && uses > 0)?;1212 ensure(permission::is_builder(me.role) && uses > 0)?;
1305 let code = invite::create(uses, hours, &me, &conn).await?;1213 let code = invite::create(uses, hours, &me, &conn).await?;
1306 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?;1214 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?;
1307 (Response::InviteCode(code), Vec::new())1215 (Response::InviteCode(code), Vec::new())
1308 }1216 }
1309- Request::InviteCodes => {1217+ LegacyRequest::InviteCodes => {
1310 builder(client, &conn).await?;1218 builder(client, &conn).await?;
1311 (1219 (
1312 Response::InviteCodes(invite::list(&conn).await?),1220 Response::InviteCodes(invite::list(&conn).await?),
1313 Vec::new(),1221 Vec::new(),
1314 )1222 )
1315 }1223 }
1316- Request::DeleteInviteCode { code } => {1224+ LegacyRequest::DeleteInviteCode { code } => {
1317 let me = builder(client, &conn).await?;1225 let me = builder(client, &conn).await?;
1318 invite::delete(&code, &conn).await?;1226 invite::delete(&code, &conn).await?;
1319 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?;1227 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?;
1320 (Response::Done, Vec::new())1228 (Response::Done, Vec::new())
1321 }1229 }
1322- Request::ReportMessage { message_id, reason } => {1230+ LegacyRequest::ReportMessage { message_id, reason } => {
1323 let me = authenticated(client, &conn).await?;1231 let me = authenticated(client, &conn).await?;
1324 let message = message::read(&message_id, &conn).await?;1232 let message = message::read(&message_id, &conn).await?;
1325 let actor = actor_rank(&me, &message.community_id, &conn).await?;1233 let actor = actor_rank(&me, &message.community_id, &conn).await?;
@@ -1341,7 +1249,7 @@ async fn dispatch(
1341 .await?;1249 .await?;
1342 (Response::Done, vec![report_created()])1250 (Response::Done, vec![report_created()])
1343 }1251 }
1344- Request::ReportUser { user_id, reason } => {1252+ LegacyRequest::ReportUser { user_id, reason } => {
1345 let me = authenticated(client, &conn).await?;1253 let me = authenticated(client, &conn).await?;
1346 user::read(&user_id, &conn).await?;1254 user::read(&user_id, &conn).await?;
1347 ensure(me.id != user_id)?;1255 ensure(me.id != user_id)?;
@@ -1353,14 +1261,14 @@ async fn dispatch(
1353 report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?;1261 report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?;
1354 (Response::Done, vec![report_created()])1262 (Response::Done, vec![report_created()])
1355 }1263 }
1356- Request::Reports { status } => {1264+ LegacyRequest::Reports { status } => {
1357 builder(client, &conn).await?;1265 builder(client, &conn).await?;
1358 (1266 (
1359 Response::Reports(report::list(status, &conn).await?),1267 Response::Reports(report::list(status, &conn).await?),
1360 Vec::new(),1268 Vec::new(),
1361 )1269 )
1362 }1270 }
1363- Request::HandleReport { report_id, status } => {1271+ LegacyRequest::HandleReport { report_id, status } => {
1364 let me = authenticated(client, &conn).await?;1272 let me = authenticated(client, &conn).await?;
1365 ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?;1273 ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?;
1366 let target = report::handle(&report_id, status, &me.id, &conn).await?;1274 let target = report::handle(&report_id, status, &me.id, &conn).await?;
@@ -1374,7 +1282,7 @@ async fn dispatch(
1374 .await?;1282 .await?;
1375 (Response::Done, Vec::new())1283 (Response::Done, Vec::new())
1376 }1284 }
1377- Request::SearchMessages {1285+ LegacyRequest::SearchMessages {
1378 text,1286 text,
1379 user_id,1287 user_id,
1380 community_id,1288 community_id,
@@ -1393,14 +1301,14 @@ async fn dispatch(
1393 .await?;1301 .await?;
1394 (Response::MessageHits(hits), Vec::new())1302 (Response::MessageHits(hits), Vec::new())
1395 }1303 }
1396- Request::SearchCommunity { community_id, text } => {1304+ LegacyRequest::SearchCommunity { community_id, text } => {
1397 let me = authenticated(client, &conn).await?;1305 let me = authenticated(client, &conn).await?;
1398 allowed(&me, &community_id, &conn, permission::can_read).await?;1306 allowed(&me, &community_id, &conn, permission::can_read).await?;
1399 let hits =1307 let hits =
1400 message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;1308 message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;
1401 (Response::MessageHits(hits), Vec::new())1309 (Response::MessageHits(hits), Vec::new())
1402 }1310 }
1403- Request::PurgeUser { user_id } => {1311+ LegacyRequest::PurgeUser { user_id } => {
1404 let me = authenticated(client, &conn).await?;1312 let me = authenticated(client, &conn).await?;
1405 managed(&me, &user_id, &conn).await?;1313 managed(&me, &user_id, &conn).await?;
1406 let tx = conn.transaction().await?;1314 let tx = conn.transaction().await?;
@@ -1439,7 +1347,7 @@ async fn dispatch(
1439 attachment::remove_files(&upload_ids, directory);1347 attachment::remove_files(&upload_ids, directory);
1440 (Response::Done, broadcasts)1348 (Response::Done, broadcasts)
1441 }1349 }
1442- Request::AllAttachments {1350+ LegacyRequest::AllAttachments {
1443 user_id,1351 user_id,
1444 community_id,1352 community_id,
1445 } => {1353 } => {
@@ -1451,7 +1359,7 @@ async fn dispatch(
1451 Vec::new(),1359 Vec::new(),
1452 )1360 )
1453 }1361 }
1454- Request::DeleteAttachment { attachment_id } => {1362+ LegacyRequest::DeleteAttachment { attachment_id } => {
1455 let me = builder(client, &conn).await?;1363 let me = builder(client, &conn).await?;
1456 let stored = attachment::read(&attachment_id, &conn).await?;1364 let stored = attachment::read(&attachment_id, &conn).await?;
1457 let community = community::label(&stored.community_id, &conn).await?;1365 let community = community::label(&stored.community_id, &conn).await?;
@@ -1474,12 +1382,12 @@ async fn dispatch(
1474 attachment::remove_files(&[attachment_id], directory);1382 attachment::remove_files(&[attachment_id], directory);
1475 (Response::Done, broadcasts)1383 (Response::Done, broadcasts)
1476 }1384 }
1477- Request::StorageUsage => {1385+ LegacyRequest::StorageUsage => {
1478 builder(client, &conn).await?;1386 builder(client, &conn).await?;
1479 let (users, communities) = attachment::usage(&conn).await?;1387 let (users, communities) = attachment::usage(&conn).await?;
1480 (Response::StorageUsage { users, communities }, Vec::new())1388 (Response::StorageUsage { users, communities }, Vec::new())
1481 }1389 }
1482- Request::CreateBackup => {1390+ LegacyRequest::CreateBackup => {
1483 let me = builder(client, &conn).await?;1391 let me = builder(client, &conn).await?;
1484 let backup = backup::create(&conn, backups).await?;1392 let backup = backup::create(&conn, backups).await?;
1485 let action = AdminAction::BackupCreated {1393 let action = AdminAction::BackupCreated {
@@ -1488,25 +1396,25 @@ async fn dispatch(
1488 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;1396 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1489 (Response::Backup(backup), Vec::new())1397 (Response::Backup(backup), Vec::new())
1490 }1398 }
1491- Request::Backups => {1399+ LegacyRequest::Backups => {
1492 builder(client, &conn).await?;1400 builder(client, &conn).await?;
1493 (Response::Backups(backup::list(backups)?), Vec::new())1401 (Response::Backups(backup::list(backups)?), Vec::new())
1494 }1402 }
1495- Request::DeleteBackup { name } => {1403+ LegacyRequest::DeleteBackup { name } => {
1496 let me = builder(client, &conn).await?;1404 let me = builder(client, &conn).await?;
1497 backup::delete(&name, backups)?;1405 backup::delete(&name, backups)?;
1498 let action = AdminAction::BackupDeleted { name };1406 let action = AdminAction::BackupDeleted { name };
1499 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;1407 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1500 (Response::Done, Vec::new())1408 (Response::Done, Vec::new())
1501 }1409 }
1502- Request::VoiceRooms => {1410+ LegacyRequest::VoiceRooms => {
1503 builder(client, &conn).await?;1411 builder(client, &conn).await?;
1504 (1412 (
1505 Response::VoiceRooms(voice_rooms(rooms, &conn).await?),1413 Response::VoiceRooms(voice_rooms(rooms, &conn).await?),
1506 Vec::new(),1414 Vec::new(),
1507 )1415 )
1508 }1416 }
1509- Request::KickFromVoice { user_id } => {1417+ LegacyRequest::KickFromVoice { user_id } => {
1510 let me = authenticated(client, &conn).await?;1418 let me = authenticated(client, &conn).await?;
1511 managed(&me, &user_id, &conn).await?;1419 managed(&me, &user_id, &conn).await?;
1512 let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?;1420 let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?;
@@ -1522,7 +1430,7 @@ async fn dispatch(
1522 }1430 }
1523 (Response::Done, broadcasts)1431 (Response::Done, broadcasts)
1524 }1432 }
1525- Request::ServerMute { user_id, muted } => {1433+ LegacyRequest::ServerMute { user_id, muted } => {
1526 let me = authenticated(client, &conn).await?;1434 let me = authenticated(client, &conn).await?;
1527 managed(&me, &user_id, &conn).await?;1435 managed(&me, &user_id, &conn).await?;
1528 user::set_voice_muted(&user_id, muted, &conn).await?;1436 user::set_voice_muted(&user_id, muted, &conn).await?;
@@ -1538,7 +1446,7 @@ async fn dispatch(
1538 let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?;1446 let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?;
1539 (Response::Done, vec![broadcast])1447 (Response::Done, vec![broadcast])
1540 }1448 }
1541- Request::SetCommunityVoice {1449+ LegacyRequest::SetCommunityVoice {
1542 community_id,1450 community_id,
1543 enabled,1451 enabled,
1544 } => {1452 } => {
@@ -1567,7 +1475,7 @@ async fn dispatch(
1567 1475
1568 (Response::Community(updated), broadcasts)1476 (Response::Community(updated), broadcasts)
1569 }1477 }
1570- Request::SetGhost { enabled } => {1478+ LegacyRequest::SetGhost { enabled } => {
1571 let me = builder(client, &conn).await?;1479 let me = builder(client, &conn).await?;
1572 user::set_ghost(&me.id, enabled, &conn).await?;1480 user::set_ghost(&me.id, enabled, &conn).await?;
1573 let action = if enabled {1481 let action = if enabled {
@@ -1738,14 +1646,14 @@ async fn remove_member(
1738 Ok((Response::Done, broadcasts))1646 Ok((Response::Done, broadcasts))
1739 }1647 }
1740 1648
1741-fn user_updated(user: &User) -> Vec<Broadcast> {1649+pub(crate) fn user_updated(user: &User) -> Vec<Broadcast> {
1742 vec![Broadcast::new(1650 vec![Broadcast::new(
1743 To::Related(user.id.clone()),1651 To::Related(user.id.clone()),
1744 Event::UserUpdated(user.clone()),1652 Event::UserUpdated(user.clone()),
1745 )]1653 )]
1746 }1654 }
1747 1655
1748-async fn effective_presence(1656+pub(crate) async fn effective_presence(
1749 hub: &Hub,1657 hub: &Hub,
1750 user_id: &str,1658 user_id: &str,
1751 conn: &Connection,1659 conn: &Connection,
@@ -1949,13 +1857,13 @@ fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {
1949 broadcasts1857 broadcasts
1950 }1858 }
1951 1859
1952-async fn authenticated(client: &Client, conn: &Connection) -> Result<User, ServerError> {1860+pub(crate) async fn authenticated(client: &Client, conn: &Connection) -> Result<User, ServerError> {
1953 let user_id = client.user_id().ok_or(CommonError::Unauthenticated)?;1861 let user_id = client.user_id().ok_or(CommonError::Unauthenticated)?;
1954 1862
1955 user::read(user_id, conn).await1863 user::read(user_id, conn).await
1956 }1864 }
1957 1865
1958-async fn builder(client: &Client, conn: &Connection) -> Result<User, ServerError> {1866+pub(crate) async fn builder(client: &Client, conn: &Connection) -> Result<User, ServerError> {
1959 let user = authenticated(client, conn).await?;1867 let user = authenticated(client, conn).await?;
1960 ensure(permission::is_builder(user.role))?;1868 ensure(permission::is_builder(user.role))?;
1961 1869
@@ -1972,7 +1880,11 @@ pub async fn actor_rank(
1972 Ok(permission::effective_rank(me.role, rank))1880 Ok(permission::effective_rank(me.role, rank))
1973 }1881 }
1974 1882
1975-async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, ServerError> {1883+pub(crate) async fn managed(
1884+ me: &User,
1885+ user_id: &str,
1886+ conn: &Connection,
1887+) -> Result<User, ServerError> {
1976 let target = user::read(user_id, conn).await?;1888 let target = user::read(user_id, conn).await?;
1977 ensure(permission::can_manage_user(1889 ensure(permission::can_manage_user(
1978 me.role,1890 me.role,
@@ -2071,7 +1983,7 @@ async fn record_ghost_voice(
2071 mod tests {1983 mod tests {
2072 use std::sync::Arc;1984 use std::sync::Arc;
2073 1985
2074- use common::{error::Error as CommonError, request::Request, response::Response};1986+ use common::{error::Error as CommonError, request::LegacyRequest, response::Response};
2075 1987
2076 use crate::{1988 use crate::{
2077 database::{self, DB},1989 database::{self, DB},
@@ -2082,14 +1994,19 @@ mod tests {
2082 test,1994 test,
2083 };1995 };
2084 1996
2085- async fn send(request: Request, client: &Client, db: &DB, services: &Services) -> Response {1997+ async fn send(
1998+ request: LegacyRequest,
1999+ client: &Client,
2000+ db: &DB,
2001+ services: &Services,
2002+ ) -> Response {
2086 send_result(request, client, db, services)2003 send_result(request, client, db, services)
2087 .await2004 .await
2088 .expect("request failed")2005 .expect("request failed")
2089 }2006 }
2090 2007
2091 async fn send_result(2008 async fn send_result(
2092- request: Request,2009+ request: LegacyRequest,
2093 client: &Client,2010 client: &Client,
2094 db: &DB,2011 db: &DB,
2095 services: &Services,2012 services: &Services,
@@ -2109,7 +2026,7 @@ mod tests {
2109 async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> {2026 async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> {
2110 let guest = Client::detached(None);2027 let guest = Client::detached(None);
2111 let Response::Session { user, token } = send(2028 let Response::Session { user, token } = send(
2112- Request::Register {2029+ LegacyRequest::Register {
2113 username: username.to_string(),2030 username: username.to_string(),
2114 password: "password".to_string(),2031 password: "password".to_string(),
2115 invite: None,2032 invite: None,
@@ -2138,7 +2055,7 @@ mod tests {
2138 services: &Services,2055 services: &Services,
2139 ) {2056 ) {
2140 let Response::User(member_user) = send(2057 let Response::User(member_user) = send(
2141- Request::FindUser {2058+ LegacyRequest::FindUser {
2142 username: username.to_string(),2059 username: username.to_string(),
2143 },2060 },
2144 owner,2061 owner,
@@ -2150,7 +2067,7 @@ mod tests {
2150 panic!("user not found");2067 panic!("user not found");
2151 };2068 };
2152 send(2069 send(
2153- Request::Invite {2070+ LegacyRequest::Invite {
2154 community_id: community_id.to_string(),2071 community_id: community_id.to_string(),
2155 user_id: member_user.id,2072 user_id: member_user.id,
2156 },2073 },
@@ -2160,7 +2077,7 @@ mod tests {
2160 )2077 )
2161 .await;2078 .await;
2162 send(2079 send(
2163- Request::AcceptInvitation {2080+ LegacyRequest::AcceptInvitation {
2164 community_id: community_id.to_string(),2081 community_id: community_id.to_string(),
2165 },2082 },
2166 member,2083 member,
@@ -2177,7 +2094,7 @@ mod tests {
2177 let owner = signed_in("Owner", &db, &services).await;2094 let owner = signed_in("Owner", &db, &services).await;
2178 let member = signed_in("Member", &db, &services).await;2095 let member = signed_in("Member", &db, &services).await;
2179 let Response::Community(community) = send(2096 let Response::Community(community) = send(
2180- Request::CreateCommunity {2097+ LegacyRequest::CreateCommunity {
2181 name: "The Community".to_string(),2098 name: "The Community".to_string(),
2182 },2099 },
2183 &owner,2100 &owner,
@@ -2191,7 +2108,7 @@ mod tests {
2191 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;2108 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2192 2109
2193 let response = send_result(2110 let response = send_result(
2194- Request::UpdateCommunity {2111+ LegacyRequest::UpdateCommunity {
2195 community_id: community.id,2112 community_id: community.id,
2196 name: "Renamed".to_string(),2113 name: "Renamed".to_string(),
2197 },2114 },
@@ -2211,7 +2128,7 @@ mod tests {
2211 let first = signed_in("First", &db, &services).await;2128 let first = signed_in("First", &db, &services).await;
2212 let second = signed_in("Second", &db, &services).await;2129 let second = signed_in("Second", &db, &services).await;
2213 let Response::User(first_user) = send(2130 let Response::User(first_user) = send(
2214- Request::FindUser {2131+ LegacyRequest::FindUser {
2215 username: "First".to_string(),2132 username: "First".to_string(),
2216 },2133 },
2217 &second,2134 &second,
@@ -2223,7 +2140,7 @@ mod tests {
2223 panic!("user not found");2140 panic!("user not found");
2224 };2141 };
2225 let Response::User(second_user) = send(2142 let Response::User(second_user) = send(
2226- Request::FindUser {2143+ LegacyRequest::FindUser {
2227 username: "Second".to_string(),2144 username: "Second".to_string(),
2228 },2145 },
2229 &first,2146 &first,
@@ -2235,7 +2152,7 @@ mod tests {
2235 panic!("user not found");2152 panic!("user not found");
2236 };2153 };
2237 send(2154 send(
2238- Request::AddFriend {2155+ LegacyRequest::AddFriend {
2239 user_id: second_user.id.clone(),2156 user_id: second_user.id.clone(),
2240 },2157 },
2241 &first,2158 &first,
@@ -2244,7 +2161,7 @@ mod tests {
2244 )2161 )
2245 .await;2162 .await;
2246 send(2163 send(
2247- Request::AcceptFriend {2164+ LegacyRequest::AcceptFriend {
2248 user_id: first_user.id.clone(),2165 user_id: first_user.id.clone(),
2249 },2166 },
2250 &second,2167 &second,
@@ -2253,12 +2170,13 @@ mod tests {
2253 )2170 )
2254 .await;2171 .await;
2255 2172
2256- let Response::Friends(first_friends) = send(Request::Friends, &first, &db, &services).await2173+ let Response::Friends(first_friends) =
2174+ send(LegacyRequest::Friends, &first, &db, &services).await
2257 else {2175 else {
2258 panic!("friends not read");2176 panic!("friends not read");
2259 };2177 };
2260 let Response::Friends(second_friends) =2178 let Response::Friends(second_friends) =
2261- send(Request::Friends, &second, &db, &services).await2179+ send(LegacyRequest::Friends, &second, &db, &services).await
2262 else {2180 else {
2263 panic!("friends not read");2181 panic!("friends not read");
2264 };2182 };
@@ -2274,7 +2192,7 @@ mod tests {
2274 let owner = signed_in("Owner", &db, &services).await;2192 let owner = signed_in("Owner", &db, &services).await;
2275 let member = signed_in("Member", &db, &services).await;2193 let member = signed_in("Member", &db, &services).await;
2276 let Response::Community(community) = send(2194 let Response::Community(community) = send(
2277- Request::CreateCommunity {2195+ LegacyRequest::CreateCommunity {
2278 name: "The Community".to_string(),2196 name: "The Community".to_string(),
2279 },2197 },
2280 &owner,2198 &owner,
@@ -2289,7 +2207,7 @@ mod tests {
2289 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;2207 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2290 2208
2291 let Response::Communities(communities) =2209 let Response::Communities(communities) =
2292- send(Request::Communities, &member, &db, &services).await2210+ send(LegacyRequest::Communities, &member, &db, &services).await
2293 else {2211 else {
2294 panic!("communities not read");2212 panic!("communities not read");
2295 };2213 };
@@ -2302,7 +2220,7 @@ mod tests {
2302 let services = Services::default();2220 let services = Services::default();
2303 let owner = signed_in("Owner", &db, &services).await;2221 let owner = signed_in("Owner", &db, &services).await;
2304 let Response::Community(community) = send(2222 let Response::Community(community) = send(
2305- Request::CreateCommunity {2223+ LegacyRequest::CreateCommunity {
2306 name: "The Community".to_string(),2224 name: "The Community".to_string(),
2307 },2225 },
2308 &owner,2226 &owner,
@@ -2314,7 +2232,7 @@ mod tests {
2314 panic!("community not created");2232 panic!("community not created");
2315 };2233 };
2316 send(2234 send(
2317- Request::CreateMessage {2235+ LegacyRequest::CreateMessage {
2318 community_id: community.id.clone(),2236 community_id: community.id.clone(),
2319 body: "Tahinli".to_string(),2237 body: "Tahinli".to_string(),
2320 attachments: Vec::new(),2238 attachments: Vec::new(),
@@ -2327,7 +2245,7 @@ mod tests {
2327 .await;2245 .await;
2328 2246
2329 send(2247 send(
2330- Request::DeleteCommunity {2248+ LegacyRequest::DeleteCommunity {
2331 community_id: community.id.clone(),2249 community_id: community.id.clone(),
2332 },2250 },
2333 &owner,2251 &owner,
crates/server/src/rooms.rsmodified+38 -43
@@ -4,9 +4,8 @@ use std::{
4 time::Instant,4 time::Instant,
5 };5 };
6 6
7-use bytes::Bytes;
8 use common::{7 use common::{
9- datagram::{Datagram, Fragment, encode_relay},8+ datagram::{self, Packet, RELAY_PREFIX, relayed},
10 error::Error,9 error::Error,
11 event::{Event, Media},10 event::{Event, Media},
12 model::CallLog,11 model::CallLog,
@@ -177,6 +176,7 @@ fn remove_viewer(
177 176
178 struct Seat {177 struct Seat {
179 user_id: String,178 user_id: String,
179+ uuid: [u8; RELAY_PREFIX],
180 connection: Connection,180 connection: Connection,
181 muted: bool,181 muted: bool,
182 ghost: bool,182 ghost: bool,
@@ -324,6 +324,9 @@ impl Rooms {
324 ) -> Result<Joined, Error> {324 ) -> Result<Joined, Error> {
325 let connection = client.conn.clone().ok_or(Error::Server)?;325 let connection = client.conn.clone().ok_or(Error::Server)?;
326 let user_id = client.user_id().ok_or(Error::Unauthenticated)?;326 let user_id = client.user_id().ok_or(Error::Unauthenticated)?;
327+ let uuid = *uuid::Uuid::parse_str(user_id)
328+ .map_err(|_| Error::Server)?
329+ .as_bytes();
327 let mut inner = self.0.lock().unwrap();330 let mut inner = self.0.lock().unwrap();
328 if client.closed.load(Ordering::Acquire) {331 if client.closed.load(Ordering::Acquire) {
329 return Err(Error::Server);332 return Err(Error::Server);
@@ -355,6 +358,7 @@ impl Rooms {
355 client.id,358 client.id,
356 Seat {359 Seat {
357 user_id: user_id.to_string(),360 user_id: user_id.to_string(),
361+ uuid,
358 connection,362 connection,
359 muted,363 muted,
360 ghost,364 ghost,
@@ -657,46 +661,35 @@ impl Rooms {
657 if from.me.is_none() {661 if from.me.is_none() {
658 return Vec::new();662 return Vec::new();
659 }663 }
660- let Some(datagram) = Datagram::decode(packet) else {
661- return Vec::new();
662- };
663 let mut inner = self.0.lock().unwrap();664 let mut inner = self.0.lock().unwrap();
664 let Some((_, room)) = inner.seat_mut(from.id) else {665 let Some((_, room)) = inner.seat_mut(from.id) else {
665 return Vec::new();666 return Vec::new();
666 };667 };
667- match datagram {668+ if let Some((kind, layer, keyframe)) = Packet::peek_video(packet) {
668- Datagram::Voice { sequence, .. } => relay_voice(room, from.id, sequence, packet),669+ return relay_video(room, from.id, kind, layer, keyframe, packet);
669- Datagram::ShareAudio { .. } => relay_share_audio(room, from.id, packet),670+ }
670- Datagram::Video(fragment) => relay_video(room, from.id, &fragment, packet),671+ match Packet::decode(packet) {
672+ Some(Packet::Voice { seq, .. }) => relay_voice(room, from.id, seq, packet),
673+ Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet),
674+ _ => Vec::new(),
671 }675 }
672 }676 }
673 }677 }
674 678
675-fn relay_voice(room: &Room, id: ConnId, sequence: u32, packet: &[u8]) -> Vec<Broadcast> {679+fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) -> Vec<Broadcast> {
676 let Some(sender) = room.seats.get(&id) else {680 let Some(sender) = room.seats.get(&id) else {
677 return Vec::new();681 return Vec::new();
678 };682 };
679 if sender.muted {683 if sender.muted {
680 return Vec::new();684 return Vec::new();
681 }685 }
682- let (Some(relay), Some(echo)) = (686+ let mut echo = Vec::new();
683- encode_relay(&sender.user_id, packet),687+ Packet::Voice { seq, opus: &[] }.encode(&mut echo);
684- encode_relay(688+ datagram::send(&sender.connection, relayed(&sender.uuid, &echo));
685- &sender.user_id,689+ let bytes = relayed(&sender.uuid, packet);
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 {690 for (other_id, seat) in &room.seats {
698 if *other_id != id {691 if *other_id != id {
699- let _ = seat.connection.send_datagram(bytes.clone());692+ datagram::send(&seat.connection, bytes.clone());
700 }693 }
701 }694 }
702 695
@@ -710,39 +703,41 @@ fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) -> Vec<Broadcast> {
710 let Some(sharing) = seat.shares.get(&Kind::Screen) else {703 let Some(sharing) = seat.shares.get(&Kind::Screen) else {
711 return Vec::new();704 return Vec::new();
712 };705 };
713- let Some(relay) = encode_relay(&seat.user_id, packet) else {706+ let bytes = relayed(&seat.uuid, packet);
714- return Vec::new();
715- };
716- let bytes = Bytes::from(relay);
717 for viewer in &sharing.viewers {707 for viewer in &sharing.viewers {
718- let _ = viewer.connection.send_datagram(bytes.clone());708+ datagram::send(&viewer.connection, bytes.clone());
719 }709 }
720 710
721 Vec::new()711 Vec::new()
722 }712 }
723 713
724-fn relay_video(room: &mut Room, id: ConnId, fragment: &Fragment, packet: &[u8]) -> Vec<Broadcast> {714+fn relay_video(
715+ room: &mut Room,
716+ id: ConnId,
717+ kind: Kind,
718+ layer: Layer,
719+ keyframe: bool,
720+ packet: &[u8],
721+) -> Vec<Broadcast> {
725 let Some(seat) = room.seats.get_mut(&id) else {722 let Some(seat) = room.seats.get_mut(&id) else {
726 return Vec::new();723 return Vec::new();
727 };724 };
728- let Some(sharing) = seat.shares.get_mut(&fragment.kind) else {725+ let Some(sharing) = seat.shares.get_mut(&kind) else {
729 return Vec::new();726 return Vec::new();
730 };727 };
731- let Some(relay) = encode_relay(&seat.user_id, packet) else {728+ let bytes = relayed(&seat.uuid, packet);
732- return Vec::new();729+ let before = keyframe.then(|| sharing.layers());
733- };
734- let bytes = Bytes::from(relay);
735- let before = sharing.layers();
736 for viewer in &mut sharing.viewers {730 for viewer in &mut sharing.viewers {
737- if fragment.keyframe {731+ if keyframe {
738- viewer.forward = viewer.forward.on_keyframe(fragment.layer);732+ viewer.forward = viewer.forward.on_keyframe(layer);
739 }733 }
740- if viewer.forward.live() == Some(fragment.layer) {734+ if viewer.forward.live() == Some(layer) {
741- let _ = viewer.connection.send_datagram(bytes.clone());735+ datagram::send(&viewer.connection, bytes.clone());
742 }736 }
743 }737 }
744 738
745- layers_changed(id, fragment.kind, sharing, before)739+ before
740+ .and_then(|before| layers_changed(id, kind, sharing, before))
746 .into_iter()741 .into_iter()
747 .collect()742 .collect()
748 }743 }