forge
Explore
Log in

Don't you dare go Hollow

Validation lives on the call and the client calls directly

Browse files at this commit

7bb542d051d0b121f3dea612cfb3e86f800120d6Ahmet Kaan GümüşParent: c0a7e2d
  • refactor
    • validation lives on the call and the client calls directly
Show full message
♻️ refactor: validation lives on the call and the client calls directly

Each call validates its own fields in Call::validate, run once by the
client before sending and once by the server before handling. GUI code
sends call structs straight through net.call, so the hundred pass through
wrappers in net/mod.rs are gone. Dead code and duplicated logic found by
an audit of the new network modules are removed.

46 changed files +835 -1546

crates/client/src/gui.rsmodified+13 -3
@@ -7,6 +7,7 @@ use std::{
7 };7 };
8 8
9 use common::{9 use common::{
10+ call::{GetAvatar, GetSettings, MarkRead},
10 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},11 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
11 error::Error,12 error::Error,
12 event::Event,13 event::Event,
@@ -899,7 +900,11 @@ impl Yumush {
899 let avatar_id = avatar_id.to_string();900 let avatar_id = avatar_id.to_string();
900 901
901 cx.spawn(async move |this, cx| {902 cx.spawn(async move |this, cx| {
902- let result = network.read_avatar(&avatar_id).await;903+ let result = network
904+ .call(GetAvatar {
905+ avatar_id: avatar_id.clone(),
906+ })
907+ .await;
903 let _ = this.update(cx, |yumush, cx| {908 let _ = this.update(cx, |yumush, cx| {
904 yumush.chat.avatar_requests.remove(&avatar_id);909 yumush.chat.avatar_requests.remove(&avatar_id);
905 if let Ok(bytes) = result {910 if let Ok(bytes) = result {
@@ -971,7 +976,12 @@ impl Yumush {
971 let message_id = message_id.to_string();976 let message_id = message_id.to_string();
972 977
973 cx.spawn(async move |_, _| {978 cx.spawn(async move |_, _| {
974- let _ = network.mark_read(&community_id, &message_id).await;979+ let _ = network
980+ .call(MarkRead {
981+ community_id,
982+ message_id,
983+ })
984+ .await;
975 })985 })
976 .detach();986 .detach();
977 }987 }
@@ -1103,7 +1113,7 @@ impl Yumush {
1103 let network = self.network.clone();1113 let network = self.network.clone();
1104 1114
1105 cx.spawn_in(window, async move |this, cx| {1115 cx.spawn_in(window, async move |this, cx| {
1106- let Ok(settings) = network.server_settings().await else {1116+ let Ok(settings) = network.call(GetSettings).await else {
1107 return;1117 return;
1108 };1118 };
1109 let _ = this.update(cx, |yumush, cx| {1119 let _ = this.update(cx, |yumush, cx| {
crates/client/src/gui/builder.rsmodified+3 -2
@@ -14,6 +14,7 @@ mod voice;
14 use std::{fmt::Display, future::Future, path::PathBuf};14 use std::{fmt::Display, future::Future, path::PathBuf};
15 15
16 use common::{16 use common::{
17+ call::{ListUsers, SetGhost},
17 model::{CommunityKind, Member, Role},18 model::{CommunityKind, Member, Role},
18 permission,19 permission,
19 };20 };
@@ -381,7 +382,7 @@ impl Yumush {
381 self.fetch_builder(382 self.fetch_builder(
382 window,383 window,
383 cx,384 cx,
384- |network| async move { network.users().await },385+ |network| async move { network.call(ListUsers).await },
385 |yumush, accounts, cx| {386 |yumush, accounts, cx| {
386 for account in &accounts {387 for account in &accounts {
387 yumush.request_user_avatar(&account.user, cx);388 yumush.request_user_avatar(&account.user, cx);
@@ -466,7 +467,7 @@ impl Yumush {
466 let network = self.network.clone();467 let network = self.network.clone();
467 468
468 cx.spawn_in(window, async move |this, cx| {469 cx.spawn_in(window, async move |this, cx| {
469- match network.set_ghost(enabled).await {470+ match network.call(SetGhost { enabled }).await {
470 Ok(()) => {471 Ok(()) => {
471 let _ = this.update(cx, |yumush, cx| {472 let _ = this.update(cx, |yumush, cx| {
472 yumush.set_ghost_state(enabled);473 yumush.set_ghost_state(enabled);
crates/client/src/gui/builder/access.rsmodified+9 -6
@@ -1,4 +1,7 @@
1-use common::model::{InviteCode, ServerBan, ServerBanKind};1+use common::{
2+ call::{CreateInviteCode, DeleteInviteCode, ListInviteCodes, ListServerBans, RemoveServerBan},
3+ model::{InviteCode, ServerBan, ServerBanKind},
4+};
2 use gpui_kit::{5 use gpui_kit::{
3 AnyElement, ClipboardItem, Context, Div, Entity, FontWeight, IntoElement, ParentElement,6 AnyElement, ClipboardItem, Context, Div, Entity, FontWeight, IntoElement, ParentElement,
4 Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px,7 Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px,
@@ -155,7 +158,7 @@ impl Yumush {
155 self.fetch_builder(158 self.fetch_builder(
156 window,159 window,
157 cx,160 cx,
158- |network| async move { network.invite_codes().await },161+ |network| async move { network.call(ListInviteCodes).await },
159 |yumush, codes, cx| {162 |yumush, codes, cx| {
160 yumush.chat.builder_invites = codes;163 yumush.chat.builder_invites = codes;
161 cx.notify();164 cx.notify();
@@ -167,7 +170,7 @@ impl Yumush {
167 self.fetch_builder(170 self.fetch_builder(
168 window,171 window,
169 cx,172 cx,
170- |network| async move { network.server_bans().await },173+ |network| async move { network.call(ListServerBans).await },
171 |yumush, bans, cx| {174 |yumush, bans, cx| {
172 yumush.chat.builder_bans = bans;175 yumush.chat.builder_bans = bans;
173 cx.notify();176 cx.notify();
@@ -191,7 +194,7 @@ impl Yumush {
191 let network = self.network.clone();194 let network = self.network.clone();
192 195
193 cx.spawn_in(window, async move |this, cx| {196 cx.spawn_in(window, async move |this, cx| {
194- match network.create_invite_code(uses, hours).await {197+ match network.call(CreateInviteCode { uses, hours }).await {
195 Ok(_) => {198 Ok(_) => {
196 let _ =199 let _ =
197 this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx));200 this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx));
@@ -216,7 +219,7 @@ impl Yumush {
216 let code = code.to_string();219 let code = code.to_string();
217 220
218 cx.spawn_in(window, async move |this, cx| {221 cx.spawn_in(window, async move |this, cx| {
219- match network.delete_invite_code(&code).await {222+ match network.call(DeleteInviteCode { code }).await {
220 Ok(()) => {223 Ok(()) => {
221 let _ =224 let _ =
222 this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx));225 this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx));
@@ -236,7 +239,7 @@ impl Yumush {
236 let id = id.to_string();239 let id = id.to_string();
237 240
238 cx.spawn_in(window, async move |this, cx| {241 cx.spawn_in(window, async move |this, cx| {
239- match network.remove_server_ban(&id).await {242+ match network.call(RemoveServerBan { id }).await {
240 Ok(()) => {243 Ok(()) => {
241 let _ = this244 let _ = this
242 .update_in(cx, |yumush, window, cx| yumush.load_server_bans(window, cx));245 .update_in(cx, |yumush, window, cx| yumush.load_server_bans(window, cx));
crates/client/src/gui/builder/backups.rsmodified+7 -4
@@ -1,4 +1,7 @@
1-use common::model::BackupInfo;1+use common::{
2+ call::{CreateBackup, DeleteBackup, ListBackups},
3+ model::BackupInfo,
4+};
2 use gpui_kit::{5 use gpui_kit::{
3 Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,6 Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,
4 component::Icon, div, prelude::FluentBuilder as _, px,7 component::Icon, div, prelude::FluentBuilder as _, px,
@@ -118,7 +121,7 @@ impl Yumush {
118 self.fetch_builder(121 self.fetch_builder(
119 window,122 window,
120 cx,123 cx,
121- |network| async move { network.backups().await },124+ |network| async move { network.call(ListBackups).await },
122 |yumush, backups, cx| {125 |yumush, backups, cx| {
123 yumush.backups = backups;126 yumush.backups = backups;
124 cx.notify();127 cx.notify();
@@ -130,7 +133,7 @@ impl Yumush {
130 let network = self.network.clone();133 let network = self.network.clone();
131 134
132 cx.spawn_in(window, async move |this, cx| {135 cx.spawn_in(window, async move |this, cx| {
133- match network.create_backup().await {136+ match network.call(CreateBackup).await {
134 Ok(_) => {137 Ok(_) => {
135 let _ =138 let _ =
136 this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));139 this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));
@@ -150,7 +153,7 @@ impl Yumush {
150 let name = name.to_string();153 let name = name.to_string();
151 154
152 cx.spawn_in(window, async move |this, cx| {155 cx.spawn_in(window, async move |this, cx| {
153- match network.delete_backup(&name).await {156+ match network.call(DeleteBackup { name }).await {
154 Ok(()) => {157 Ok(()) => {
155 let _ =158 let _ =
156 this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));159 this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));
crates/client/src/gui/builder/communities.rsmodified+35 -7
@@ -1,4 +1,10 @@
1-use common::model::{Community, CommunitySummary, Member, Rank};1+use common::{
2+ call::{
3+ DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice,
4+ TransferOwnership,
5+ },
6+ model::{Community, CommunitySummary, Member, Rank},
7+};
2 use gpui_kit::{8 use gpui_kit::{
3 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,9 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
4 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,10 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,
@@ -25,7 +31,13 @@ impl Yumush {
25 let community_id = community_id.to_string();31 let community_id = community_id.to_string();
26 32
27 cx.spawn_in(window, async move |this, cx| {33 cx.spawn_in(window, async move |this, cx| {
28- match network.set_community_voice(&community_id, enabled).await {34+ match network
35+ .call(SetCommunityVoice {
36+ community_id,
37+ enabled,
38+ })
39+ .await
40+ {
29 Ok(_) => {41 Ok(_) => {
30 let _ = this.update_in(cx, |yumush, window, cx| {42 let _ = this.update_in(cx, |yumush, window, cx| {
31 yumush.load_builder_communities(window, cx)43 yumush.load_builder_communities(window, cx)
@@ -41,7 +53,7 @@ impl Yumush {
41 self.fetch_builder(53 self.fetch_builder(
42 window,54 window,
43 cx,55 cx,
44- |network| async move { network.all_communities().await },56+ |network| async move { network.call(ListAllCommunities).await },
45 |yumush, summaries, cx| {57 |yumush, summaries, cx| {
46 for summary in &summaries {58 for summary in &summaries {
47 if let Some(avatar_id) = &summary.community.avatar_id {59 if let Some(avatar_id) = &summary.community.avatar_id {
@@ -71,7 +83,12 @@ impl Yumush {
71 let community_id = community_id.to_string();83 let community_id = community_id.to_string();
72 84
73 cx.spawn_in(window, async move |this, cx| {85 cx.spawn_in(window, async move |this, cx| {
74- match network.delete_community(&community_id).await {86+ match network
87+ .call(DeleteCommunity {
88+ community_id: community_id.clone(),
89+ })
90+ .await
91+ {
75 Ok(()) => {92 Ok(()) => {
76 let _ = this.update_in(cx, |yumush, window, cx| {93 let _ = this.update_in(cx, |yumush, window, cx| {
77 yumush.chat.remove_community(&community_id);94 yumush.chat.remove_community(&community_id);
@@ -118,7 +135,12 @@ impl Yumush {
118 let network = self.network.clone();135 let network = self.network.clone();
119 136
120 cx.spawn_in(window, async move |this, cx| {137 cx.spawn_in(window, async move |this, cx| {
121- let members = match network.members(&community_id).await {138+ let members = match network
139+ .call(ListMembers {
140+ community_id: community_id.clone(),
141+ })
142+ .await
143+ {
122 Ok(members) => members,144 Ok(members) => members,
123 Err(error) => {145 Err(error) => {
124 notify_error(&this, cx, error);146 notify_error(&this, cx, error);
@@ -179,7 +201,13 @@ impl Yumush {
179 let user_id = user_id.to_string();201 let user_id = user_id.to_string();
180 202
181 cx.spawn_in(window, async move |this, cx| {203 cx.spawn_in(window, async move |this, cx| {
182- match network.transfer_ownership(&community_id, &user_id).await {204+ match network
205+ .call(TransferOwnership {
206+ community_id,
207+ user_id,
208+ })
209+ .await
210+ {
183 Ok(()) => {211 Ok(()) => {
184 let _ = this.update_in(cx, |yumush, window, cx| {212 let _ = this.update_in(cx, |yumush, window, cx| {
185 yumush.chat.transfer = None;213 yumush.chat.transfer = None;
@@ -212,7 +240,7 @@ impl Yumush {
212 let network = self.network.clone();240 let network = self.network.clone();
213 241
214 cx.spawn_in(window, async move |this, cx| {242 cx.spawn_in(window, async move |this, cx| {
215- match network.read_community(&community_id).await {243+ match network.call(GetCommunity { community_id }).await {
216 Ok(community) => {244 Ok(community) => {
217 let _ = this.update_in(cx, |yumush, window, cx| {245 let _ = this.update_in(cx, |yumush, window, cx| {
218 yumush.enter(community, voice, window, cx)246 yumush.enter(community, voice, window, cx)
crates/client/src/gui/builder/log.rsmodified+8 -1
@@ -1,4 +1,5 @@
1 use common::{1 use common::{
2+ call::ListAdminLogs,
2 model::{AdminAction, AdminLogEntry, action_detail},3 model::{AdminAction, AdminLogEntry, action_detail},
3 time::{created_at_ms, now_ms},4 time::{created_at_ms, now_ms},
4 };5 };
@@ -222,7 +223,13 @@ impl Yumush {
222 cx,223 cx,
223 move |network| async move {224 move |network| async move {
224 network225 network
225- .admin_logs(actor_id, target_id, action, after_ms, before_ms)226+ .call(ListAdminLogs {
227+ actor_id,
228+ target_id,
229+ action,
230+ after_ms,
231+ before_ms,
232+ })
226 .await233 .await
227 },234 },
228 |yumush, entries, cx| {235 |yumush, entries, cx| {
crates/client/src/gui/builder/messages.rsmodified+17 -3
@@ -1,4 +1,7 @@
1-use common::model::MessageHit;1+use common::{
2+ call::{DeleteMessage, SearchMessages},
3+ model::MessageHit,
4+};
2 use gpui_kit::{5 use gpui_kit::{
3 AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,6 AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
4 assets::IconName,7 assets::IconName,
@@ -224,7 +227,13 @@ impl Yumush {
224 227
225 cx.spawn_in(window, async move |this, cx| {228 cx.spawn_in(window, async move |this, cx| {
226 let hits = match network229 let hits = match network
227- .search_messages(text, user_id, community_id, after_ms, before_ms)230+ .call(SearchMessages {
231+ text,
232+ user_id,
233+ community_id,
234+ after_ms,
235+ before_ms,
236+ })
228 .await237 .await
229 {238 {
230 Ok(hits) => hits,239 Ok(hits) => hits,
@@ -256,7 +265,12 @@ impl Yumush {
256 let message_id = message_id.to_string();265 let message_id = message_id.to_string();
257 266
258 cx.spawn_in(window, async move |this, cx| {267 cx.spawn_in(window, async move |this, cx| {
259- match network.delete_message(&message_id).await {268+ match network
269+ .call(DeleteMessage {
270+ message_id: message_id.clone(),
271+ })
272+ .await
273+ {
260 Ok(()) => {274 Ok(()) => {
261 let _ = this.update(cx, |yumush, cx| {275 let _ = this.update(cx, |yumush, cx| {
262 yumush276 yumush
crates/client/src/gui/builder/overview.rsmodified+9 -2
@@ -1,5 +1,9 @@
1 use crate::net::Fail;1 use crate::net::Fail;
2-use common::{model::DayStat, time::DAY_MILLIS};2+use common::{
3+ call::{GetDailyStats, GetOverview},
4+ model::DayStat,
5+ time::DAY_MILLIS,
6+};
3 use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px};7 use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px};
4 use jiff::Timestamp;8 use jiff::Timestamp;
5 9
@@ -108,7 +112,10 @@ impl Yumush {
108 window,112 window,
109 cx,113 cx,
110 |network| async move {114 |network| async move {
111- Ok::<_, Fail>((network.overview().await?, network.daily_stats(30).await?))115+ Ok::<_, Fail>((
116+ network.call(GetOverview).await?,
117+ network.call(GetDailyStats { days: 30 }).await?,
118+ ))
112 },119 },
113 |yumush, (overview, stats), cx| {120 |yumush, (overview, stats), cx| {
114 yumush.chat.builder_overview = Some(overview);121 yumush.chat.builder_overview = Some(overview);
crates/client/src/gui/builder/reports.rsmodified+21 -7
@@ -1,6 +1,9 @@
1 use std::future::Future;1 use std::future::Future;
2 2
3-use common::model::{BanScope, Report, ReportStatus};3+use common::{
4+ call::{BanUser, DeleteMessage, HandleReport, ListReports, TimeoutUser},
5+ model::{BanScope, Report, ReportStatus},
6+};
4 use gpui_kit::{7 use gpui_kit::{
5 AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window,8 AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window,
6 div, px,9 div, px,
@@ -42,7 +45,9 @@ impl Yumush {
42 cx,45 cx,
43 |network| async move {46 |network| async move {
44 network47 network
45- .reports(Some(ReportStatus::Open))48+ .call(ListReports {
49+ status: Some(ReportStatus::Open),
50+ })
46 .await51 .await
47 .map(|reports| reports.len())52 .map(|reports| reports.len())
48 },53 },
@@ -58,7 +63,7 @@ impl Yumush {
58 self.fetch_builder(63 self.fetch_builder(
59 window,64 window,
60 cx,65 cx,
61- move |network| async move { network.reports(status).await },66+ move |network| async move { network.call(ListReports { status }).await },
62 |yumush, reports, cx| {67 |yumush, reports, cx| {
63 yumush.chat.builder_reports = reports;68 yumush.chat.builder_reports = reports;
64 cx.notify();69 cx.notify();
@@ -110,7 +115,7 @@ impl Yumush {
110 ) {115 ) {
111 let report_id = report_id.to_string();116 let report_id = report_id.to_string();
112 self.report_action(window, cx, move |network| async move {117 self.report_action(window, cx, move |network| async move {
113- network.handle_report(&report_id, status).await118+ network.call(HandleReport { report_id, status }).await
114 });119 });
115 }120 }
116 121
@@ -122,7 +127,7 @@ impl Yumush {
122 ) {127 ) {
123 let message_id = message_id.to_string();128 let message_id = message_id.to_string();
124 self.report_action(window, cx, move |network| async move {129 self.report_action(window, cx, move |network| async move {
125- network.delete_message(&message_id).await130+ network.call(DeleteMessage { message_id }).await
126 });131 });
127 }132 }
128 133
@@ -134,7 +139,12 @@ impl Yumush {
134 ) {139 ) {
135 let user_id = user_id.to_string();140 let user_id = user_id.to_string();
136 self.report_action(window, cx, move |network| async move {141 self.report_action(window, cx, move |network| async move {
137- network.timeout_user(&user_id, 60).await142+ network
143+ .call(TimeoutUser {
144+ user_id,
145+ minutes: 60,
146+ })
147+ .await
138 });148 });
139 }149 }
140 150
@@ -149,7 +159,11 @@ impl Yumush {
149 let reason = reason.to_string();159 let reason = reason.to_string();
150 self.report_action(window, cx, move |network| async move {160 self.report_action(window, cx, move |network| async move {
151 network161 network
152- .ban_user(&user_id, Some(reason.as_str()), BanScope::Account)162+ .call(BanUser {
163+ user_id,
164+ reason: Some(reason),
165+ scope: BanScope::Account,
166+ })
153 .await167 .await
154 });168 });
155 }169 }
crates/client/src/gui/builder/server.rsmodified+2 -2
@@ -1,4 +1,4 @@
1-use common::model::ServerSettings;1+use common::{call::UpdateServerSettings, model::ServerSettings};
2 use gpui_kit::{2 use gpui_kit::{
3 AnyElement, App, Context, Entity, IntoElement, Window,3 AnyElement, App, Context, Entity, IntoElement, Window,
4 component::{WindowExt, input::InputState, notification::Notification},4 component::{WindowExt, input::InputState, notification::Notification},
@@ -128,7 +128,7 @@ impl Yumush {
128 let network = self.network.clone();128 let network = self.network.clone();
129 129
130 cx.spawn_in(window, async move |this, cx| {130 cx.spawn_in(window, async move |this, cx| {
131- match network.update_server_settings(settings).await {131+ match network.call(UpdateServerSettings { settings }).await {
132 Ok(settings) => {132 Ok(settings) => {
133 let _ = this.update(cx, |yumush, cx| {133 let _ = this.update(cx, |yumush, cx| {
134 yumush.server = Some(settings);134 yumush.server = Some(settings);
crates/client/src/gui/builder/storage.rsmodified+12 -3
@@ -1,4 +1,7 @@
1-use common::model::AttachmentInfo;1+use common::{
2+ call::{DeleteAttachment, ListAttachments},
3+ model::AttachmentInfo,
4+};
2 use gpui_kit::{5 use gpui_kit::{
3 AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,6 AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
4 assets::IconName,7 assets::IconName,
@@ -282,7 +285,13 @@ impl Yumush {
282 let network = self.network.clone();285 let network = self.network.clone();
283 286
284 cx.spawn_in(window, async move |this, cx| {287 cx.spawn_in(window, async move |this, cx| {
285- let attachments = match network.attachments(user_id, community_id).await {288+ let attachments = match network
289+ .call(ListAttachments {
290+ user_id,
291+ community_id,
292+ })
293+ .await
294+ {
286 Ok(attachments) => attachments,295 Ok(attachments) => attachments,
287 Err(error) => {296 Err(error) => {
288 notify_error(&this, cx, error);297 notify_error(&this, cx, error);
@@ -312,7 +321,7 @@ impl Yumush {
312 let attachment_id = attachment_id.to_string();321 let attachment_id = attachment_id.to_string();
313 322
314 cx.spawn_in(window, async move |this, cx| {323 cx.spawn_in(window, async move |this, cx| {
315- match network.delete_attachment(&attachment_id).await {324+ match network.call(DeleteAttachment { attachment_id }).await {
316 Ok(()) => {325 Ok(()) => {
317 let _ = this.update_in(cx, |yumush, window, cx| {326 let _ = this.update_in(cx, |yumush, window, cx| {
318 yumush.load_storage(window, cx);327 yumush.load_storage(window, cx);
crates/client/src/gui/builder/users.rsmodified+47 -13
@@ -1,6 +1,10 @@
1 use std::future::Future;1 use std::future::Future;
2 2
3 use common::{3 use common::{
4+ call::{
5+ BanUser, ClearProfile, CreateUser, DeleteUser, ListSessions, PurgeUser, RenameUser,
6+ ResetPassword, RevokeSession, RevokeSessions, SetRole, SuspendUser, TimeoutUser,
7+ },
4 model::{Account, BanScope, Role, SessionInfo, User},8 model::{Account, BanScope, Role, SessionInfo, User},
5 permission,9 permission,
6 time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms},10 time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms},
@@ -59,7 +63,7 @@ impl Yumush {
59 let network = self.network.clone();63 let network = self.network.clone();
60 64
61 cx.spawn_in(window, async move |this, cx| {65 cx.spawn_in(window, async move |this, cx| {
62- match network.create_user(&username, &password).await {66+ match network.call(CreateUser { username, password }).await {
63 Ok(_) => {67 Ok(_) => {
64 let _ = this.update_in(cx, |yumush, window, cx| {68 let _ = this.update_in(cx, |yumush, window, cx| {
65 yumush69 yumush
@@ -86,7 +90,7 @@ impl Yumush {
86 let user_id = user_id.to_string();90 let user_id = user_id.to_string();
87 91
88 cx.spawn_in(window, async move |this, cx| {92 cx.spawn_in(window, async move |this, cx| {
89- match network.set_role(&user_id, role).await {93+ match network.call(SetRole { user_id, role }).await {
90 Ok(user) => {94 Ok(user) => {
91 let _ = this.update(cx, |yumush, cx| {95 let _ = this.update(cx, |yumush, cx| {
92 let index = yumush96 let index = yumush
@@ -120,7 +124,12 @@ impl Yumush {
120 let user_id = user_id.to_string();124 let user_id = user_id.to_string();
121 125
122 cx.spawn_in(window, async move |this, cx| {126 cx.spawn_in(window, async move |this, cx| {
123- match network.delete_user(&user_id).await {127+ match network
128+ .call(DeleteUser {
129+ user_id: user_id.clone(),
130+ })
131+ .await
132+ {
124 Ok(()) => {133 Ok(()) => {
125 let _ = this.update(cx, |yumush, cx| {134 let _ = this.update(cx, |yumush, cx| {
126 yumush135 yumush
@@ -164,7 +173,7 @@ impl Yumush {
164 ) {173 ) {
165 let user_id = user_id.to_string();174 let user_id = user_id.to_string();
166 self.builder_user_action(window, cx, move |network| async move {175 self.builder_user_action(window, cx, move |network| async move {
167- network.suspend_user(&user_id, suspended).await176+ network.call(SuspendUser { user_id, suspended }).await
168 });177 });
169 }178 }
170 179
@@ -176,7 +185,7 @@ impl Yumush {
176 ) {185 ) {
177 let user_id = user_id.to_string();186 let user_id = user_id.to_string();
178 self.builder_user_action(window, cx, move |network| async move {187 self.builder_user_action(window, cx, move |network| async move {
179- network.revoke_sessions(&user_id).await188+ network.call(RevokeSessions { user_id }).await
180 });189 });
181 }190 }
182 191
@@ -188,7 +197,7 @@ impl Yumush {
188 ) {197 ) {
189 let user_id = user_id.to_string();198 let user_id = user_id.to_string();
190 self.builder_user_action(window, cx, move |network| async move {199 self.builder_user_action(window, cx, move |network| async move {
191- network.clear_profile(&user_id).await.map(|_| ())200+ network.call(ClearProfile { user_id }).await.map(|_| ())
192 });201 });
193 }202 }
194 203
@@ -210,7 +219,7 @@ impl Yumush {
210 .builder_password219 .builder_password
211 .update(cx, |input, cx| input.set_value("", window, cx));220 .update(cx, |input, cx| input.set_value("", window, cx));
212 self.builder_user_action(window, cx, move |network| async move {221 self.builder_user_action(window, cx, move |network| async move {
213- network.reset_password(&user_id, &password).await222+ network.call(ResetPassword { user_id, password }).await
214 });223 });
215 }224 }
216 225
@@ -223,7 +232,12 @@ impl Yumush {
223 let network = self.network.clone();232 let network = self.network.clone();
224 233
225 cx.spawn_in(window, async move |this, cx| {234 cx.spawn_in(window, async move |this, cx| {
226- match network.sessions(&user_id).await {235+ match network
236+ .call(ListSessions {
237+ user_id: user_id.clone(),
238+ })
239+ .await
240+ {
227 Ok(sessions) => {241 Ok(sessions) => {
228 let _ = this.update(cx, |yumush, cx| {242 let _ = this.update(cx, |yumush, cx| {
229 yumush.chat.builder_sessions = Some((user_id, sessions));243 yumush.chat.builder_sessions = Some((user_id, sessions));
@@ -267,7 +281,13 @@ impl Yumush {
267 let session_id = session_id.to_string();281 let session_id = session_id.to_string();
268 282
269 cx.spawn_in(window, async move |this, cx| {283 cx.spawn_in(window, async move |this, cx| {
270- match network.revoke_session(&user_id, &session_id).await {284+ match network
285+ .call(RevokeSession {
286+ user_id: user_id.clone(),
287+ session_id,
288+ })
289+ .await
290+ {
271 Ok(()) => {291 Ok(()) => {
272 let _ = this.update_in(cx, |yumush, window, cx| {292 let _ = this.update_in(cx, |yumush, window, cx| {
273 yumush.load_sessions(user_id, window, cx)293 yumush.load_sessions(user_id, window, cx)
@@ -297,7 +317,10 @@ impl Yumush {
297 .builder_rename317 .builder_rename
298 .update(cx, |input, cx| input.set_value("", window, cx));318 .update(cx, |input, cx| input.set_value("", window, cx));
299 self.builder_user_action(window, cx, move |network| async move {319 self.builder_user_action(window, cx, move |network| async move {
300- network.rename_user(&user_id, &username).await.map(|_| ())320+ network
321+ .call(RenameUser { user_id, username })
322+ .await
323+ .map(|_| ())
301 });324 });
302 }325 }
303 326
@@ -323,7 +346,7 @@ impl Yumush {
323 .builder_timeout346 .builder_timeout
324 .update(cx, |input, cx| input.set_value("", window, cx));347 .update(cx, |input, cx| input.set_value("", window, cx));
325 self.builder_user_action(window, cx, move |network| async move {348 self.builder_user_action(window, cx, move |network| async move {
326- network.timeout_user(&user_id, minutes).await349+ network.call(TimeoutUser { user_id, minutes }).await
327 });350 });
328 }351 }
329 352
@@ -356,7 +379,13 @@ impl Yumush {
356 .builder_ban_reason379 .builder_ban_reason
357 .update(cx, |input, cx| input.set_value("", window, cx));380 .update(cx, |input, cx| input.set_value("", window, cx));
358 self.builder_user_action(window, cx, move |network| async move {381 self.builder_user_action(window, cx, move |network| async move {
359- network.ban_user(&user_id, reason.as_deref(), scope).await382+ network
383+ .call(BanUser {
384+ user_id,
385+ reason,
386+ scope,
387+ })
388+ .await
360 });389 });
361 }390 }
362 391
@@ -374,7 +403,12 @@ impl Yumush {
374 let user_id = user_id.to_string();403 let user_id = user_id.to_string();
375 404
376 cx.spawn_in(window, async move |this, cx| {405 cx.spawn_in(window, async move |this, cx| {
377- match network.purge_user(&user_id).await {406+ match network
407+ .call(PurgeUser {
408+ user_id: user_id.clone(),
409+ })
410+ .await
411+ {
378 Ok(()) => {412 Ok(()) => {
379 let _ = this.update_in(cx, |yumush, window, cx| {413 let _ = this.update_in(cx, |yumush, window, cx| {
380 yumush414 yumush
crates/client/src/gui/builder/voice.rsmodified+7 -4
@@ -1,6 +1,9 @@
1 use std::future::Future;1 use std::future::Future;
2 2
3-use common::model::{User, VoiceRoom};3+use common::{
4+ call::{KickFromVoice, ListVoiceRooms, ServerMute},
5+ model::{User, VoiceRoom},
6+};
4 use gpui_kit::{7 use gpui_kit::{
5 AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,8 AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,
6 div, px,9 div, px,
@@ -17,7 +20,7 @@ impl Yumush {
17 self.fetch_builder(20 self.fetch_builder(
18 window,21 window,
19 cx,22 cx,
20- |network| async move { network.voice_rooms().await },23+ |network| async move { network.call(ListVoiceRooms).await },
21 |yumush, rooms, cx| {24 |yumush, rooms, cx| {
22 yumush.chat.builder_voice_rooms = rooms;25 yumush.chat.builder_voice_rooms = rooms;
23 cx.notify();26 cx.notify();
@@ -54,7 +57,7 @@ impl Yumush {
54 ) {57 ) {
55 let user_id = user_id.to_string();58 let user_id = user_id.to_string();
56 self.voice_action(window, cx, move |network| async move {59 self.voice_action(window, cx, move |network| async move {
57- network.server_mute(&user_id, muted).await60+ network.call(ServerMute { user_id, muted }).await
58 });61 });
59 }62 }
60 63
@@ -66,7 +69,7 @@ impl Yumush {
66 ) {69 ) {
67 let user_id = user_id.to_string();70 let user_id = user_id.to_string();
68 self.voice_action(window, cx, move |network| async move {71 self.voice_action(window, cx, move |network| async move {
69- network.kick_from_voice(&user_id).await72+ network.call(KickFromVoice { user_id }).await
70 });73 });
71 }74 }
72 75
crates/client/src/gui/chat.rsmodified+67 -15
@@ -33,6 +33,11 @@ use crate::settings::VOLUME;
33 use crate::share::session::ShareSample;33 use crate::share::session::ShareSample;
34 use crate::voice::VoiceSample;34 use crate::voice::VoiceSample;
35 use common::{35 use common::{
36+ call::{
37+ CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans,
38+ ListCommunities, ListMembers, ListMessages, ListPins, ListUnreads, ListVoiceParticipants,
39+ SearchCommunity, WatchCommunity,
40+ },
36 constant::MESSAGE_PAGE_LIMIT,41 constant::MESSAGE_PAGE_LIMIT,
37 event::Event,42 event::Event,
38 model::{43 model::{
@@ -1168,7 +1173,8 @@ pub(super) fn create_community(
1168 let network = this.network.clone();1173 let network = this.network.clone();
1169 1174
1170 cx.spawn_in(window, async move |this, cx| {1175 cx.spawn_in(window, async move |this, cx| {
1171- let Some(community) = ok_or_notify(network.create_community(&name).await, &this, cx) else {1176+ let Some(community) = ok_or_notify(network.call(CreateCommunity { name }).await, &this, cx)
1177+ else {
1172 return;1178 return;
1173 };1179 };
1174 1180
@@ -1635,10 +1641,11 @@ impl Yumush {
1635 let network = self.network.clone();1641 let network = self.network.clone();
1636 1642
1637 cx.spawn_in(window, async move |this, cx| {1643 cx.spawn_in(window, async move |this, cx| {
1638- let Some(communities) = ok_or_notify(network.communities().await, &this, cx) else {1644+ let Some(communities) = ok_or_notify(network.call(ListCommunities).await, &this, cx)
1645+ else {
1639 return;1646 return;
1640 };1647 };
1641- let unreads = network.unreads().await.unwrap_or_default();1648+ let unreads = network.call(ListUnreads).await.unwrap_or_default();
1642 1649
1643 let _ = this.update_in(cx, |yumush, window, cx| {1650 let _ = this.update_in(cx, |yumush, window, cx| {
1644 yumush.chat.unread = unreads1651 yumush.chat.unread = unreads
@@ -1676,7 +1683,12 @@ impl Yumush {
1676 1683
1677 cx.spawn_in(window, async move |this, cx| {1684 cx.spawn_in(window, async move |this, cx| {
1678 let Some(hits) = ok_or_notify(1685 let Some(hits) = ok_or_notify(
1679- network.search_community(community_id.clone(), text).await,1686+ network
1687+ .call(SearchCommunity {
1688+ community_id: community_id.clone(),
1689+ text,
1690+ })
1691+ .await,
1680 &this,1692 &this,
1681 cx,1693 cx,
1682 ) else {1694 ) else {
@@ -1700,7 +1712,15 @@ impl Yumush {
1700 let network = self.network.clone();1712 let network = self.network.clone();
1701 1713
1702 cx.spawn_in(window, async move |this, cx| {1714 cx.spawn_in(window, async move |this, cx| {
1703- let Some(pins) = ok_or_notify(network.pins(&community_id).await, &this, cx) else {1715+ let Some(pins) = ok_or_notify(
1716+ network
1717+ .call(ListPins {
1718+ community_id: community_id.clone(),
1719+ })
1720+ .await,
1721+ &this,
1722+ cx,
1723+ ) else {
1704 return;1724 return;
1705 };1725 };
1706 1726
@@ -1721,8 +1741,15 @@ impl Yumush {
1721 let network = self.network.clone();1741 let network = self.network.clone();
1722 1742
1723 cx.spawn_in(window, async move |this, cx| {1743 cx.spawn_in(window, async move |this, cx| {
1724- let Some(members) = ok_or_notify(network.members(&community_id).await, &this, cx)1744+ let Some(members) = ok_or_notify(
1725- else {1745+ network
1746+ .call(ListMembers {
1747+ community_id: community_id.clone(),
1748+ })
1749+ .await,
1750+ &this,
1751+ cx,
1752+ ) else {
1726 return;1753 return;
1727 };1754 };
1728 1755
@@ -1755,7 +1782,7 @@ impl Yumush {
1755 1782
1756 cx.spawn(async move |this, cx| {1783 cx.spawn(async move |this, cx| {
1757 for user_id in missing {1784 for user_id in missing {
1758- let Ok(user) = network.read_user(&user_id).await else {1785+ let Ok(user) = network.call(GetUser { user_id }).await else {
1759 continue;1786 continue;
1760 };1787 };
1761 let _ = this.update(cx, |yumush, cx| {1788 let _ = this.update(cx, |yumush, cx| {
@@ -1778,7 +1805,15 @@ impl Yumush {
1778 let network = self.network.clone();1805 let network = self.network.clone();
1779 1806
1780 cx.spawn_in(window, async move |this, cx| {1807 cx.spawn_in(window, async move |this, cx| {
1781- let Some(bans) = ok_or_notify(network.bans(&community_id).await, &this, cx) else {1808+ let Some(bans) = ok_or_notify(
1809+ network
1810+ .call(ListBans {
1811+ community_id: community_id.clone(),
1812+ })
1813+ .await,
1814+ &this,
1815+ cx,
1816+ ) else {
1782 return;1817 return;
1783 };1818 };
1784 1819
@@ -1841,11 +1876,18 @@ impl Yumush {
1841 1876
1842 cx.spawn_in(window, async move |this, cx| {1877 cx.spawn_in(window, async move |this, cx| {
1843 if before.is_none() {1878 if before.is_none() {
1844- let _ = network.watch_community(Some(&community_id)).await;1879+ let _ = network
1880+ .call(WatchCommunity {
1881+ community_id: Some(community_id.clone()),
1882+ })
1883+ .await;
1845 }1884 }
1846 let Some(page) = ok_or_notify(1885 let Some(page) = ok_or_notify(
1847 network1886 network
1848- .read_messages(&community_id, before.as_deref())1887+ .call(ListMessages {
1888+ community_id: community_id.clone(),
1889+ before,
1890+ })
1849 .await,1891 .await,
1850 &this,1892 &this,
1851 cx,1893 cx,
@@ -1910,7 +1952,7 @@ impl Yumush {
1910 let message_id = message_id.to_string();1952 let message_id = message_id.to_string();
1911 1953
1912 spawn_done(window, cx, async move {1954 spawn_done(window, cx, async move {
1913- network.delete_message(&message_id).await1955+ network.call(DeleteMessage { message_id }).await
1914 });1956 });
1915 }1957 }
1916 1958
@@ -1923,7 +1965,12 @@ impl Yumush {
1923 let network = self.network.clone();1965 let network = self.network.clone();
1924 1966
1925 cx.spawn_in(window, async move |this, cx| {1967 cx.spawn_in(window, async move |this, cx| {
1926- if let Err(error) = network.leave_community(&community_id).await {1968+ if let Err(error) = network
1969+ .call(LeaveCommunity {
1970+ community_id: community_id.clone(),
1971+ })
1972+ .await
1973+ {
1927 notify_error(&this, cx, error);1974 notify_error(&this, cx, error);
1928 return;1975 return;
1929 }1976 }
@@ -1941,7 +1988,12 @@ impl Yumush {
1941 let network = self.network.clone();1988 let network = self.network.clone();
1942 1989
1943 cx.spawn(async move |this, cx| {1990 cx.spawn(async move |this, cx| {
1944- let Ok(participants) = network.voice_participants(&community_id).await else {1991+ let Ok(participants) = network
1992+ .call(ListVoiceParticipants {
1993+ community_id: community_id.clone(),
1994+ })
1995+ .await
1996+ else {
1945 return;1997 return;
1946 };1998 };
1947 1999
@@ -2423,7 +2475,7 @@ impl Yumush {
2423 2475
2424 let network = self.network.clone();2476 let network = self.network.clone();
2425 spawn_done(window, cx, async move {2477 spawn_done(window, cx, async move {
2426- network.decline_call(&community_id).await2478+ network.call(DeclineCall { community_id }).await
2427 });2479 });
2428 }2480 }
2429 2481
crates/client/src/gui/community_settings.rsmodified+30 -7
@@ -2,6 +2,9 @@ use std::{collections::HashMap, sync::Arc};
2 2
3 use crate::net::Fail;3 use crate::net::Fail;
4 use common::{4 use common::{
5+ call::{
6+ DeleteCommunity, ListLogs, SetCommunityVoice, Unban, UpdateCommunity, UpdateCommunityAvatar,
7+ },
5 model::{Ban, Community, LogAction, LogEntry, User},8 model::{Ban, Community, LogAction, LogEntry, User},
6 permission,9 permission,
7 validate::validate_community_name,10 validate::validate_community_name,
@@ -215,7 +218,12 @@ impl Yumush {
215 let network = self.network.clone();218 let network = self.network.clone();
216 219
217 cx.spawn_in(window, async move |this, cx| {220 cx.spawn_in(window, async move |this, cx| {
218- let result = network.set_community_voice(&community_id, enabled).await;221+ let result = network
222+ .call(SetCommunityVoice {
223+ community_id,
224+ enabled,
225+ })
226+ .await;
219 apply_community(&this, cx, result);227 apply_community(&this, cx, result);
220 })228 })
221 .detach();229 .detach();
@@ -242,7 +250,7 @@ impl Yumush {
242 let network = self.network.clone();250 let network = self.network.clone();
243 251
244 cx.spawn_in(window, async move |this, cx| {252 cx.spawn_in(window, async move |this, cx| {
245- let result = network.update_community(&community_id, &name).await;253+ let result = network.call(UpdateCommunity { community_id, name }).await;
246 apply_community(&this, cx, result);254 apply_community(&this, cx, result);
247 })255 })
248 .detach();256 .detach();
@@ -262,7 +270,10 @@ impl Yumush {
262 let result = match prepared {270 let result = match prepared {
263 Ok(bytes) => {271 Ok(bytes) => {
264 network272 network
265- .update_community_avatar(&community_id, Some(bytes))273+ .call(UpdateCommunityAvatar {
274+ community_id,
275+ image: Some(bytes),
276+ })
266 .await277 .await
267 }278 }
268 Err(error) => Err(error),279 Err(error) => Err(error),
@@ -279,7 +290,12 @@ impl Yumush {
279 let network = self.network.clone();290 let network = self.network.clone();
280 291
281 cx.spawn_in(window, async move |this, cx| {292 cx.spawn_in(window, async move |this, cx| {
282- let result = network.update_community_avatar(&community_id, None).await;293+ let result = network
294+ .call(UpdateCommunityAvatar {
295+ community_id,
296+ image: None,
297+ })
298+ .await;
283 apply_community(&this, cx, result);299 apply_community(&this, cx, result);
284 })300 })
285 .detach();301 .detach();
@@ -295,7 +311,10 @@ impl Yumush {
295 let network = self.network.clone();311 let network = self.network.clone();
296 312
297 cx.spawn_in(window, async move |this, cx| {313 cx.spawn_in(window, async move |this, cx| {
298- match network.delete_community(&community_id).await {314+ let call = DeleteCommunity {
315+ community_id: community_id.clone(),
316+ };
317+ match network.call(call).await {
299 Ok(()) => {318 Ok(()) => {
300 let _ = this.update_in(cx, |yumush, window, cx| {319 let _ = this.update_in(cx, |yumush, window, cx| {
301 yumush.chat.remove_community(&community_id);320 yumush.chat.remove_community(&community_id);
@@ -316,7 +335,11 @@ impl Yumush {
316 let user_id = user_id.to_string();335 let user_id = user_id.to_string();
317 336
318 cx.spawn_in(window, async move |this, cx| {337 cx.spawn_in(window, async move |this, cx| {
319- match network.unban(&community_id, &user_id).await {338+ let call = Unban {
339+ community_id,
340+ user_id: user_id.clone(),
341+ };
342+ match network.call(call).await {
320 Ok(()) => {343 Ok(()) => {
321 let _ = this.update_in(cx, |yumush, window, cx| {344 let _ = this.update_in(cx, |yumush, window, cx| {
322 yumush.chat.bans.retain(|ban| ban.user.id != user_id);345 yumush.chat.bans.retain(|ban| ban.user.id != user_id);
@@ -415,7 +438,7 @@ impl Yumush {
415 let network = self.network.clone();438 let network = self.network.clone();
416 439
417 cx.spawn_in(window, async move |this, cx| {440 cx.spawn_in(window, async move |this, cx| {
418- let logs = match network.logs(&community_id).await {441+ let logs = match network.call(ListLogs { community_id }).await {
419 Ok(logs) => logs,442 Ok(logs) => logs,
420 Err(error) => {443 Err(error) => {
421 notify_error(&this, cx, error);444 notify_error(&this, cx, error);
crates/client/src/gui/composer.rsmodified+21 -4
@@ -4,6 +4,7 @@ use std::time::{Duration, Instant};
4 4
5 use crate::net::Fail;5 use crate::net::Fail;
6 use common::{6 use common::{
7+ call::{CreateMessage, CreatePoll, Typing, UpdateMessage},
7 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS},8 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS},
8 error::Error,9 error::Error,
9 model::Attachment,10 model::Attachment,
@@ -232,7 +233,7 @@ impl Yumush {
232 .insert(community_id.clone(), Instant::now());233 .insert(community_id.clone(), Instant::now());
233 let network = self.network.clone();234 let network = self.network.clone();
234 cx.spawn(async move |_, _| {235 cx.spawn(async move |_, _| {
235- let _ = network.typing(&community_id).await;236+ let _ = network.call(Typing { community_id }).await;
236 })237 })
237 .detach();238 .detach();
238 }239 }
@@ -272,7 +273,12 @@ impl Yumush {
272 273
273 cx.spawn_in(window, async move |this, cx| {274 cx.spawn_in(window, async move |this, cx| {
274 match network275 match network
275- .create_message(&community_id, &body, attachments, reply)276+ .call(CreateMessage {
277+ community_id: community_id.clone(),
278+ body: body.clone(),
279+ attachments,
280+ reply_to: reply,
281+ })
276 .await282 .await
277 {283 {
278 Ok(_) => {}284 Ok(_) => {}
@@ -355,7 +361,13 @@ impl Yumush {
355 let restore = input.clone();361 let restore = input.clone();
356 362
357 cx.spawn_in(window, async move |this, cx| {363 cx.spawn_in(window, async move |this, cx| {
358- if let Err(error) = network.update_message(&message_id, &body).await {364+ if let Err(error) = network
365+ .call(UpdateMessage {
366+ message_id: message_id.clone(),
367+ body: body.clone(),
368+ })
369+ .await
370+ {
359 let _ = this.update_in(cx, |yumush, window, cx| {371 let _ = this.update_in(cx, |yumush, window, cx| {
360 if restore.read(cx).text().len() == 0 {372 if restore.read(cx).text().len() == 0 {
361 restore.update(cx, |state, cx| state.set_value(body, window, cx));373 restore.update(cx, |state, cx| state.set_value(body, window, cx));
@@ -697,7 +709,12 @@ impl Yumush {
697 709
698 spawn_done(window, cx, async move {710 spawn_done(window, cx, async move {
699 network711 network
700- .create_poll(&community_id, &question, options, multiple)712+ .call(CreatePoll {
713+ community_id,
714+ question,
715+ options,
716+ multiple,
717+ })
701 .await718 .await
702 });719 });
703 720
crates/client/src/gui/forward.rsmodified+6 -1
@@ -1,4 +1,5 @@
1 use super::text;1 use super::text;
2+use common::call::ForwardMessages;
2 use gpui_kit::{3 use gpui_kit::{
3 AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,4 AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
4 StatefulInteractiveElement, Styled, Window,5 StatefulInteractiveElement, Styled, Window,
@@ -168,7 +169,11 @@ impl Yumush {
168 169
169 spawn_done(window, cx, async move {170 spawn_done(window, cx, async move {
170 network171 network
171- .forward_messages(ids, &community_id, keep_authors)172+ .call(ForwardMessages {
173+ message_ids: ids,
174+ community_id,
175+ snippet: keep_authors,
176+ })
172 .await177 .await
173 });178 });
174 cx.notify();179 cx.notify();
crates/client/src/gui/message_actions.rsmodified+10 -4
@@ -1,5 +1,6 @@
1 use super::text;1 use super::text;
2 use common::{2 use common::{
3+ call::{Pin, React, ReportMessage, ReportUser},
3 constant::REACTIONS,4 constant::REACTIONS,
4 model::{Message, User},5 model::{Message, User},
5 };6 };
@@ -488,7 +489,12 @@ impl Yumush {
488 let network = self.network.clone();489 let network = self.network.clone();
489 490
490 spawn_done(window, cx, async move {491 spawn_done(window, cx, async move {
491- network.pin(&message_id, !pinned).await492+ network
493+ .call(Pin {
494+ message_id,
495+ pinned: !pinned,
496+ })
497+ .await
492 });498 });
493 }499 }
494 500
@@ -502,7 +508,7 @@ impl Yumush {
502 let network = self.network.clone();508 let network = self.network.clone();
503 509
504 spawn_done(window, cx, async move {510 spawn_done(window, cx, async move {
505- network.react(&message_id, &emoji).await511+ network.call(React { message_id, emoji }).await
506 });512 });
507 }513 }
508 514
@@ -534,9 +540,9 @@ impl Yumush {
534 cx.spawn_in(window, async move |this, cx| {540 cx.spawn_in(window, async move |this, cx| {
535 let result = match target {541 let result = match target {
536 ReportTarget::Message(message_id) => {542 ReportTarget::Message(message_id) => {
537- network.report_message(&message_id, &reason).await543+ network.call(ReportMessage { message_id, reason }).await
538 }544 }
539- ReportTarget::User(user_id) => network.report_user(&user_id, &reason).await,545+ ReportTarget::User(user_id) => network.call(ReportUser { user_id, reason }).await,
540 };546 };
541 match result {547 match result {
542 Ok(()) => {548 Ok(()) => {
crates/client/src/gui/poll.rsmodified+10 -6
@@ -1,5 +1,6 @@
1 use std::collections::HashSet;1 use std::collections::HashSet;
2 2
3+use common::call::{ClosePoll, Vote};
3 use common::model::{Message, Poll, Rank, User};4 use common::model::{Message, Poll, Rank, User};
4 use gpui_kit::{5 use gpui_kit::{
5 Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled,6 Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled,
@@ -318,7 +319,12 @@ impl Yumush {
318 let network = self.network.clone();319 let network = self.network.clone();
319 320
320 spawn_done(window, cx, async move {321 spawn_done(window, cx, async move {
321- network.vote(&message_id, positions).await322+ network
323+ .call(Vote {
324+ message_id,
325+ positions,
326+ })
327+ .await
322 });328 });
323 }329 }
324 330
@@ -330,10 +336,8 @@ impl Yumush {
330 ) {336 ) {
331 let network = self.network.clone();337 let network = self.network.clone();
332 338
333- spawn_done(339+ spawn_done(window, cx, async move {
334- window,340+ network.call(ClosePoll { message_id }).await
335- cx,341+ });
336- async move { network.close_poll(&message_id).await },
337- );
338 }342 }
339 }343 }
crates/client/src/gui/profile.rsmodified+33 -6
@@ -1,6 +1,7 @@
1 use std::{collections::HashMap, sync::Arc};1 use std::{collections::HashMap, sync::Arc};
2 2
3 use common::{3 use common::{
4+ call::{BanMember, DeleteUser, Kick, SetRank, UpdatePresence},
4 model::{Presence, Rank, User},5 model::{Presence, Rank, User},
5 permission,6 permission,
6 };7 };
@@ -642,10 +643,25 @@ impl Yumush {
642 let user_id = user_id.to_string();643 let user_id = user_id.to_string();
643 644
644 cx.spawn_in(window, async move |this, cx| {645 cx.spawn_in(window, async move |this, cx| {
645- let reason = reason.as_deref();
646 let result = match removal {646 let result = match removal {
647- Removal::Kick => network.kick(&community_id, &user_id, reason).await,647+ Removal::Kick => {
648- Removal::Ban => network.ban(&community_id, &user_id, reason).await,648+ network
649+ .call(Kick {
650+ community_id,
651+ user_id,
652+ reason,
653+ })
654+ .await
655+ }
656+ Removal::Ban => {
657+ network
658+ .call(BanMember {
659+ community_id,
660+ user_id,
661+ reason,
662+ })
663+ .await
664+ }
649 };665 };
650 match result {666 match result {
651 Ok(()) => {667 Ok(()) => {
@@ -676,7 +692,13 @@ impl Yumush {
676 let user_id = user_id.to_string();692 let user_id = user_id.to_string();
677 693
678 spawn_done(window, cx, async move {694 spawn_done(window, cx, async move {
679- network.set_rank(&community_id, &user_id, rank).await695+ network
696+ .call(SetRank {
697+ community_id,
698+ user_id,
699+ rank,
700+ })
701+ .await
680 });702 });
681 }703 }
682 704
@@ -695,7 +717,7 @@ impl Yumush {
695 let network = self.network.clone();717 let network = self.network.clone();
696 718
697 spawn_done(window, cx, async move {719 spawn_done(window, cx, async move {
698- network.update_presence(presence).await720+ network.call(UpdatePresence { presence }).await
699 });721 });
700 }722 }
701 723
@@ -715,7 +737,12 @@ impl Yumush {
715 let user_id = user_id.to_string();737 let user_id = user_id.to_string();
716 738
717 cx.spawn_in(window, async move |this, cx| {739 cx.spawn_in(window, async move |this, cx| {
718- match network.delete_user(&user_id).await {740+ match network
741+ .call(DeleteUser {
742+ user_id: user_id.clone(),
743+ })
744+ .await
745+ {
719 Ok(()) => {746 Ok(()) => {
720 let _ = this.update(cx, |yumush, cx| {747 let _ = this.update(cx, |yumush, cx| {
721 yumush.chat.remove_member(&user_id);748 yumush.chat.remove_member(&user_id);
crates/client/src/gui/settings_page.rsmodified+9 -6
@@ -1,7 +1,10 @@
1 use std::future::Future;1 use std::future::Future;
2 2
3 use crate::net::Fail;3 use crate::net::Fail;
4-use common::model::User;4+use common::{
5+ call::{DeleteUser, RemoveAvatar, UpdateAvatar, UpdateStatus, UpdateUser},
6+ model::User,
7+};
5 use gpui_kit::{8 use gpui_kit::{
6 AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla,9 AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla,
7 InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful,10 InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful,
@@ -162,7 +165,7 @@ impl Yumush {
162 let network = self.network.clone();165 let network = self.network.clone();
163 166
164 cx.spawn_in(window, async move |this, cx| {167 cx.spawn_in(window, async move |this, cx| {
165- let result = network.update_user(&username).await;168+ let result = network.call(UpdateUser { username }).await;
166 apply_user(&this, cx, result);169 apply_user(&this, cx, result);
167 })170 })
168 .detach();171 .detach();
@@ -173,7 +176,7 @@ impl Yumush {
173 let network = self.network.clone();176 let network = self.network.clone();
174 177
175 cx.spawn_in(window, async move |this, cx| {178 cx.spawn_in(window, async move |this, cx| {
176- let result = network.update_status(&status).await;179+ let result = network.call(UpdateStatus { status }).await;
177 apply_user(&this, cx, result);180 apply_user(&this, cx, result);
178 })181 })
179 .detach();182 .detach();
@@ -188,7 +191,7 @@ impl Yumush {
188 return;191 return;
189 };192 };
190 let result = match prepared {193 let result = match prepared {
191- Ok(bytes) => network.update_avatar(bytes).await,194+ Ok(bytes) => network.call(UpdateAvatar { image: bytes }).await,
192 Err(error) => Err(error),195 Err(error) => Err(error),
193 };196 };
194 apply_user(&this, cx, result);197 apply_user(&this, cx, result);
@@ -200,7 +203,7 @@ impl Yumush {
200 let network = self.network.clone();203 let network = self.network.clone();
201 204
202 cx.spawn_in(window, async move |this, cx| {205 cx.spawn_in(window, async move |this, cx| {
203- let result = network.remove_avatar().await;206+ let result = network.call(RemoveAvatar).await;
204 apply_user(&this, cx, result);207 apply_user(&this, cx, result);
205 })208 })
206 .detach();209 .detach();
@@ -225,7 +228,7 @@ impl Yumush {
225 let network = self.network.clone();228 let network = self.network.clone();
226 229
227 cx.spawn_in(window, async move |this, cx| {230 cx.spawn_in(window, async move |this, cx| {
228- match network.delete_user(&user_id).await {231+ match network.call(DeleteUser { user_id }).await {
229 Ok(()) => {232 Ok(()) => {
230 let _ = this.update_in(cx, |yumush, window, cx| {233 let _ = this.update_in(cx, |yumush, window, cx| {
231 yumush.end_session(window, cx);234 yumush.end_session(window, cx);
crates/client/src/gui/social.rsmodified+48 -30
@@ -1,6 +1,11 @@
1 use std::{fmt::Display, future::Future};1 use std::{fmt::Display, future::Future};
2 2
3 use common::{3 use common::{
4+ call::{
5+ AcceptFriend, AcceptInvitation, AddFriend, DeclineInvitation, FindUser, Invite,
6+ ListFriends, ListInvitations, ListMembers, ListPresences, OpenDirect, OpenNotes,
7+ RemoveFriend,
8+ },
4 model::{Community, CommunityKind, Rank, User},9 model::{Community, CommunityKind, Rank, User},
5 validate::validate_username,10 validate::validate_username,
6 };11 };
@@ -122,9 +127,9 @@ impl Yumush {
122 127
123 cx.spawn_in(window, async move |this, cx| {128 cx.spawn_in(window, async move |this, cx| {
124 let (friends, invitations, presences) = match (129 let (friends, invitations, presences) = match (
125- network.friends().await,130+ network.call(ListFriends).await,
126- network.invitations().await,131+ network.call(ListInvitations).await,
127- network.read_presences().await,132+ network.call(ListPresences).await,
128 ) {133 ) {
129 (Ok(friends), Ok(invitations), Ok(presences)) => (friends, invitations, presences),134 (Ok(friends), Ok(invitations), Ok(presences)) => (friends, invitations, presences),
130 (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {135 (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
@@ -154,7 +159,12 @@ impl Yumush {
154 let network = self.network.clone();159 let network = self.network.clone();
155 160
156 cx.spawn_in(window, async move |this, cx| {161 cx.spawn_in(window, async move |this, cx| {
157- let found = network.find_user(&username).await.ok();162+ let found = network
163+ .call(FindUser {
164+ username: username.clone(),
165+ })
166+ .await
167+ .ok();
158 let _ = this.update(cx, |yumush, cx| {168 let _ = this.update(cx, |yumush, cx| {
159 if search_text(&yumush.chat.search_input, cx) != username {169 if search_text(&yumush.chat.search_input, cx) != username {
160 return;170 return;
@@ -183,17 +193,15 @@ impl Yumush {
183 }193 }
184 let network = self.network.clone();194 let network = self.network.clone();
185 195
186- spawn_community(window, cx, async move { network.open_notes().await });196+ spawn_community(window, cx, async move { network.call(OpenNotes).await });
187 }197 }
188 198
189 pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {199 pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {
190 let network = self.network.clone();200 let network = self.network.clone();
191 201
192- spawn_community(202+ spawn_community(window, cx, async move {
193- window,203+ network.call(OpenDirect { user_id }).await
194- cx,204+ });
195- async move { network.open_direct(&user_id).await },
196- );
197 }205 }
198 206
199 pub(super) fn friend_action(207 pub(super) fn friend_action(
@@ -214,11 +222,9 @@ impl Yumush {
214 pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {222 pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {
215 let network = self.network.clone();223 let network = self.network.clone();
216 224
217- spawn_done(225+ spawn_done(window, cx, async move {
218- window,226+ network.call(AddFriend { user_id }).await
219- cx,227+ });
220- async move { network.add_friend(&user_id).await },
221- );
222 }228 }
223 229
224 pub(super) fn accept_friend(230 pub(super) fn accept_friend(
@@ -229,11 +235,9 @@ impl Yumush {
229 ) {235 ) {
230 let network = self.network.clone();236 let network = self.network.clone();
231 237
232- spawn_done(238+ spawn_done(window, cx, async move {
233- window,239+ network.call(AcceptFriend { user_id }).await
234- cx,240+ });
235- async move { network.accept_friend(&user_id).await },
236- );
237 }241 }
238 242
239 pub(super) fn remove_friend(243 pub(super) fn remove_friend(
@@ -244,11 +248,9 @@ impl Yumush {
244 ) {248 ) {
245 let network = self.network.clone();249 let network = self.network.clone();
246 250
247- spawn_done(251+ spawn_done(window, cx, async move {
248- window,252+ network.call(RemoveFriend { user_id }).await
249- cx,253+ });
250- async move { network.remove_friend(&user_id).await },
251- );
252 }254 }
253 255
254 pub(super) fn accept_invitation(256 pub(super) fn accept_invitation(
@@ -260,7 +262,7 @@ impl Yumush {
260 let network = self.network.clone();262 let network = self.network.clone();
261 263
262 spawn_community(window, cx, async move {264 spawn_community(window, cx, async move {
263- network.accept_invitation(&community_id).await265+ network.call(AcceptInvitation { community_id }).await
264 });266 });
265 }267 }
266 268
@@ -273,7 +275,7 @@ impl Yumush {
273 let network = self.network.clone();275 let network = self.network.clone();
274 276
275 spawn_done(window, cx, async move {277 spawn_done(window, cx, async move {
276- network.decline_invitation(&community_id).await278+ network.call(DeclineInvitation { community_id }).await
277 });279 });
278 }280 }
279 281
@@ -338,9 +340,19 @@ impl Yumush {
338 let input = input.clone();340 let input = input.clone();
339 341
340 cx.spawn_in(window, async move |this, cx| {342 cx.spawn_in(window, async move |this, cx| {
341- let lookup = match network.find_user(&username).await {343+ let lookup = match network
344+ .call(FindUser {
345+ username: username.clone(),
346+ })
347+ .await
348+ {
342 Ok(user) => {349 Ok(user) => {
343- let members = network.members(&community_id).await.unwrap_or_default();350+ let members = network
351+ .call(ListMembers {
352+ community_id: community_id.clone(),
353+ })
354+ .await
355+ .unwrap_or_default();
344 if members.iter().any(|member| member.user.id == user.id) {356 if members.iter().any(|member| member.user.id == user.id) {
345 InviteLookup::Member(user)357 InviteLookup::Member(user)
346 } else {358 } else {
@@ -371,7 +383,13 @@ impl Yumush {
371 let user_id = user.id.clone();383 let user_id = user.id.clone();
372 384
373 cx.spawn_in(window, async move |this, cx| {385 cx.spawn_in(window, async move |this, cx| {
374- match network.invite(&community_id, &user_id).await {386+ match network
387+ .call(Invite {
388+ community_id,
389+ user_id,
390+ })
391+ .await
392+ {
375 Ok(()) => {393 Ok(()) => {
376 let _ = this.update_in(cx, |_, window, cx| window.close_dialog(cx));394 let _ = this.update_in(cx, |_, window, cx| window.close_dialog(cx));
377 }395 }
crates/client/src/gui/voice_note.rsmodified+7 -1
@@ -4,6 +4,7 @@ use std::{
4 time::{Duration, Instant},4 time::{Duration, Instant},
5 };5 };
6 6
7+use common::call::CreateMessage;
7 use common::constant::VOICE_SAMPLE_RATE;8 use common::constant::VOICE_SAMPLE_RATE;
8 use gpui_kit::{9 use gpui_kit::{
9 App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled,10 App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled,
@@ -283,7 +284,12 @@ impl Yumush {
283 };284 };
284 ok_or_notify(285 ok_or_notify(
285 network286 network
286- .create_message(&community_id, "", vec![attachment.id], None)287+ .call(CreateMessage {
288+ community_id,
289+ body: String::new(),
290+ attachments: vec![attachment.id],
291+ reply_to: None,
292+ })
287 .await,293 .await,
288 &this,294 &this,
289 cx,295 cx,
crates/client/src/net/fail.rsmodified+3 -11
@@ -7,7 +7,6 @@ const CRYPTO_ERRORS: std::ops::Range<u64> = 0x100..0x200;
7 pub enum LinkError {7 pub enum LinkError {
8 Unreachable,8 Unreachable,
9 Tls,9 Tls,
10- Timeout,
11 Outdated,10 Outdated,
12 Reset,11 Reset,
13 Closed(Close),12 Closed(Close),
@@ -16,7 +15,7 @@ pub enum LinkError {
16 impl std::fmt::Display for LinkError {15 impl std::fmt::Display for LinkError {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 match self {17 match self {
19- Self::Unreachable | Self::Timeout => write!(f, "Server unreachable"),18+ Self::Unreachable => write!(f, "Server unreachable"),
20 Self::Tls => write!(f, "Certificate error"),19 Self::Tls => write!(f, "Certificate error"),
21 Self::Outdated => write!(f, "Client is outdated"),20 Self::Outdated => write!(f, "Client is outdated"),
22 Self::Reset => write!(f, "Connection lost"),21 Self::Reset => write!(f, "Connection lost"),
@@ -38,7 +37,7 @@ impl LinkError {
38 impl From<quinn::ConnectionError> for LinkError {37 impl From<quinn::ConnectionError> for LinkError {
39 fn from(error: quinn::ConnectionError) -> Self {38 fn from(error: quinn::ConnectionError) -> Self {
40 match error {39 match error {
41- quinn::ConnectionError::TimedOut => Self::Timeout,40+ quinn::ConnectionError::TimedOut => Self::Unreachable,
42 quinn::ConnectionError::ConnectionClosed(close) => {41 quinn::ConnectionError::ConnectionClosed(close) => {
43 Self::by_code(u64::from(close.error_code))42 Self::by_code(u64::from(close.error_code))
44 }43 }
@@ -116,19 +115,12 @@ impl From<quinn::ClosedStream> for Fail {
116 }115 }
117 }116 }
118 117
119-impl From<quinn::ConnectError> for Fail {
120- fn from(_: quinn::ConnectError) -> Self {
121- Self::Link(LinkError::Unreachable)
122- }
123-}
124-
125 impl From<FrameError> for Fail {118 impl From<FrameError> for Fail {
126 fn from(error: FrameError) -> Self {119 fn from(error: FrameError) -> Self {
127 match error {120 match error {
128 FrameError::Connection(error) => error.into(),121 FrameError::Connection(error) => error.into(),
129 FrameError::Write(error) => error.into(),122 FrameError::Write(error) => error.into(),
130- FrameError::Read(quinn::ReadExactError::ReadError(error)) => error.into(),123+ FrameError::Read(error) => error.into(),
131- FrameError::Read(quinn::ReadExactError::FinishedEarly(_)) => Self::Protocol,
132 FrameError::Closed(error) => error.into(),124 FrameError::Closed(error) => error.into(),
133 FrameError::TooLarge { .. } | FrameError::Decode(_) => Self::Protocol,125 FrameError::TooLarge { .. } | FrameError::Decode(_) => Self::Protocol,
134 }126 }
crates/client/src/net/fetch.rsmodified+6 -3
@@ -1,4 +1,7 @@
1-use std::{collections::HashMap, sync::Mutex};1+use std::{
2+ collections::HashMap,
3+ sync::{Arc, Mutex},
4+};
2 5
3 use common::open::Blob;6 use common::open::Blob;
4 use tokio::sync::{Semaphore, SemaphorePermit, oneshot};7 use tokio::sync::{Semaphore, SemaphorePermit, oneshot};
@@ -7,7 +10,7 @@ use super::{Fail, link};
7 10
8 const PARALLEL_FETCHES: usize = 6;11 const PARALLEL_FETCHES: usize = 6;
9 12
10-type Waiter = oneshot::Sender<Result<std::sync::Arc<Vec<u8>>, Fail>>;13+type Waiter = oneshot::Sender<Result<Arc<Vec<u8>>, Fail>>;
11 14
12 pub(super) struct Fetches {15 pub(super) struct Fetches {
13 permits: Semaphore,16 permits: Semaphore,
@@ -49,7 +52,7 @@ impl Fetches {
49 let _permit = self.permit().await;52 let _permit = self.permit().await;
50 link::download(connection, &blob).await53 link::download(connection, &blob).await
51 }54 }
52- .map(std::sync::Arc::new);55+ .map(Arc::new);
53 let senders = self56 let senders = self
54 .waiting57 .waiting
55 .lock()58 .lock()
crates/client/src/net/link.rsmodified+70 -107
@@ -4,26 +4,26 @@ use common::{
4 call::Call,4 call::Call,
5 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},5 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},
6 error::Error,6 error::Error,
7- frame::{self, DOWN_MAX, Sending, UP_MAX},7+ frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX},
8 model::{Attachment, User},8 model::{Attachment, User},
9 open::{Blob, Open, Upload},9 open::{Blob, Open, Upload},
10 session::{Hello, Welcome},10 session::{Hello, Welcome},
11- transport::{Close, alpn, transport},11+ transport::{ALPN, Close, transport},
12 validate::{validate_attachment_name, validate_attachment_size},12 validate::{validate_attachment_name, validate_attachment_size},
13 };13 };
14-use quinn::Endpoint;14+use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls};
15 #[cfg(debug_assertions)]15 #[cfg(debug_assertions)]
16-use quinn::{16+use quinn::rustls::{
17- crypto::rustls::QuicClientConfig,17+ DigitallySignedStruct, SignatureScheme,
18- rustls::{18+ client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
19- self, DigitallySignedStruct, SignatureScheme,19+ pki_types::{CertificateDer, ServerName, UnixTime},
20- client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
21- pki_types::{CertificateDer, ServerName, UnixTime},
22- },
23 };20 };
24 #[cfg(debug_assertions)]21 #[cfg(debug_assertions)]
25 use rustls_platform_verifier as _;22 use rustls_platform_verifier as _;
26-use tokio::sync::{mpsc, oneshot};23+use tokio::{
24+ io::AsyncReadExt,
25+ sync::{mpsc, oneshot},
26+};
27 use tracing::{info, warn};27 use tracing::{info, warn};
28 28
29 use crate::ClientConfig;29 use crate::ClientConfig;
@@ -95,14 +95,15 @@ impl Endpoints {
95 }95 }
96 }96 }
97 97
98-fn backoff(attempt: u32) -> Duration {98+async fn backoff(attempt: &mut u32) {
99- let base = (BACKOFF_BASE_MILLIS << attempt.min(10)).min(BACKOFF_CAP_MILLIS);99+ let base = (BACKOFF_BASE_MILLIS << (*attempt).min(10)).min(BACKOFF_CAP_MILLIS);
100 let nanos = std::time::SystemTime::now()100 let nanos = std::time::SystemTime::now()
101 .duration_since(std::time::UNIX_EPOCH)101 .duration_since(std::time::UNIX_EPOCH)
102 .map_or(0, |elapsed| elapsed.subsec_nanos() as u64);102 .map_or(0, |elapsed| elapsed.subsec_nanos() as u64);
103 let jitter = base * (80 + nanos % 41) / 100;103 let jitter = base * (80 + nanos % 41) / 100;
104 104
105- Duration::from_millis(jitter)105+ tokio::time::sleep(Duration::from_millis(jitter)).await;
106+ *attempt += 1;
106 }107 }
107 108
108 async fn connect(109 async fn connect(
@@ -206,91 +207,61 @@ impl ServerCertVerifier for AcceptAnyCertificate {
206 }207 }
207 }208 }
208 209
209-#[cfg(debug_assertions)]210+fn config() -> Result<quinn::ClientConfig, LinkError> {
210-fn accept_any_client_config() -> Result<quinn::ClientConfig, LinkError> {
211 let provider = Arc::new(rustls::crypto::ring::default_provider());211 let provider = Arc::new(rustls::crypto::ring::default_provider());
212- let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone())212+ #[cfg(debug_assertions)]
213+ let verifier = Arc::new(AcceptAnyCertificate {
214+ provider: provider.clone(),
215+ });
216+ #[cfg(not(debug_assertions))]
217+ let verifier =
218+ Arc::new(rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?);
219+
220+ let mut tls = rustls::ClientConfig::builder_with_provider(provider)
213 .with_protocol_versions(&[&rustls::version::TLS13])221 .with_protocol_versions(&[&rustls::version::TLS13])
214 .map_err(tls_error)?222 .map_err(tls_error)?
215 .dangerous()223 .dangerous()
216- .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider }))224+ .with_custom_certificate_verifier(verifier)
217 .with_no_client_auth();225 .with_no_client_auth();
218- tls.alpn_protocols = vec![alpn()];226+ tls.alpn_protocols = vec![ALPN.to_vec()];
219 227
220 let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?;228 let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?;
229+ let mut client_config = quinn::ClientConfig::new(Arc::new(crypto));
230+ client_config.transport_config(Arc::new(transport()));
221 231
222- Ok(quinn::ClientConfig::new(Arc::new(crypto)))232+ Ok(client_config)
223-}
224-
225-#[cfg(not(debug_assertions))]
226-fn platform_client_config() -> Result<quinn::ClientConfig, LinkError> {
227- let provider = Arc::new(quinn::rustls::crypto::ring::default_provider());
228- let verifier = rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?;
229- let mut tls = quinn::rustls::ClientConfig::builder_with_provider(provider)
230- .with_protocol_versions(&[&quinn::rustls::version::TLS13])
231- .map_err(tls_error)?
232- .dangerous()
233- .with_custom_certificate_verifier(Arc::new(verifier))
234- .with_no_client_auth();
235- tls.alpn_protocols = vec![alpn()];
236-
237- let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(tls_error)?;
238-
239- Ok(quinn::ClientConfig::new(Arc::new(crypto)))
240 }233 }
241 234
242-fn config() -> Result<quinn::ClientConfig, LinkError> {235+async fn exchange<R: DecodeOwned>(
243- #[cfg(debug_assertions)]236+ connection: &quinn::Connection,
244- let mut client_config = accept_any_client_config()?;237+ request: &impl Encode,
245-238+) -> Result<(R, quinn::RecvStream), Fail> {
246- #[cfg(not(debug_assertions))]239+ let (send_stream, mut receive_stream) = connection.open_bi().await?;
247- let mut client_config = platform_client_config()?;240+ let mut send_stream = Sending::new(send_stream);
241+ frame::write(&mut send_stream, request, UP_MAX).await?;
242+ send_stream.finish()?;
248 243
249- client_config.transport_config(Arc::new(transport()));244+ let reply = frame::read::<Result<R, Error>>(&mut receive_stream, DOWN_MAX).await??;
250 245
251- Ok(client_config)246+ Ok((reply, receive_stream))
252 }247 }
253 248
254 pub(super) async fn call<C: Call>(249 pub(super) async fn call<C: Call>(
255 connection: &quinn::Connection,250 connection: &quinn::Connection,
256 call: C,251 call: C,
257 ) -> Result<C::Reply, Fail> {252 ) -> Result<C::Reply, Fail> {
258- let (send_stream, mut receive_stream) = connection.open_bi().await?;253+ Ok(exchange(connection, &Open::Call(call.into_request()))
259- let mut send_stream = Sending::new(send_stream);254+ .await?
260- frame::write(&mut send_stream, &Open::Call(call.into_request()), UP_MAX).await?;255+ .0)
261- send_stream.finish()?;
262-
263- Ok(frame::read::<Result<C::Reply, Error>>(&mut receive_stream, DOWN_MAX).await??)
264 }256 }
265 257
266 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {258 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {
267- let (send_stream, mut receive_stream) = connection.open_bi().await?;
268- let mut send_stream = Sending::new(send_stream);
269 let hello = Hello {259 let hello = Hello {
270 token,260 token,
271 device: device_name(),261 device: device_name(),
272 };262 };
273- frame::write(&mut send_stream, &hello, UP_MAX).await?;
274- send_stream.finish()?;
275 263
276- Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)264+ Ok(exchange(connection, &hello).await?.0)
277-}
278-
279-pub(super) async fn send_body(
280- send_stream: &mut quinn::SendStream,
281- file: &mut tokio::fs::File,
282-) -> Result<(), Fail> {
283- use tokio::io::AsyncReadExt;
284-
285- let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
286- loop {
287- let read = file.read(&mut buffer).await?;
288- if read == 0 {
289- return Ok(());
290- }
291-
292- send_stream.write_all(&buffer[..read]).await?;
293- }
294 }265 }
295 266
296 pub(super) async fn upload(267 pub(super) async fn upload(
@@ -321,7 +292,16 @@ pub(super) async fn upload(
321 frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?;292 frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?;
322 293
323 let write = async move {294 let write = async move {
324- send_body(send_stream.get(), &mut file).await?;295+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
296+ loop {
297+ let read = file.read(&mut buffer).await?;
298+ if read == 0 {
299+ break;
300+ }
301+
302+ send_stream.get().write_all(&buffer[..read]).await?;
303+ }
304+
325 Ok(send_stream.finish()?)305 Ok(send_stream.finish()?)
326 };306 };
327 let read = frame::read::<Result<Attachment, Error>>(&mut receive_stream, DOWN_MAX);307 let read = frame::read::<Result<Attachment, Error>>(&mut receive_stream, DOWN_MAX);
@@ -334,31 +314,15 @@ pub(super) async fn upload(
334 }314 }
335 }315 }
336 316
337-async fn open_fetch(
338- connection: &quinn::Connection,
339- blob: &Blob,
340-) -> Result<(quinn::RecvStream, u64), Fail> {
341- let (send_stream, mut receive_stream) = connection.open_bi().await?;
342- let mut send_stream = Sending::new(send_stream);
343- frame::write(&mut send_stream, &Open::Fetch(blob.clone()), UP_MAX).await?;
344- send_stream.finish()?;
345-
346- let length = frame::read::<Result<u64, Error>>(&mut receive_stream, DOWN_MAX).await??;
347-
348- Ok((receive_stream, length))
349-}
350-
351 pub(super) async fn backup_download(317 pub(super) async fn backup_download(
352 connection: &quinn::Connection,318 connection: &quinn::Connection,
353 name: &str,319 name: &str,
354 path: &Path,320 path: &Path,
355 ) -> Result<(), Fail> {321 ) -> Result<(), Fail> {
356- let (mut receive_stream, length) =322+ let (length, mut receive_stream) =
357- open_fetch(connection, &Blob::Backup(name.to_string())).await?;323+ exchange::<u64>(connection, &Open::Fetch(Blob::Backup(name.to_string()))).await?;
358 324
359- let mut part = path.as_os_str().to_owned();325+ let part = path.with_added_extension("part");
360- part.push(".part");
361- let part = std::path::PathBuf::from(part);
362 326
363 let copied = async {327 let copied = async {
364 let mut file = tokio::fs::File::create(&part).await?;328 let mut file = tokio::fs::File::create(&part).await?;
@@ -379,7 +343,8 @@ pub(super) async fn backup_download(
379 }343 }
380 344
381 pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Result<Vec<u8>, Fail> {345 pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Result<Vec<u8>, Fail> {
382- let (mut receive_stream, length) = open_fetch(connection, blob).await?;346+ let (length, mut receive_stream) =
347+ exchange::<u64>(connection, &Open::Fetch(blob.clone())).await?;
383 348
384 if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {349 if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
385 return Err(Fail::Protocol);350 return Err(Fail::Protocol);
@@ -433,8 +398,7 @@ async fn actor(
433 return;398 return;
434 }399 }
435 400
436- tokio::time::sleep(backoff(attempt)).await;401+ backoff(&mut attempt).await;
437- attempt += 1;
438 }402 }
439 };403 };
440 };404 };
@@ -464,16 +428,16 @@ async fn actor(
464 }428 }
465 Err(error) => {429 Err(error) => {
466 warn!("hello failed: {error}");430 warn!("hello failed: {error}");
467- if let Some(reason) = connection.close_reason() {431+ if connection.close_reason().map(LinkError::from)
468- let event = LinkError::from(reason);432+ == Some(LinkError::Closed(Close::Banned))
469- if event == LinkError::Closed(Close::Banned) {433+ {
470- let _ = event_sender.send(NetworkEvent::Disconnected(event)).await;434+ let _ = event_sender
471- while command_receiver.recv().await.is_some() {}435+ .send(NetworkEvent::Disconnected(LinkError::Closed(Close::Banned)))
472- return;436+ .await;
473- }437+ while command_receiver.recv().await.is_some() {}
438+ return;
474 }439 }
475- tokio::time::sleep(backoff(attempt)).await;440+ backoff(&mut attempt).await;
476- attempt += 1;
477 continue 'session;441 continue 'session;
478 }442 }
479 };443 };
@@ -548,8 +512,7 @@ async fn actor(
548 return;512 return;
549 }513 }
550 514
551- tokio::time::sleep(backoff(attempt)).await;515+ backoff(&mut attempt).await;
552- attempt += 1;
553 break;516 break;
554 }517 }
555 }518 }
crates/client/src/net/media.rsmodified+66 -120
@@ -49,6 +49,7 @@ struct Want {
49 deafened: bool,49 deafened: bool,
50 }50 }
51 51
52+#[derive(Default)]
52 struct Inner {53 struct Inner {
53 epoch: u64,54 epoch: u64,
54 connection: Option<Connection>,55 connection: Option<Connection>,
@@ -70,6 +71,12 @@ impl Inner {
70 self.sharing.clear();71 self.sharing.clear();
71 }72 }
72 73
74+ fn end_voice(&mut self) {
75+ self.drop_calls();
76+ self.want_voice = None;
77+ self.watching.clear();
78+ }
79+
73 fn install_voice(&mut self, mut voice: Voice, want: Want) {80 fn install_voice(&mut self, mut voice: Voice, want: Want) {
74 voice.apply(&want.settings);81 voice.apply(&want.settings);
75 voice.set_muted(want.muted);82 voice.set_muted(want.muted);
@@ -78,6 +85,16 @@ impl Inner {
78 self.voice = Some(voice);85 self.voice = Some(voice);
79 self.want_voice = Some(want);86 self.want_voice = Some(want);
80 }87 }
88+
89+ fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> {
90+ self.watching
91+ .iter()
92+ .map(|((user_id, kind), watching)| {
93+ let request = watch_request(user_id.clone(), *kind, watching.wanted());
94+ ((user_id.clone(), *kind), request)
95+ })
96+ .collect()
97+ }
81 }98 }
82 99
83 pub(super) struct Media {100 pub(super) struct Media {
@@ -89,16 +106,7 @@ impl Media {
89 pub(super) fn new(handle: Handle) -> Arc<Media> {106 pub(super) fn new(handle: Handle) -> Arc<Media> {
90 let media = Arc::new(Media {107 let media = Arc::new(Media {
91 handle: handle.clone(),108 handle: handle.clone(),
92- inner: Mutex::new(Inner {109+ inner: Mutex::default(),
93- epoch: 0,
94- connection: None,
95- want_voice: None,
96- voice: None,
97- joining: 0,
98- mic_test: None,
99- sharing: HashMap::new(),
100- watching: HashMap::new(),
101- }),
102 });110 });
103 handle.spawn(tick_loop(media.clone()));111 handle.spawn(tick_loop(media.clone()));
104 112
@@ -159,9 +167,7 @@ impl Media {
159 pub(super) fn reset(&self) {167 pub(super) fn reset(&self) {
160 let mut inner = self.lock();168 let mut inner = self.lock();
161 inner.connection = None;169 inner.connection = None;
162- inner.drop_calls();170+ inner.end_voice();
163- inner.want_voice = None;
164- inner.watching.clear();
165 }171 }
166 172
167 async fn rejoin(173 async fn rejoin(
@@ -259,9 +265,7 @@ impl Media {
259 }265 }
260 }266 }
261 Down::VoiceEnded => {267 Down::VoiceEnded => {
262- inner.drop_calls();268+ inner.end_voice();
263- inner.want_voice = None;
264- inner.watching.clear();
265 return true;269 return true;
266 }270 }
267 }271 }
@@ -288,7 +292,7 @@ impl Media {
288 }292 }
289 293
290 async fn join_voice(294 async fn join_voice(
291- &self,295+ self: Arc<Self>,
292 community_id: String,296 community_id: String,
293 settings: VoiceSettings,297 settings: VoiceSettings,
294 ) -> Result<Vec<String>, Fail> {298 ) -> Result<Vec<String>, Fail> {
@@ -322,19 +326,17 @@ impl Media {
322 Ok(participants)326 Ok(participants)
323 }327 }
324 328
325- async fn leave_voice(&self) -> Result<(), Fail> {329+ async fn leave_voice(self: Arc<Self>) -> Result<(), Fail> {
326 let connection = {330 let connection = {
327 let mut inner = self.lock();331 let mut inner = self.lock();
328- inner.drop_calls();332+ inner.end_voice();
329- inner.want_voice = None;
330- inner.watching.clear();
331 inner.connection.clone().ok_or(Fail::Offline)?333 inner.connection.clone().ok_or(Fail::Offline)?
332 };334 };
333 335
334 call(&connection, LeaveVoice).await336 call(&connection, LeaveVoice).await
335 }337 }
336 338
337- async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {339+ async fn start_share(self: Arc<Self>, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {
338 let (connection, epoch) = self.current_wait().await?;340 let (connection, epoch) = self.current_wait().await?;
339 let top = match kind {341 let top = match kind {
340 Kind::Screen => settings.top,342 Kind::Screen => settings.top,
@@ -366,11 +368,12 @@ impl Media {
366 result368 result
367 }369 }
368 370
369- async fn update_share(&self, settings: ShareSettings) -> Result<(), Fail> {371+ async fn update_share(self: Arc<Self>, settings: ShareSettings) -> Result<(), Fail> {
372+ let kind = Kind::Screen;
370 let (connection, _) = self.current_wait().await?;373 let (connection, _) = self.current_wait().await?;
371 let source = {374 let source = {
372 let mut inner = self.lock();375 let mut inner = self.lock();
373- let Some(sharing) = inner.sharing.get_mut(&Kind::Screen) else {376+ let Some(sharing) = inner.sharing.get_mut(&kind) else {
374 return Ok(());377 return Ok(());
375 };378 };
376 sharing379 sharing
@@ -383,17 +386,10 @@ impl Media {
383 .map_err(Fail::Io)?386 .map_err(Fail::Io)?
384 };387 };
385 388
386- call(389+ call(&connection, StartShare { kind, source }).await
387- &connection,
388- StartShare {
389- kind: Kind::Screen,
390- source,
391- },
392- )
393- .await
394 }390 }
395 391
396- async fn stop_share(&self, kind: Kind) -> Result<(), Fail> {392+ async fn stop_share(self: Arc<Self>, kind: Kind) -> Result<(), Fail> {
397 self.lock().sharing.remove(&kind);393 self.lock().sharing.remove(&kind);
398 let (connection, _) = self.current_wait().await?;394 let (connection, _) = self.current_wait().await?;
399 395
@@ -401,20 +397,12 @@ impl Media {
401 }397 }
402 }398 }
403 399
404-impl Inner {400+fn watch_request(user_id: String, kind: Kind, quality: Quality) -> WatchShare {
405- fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> {401+ WatchShare {
406- self.watching402+ user_id,
407- .iter()403+ kind,
408- .map(|((user_id, kind), watching)| {404+ quality,
409- let request = WatchShare {405+ decode: capabilities().decode.clone(),
410- user_id: user_id.clone(),
411- kind: *kind,
412- quality: watching.wanted(),
413- decode: capabilities().decode.clone(),
414- };
415- ((user_id.clone(), *kind), request)
416- })
417- .collect()
418 }406 }
419 }407 }
420 408
@@ -442,52 +430,31 @@ async fn tick_loop(media: Arc<Media>) {
442 let mut ticker = tokio::time::interval(TICK);430 let mut ticker = tokio::time::interval(TICK);
443 loop {431 loop {
444 ticker.tick().await;432 ticker.tick().await;
445- let (connection, requests) = {433+ let mut inner = media.lock();
446- let mut inner = media.lock();434+ let connection = inner.connection.clone();
447- (inner.connection.clone(), watch_ticks(&mut inner.watching))435+ for ((user_id, kind), watching) in inner.watching.iter_mut() {
448- };436+ for tick in watching.tick() {
449- let Some(connection) = connection else {437+ let Some(connection) = connection.clone() else {
450- continue;438+ continue;
451- };439+ };
452- for request in requests {440+ match tick {
453- match request {441+ Tick::Quality(quality) => tokio::spawn(send_quietly(
454- Ping::Watch(request) => tokio::spawn(send_quietly(connection.clone(), request)),442+ connection,
455- Ping::Keyframe(request) => tokio::spawn(send_quietly(connection.clone(), request)),443+ watch_request(user_id.clone(), *kind, quality),
456- };444+ )),
445+ Tick::Keyframe => tokio::spawn(send_quietly(
446+ connection,
447+ RequestKeyframe {
448+ user_id: user_id.clone(),
449+ kind: *kind,
450+ },
451+ )),
452+ };
453+ }
457 }454 }
458 }455 }
459 }456 }
460 457
461-enum Ping {
462- Watch(WatchShare),
463- Keyframe(RequestKeyframe),
464-}
465-
466-fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<Ping> {
467- watching
468- .iter_mut()
469- .flat_map(|((user_id, kind), watching)| {
470- let (user_id, kind) = (user_id.clone(), *kind);
471- watching
472- .tick()
473- .into_iter()
474- .map(|tick| match tick {
475- Tick::Quality(quality) => Ping::Watch(WatchShare {
476- user_id: user_id.clone(),
477- kind,
478- quality,
479- decode: capabilities().decode.clone(),
480- }),
481- Tick::Keyframe => Ping::Keyframe(RequestKeyframe {
482- user_id: user_id.clone(),
483- kind,
484- }),
485- })
486- .collect::<Vec<_>>()
487- })
488- .collect()
489-}
490-
491 impl NetworkHandle {458 impl NetworkHandle {
492 fn media(&self) -> &Arc<Media> {459 fn media(&self) -> &Arc<Media> {
493 &self.shared.media460 &self.shared.media
@@ -498,21 +465,17 @@ impl NetworkHandle {
498 community_id: &str,465 community_id: &str,
499 settings: &VoiceSettings,466 settings: &VoiceSettings,
500 ) -> Result<Vec<String>, Fail> {467 ) -> Result<Vec<String>, Fail> {
501- let media = self.media().clone();
502- let community_id = community_id.to_string();
503- let settings = settings.clone();
504-
505 self.media()468 self.media()
506- .run(async move { media.join_voice(community_id, settings).await })469+ .run(
470+ self.media()
471+ .clone()
472+ .join_voice(community_id.to_string(), settings.clone()),
473+ )
507 .await474 .await
508 }475 }
509 476
510 pub async fn leave_voice(&self) -> Result<(), Fail> {477 pub async fn leave_voice(&self) -> Result<(), Fail> {
511- let media = self.media().clone();478+ self.media().run(self.media().clone().leave_voice()).await
512-
513- self.media()
514- .run(async move { media.leave_voice().await })
515- .await
516 }479 }
517 480
518 pub fn set_voice_settings(&self, settings: &VoiceSettings) {481 pub fn set_voice_settings(&self, settings: &VoiceSettings) {
@@ -618,20 +581,14 @@ impl NetworkHandle {
618 }581 }
619 582
620 async fn start(&self, kind: Kind, settings: &ShareSettings) -> Result<(), Fail> {583 async fn start(&self, kind: Kind, settings: &ShareSettings) -> Result<(), Fail> {
621- let media = self.media().clone();
622- let settings = settings.clone();
623-
624 self.media()584 self.media()
625- .run(async move { media.start_share(kind, settings).await })585+ .run(self.media().clone().start_share(kind, settings.clone()))
626 .await586 .await
627 }587 }
628 588
629 pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> {589 pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> {
630- let media = self.media().clone();
631- let settings = settings.clone();
632-
633 self.media()590 self.media()
634- .run(async move { media.update_share(settings).await })591+ .run(self.media().clone().update_share(settings.clone()))
635 .await592 .await
636 }593 }
637 594
@@ -644,10 +601,8 @@ impl NetworkHandle {
644 }601 }
645 602
646 async fn stop(&self, kind: Kind) -> Result<(), Fail> {603 async fn stop(&self, kind: Kind) -> Result<(), Fail> {
647- let media = self.media().clone();
648-
649 self.media()604 self.media()
650- .run(async move { media.stop_share(kind).await })605+ .run(self.media().clone().stop_share(kind))
651 .await606 .await
652 }607 }
653 608
@@ -697,16 +652,7 @@ impl NetworkHandle {
697 }652 }
698 inner.watching.insert(key.clone(), watching);653 inner.watching.insert(key.clone(), watching);
699 }654 }
700- let result = call(655+ let result = call(&connection, watch_request(key.0.clone(), kind, quality)).await;
701- &connection,
702- WatchShare {
703- user_id: key.0.clone(),
704- kind,
705- quality,
706- decode: capabilities().decode.clone(),
707- },
708- )
709- .await;
710 if result.is_err() {656 if result.is_err() {
711 media.lock().watching.remove(&key);657 media.lock().watching.remove(&key);
712 }658 }
crates/client/src/net/mod.rsmodified+5 -774
@@ -1,38 +1,10 @@
1 use std::{path::PathBuf, sync::Arc};1 use std::{path::PathBuf, sync::Arc};
2 2
3 use common::{3 use common::{
4- call::{4+ call::{Call, GetStorageUsage, Login, Logout, Register, Session},
5- AcceptFriend, AcceptInvitation, AddFriend, BanMember, BanUser, Call, ClearProfile,
6- ClosePoll, CreateBackup, CreateCommunity, CreateInviteCode, CreateMessage, CreatePoll,
7- CreateUser, DeclineCall, DeclineInvitation, DeleteAttachment, DeleteBackup,
8- DeleteCommunity, DeleteInviteCode, DeleteMessage, DeleteUser, FindUser, ForwardMessages,
9- GetAvatar, GetCommunity, GetDailyStats, GetOverview, GetSettings, GetStorageUsage, GetUser,
10- HandleReport, Invite, Kick, KickFromVoice, LeaveCommunity, ListAdminLogs,
11- ListAllCommunities, ListAttachments, ListBackups, ListBans, ListCommunities, ListFriends,
12- ListInvitations, ListInviteCodes, ListLogs, ListMembers, ListMessages, ListPins,
13- ListPresences, ListReports, ListServerBans, ListSessions, ListUnreads, ListUsers,
14- ListVoiceParticipants, ListVoiceRooms, Login, Logout, MarkRead, OpenDirect, OpenNotes, Pin,
15- PurgeUser, React, Register, RemoveAvatar, RemoveFriend, RemoveServerBan, RenameUser,
16- ReportMessage, ReportUser, ResetPassword, RevokeSession, RevokeSessions, SearchCommunity,
17- SearchMessages, ServerMute, Session, SetCommunityVoice, SetGhost, SetRank, SetRole,
18- SuspendUser, TimeoutUser, TransferOwnership, Typing, Unban, UpdateAvatar, UpdateCommunity,
19- UpdateCommunityAvatar, UpdateMessage, UpdatePresence, UpdateServerSettings, UpdateStatus,
20- UpdateUser, Vote, WatchCommunity,
21- },
22- constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
23 event::Event,5 event::Event,
24- model::{6+ model::{Attachment, CommunityUsage, Usage, User},
25- Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
26- CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
27- Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
28- ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
29- },
30 open::Blob,7 open::Blob,
31- validate::{
32- validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
33- validate_password, validate_poll, validate_reason, validate_server_settings,
34- validate_status, validate_username,
35- },
36 };8 };
37 use tokio::sync::{mpsc, oneshot};9 use tokio::sync::{mpsc, oneshot};
38 10
@@ -128,7 +100,9 @@ impl NetworkHandle {
128 response.await.map_err(|_| Fail::Offline)?100 response.await.map_err(|_| Fail::Offline)?
129 }101 }
130 102
131- async fn call<C: Call>(&self, call: C) -> Result<C::Reply, Fail> {103+ pub async fn call<C: Call>(&self, call: C) -> Result<C::Reply, Fail> {
104+ call.validate()?;
105+
132 self.ask(|reply| {106 self.ask(|reply| {
133 Command::Call(Box::new(move |connection| {107 Command::Call(Box::new(move |connection| {
134 link::answer(reply, async move { link::call(&connection, call).await });108 link::answer(reply, async move { link::call(&connection, call).await });
@@ -147,31 +121,6 @@ impl NetworkHandle {
147 Ok((session.user, session.token))121 Ok((session.user, session.token))
148 }122 }
149 123
150- pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {
151- self.call(ListSessions {
152- user_id: user_id.to_string(),
153- })
154- .await
155- }
156-
157- pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> {
158- self.call(RevokeSession {
159- user_id: user_id.to_string(),
160- session_id: session_id.to_string(),
161- })
162- .await
163- }
164-
165- pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Fail> {
166- validate_username(username)?;
167-
168- self.call(RenameUser {
169- user_id: user_id.to_string(),
170- username: username.to_string(),
171- })
172- .await
173- }
174-
175 pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {124 pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {
176 let user = self125 let user = self
177 .switch(Some(token.to_string()))126 .switch(Some(token.to_string()))
@@ -191,9 +140,6 @@ impl NetworkHandle {
191 password: &str,140 password: &str,
192 invite: Option<&str>,141 invite: Option<&str>,
193 ) -> Result<(User, String), Fail> {142 ) -> Result<(User, String), Fail> {
194- validate_username(username)?;
195- validate_password(password)?;
196-
197 let session = self143 let session = self
198 .call(Register {144 .call(Register {
199 username: username.to_string(),145 username: username.to_string(),
@@ -206,8 +152,6 @@ impl NetworkHandle {
206 }152 }
207 153
208 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {154 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {
209- validate_password(password)?;
210-
211 let session = self155 let session = self
212 .call(Login {156 .call(Login {
213 username: username.to_string(),157 username: username.to_string(),
@@ -224,596 +168,12 @@ impl NetworkHandle {
224 result168 result
225 }169 }
226 170
227- pub async fn update_user(&self, username: &str) -> Result<User, Fail> {
228- validate_username(username)?;
229-
230- self.call(UpdateUser {
231- username: username.to_string(),
232- })
233- .await
234- }
235-
236- pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {
237- self.call(DeleteUser {
238- user_id: user_id.to_string(),
239- })
240- .await
241- }
242-
243- pub async fn users(&self) -> Result<Vec<Account>, Fail> {
244- self.call(ListUsers).await
245- }
246-
247- pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {
248- self.call(SuspendUser {
249- user_id: user_id.to_string(),
250- suspended,
251- })
252- .await
253- }
254-
255- pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {
256- self.call(TimeoutUser {
257- user_id: user_id.to_string(),
258- minutes,
259- })
260- .await
261- }
262-
263- pub async fn ban_user(
264- &self,
265- user_id: &str,
266- reason: Option<&str>,
267- scope: BanScope,
268- ) -> Result<(), Fail> {
269- validate_reason(reason)?;
270-
271- self.call(BanUser {
272- user_id: user_id.to_string(),
273- reason: reason.map(str::to_string),
274- scope,
275- })
276- .await
277- }
278-
279- pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {
280- self.call(ListServerBans).await
281- }
282-
283- pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {
284- self.call(RemoveServerBan { id: id.to_string() }).await
285- }
286-
287- pub async fn create_invite_code(
288- &self,
289- uses: u32,
290- hours: Option<u32>,
291- ) -> Result<InviteCode, Fail> {
292- self.call(CreateInviteCode { uses, hours }).await
293- }
294-
295- pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {
296- self.call(ListInviteCodes).await
297- }
298-
299- pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {
300- self.call(DeleteInviteCode {
301- code: code.to_string(),
302- })
303- .await
304- }
305-
306- pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {
307- self.call(RevokeSessions {
308- user_id: user_id.to_string(),
309- })
310- .await
311- }
312-
313- pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {
314- validate_password(password)?;
315-
316- self.call(ResetPassword {
317- user_id: user_id.to_string(),
318- password: password.to_string(),
319- })
320- .await
321- }
322-
323- pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {
324- self.call(ClearProfile {
325- user_id: user_id.to_string(),
326- })
327- .await
328- }
329-
330- pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {
331- self.call(SetRole {
332- user_id: user_id.to_string(),
333- role,
334- })
335- .await
336- }
337-
338- pub async fn admin_logs(
339- &self,
340- actor_id: Option<String>,
341- target_id: Option<String>,
342- action: Option<String>,
343- after_ms: Option<u64>,
344- before_ms: Option<u64>,
345- ) -> Result<Vec<AdminLogEntry>, Fail> {
346- self.call(ListAdminLogs {
347- actor_id,
348- target_id,
349- action,
350- after_ms,
351- before_ms,
352- })
353- .await
354- }
355-
356- pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {
357- self.call(GetDailyStats { days }).await
358- }
359-
360- pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {
361- self.call(GetSettings).await
362- }
363-
364- pub async fn update_server_settings(
365- &self,
366- settings: ServerSettings,
367- ) -> Result<ServerSettings, Fail> {
368- validate_server_settings(&settings)?;
369-
370- self.call(UpdateServerSettings { settings }).await
371- }
372-
373- pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Fail> {
374- validate_username(username)?;
375- validate_password(password)?;
376-
377- self.call(CreateUser {
378- username: username.to_string(),
379- password: password.to_string(),
380- })
381- .await
382- }
383-
384- pub async fn overview(&self) -> Result<Overview, Fail> {
385- self.call(GetOverview).await
386- }
387-
388- pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {
389- self.call(ListAllCommunities).await
390- }
391-
392- pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
393- self.call(TransferOwnership {
394- community_id: community_id.to_string(),
395- user_id: user_id.to_string(),
396- })
397- .await
398- }
399-
400- pub async fn read_user(&self, user_id: &str) -> Result<User, Fail> {
401- self.call(GetUser {
402- user_id: user_id.to_string(),
403- })
404- .await
405- }
406-
407- pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {
408- validate_community_name(name)?;
409-
410- self.call(CreateCommunity {
411- name: name.to_string(),
412- })
413- .await
414- }
415-
416- pub async fn update_community(
417- &self,
418- community_id: &str,
419- name: &str,
420- ) -> Result<Community, Fail> {
421- validate_community_name(name)?;
422-
423- self.call(UpdateCommunity {
424- community_id: community_id.to_string(),
425- name: name.to_string(),
426- })
427- .await
428- }
429-
430- pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {
431- self.call(DeleteCommunity {
432- community_id: community_id.to_string(),
433- })
434- .await
435- }
436-
437- pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {
438- self.call(LeaveCommunity {
439- community_id: community_id.to_string(),
440- })
441- .await
442- }
443-
444- pub async fn communities(&self) -> Result<Vec<Community>, Fail> {
445- self.call(ListCommunities).await
446- }
447-
448- pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {
449- self.call(ListMembers {
450- community_id: community_id.to_string(),
451- })
452- .await
453- }
454-
455- pub async fn kick(
456- &self,
457- community_id: &str,
458- user_id: &str,
459- reason: Option<&str>,
460- ) -> Result<(), Fail> {
461- validate_reason(reason)?;
462- self.call(Kick {
463- community_id: community_id.to_string(),
464- user_id: user_id.to_string(),
465- reason: reason.map(str::to_string),
466- })
467- .await
468- }
469-
470- pub async fn ban(
471- &self,
472- community_id: &str,
473- user_id: &str,
474- reason: Option<&str>,
475- ) -> Result<(), Fail> {
476- validate_reason(reason)?;
477- self.call(BanMember {
478- community_id: community_id.to_string(),
479- user_id: user_id.to_string(),
480- reason: reason.map(str::to_string),
481- })
482- .await
483- }
484-
485- pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
486- self.call(Unban {
487- community_id: community_id.to_string(),
488- user_id: user_id.to_string(),
489- })
490- .await
491- }
492-
493- pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {
494- self.call(ListBans {
495- community_id: community_id.to_string(),
496- })
497- .await
498- }
499-
500- pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {
501- self.call(ListLogs {
502- community_id: community_id.to_string(),
503- })
504- .await
505- }
506-
507- pub async fn set_rank(
508- &self,
509- community_id: &str,
510- user_id: &str,
511- rank: Rank,
512- ) -> Result<(), Fail> {
513- self.call(SetRank {
514- community_id: community_id.to_string(),
515- user_id: user_id.to_string(),
516- rank,
517- })
518- .await
519- }
520-
521- pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {
522- self.call(DeleteMessage {
523- message_id: message_id.to_string(),
524- })
525- .await
526- }
527-
528- pub async fn create_message(
529- &self,
530- community_id: &str,
531- body: &str,
532- attachments: Vec<String>,
533- reply_to: Option<String>,
534- ) -> Result<Message, Fail> {
535- validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
536-
537- self.call(CreateMessage {
538- community_id: community_id.to_string(),
539- body: body.to_string(),
540- attachments,
541- reply_to,
542- })
543- .await
544- }
545-
546- pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Fail> {
547- validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
548-
549- self.call(UpdateMessage {
550- message_id: message_id.to_string(),
551- body: body.to_string(),
552- })
553- .await
554- }
555-
556- pub async fn forward_messages(
557- &self,
558- message_ids: Vec<String>,
559- community_id: &str,
560- snippet: bool,
561- ) -> Result<Vec<Message>, Fail> {
562- validate_forward(message_ids.len())?;
563-
564- self.call(ForwardMessages {
565- message_ids,
566- community_id: community_id.to_string(),
567- snippet,
568- })
569- .await
570- }
571-
572- pub async fn find_user(&self, username: &str) -> Result<User, Fail> {
573- self.call(FindUser {
574- username: username.to_string(),
575- })
576- .await
577- }
578-
579- pub async fn open_notes(&self) -> Result<Community, Fail> {
580- self.call(OpenNotes).await
581- }
582-
583- pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {
584- self.call(OpenDirect {
585- user_id: user_id.to_string(),
586- })
587- .await
588- }
589-
590- pub async fn friends(&self) -> Result<Friends, Fail> {
591- self.call(ListFriends).await
592- }
593-
594- pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {
595- self.call(ListPresences).await
596- }
597-
598- pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> {
599- self.call(UpdatePresence { presence }).await
600- }
601-
602- pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {
603- self.call(AddFriend {
604- user_id: user_id.to_string(),
605- })
606- .await
607- }
608-
609- pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {
610- self.call(AcceptFriend {
611- user_id: user_id.to_string(),
612- })
613- .await
614- }
615-
616- pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {
617- self.call(RemoveFriend {
618- user_id: user_id.to_string(),
619- })
620- .await
621- }
622-
623- pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
624- self.call(Invite {
625- community_id: community_id.to_string(),
626- user_id: user_id.to_string(),
627- })
628- .await
629- }
630-
631- pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {
632- self.call(ListInvitations).await
633- }
634-
635- pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {
636- self.call(AcceptInvitation {
637- community_id: community_id.to_string(),
638- })
639- .await
640- }
641-
642- pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {
643- self.call(DeclineInvitation {
644- community_id: community_id.to_string(),
645- })
646- .await
647- }
648-
649- pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {
650- self.call(DeclineCall {
651- community_id: community_id.to_string(),
652- })
653- .await
654- }
655-
656- pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {
657- self.call(React {
658- message_id: message_id.to_string(),
659- emoji: emoji.to_string(),
660- })
661- .await
662- }
663-
664- pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {
665- self.call(Pin {
666- message_id: message_id.to_string(),
667- pinned,
668- })
669- .await
670- }
671-
672- pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {
673- self.call(ListPins {
674- community_id: community_id.to_string(),
675- })
676- .await
677- }
678-
679- pub async fn create_poll(
680- &self,
681- community_id: &str,
682- question: &str,
683- options: Vec<String>,
684- multiple: bool,
685- ) -> Result<Message, Fail> {
686- validate_poll(question, &options)?;
687-
688- self.call(CreatePoll {
689- community_id: community_id.to_string(),
690- question: question.to_string(),
691- options,
692- multiple,
693- })
694- .await
695- }
696-
697- pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {
698- self.call(Vote {
699- message_id: message_id.to_string(),
700- positions,
701- })
702- .await
703- }
704-
705- pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {
706- self.call(ClosePoll {
707- message_id: message_id.to_string(),
708- })
709- .await
710- }
711-
712- pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {
713- validate_reason(Some(reason))?;
714-
715- self.call(ReportMessage {
716- message_id: message_id.to_string(),
717- reason: reason.to_string(),
718- })
719- .await
720- }
721-
722- pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {
723- validate_reason(Some(reason))?;
724-
725- self.call(ReportUser {
726- user_id: user_id.to_string(),
727- reason: reason.to_string(),
728- })
729- .await
730- }
731-
732- pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {
733- self.call(ListReports { status }).await
734- }
735-
736- pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {
737- self.call(HandleReport {
738- report_id: report_id.to_string(),
739- status,
740- })
741- .await
742- }
743-
744- pub async fn search_messages(
745- &self,
746- text: Option<String>,
747- user_id: Option<String>,
748- community_id: Option<String>,
749- after_ms: Option<u64>,
750- before_ms: Option<u64>,
751- ) -> Result<Vec<MessageHit>, Fail> {
752- self.call(SearchMessages {
753- text,
754- user_id,
755- community_id,
756- after_ms,
757- before_ms,
758- })
759- .await
760- }
761-
762- pub async fn search_community(
763- &self,
764- community_id: String,
765- text: String,
766- ) -> Result<Vec<MessageHit>, Fail> {
767- self.call(SearchCommunity { community_id, text }).await
768- }
769-
770 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {171 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {
771 let usage = self.call(GetStorageUsage).await?;172 let usage = self.call(GetStorageUsage).await?;
772 173
773 Ok((usage.users, usage.communities))174 Ok((usage.users, usage.communities))
774 }175 }
775 176
776- pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {
777- self.call(CreateBackup).await
778- }
779-
780- pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {
781- self.call(ListBackups).await
782- }
783-
784- pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {
785- self.call(DeleteBackup {
786- name: name.to_string(),
787- })
788- .await
789- }
790-
791- pub async fn attachments(
792- &self,
793- user_id: Option<String>,
794- community_id: Option<String>,
795- ) -> Result<Vec<AttachmentInfo>, Fail> {
796- self.call(ListAttachments {
797- user_id,
798- community_id,
799- })
800- .await
801- }
802-
803- pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {
804- self.call(DeleteAttachment {
805- attachment_id: attachment_id.to_string(),
806- })
807- .await
808- }
809-
810- pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {
811- self.call(PurgeUser {
812- user_id: user_id.to_string(),
813- })
814- .await
815- }
816-
817 pub async fn upload_attachment(177 pub async fn upload_attachment(
818 &self,178 &self,
819 community_id: &str,179 community_id: &str,
@@ -851,133 +211,4 @@ impl NetworkHandle {
851 })211 })
852 .await212 .await
853 }213 }
854-
855- pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {
856- self.call(WatchCommunity {
857- community_id: community_id.map(str::to_string),
858- })
859- .await
860- }
861-
862- pub async fn read_messages(
863- &self,
864- community_id: &str,
865- before: Option<&str>,
866- ) -> Result<Vec<Message>, Fail> {
867- self.call(ListMessages {
868- community_id: community_id.to_string(),
869- before: before.map(str::to_string),
870- })
871- .await
872- }
873-
874- pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {
875- self.call(ListUnreads).await
876- }
877-
878- pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {
879- self.call(MarkRead {
880- community_id: community_id.to_string(),
881- message_id: message_id.to_string(),
882- })
883- .await
884- }
885-
886- pub async fn update_status(&self, status: &str) -> Result<User, Fail> {
887- validate_status(status)?;
888-
889- self.call(UpdateStatus {
890- status: status.to_string(),
891- })
892- .await
893- }
894-
895- pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Fail> {
896- validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?;
897-
898- self.call(UpdateAvatar { image: bytes }).await
899- }
900-
901- pub async fn update_community_avatar(
902- &self,
903- community_id: &str,
904- image: Option<Vec<u8>>,
905- ) -> Result<Community, Fail> {
906- if let Some(bytes) = &image {
907- validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
908- }
909-
910- self.call(UpdateCommunityAvatar {
911- community_id: community_id.to_string(),
912- image,
913- })
914- .await
915- }
916-
917- pub async fn remove_avatar(&self) -> Result<User, Fail> {
918- self.call(RemoveAvatar).await
919- }
920-
921- pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Fail> {
922- self.call(GetAvatar {
923- avatar_id: avatar_id.to_string(),
924- })
925- .await
926- }
927-
928- pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {
929- self.call(Typing {
930- community_id: community_id.to_string(),
931- })
932- .await
933- }
934-
935- pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {
936- self.call(GetCommunity {
937- community_id: community_id.to_string(),
938- })
939- .await
940- }
941-
942- pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {
943- self.call(ListVoiceParticipants {
944- community_id: community_id.to_string(),
945- })
946- .await
947- }
948-
949- pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {
950- self.call(ListVoiceRooms).await
951- }
952-
953- pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {
954- self.call(SetGhost { enabled }).await
955- }
956-
957- pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {
958- self.call(KickFromVoice {
959- user_id: user_id.to_string(),
960- })
961- .await
962- }
963-
964- pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {
965- self.call(ServerMute {
966- user_id: user_id.to_string(),
967- muted,
968- })
969- .await
970- }
971-
972- pub async fn set_community_voice(
973- &self,
974- community_id: &str,
975- enabled: bool,
976- ) -> Result<Community, Fail> {
977- self.call(SetCommunityVoice {
978- community_id: community_id.to_string(),
979- enabled,
980- })
981- .await
982- }
983 }214 }
crates/client/src/voice/engine.rsmodified+2 -2
@@ -7,7 +7,7 @@ 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::{Packet, RELAY_PREFIX},10+ datagram::{Packet, RELAY_PREFIX, VOICE_HEADER},
11 };11 };
12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13 use uuid::Uuid;13 use uuid::Uuid;
@@ -293,7 +293,7 @@ impl Engine {
293 pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) {293 pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) {
294 let user_id = Uuid::from_bytes(*from).to_string();294 let user_id = Uuid::from_bytes(*from).to_string();
295 let now = Instant::now();295 let now = Instant::now();
296- self.received_bytes += RELAY_PREFIX + 5 + payload.len();296+ self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len();
297 297
298 let speaker = self298 let speaker = self
299 .speakers299 .speakers
crates/common/src/call.rsmodified+41 -23
@@ -1,6 +1,8 @@
1 use bitcode::{Decode, DecodeOwned, Encode};1 use bitcode::{Decode, DecodeOwned, Encode};
2 2
3 use crate::{3 use crate::{
4+ constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
5+ error::Error,
4 model::{6 model::{
5 Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community,7 Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
6 CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,8 CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
@@ -8,6 +10,11 @@ use crate::{
8 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,10 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
9 },11 },
10 share::{Codec, Kind, Quality, Share, Source},12 share::{Codec, Kind, Quality, Share, Source},
13+ validate::{
14+ validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
15+ validate_password, validate_poll, validate_reaction, validate_reason,
16+ validate_server_settings, validate_status, validate_username,
17+ },
11 };18 };
12 19
13 #[derive(Debug, Clone, Copy, PartialEq, Eq)]20 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -22,10 +29,14 @@ pub trait Call: Encode + DecodeOwned + Send + 'static {
22 const GATE: Gate;29 const GATE: Gate;
23 30
24 fn into_request(self) -> Request;31 fn into_request(self) -> Request;
32+
33+ fn validate(&self) -> Result<(), Error> {
34+ Ok(())
35+ }
25 }36 }
26 37
27 macro_rules! calls {38 macro_rules! calls {
28- ($($name:ident: $gate:ident -> $reply:ty;)*) => {39+ ($($name:ident: $gate:ident -> $reply:ty $(, |$c:ident| $check:expr)?;)*) => {
29 #[derive(Debug, Clone, Encode, Decode)]40 #[derive(Debug, Clone, Encode, Decode)]
30 pub enum Request {41 pub enum Request {
31 $($name($name),)*42 $($name($name),)*
@@ -39,6 +50,13 @@ macro_rules! calls {
39 fn into_request(self) -> Request {50 fn into_request(self) -> Request {
40 Request::$name(self)51 Request::$name(self)
41 }52 }
53+
54+ $(
55+ fn validate(&self) -> Result<(), Error> {
56+ let $c = self;
57+ $check
58+ }
59+ )?
42 }60 }
43 )*61 )*
44 };62 };
@@ -600,37 +618,37 @@ pub struct StorageUsage {
600 calls! {618 calls! {
601 GetSettings: Guest -> ServerSettings;619 GetSettings: Guest -> ServerSettings;
602 GetUser: User -> User;620 GetUser: User -> User;
603- UpdateUser: User -> User;621+ UpdateUser: User -> User, |c| validate_username(&c.username);
604- UpdateStatus: User -> User;622+ UpdateStatus: User -> User, |c| validate_status(&c.status);
605 UpdatePresence: User -> ();623 UpdatePresence: User -> ();
606 ListPresences: User -> Vec<(String, Presence)>;624 ListPresences: User -> Vec<(String, Presence)>;
607- UpdateAvatar: User -> User;625+ UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64);
608 RemoveAvatar: User -> User;626 RemoveAvatar: User -> User;
609 GetAvatar: User -> Vec<u8>;627 GetAvatar: User -> Vec<u8>;
610 ListSessions: User -> Vec<SessionInfo>;628 ListSessions: User -> Vec<SessionInfo>;
611 RevokeSession: User -> ();629 RevokeSession: User -> ();
612- CreateCommunity: User -> Community;630+ CreateCommunity: User -> Community, |c| validate_community_name(&c.name);
613 GetCommunity: User -> Community;631 GetCommunity: User -> Community;
614- UpdateCommunity: User -> Community;632+ UpdateCommunity: User -> Community, |c| validate_community_name(&c.name);
615- UpdateCommunityAvatar: User -> Community;633+ UpdateCommunityAvatar: User -> Community, |c| c.image.as_deref().map_or(Ok(()), |image| validate_avatar_size(image, MAXIMUM_AVATAR_BYTES as u64));
616 DeleteCommunity: User -> ();634 DeleteCommunity: User -> ();
617 LeaveCommunity: User -> ();635 LeaveCommunity: User -> ();
618 ListCommunities: User -> Vec<Community>;636 ListCommunities: User -> Vec<Community>;
619 ListMembers: User -> Vec<Member>;637 ListMembers: User -> Vec<Member>;
620- Kick: User -> ();638+ Kick: User -> (), |c| validate_reason(c.reason.as_deref());
621- BanMember: User -> ();639+ BanMember: User -> (), |c| validate_reason(c.reason.as_deref());
622 Unban: User -> ();640 Unban: User -> ();
623 ListBans: User -> Vec<Ban>;641 ListBans: User -> Vec<Ban>;
624 SetRank: User -> ();642 SetRank: User -> ();
625 ListLogs: User -> Vec<LogEntry>;643 ListLogs: User -> Vec<LogEntry>;
626- CreateMessage: User -> Message;644+ CreateMessage: User -> Message, |c| validate_new_message(&c.body, c.attachments.len(), MAXIMUM_MESSAGE_LENGTH);
627- ForwardMessages: User -> Vec<Message>;645+ ForwardMessages: User -> Vec<Message>, |c| validate_forward(c.message_ids.len());
628- UpdateMessage: User -> Message;646+ UpdateMessage: User -> Message, |c| validate_new_message(&c.body, 0, MAXIMUM_MESSAGE_LENGTH);
629 DeleteMessage: User -> ();647 DeleteMessage: User -> ();
630- CreatePoll: User -> Message;648+ CreatePoll: User -> Message, |c| validate_poll(&c.question, &c.options);
631 Vote: User -> ();649 Vote: User -> ();
632 ClosePoll: User -> ();650 ClosePoll: User -> ();
633- React: User -> ();651+ React: User -> (), |c| validate_reaction(&c.emoji);
634 Pin: User -> ();652 Pin: User -> ();
635 ListPins: User -> Vec<Message>;653 ListPins: User -> Vec<Message>;
636 ListMessages: User -> Vec<Message>;654 ListMessages: User -> Vec<Message>;
@@ -648,8 +666,8 @@ calls! {
648 ListInvitations: User -> Vec<Invitation>;666 ListInvitations: User -> Vec<Invitation>;
649 AcceptInvitation: User -> Community;667 AcceptInvitation: User -> Community;
650 DeclineInvitation: User -> ();668 DeclineInvitation: User -> ();
651- ReportMessage: User -> ();669+ ReportMessage: User -> (), |c| validate_reason(Some(&c.reason));
652- ReportUser: User -> ();670+ ReportUser: User -> (), |c| validate_reason(Some(&c.reason));
653 ListReports: Builder -> Vec<Report>;671 ListReports: Builder -> Vec<Report>;
654 HandleReport: User -> ();672 HandleReport: User -> ();
655 JoinVoice: User -> Vec<String>;673 JoinVoice: User -> Vec<String>;
@@ -665,8 +683,8 @@ calls! {
665 ListVoiceRooms: Builder -> Vec<VoiceRoom>;683 ListVoiceRooms: Builder -> Vec<VoiceRoom>;
666 KickFromVoice: User -> ();684 KickFromVoice: User -> ();
667 ServerMute: User -> ();685 ServerMute: User -> ();
668- Register: Guest -> Session;686+ Register: Guest -> Session, |c| validate_username(&c.username).and(validate_password(&c.password));
669- Login: Guest -> Session;687+ Login: Guest -> Session, |c| validate_password(&c.password);
670 Logout: User -> ();688 Logout: User -> ();
671 DeleteUser: User -> ();689 DeleteUser: User -> ();
672 WatchCommunity: User -> ();690 WatchCommunity: User -> ();
@@ -676,15 +694,15 @@ calls! {
676 GetOverview: Builder -> Overview;694 GetOverview: Builder -> Overview;
677 SuspendUser: User -> ();695 SuspendUser: User -> ();
678 RevokeSessions: User -> ();696 RevokeSessions: User -> ();
679- ResetPassword: User -> ();697+ ResetPassword: User -> (), |c| validate_password(&c.password);
680 ClearProfile: User -> User;698 ClearProfile: User -> User;
681 ListAllCommunities: Builder -> Vec<CommunitySummary>;699 ListAllCommunities: Builder -> Vec<CommunitySummary>;
682 TransferOwnership: User -> ();700 TransferOwnership: User -> ();
683- UpdateServerSettings: Builder -> ServerSettings;701+ UpdateServerSettings: Builder -> ServerSettings, |c| validate_server_settings(&c.settings);
684- CreateUser: Builder -> User;702+ CreateUser: Builder -> User, |c| validate_username(&c.username).and(validate_password(&c.password));
685- RenameUser: User -> User;703+ RenameUser: User -> User, |c| validate_username(&c.username);
686 TimeoutUser: User -> ();704 TimeoutUser: User -> ();
687- BanUser: User -> ();705+ BanUser: User -> (), |c| validate_reason(c.reason.as_deref());
688 ListServerBans: Builder -> Vec<ServerBan>;706 ListServerBans: Builder -> Vec<ServerBan>;
689 RemoveServerBan: Builder -> ();707 RemoveServerBan: Builder -> ();
690 CreateInviteCode: User -> InviteCode;708 CreateInviteCode: User -> InviteCode;
crates/common/src/datagram.rsmodified+6 -15
@@ -12,9 +12,9 @@ use crate::{
12 };12 };
13 13
14 pub const RELAY_PREFIX: usize = 16;14 pub const RELAY_PREFIX: usize = 16;
15-pub const MAX_DATAGRAM: usize = 1200 - 48;15+const MAX_DATAGRAM: usize = 1200 - 48;
16 16
17-const VOICE_HEADER: usize = 5;17+pub const VOICE_HEADER: usize = 5;
18 const SHARE_AUDIO_HEADER: usize = 9;18 const SHARE_AUDIO_HEADER: usize = 9;
19 const VIDEO_HEADER: usize = 17;19 const VIDEO_HEADER: usize = 17;
20 const KEYFRAME_FLAG: u8 = 1;20 const KEYFRAME_FLAG: u8 = 1;
@@ -186,10 +186,7 @@ impl<'a> Packet<'a> {
186 }186 }
187 187
188 pub fn relayed(from: &[u8; RELAY_PREFIX], uplink: &[u8]) -> Bytes {188 pub fn relayed(from: &[u8; RELAY_PREFIX], uplink: &[u8]) -> Bytes {
189- let mut bytes = Vec::with_capacity(RELAY_PREFIX + uplink.len());189+ Bytes::from([from.as_slice(), uplink].concat())
190- bytes.extend_from_slice(from);
191- bytes.extend_from_slice(uplink);
192- Bytes::from(bytes)
193 }190 }
194 191
195 pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> {192 pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> {
@@ -258,15 +255,9 @@ pub fn send(connection: &Connection, bytes: Bytes) {
258 }255 }
259 256
260 pub fn warn_if_small(connection: &Connection) {257 pub fn warn_if_small(connection: &Connection) {
261- if connection258+ let max = connection.max_datagram_size();
262- .max_datagram_size()259+ if max.is_none_or(|size| size < MAX_DATAGRAM) {
263- .is_none_or(|size| size < MAX_DATAGRAM)260+ warn!(?max, needed = MAX_DATAGRAM, "datagram size limit below media packets");
264- {
265- warn!(
266- max = ?connection.max_datagram_size(),
267- needed = MAX_DATAGRAM,
268- "datagram size limit below media packets"
269- );
270 }261 }
271 }262 }
272 263
crates/common/src/frame.rsmodified+11 -12
@@ -1,4 +1,4 @@
1-use bitcode::{DecodeOwned, Encode};1+pub use bitcode::{DecodeOwned, Encode};
2 use quinn::{RecvStream, SendStream};2 use quinn::{RecvStream, SendStream};
3 3
4 use crate::constant::MAXIMUM_AVATAR_BYTES;4 use crate::constant::MAXIMUM_AVATAR_BYTES;
@@ -50,24 +50,23 @@ impl Drop for Sending {
50 }50 }
51 }51 }
52 52
53-pub fn encode<T: Encode>(value: &T) -> Vec<u8> {53+pub fn encode<T: Encode>(value: &T, max: u32) -> Result<Vec<u8>, FrameError> {
54 let payload = bitcode::encode(value);54 let payload = bitcode::encode(value);
55- let mut framed = Vec::with_capacity(4 + payload.len());55+ let length = payload.len() as u32;
56- framed.extend_from_slice(&(payload.len() as u32).to_le_bytes());
57- framed.extend_from_slice(&payload);
58- framed
59-}
60-
61-pub async fn write<T: Encode>(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> {
62- let framed = encode(value);
63- let length = framed.len() as u32 - 4;
64 if length > max {56 if length > max {
65 return Err(FrameError::TooLarge {57 return Err(FrameError::TooLarge {
66 actual: length,58 actual: length,
67 maximum: max,59 maximum: max,
68 });60 });
69 }61 }
70- stream.get().write_all(&framed).await?;62+ let mut framed = Vec::with_capacity(4 + payload.len());
63+ framed.extend_from_slice(&length.to_le_bytes());
64+ framed.extend_from_slice(&payload);
65+ Ok(framed)
66+}
67+
68+pub async fn write<T: Encode>(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> {
69+ stream.get().write_all(&encode(value, max)?).await?;
71 Ok(())70 Ok(())
72 }71 }
73 72
crates/common/src/transport.rsmodified+2 -8
@@ -2,17 +2,13 @@ use std::time::Duration;
2 2
3 use quinn::{TransportConfig, VarInt};3 use quinn::{TransportConfig, VarInt};
4 4
5-pub const PROTOCOL: u32 = 2;5+pub const ALPN: &[u8] = b"yumush/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);
9 const BIDI_STREAMS: u32 = 256;9 const BIDI_STREAMS: u32 = 256;
10 const DATAGRAM_RECEIVE_BYTES: usize = 1 << 20;10 const DATAGRAM_RECEIVE_BYTES: usize = 1 << 20;
11 11
12-pub fn alpn() -> Vec<u8> {
13- format!("yumush/{PROTOCOL}").into_bytes()
14-}
15-
16 pub fn transport() -> TransportConfig {12 pub fn transport() -> TransportConfig {
17 let mut config = TransportConfig::default();13 let mut config = TransportConfig::default();
18 config.keep_alive_interval(Some(KEEP_ALIVE));14 config.keep_alive_interval(Some(KEEP_ALIVE));
@@ -46,9 +42,7 @@ impl Close {
46 ];42 ];
47 43
48 pub fn of(code: VarInt) -> Option<Self> {44 pub fn of(code: VarInt) -> Option<Self> {
49- Self::ALL45+ Self::ALL.into_iter().find(|close| close.code() == code)
50- .into_iter()
51- .find(|close| u64::from(code) == u64::from(*close as u32))
52 }46 }
53 47
54 pub fn reason(self) -> &'static str {48 pub fn reason(self) -> &'static str {
crates/server/src/call/admin.rsmodified+26 -38
@@ -20,20 +20,22 @@ use common::{
20 permission,20 permission,
21 time::{self, MINUTE_MILLIS},21 time::{self, MINUTE_MILLIS},
22 transport::Close,22 transport::Close,
23- validate::{validate_reason, validate_server_settings},
24 };23 };
25 24
26 use crate::{25 use crate::{
27- admin_log, attachment, authentication, backup,26+ admin_log, attachment,
27+ authentication::{self, Revoke},
28+ backup,
29+ call::user::user_updated,
28 call::{Cx, Handle, Me},30 call::{Cx, Handle, Me},
29 community,31 community,
30 error::ServerError,32 error::ServerError,
31 invite, log, message, overview,33 invite, log, message, overview,
32 publish::{Broadcast, To},34 publish::{Broadcast, To},
33 request::{35 request::{
34- allowed, call_ended, ensure, ensure_editable, is_outsider, leave_user_voice, limit_logins,36+ allowed, call_ended, ensure, ensure_editable, is_outsider, leave_room_voice,
35- managed, message_event, record_ghost_voice, shares_ended, user_updated, voice_closed,37+ leave_user_voice, limit_logins, managed, message_event, record_ghost_voice, shares_ended,
36- voice_joined, voice_silenced, voice_unmuted,38+ voice_closed, voice_joined, voice_muted,
37 },39 },
38 server_ban, server_settings, stats, user, user_community,40 server_ban, server_settings, stats, user, user_community,
39 };41 };
@@ -76,7 +78,6 @@ impl Handle for UpdateServerSettings {
76 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> {78 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> {
77 let me = me.user()?;79 let me = me.user()?;
78 let settings = self.settings;80 let settings = self.settings;
79- validate_server_settings(&settings)?;
80 server_settings::update(&settings, &cx.db).await?;81 server_settings::update(&settings, &cx.db).await?;
81 admin_log::record(82 admin_log::record(
82 Some(&me.id),83 Some(&me.id),
@@ -114,7 +115,7 @@ impl Handle for RenameUser {
114 &cx.db,115 &cx.db,
115 )116 )
116 .await?;117 .await?;
117- cx.out.extend(user_updated(&user));118+ user_updated(&user, cx);
118 119
119 Ok(user)120 Ok(user)
120 }121 }
@@ -181,12 +182,8 @@ impl Handle for SuspendUser {
181 };182 };
182 admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?;183 admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?;
183 if self.suspended {184 if self.suspended {
184- authentication::revoke(185+ authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db)
185- &cx.sh.services.hub,186+ .await?;
186- authentication::Revoke::User(&self.user_id),
187- &cx.db,
188- )
189- .await?;
190 }187 }
191 188
192 Ok(())189 Ok(())
@@ -197,12 +194,7 @@ impl Handle for RevokeSessions {
197 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {194 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
198 let me = me.user()?;195 let me = me.user()?;
199 managed(&me, &self.user_id, &cx.db).await?;196 managed(&me, &self.user_id, &cx.db).await?;
200- authentication::revoke(197+ authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?;
201- &cx.sh.services.hub,
202- authentication::Revoke::User(&self.user_id),
203- &cx.db,
204- )
205- .await?;
206 admin_log::record(198 admin_log::record(
207 Some(&me.id),199 Some(&me.id),
208 Some(&self.user_id),200 Some(&self.user_id),
@@ -221,12 +213,7 @@ impl Handle for ResetPassword {
221 let me = me.user()?;213 let me = me.user()?;
222 managed(&me, &self.user_id, &cx.db).await?;214 managed(&me, &self.user_id, &cx.db).await?;
223 authentication::reset_password(&self.user_id, &self.password, &cx.db).await?;215 authentication::reset_password(&self.user_id, &self.password, &cx.db).await?;
224- authentication::revoke(216+ authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?;
225- &cx.sh.services.hub,
226- authentication::Revoke::User(&self.user_id),
227- &cx.db,
228- )
229- .await?;
230 admin_log::record(217 admin_log::record(
231 Some(&me.id),218 Some(&me.id),
232 Some(&self.user_id),219 Some(&self.user_id),
@@ -254,7 +241,7 @@ impl Handle for ClearProfile {
254 &cx.db,241 &cx.db,
255 )242 )
256 .await?;243 .await?;
257- cx.out.extend(user_updated(&user));244+ user_updated(&user, cx);
258 245
259 Ok(user)246 Ok(user)
260 }247 }
@@ -274,10 +261,12 @@ impl Handle for SetRole {
274 &cx.db,261 &cx.db,
275 )262 )
276 .await?;263 .await?;
277- cx.out.extend(user_updated(&user));264+ user_updated(&user, cx);
278 if permission::is_builder(role) {265 if permission::is_builder(role) {
279- let broadcasts = voice_unmuted(&cx.sh.services.rooms, &user_id, &cx.db).await?;266+ if let Some(community_id) = cx.sh.services.rooms.set_muted(&user_id, false) {
280- cx.out.extend(broadcasts);267+ cx.out
268+ .push(voice_muted(Some(community_id), &user_id, false, &cx.db).await?);
269+ }
281 } else {270 } else {
282 user::set_ghost(&user_id, false, &cx.db).await?;271 user::set_ghost(&user_id, false, &cx.db).await?;
283 cx.sh.services.hub.kick_user(&user_id, Close::Revoked);272 cx.sh.services.hub.kick_user(&user_id, Close::Revoked);
@@ -466,12 +455,7 @@ impl Handle for TimeoutUser {
466 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);455 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);
467 user::set_timeout(&user_id, until, &cx.db).await?;456 user::set_timeout(&user_id, until, &cx.db).await?;
468 if until.is_some() {457 if until.is_some() {
469- authentication::revoke(458+ authentication::revoke(&cx.sh.services.hub, Revoke::User(&user_id), &cx.db).await?;
470- &cx.sh.services.hub,
471- authentication::Revoke::User(&user_id),
472- &cx.db,
473- )
474- .await?;
475 }459 }
476 admin_log::record(460 admin_log::record(
477 Some(&me.id),461 Some(&me.id),
@@ -495,7 +479,6 @@ impl Handle for BanUser {
495 scope,479 scope,
496 } = self;480 } = self;
497 let target = managed(&me, &user_id, &cx.db).await?;481 let target = managed(&me, &user_id, &cx.db).await?;
498- validate_reason(reason.as_deref())?;
499 let tx = cx.db.transaction().await?;482 let tx = cx.db.transaction().await?;
500 user::set_suspended(&user_id, true, &tx).await?;483 user::set_suspended(&user_id, true, &tx).await?;
501 authentication::revoke_sessions(&user_id, &tx).await?;484 authentication::revoke_sessions(&user_id, &tx).await?;
@@ -756,8 +739,13 @@ impl Handle for SetCommunityVoice {
756 }739 }
757 tx.commit().await?;740 tx.commit().await?;
758 if !enabled {741 if !enabled {
759- let broadcasts = voice_silenced(&cx.sh.services.rooms, &community_id, &cx.db).await?;742+ let rooms = &cx.sh.services.rooms;
760- cx.out.extend(broadcasts);743+ for user_id in rooms.room_users(&community_id) {
744+ if !permission::is_builder(user::read(&user_id, &cx.db).await?.role) {
745+ cx.out
746+ .extend(leave_room_voice(rooms, &community_id, &user_id, &cx.db).await?);
747+ }
748+ }
761 }749 }
762 cx.emit(750 cx.emit(
763 To::Community(community_id),751 To::Community(community_id),
crates/server/src/call/community.rsmodified+27 -33
@@ -8,7 +8,7 @@ use common::{
8 event::Event,8 event::Event,
9 model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User},9 model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User},
10 permission,10 permission,
11- validate::{validate_avatar_size, validate_reason},11+ validate::validate_avatar_size,
12 };12 };
13 13
14 use crate::{14 use crate::{
@@ -24,21 +24,14 @@ use crate::{
24 server_settings, user, user_community,24 server_settings, user, user_community,
25 };25 };
26 26
27-struct Removal {27+async fn remove_member(
28+ me: &User,
28 community_id: String,29 community_id: String,
29 user_id: String,30 user_id: String,
30 reason: Option<String>,31 reason: Option<String>,
31 sanction: Sanction,32 sanction: Sanction,
32-}33+ cx: &mut Cx<'_>,
33-34+) -> Result<(), ServerError> {
34-async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<(), ServerError> {
35- let Removal {
36- community_id,
37- user_id,
38- reason,
39- sanction,
40- } = removal;
41- validate_reason(reason.as_deref())?;
42 ensure_editable(&community_id, &cx.db).await?;35 ensure_editable(&community_id, &cx.db).await?;
43 let target = user::read(&user_id, &cx.db).await?;36 let target = user::read(&user_id, &cx.db).await?;
44 ensure(permission::can_moderate(37 ensure(permission::can_moderate(
@@ -61,9 +54,8 @@ async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<(
61 };54 };
62 log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;55 log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;
63 tx.commit().await?;56 tx.commit().await?;
64- let broadcasts =57+ cx.out
65- leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?;58+ .extend(leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?);
66- cx.out.extend(broadcasts);
67 cx.emit(59 cx.emit(
68 To::User(user_id.clone()),60 To::User(user_id.clone()),
69 Event::Removed {61 Event::Removed {
@@ -199,8 +191,8 @@ impl Handle for DeleteCommunity {
199 .await?;191 .await?;
200 }192 }
201 tx.commit().await?;193 tx.commit().await?;
202- let broadcasts = voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?;194+ cx.out
203- cx.out.extend(broadcasts);195+ .extend(voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?);
204 cx.emit(196 cx.emit(
205 To::Users(member_ids),197 To::Users(member_ids),
206 Event::CommunityDeleted {198 Event::CommunityDeleted {
@@ -269,28 +261,30 @@ impl Handle for ListMembers {
269 impl Handle for Kick {261 impl Handle for Kick {
270 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {262 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
271 let me = me.user()?;263 let me = me.user()?;
272- let removal = Removal {264+ remove_member(
273- community_id: self.community_id,265+ &me,
274- user_id: self.user_id,266+ self.community_id,
275- reason: self.reason,267+ self.user_id,
276- sanction: Sanction::Kick,268+ self.reason,
277- };269+ Sanction::Kick,
278-270+ cx,
279- remove_member(&me, removal, cx).await271+ )
272+ .await
280 }273 }
281 }274 }
282 275
283 impl Handle for BanMember {276 impl Handle for BanMember {
284 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {277 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
285 let me = me.user()?;278 let me = me.user()?;
286- let removal = Removal {279+ remove_member(
287- community_id: self.community_id,280+ &me,
288- user_id: self.user_id,281+ self.community_id,
289- reason: self.reason,282+ self.user_id,
290- sanction: Sanction::Ban,283+ self.reason,
291- };284+ Sanction::Ban,
292-285+ cx,
293- remove_member(&me, removal, cx).await286+ )
287+ .await
294 }288 }
295 }289 }
296 290
crates/server/src/call/message.rsmodified+10 -22
@@ -7,9 +7,7 @@ use common::{
7 event::Event,7 event::Event,
8 model::{AdminAction, LogAction, Message, ServerSettings, Unread, User},8 model::{AdminAction, LogAction, Message, ServerSettings, Unread, User},
9 permission,9 permission,
10- validate::{10+ validate::{validate_new_message, validate_vote},
11- validate_forward, validate_new_message, validate_poll, validate_reaction, validate_vote,
12- },
13 };11 };
14 12
15 use crate::{13 use crate::{
@@ -19,7 +17,7 @@ use crate::{
19 error::ServerError,17 error::ServerError,
20 log, message,18 log, message,
21 publish::To,19 publish::To,
22- request::{actor_rank, allowed, ensure, is_outsider},20+ request::{actor_rank, allowed, ensure, is_outsider, message_event},
23 server_settings, stats, user, user_community,21 server_settings, stats, user, user_community,
24 };22 };
25 23
@@ -35,13 +33,6 @@ fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(
35 .allow(&me.id, settings.messages_per_minute)?)33 .allow(&me.id, settings.messages_per_minute)?)
36 }34 }
37 35
38-fn emit_message(message: &Message, event: fn(Message) -> Event, cx: &mut Cx<'_>) {
39- cx.emit(
40- To::Community(message.community_id.clone()),
41- event(message.clone()),
42- );
43-}
44-
45 impl Handle for CreateMessage {36 impl Handle for CreateMessage {
46 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {37 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {
47 let me = me.user()?;38 let me = me.user()?;
@@ -65,7 +56,7 @@ impl Handle for CreateMessage {
65 .await?;56 .await?;
66 stats::mark_active(&me.id, &tx).await?;57 stats::mark_active(&me.id, &tx).await?;
67 tx.commit().await?;58 tx.commit().await?;
68- emit_message(&created, Event::MessageCreated, cx);59+ cx.out.push(message_event(&created, Event::MessageCreated));
69 60
70 Ok(created)61 Ok(created)
71 }62 }
@@ -75,7 +66,6 @@ impl Handle for ForwardMessages {
75 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> {66 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> {
76 let me = me.user()?;67 let me = me.user()?;
77 limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?;68 limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?;
78- validate_forward(self.message_ids.len())?;
79 ensure(permission::can_post(69 ensure(permission::can_post(
80 actor_rank(&me, &self.community_id, &cx.db).await?,70 actor_rank(&me, &self.community_id, &cx.db).await?,
81 ))?;71 ))?;
@@ -104,7 +94,7 @@ impl Handle for ForwardMessages {
104 .await?;94 .await?;
105 tx.commit().await?;95 tx.commit().await?;
106 for message in &created {96 for message in &created {
107- emit_message(message, Event::MessageCreated, cx);97+ cx.out.push(message_event(message, Event::MessageCreated));
108 }98 }
109 99
110 Ok(created)100 Ok(created)
@@ -123,7 +113,7 @@ impl Handle for UpdateMessage {
123 server_settings::read(&cx.db).await?.max_message_length as usize,113 server_settings::read(&cx.db).await?.max_message_length as usize,
124 )?;114 )?;
125 let updated = message::update(&self.message_id, &self.body, &cx.db).await?;115 let updated = message::update(&self.message_id, &self.body, &cx.db).await?;
126- emit_message(&updated, Event::MessageUpdated, cx);116+ cx.out.push(message_event(&updated, Event::MessageUpdated));
127 117
128 Ok(updated)118 Ok(updated)
129 }119 }
@@ -178,7 +168,6 @@ impl Handle for CreatePoll {
178 let me = me.user()?;168 let me = me.user()?;
179 let settings = server_settings::read(&cx.db).await?;169 let settings = server_settings::read(&cx.db).await?;
180 limit_messages(&me, &settings, cx)?;170 limit_messages(&me, &settings, cx)?;
181- validate_poll(&self.question, &self.options)?;
182 allowed(&me, &self.community_id, &cx.db, permission::can_post).await?;171 allowed(&me, &self.community_id, &cx.db, permission::can_post).await?;
183 let tx = cx.db.transaction().await?;172 let tx = cx.db.transaction().await?;
184 let created = message::create_poll(173 let created = message::create_poll(
@@ -192,7 +181,7 @@ impl Handle for CreatePoll {
192 .await?;181 .await?;
193 stats::mark_active(&me.id, &tx).await?;182 stats::mark_active(&me.id, &tx).await?;
194 tx.commit().await?;183 tx.commit().await?;
195- emit_message(&created, Event::MessageCreated, cx);184+ cx.out.push(message_event(&created, Event::MessageCreated));
196 185
197 Ok(created)186 Ok(created)
198 }187 }
@@ -208,7 +197,7 @@ impl Handle for Vote {
208 let poll = existing.poll.as_ref().ok_or(Error::NotFound)?;197 let poll = existing.poll.as_ref().ok_or(Error::NotFound)?;
209 validate_vote(poll, &self.positions)?;198 validate_vote(poll, &self.positions)?;
210 let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?;199 let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?;
211- emit_message(&updated, Event::MessageUpdated, cx);200+ cx.out.push(message_event(&updated, Event::MessageUpdated));
212 201
213 Ok(())202 Ok(())
214 }203 }
@@ -223,7 +212,7 @@ impl Handle for ClosePoll {
223 existing.user_id == me.id,212 existing.user_id == me.id,
224 ))?;213 ))?;
225 let updated = message::close_poll(&self.message_id, &cx.db).await?;214 let updated = message::close_poll(&self.message_id, &cx.db).await?;
226- emit_message(&updated, Event::MessageUpdated, cx);215+ cx.out.push(message_event(&updated, Event::MessageUpdated));
227 216
228 Ok(())217 Ok(())
229 }218 }
@@ -232,13 +221,12 @@ impl Handle for ClosePoll {
232 impl Handle for React {221 impl Handle for React {
233 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {222 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
234 let me = me.user()?;223 let me = me.user()?;
235- validate_reaction(&self.emoji)?;
236 let existing = message::read(&self.message_id, &cx.db).await?;224 let existing = message::read(&self.message_id, &cx.db).await?;
237 ensure(permission::can_read(225 ensure(permission::can_read(
238 actor_rank(&me, &existing.community_id, &cx.db).await?,226 actor_rank(&me, &existing.community_id, &cx.db).await?,
239 ))?;227 ))?;
240 let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?;228 let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?;
241- emit_message(&updated, Event::MessageUpdated, cx);229+ cx.out.push(message_event(&updated, Event::MessageUpdated));
242 230
243 Ok(())231 Ok(())
244 }232 }
@@ -254,7 +242,7 @@ impl Handle for Pin {
254 direct,242 direct,
255 ))?;243 ))?;
256 let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?;244 let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?;
257- emit_message(&updated, Event::MessageUpdated, cx);245+ cx.out.push(message_event(&updated, Event::MessageUpdated));
258 246
259 Ok(())247 Ok(())
260 }248 }
crates/server/src/call/mod.rsmodified+11 -7
@@ -13,6 +13,7 @@ use common::{
13 event::Event,13 event::Event,
14 frame::{self, DOWN_MAX},14 frame::{self, DOWN_MAX},
15 model::User,15 model::User,
16+ permission,
16 };17 };
17 use turso::Connection;18 use turso::Connection;
18 19
@@ -72,12 +73,18 @@ async fn gate(gate: Gate, cx: &Cx<'_>) -> Result<Me, ServerError> {
72 match gate {73 match gate {
73 Gate::Guest => Ok(Me::Guest),74 Gate::Guest => Ok(Me::Guest),
74 Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)),75 Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)),
75- Gate::Builder => Ok(Me::User(request::builder(cx.client, &cx.db).await?)),76+ Gate::Builder => {
77+ let user = request::authenticated(cx.client, &cx.db).await?;
78+ request::ensure(permission::is_builder(user.role))?;
79+
80+ Ok(Me::User(user))
81+ }
76 }82 }
77 }83 }
78 84
79 async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {85 async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {
80 let reply = async {86 let reply = async {
87+ call.validate()?;
81 let me = gate(C::GATE, cx).await?;88 let me = gate(C::GATE, cx).await?;
82 call.handle(me, cx).await89 call.handle(me, cx).await
83 }90 }
@@ -85,12 +92,9 @@ async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {
85 publish(cx.sh, std::mem::take(&mut cx.out)).await;92 publish(cx.sh, std::mem::take(&mut cx.out)).await;
86 93
87 let reply = reply.map_err(Error::from);94 let reply = reply.map_err(Error::from);
88- let framed = frame::encode(&reply);95+ frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| {
89- if framed.len() - 4 > DOWN_MAX as usize {96+ frame::encode(&Err::<C::Reply, Error>(Error::Server), DOWN_MAX).expect("small")
90- return frame::encode(&Err::<C::Reply, Error>(Error::Server));97+ })
91- }
92-
93- framed
94 }98 }
95 99
96 pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {100 pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
crates/server/src/call/social.rsmodified+0 -3
@@ -11,7 +11,6 @@ use common::{
11 User,11 User,
12 },12 },
13 permission,13 permission,
14- validate::validate_reason,
15 };14 };
16 15
17 use crate::{16 use crate::{
@@ -197,7 +196,6 @@ impl Handle for ReportMessage {
197 let message = message::read(&self.message_id, &cx.db).await?;196 let message = message::read(&self.message_id, &cx.db).await?;
198 let actor = actor_rank(&me, &message.community_id, &cx.db).await?;197 let actor = actor_rank(&me, &message.community_id, &cx.db).await?;
199 ensure(permission::can_read(actor) && me.id != message.user_id)?;198 ensure(permission::can_read(actor) && me.id != message.user_id)?;
200- validate_reason(Some(&self.reason))?;
201 ensure_with(199 ensure_with(
202 !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?,200 !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?,
203 Error::Taken,201 Error::Taken,
@@ -223,7 +221,6 @@ impl Handle for ReportUser {
223 let me = me.user()?;221 let me = me.user()?;
224 user::read(&self.user_id, &cx.db).await?;222 user::read(&self.user_id, &cx.db).await?;
225 ensure(me.id != self.user_id)?;223 ensure(me.id != self.user_id)?;
226- validate_reason(Some(&self.reason))?;
227 ensure_with(224 ensure_with(
228 !report::is_open(&me.id, &self.user_id, None, &cx.db).await?,225 !report::is_open(&me.id, &self.user_id, None, &cx.db).await?,
229 Error::Taken,226 Error::Taken,
crates/server/src/call/user.rsmodified+3 -3
@@ -17,7 +17,7 @@ use crate::{
17 server_settings, user,17 server_settings, user,
18 };18 };
19 19
20-fn user_updated(user: &User, cx: &mut Cx<'_>) {20+pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) {
21 cx.emit(21 cx.emit(
22 To::Related(user.id.clone()),22 To::Related(user.id.clone()),
23 Event::UserUpdated(user.clone()),23 Event::UserUpdated(user.clone()),
@@ -60,8 +60,8 @@ impl Handle for UpdatePresence {
60 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {60 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
61 let me = me.user()?;61 let me = me.user()?;
62 user::update_presence(&me.id, self.presence, &cx.db).await?;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?;63+ cx.out
64- cx.out.extend(broadcasts);64+ .extend(presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?);
65 65
66 Ok(())66 Ok(())
67 }67 }
crates/server/src/call/voice.rsmodified+39 -20
@@ -17,10 +17,10 @@ use crate::{
17 community,17 community,
18 error::ServerError,18 error::ServerError,
19 message,19 message,
20- publish::{Broadcast, To},20+ publish::To,
21 request::{21 request::{
22 allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event,22 allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event,
23- share_ended, voice_joined, voice_muted, voice_rooms,23+ share_ended, voice_joined, voice_muted,
24 },24 },
25 user,25 user,
26 };26 };
@@ -65,8 +65,7 @@ impl Handle for LeaveVoice {
65 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {65 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
66 me.user()?;66 me.user()?;
67 if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) {67 if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) {
68- let broadcasts = departed(departure, &cx.db).await?;68+ cx.out.extend(departed(departure, &cx.db).await?);
69- cx.out.extend(broadcasts);
70 }69 }
71 70
72 Ok(())71 Ok(())
@@ -91,13 +90,11 @@ impl Handle for StartShare {
91 source: self.source.clone(),90 source: self.source.clone(),
92 },91 },
93 };92 };
94- let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)];93+ let media = rooms
95- broadcasts.extend(94+ .start_share(cx.client.id, self.kind, self.source)
96- rooms95+ .ok_or(Error::NotFound)?;
97- .start_share(cx.client.id, self.kind, self.source)96+ cx.emit(To::Community(community_id), event);
98- .ok_or(Error::NotFound)?,97+ cx.out.extend(media);
99- );
100- cx.out.extend(broadcasts);
101 98
102 Ok(())99 Ok(())
103 }100 }
@@ -126,7 +123,7 @@ impl Handle for ListShares {
126 impl Handle for WatchShare {123 impl Handle for WatchShare {
127 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {124 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
128 me.user()?;125 me.user()?;
129- let broadcasts = cx126+ let media = cx
130 .sh127 .sh
131 .services128 .services
132 .rooms129 .rooms
@@ -138,7 +135,7 @@ impl Handle for WatchShare {
138 &self.decode,135 &self.decode,
139 )136 )
140 .ok_or(Error::NotFound)?;137 .ok_or(Error::NotFound)?;
141- cx.out.extend(broadcasts);138+ cx.out.extend(media);
142 139
143 Ok(())140 Ok(())
144 }141 }
@@ -147,12 +144,12 @@ impl Handle for WatchShare {
147 impl Handle for UnwatchShare {144 impl Handle for UnwatchShare {
148 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {145 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
149 me.user()?;146 me.user()?;
150- let broadcasts = cx147+ cx.out.extend(
151- .sh148+ cx.sh
152- .services149+ .services
153- .rooms150+ .rooms
154- .unwatch(cx.client.id, &self.user_id, self.kind);151+ .unwatch(cx.client.id, &self.user_id, self.kind),
155- cx.out.extend(broadcasts);152+ );
156 153
157 Ok(())154 Ok(())
158 }155 }
@@ -202,7 +199,29 @@ impl Handle for ListVoiceParticipants {
202 199
203 impl Handle for ListVoiceRooms {200 impl Handle for ListVoiceRooms {
204 async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<VoiceRoom>, ServerError> {201 async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<VoiceRoom>, ServerError> {
205- voice_rooms(&cx.sh.services.rooms, &cx.db).await202+ let mut rooms = Vec::new();
203+ for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() {
204+ let community = community::label(&community_id, &cx.db).await?;
205+ let mut users = Vec::new();
206+ let mut muted = Vec::new();
207+ for user_id in user_ids {
208+ let user = user::read(&user_id, &cx.db).await?;
209+ if user::voice_muted(&user_id, &cx.db).await? {
210+ muted.push(user_id);
211+ }
212+ users.push(user);
213+ }
214+ rooms.push(VoiceRoom {
215+ community_id,
216+ community,
217+ users,
218+ muted,
219+ ghosts,
220+ });
221+ }
222+ rooms.sort_by(|a, b| a.community.cmp(&b.community));
223+
224+ Ok(rooms)
206 }225 }
207 }226 }
208 227
crates/server/src/certificate.rsmodified+1 -1
@@ -115,7 +115,7 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi
115 .with_no_client_auth()115 .with_no_client_auth()
116 .with_cert_resolver(reloader.clone());116 .with_cert_resolver(reloader.clone());
117 tls.max_early_data_size = u32::MAX;117 tls.max_early_data_size = u32::MAX;
118- tls.alpn_protocols = vec![common::transport::alpn()];118+ tls.alpn_protocols = vec![common::transport::ALPN.to_vec()];
119 119
120 let crypto =120 let crypto =
121 quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;121 quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
crates/server/src/hub.rsmodified+8 -20
@@ -29,8 +29,8 @@ pub struct Client {
29 pub me: Option<Signed>,29 pub me: Option<Signed>,
30 tx: mpsc::Sender<Bytes>,30 tx: mpsc::Sender<Bytes>,
31 pub closed: AtomicBool,31 pub closed: AtomicBool,
32- pub watching: Mutex<Option<String>>,32+ watching: Mutex<Option<String>>,
33- pub ghost_logged: Mutex<HashSet<String>>,33+ ghost_logged: Mutex<HashSet<String>>,
34 }34 }
35 35
36 impl Client {36 impl Client {
@@ -73,10 +73,6 @@ impl Client {
73 pub fn watch(&self, community_id: Option<&str>) {73 pub fn watch(&self, community_id: Option<&str>) {
74 *self.watching.lock().unwrap() = community_id.map(str::to_string);74 *self.watching.lock().unwrap() = community_id.map(str::to_string);
75 }75 }
76-
77- fn watches(&self, community_id: &str) -> bool {
78- self.watching.lock().unwrap().as_deref() == Some(community_id)
79- }
80 }76 }
81 77
82 pub enum Presence {78 pub enum Presence {
@@ -127,22 +123,14 @@ impl Hub {
127 Self::online_in(&self.0.lock().unwrap(), user_id)123 Self::online_in(&self.0.lock().unwrap(), user_id)
128 }124 }
129 125
130- pub fn user_ids(&self) -> Vec<String> {126+ pub fn online(&self) -> usize {
131- let mut user_ids: Vec<String> = self127+ let clients = self.0.lock().unwrap();
132- .0128+ let ids: HashSet<&str> = clients
133- .lock()
134- .unwrap()
135 .values()129 .values()
136- .filter_map(|client| client.user_id().map(str::to_string))130+ .filter_map(|client| client.user_id())
137 .collect();131 .collect();
138- user_ids.sort();
139- user_ids.dedup();
140 132
141- user_ids133+ ids.len()
142- }
143-
144- pub fn online(&self) -> usize {
145- self.user_ids().len()
146 }134 }
147 135
148 pub fn conns_of(&self, user_ids: &[String]) -> Vec<ConnId> {136 pub fn conns_of(&self, user_ids: &[String]) -> Vec<ConnId> {
@@ -164,7 +152,7 @@ impl Hub {
164 .lock()152 .lock()
165 .unwrap()153 .unwrap()
166 .values()154 .values()
167- .filter(|client| client.watches(community_id))155+ .filter(|client| client.watching.lock().unwrap().as_deref() == Some(community_id))
168 .map(|client| client.id)156 .map(|client| client.id)
169 .collect()157 .collect()
170 }158 }
crates/server/src/network.rsmodified+6 -1
@@ -214,7 +214,12 @@ async fn admit(
214 let conn = database::connect(&shared.db).await?;214 let conn = database::connect(&shared.db).await?;
215 let user = authentication::resume(&token, &conn).await?;215 let user = authentication::resume(&token, &conn).await?;
216 stats::mark_active(&user.id, &conn).await?;216 stats::mark_active(&user.id, &conn).await?;
217- request::record_address(&user, Some(connection), &conn).await?;217+ user::set_last_ip(
218+ &user.id,
219+ &connection.remote_address().ip().to_string(),
220+ &conn,
221+ )
222+ .await?;
218 if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await {223 if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await {
219 warn!("device: {error}");224 warn!("device: {error}");
220 }225 }
crates/server/src/publish.rsmodified+3 -4
@@ -54,11 +54,10 @@ pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) {
54 }54 }
55 };55 };
56 let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. }));56 let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. }));
57- let framed = frame::encode(&broadcast.down);57+ let Ok(framed) = frame::encode(&broadcast.down, DOWN_MAX) else {
58- if framed.len() - 4 > DOWN_MAX as usize {58+ warn!("event too large");
59- warn!("event too large: {} bytes", framed.len() - 4);
60 continue;59 continue;
61- }60+ };
62 let bytes = Bytes::from(framed);61 let bytes = Bytes::from(framed);
63 shared.services.hub.send(&ids, &bytes, droppable);62 shared.services.hub.send(&ids, &bytes, droppable);
64 }63 }
crates/server/src/request.rsmodified+6 -93
@@ -1,7 +1,7 @@
1 use common::{1 use common::{
2 error::Error as CommonError,2 error::Error as CommonError,
3 event::Event,3 event::Event,
4- model::{AdminAction, CallLog, Message, Presence, Rank, User, VoiceRoom},4+ model::{AdminAction, CallLog, Message, Presence, Rank, User},
5 permission,5 permission,
6 share::Kind,6 share::Kind,
7 };7 };
@@ -18,39 +18,6 @@ use crate::{
18 server_settings, user, user_community,18 server_settings, user, user_community,
19 };19 };
20 20
21-pub(crate) async fn voice_rooms(
22- occupied: &Rooms,
23- conn: &Connection,
24-) -> Result<Vec<VoiceRoom>, ServerError> {
25- let mut rooms = Vec::new();
26- for (community_id, user_ids, ghosts) in occupied.list() {
27- let community = community::label(&community_id, conn).await?;
28- let mut users = Vec::new();
29- let mut muted = Vec::new();
30- for user_id in user_ids {
31- let user = user::read(&user_id, conn).await?;
32- if user::voice_muted(&user_id, conn).await? {
33- muted.push(user.id.clone());
34- }
35- users.push(user);
36- }
37- rooms.push(VoiceRoom {
38- community_id,
39- community,
40- users,
41- muted,
42- ghosts,
43- });
44- }
45- rooms.sort_by(|a, b| a.community.cmp(&b.community));
46-
47- Ok(rooms)
48-}
49-
50-fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> {
51- connection.map(|connection| connection.remote_address().ip().to_string())
52-}
53-
54 pub(crate) async fn limit_logins(21 pub(crate) async fn limit_logins(
55 rate_limit: &RateLimit,22 rate_limit: &RateLimit,
56 connection: Option<&quinn::Connection>,23 connection: Option<&quinn::Connection>,
@@ -58,26 +25,11 @@ pub(crate) async fn limit_logins(
58 ) -> Result<(), ServerError> {25 ) -> Result<(), ServerError> {
59 let limit = server_settings::read(conn).await?.logins_per_minute;26 let limit = server_settings::read(conn).await?.logins_per_minute;
60 27
61- Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)28+ let ip = connection
62-}29+ .map(|connection| connection.remote_address().ip().to_string())
30+ .unwrap_or_default();
63 31
64-pub(crate) async fn record_address(32+ Ok(rate_limit.allow(&ip, limit)?)
65- user: &User,
66- connection: Option<&quinn::Connection>,
67- conn: &Connection,
68-) -> Result<(), ServerError> {
69- if let Some(ip) = ip_of(connection) {
70- user::set_last_ip(&user.id, &ip, conn).await?;
71- }
72-
73- Ok(())
74-}
75-
76-pub(crate) fn user_updated(user: &User) -> Vec<Broadcast> {
77- vec![Broadcast::new(
78- To::Related(user.id.clone()),
79- Event::UserUpdated(user.clone()),
80- )]
81 }33 }
82 34
83 pub(crate) async fn effective_presence(35 pub(crate) async fn effective_presence(
@@ -133,20 +85,6 @@ pub(crate) async fn leave_room_voice(
133 }85 }
134 }86 }
135 87
136-pub(crate) async fn voice_unmuted(
137- rooms: &Rooms,
138- user_id: &str,
139- conn: &Connection,
140-) -> Result<Vec<Broadcast>, ServerError> {
141- let Some(community_id) = rooms.set_muted(user_id, false) else {
142- return Ok(Vec::new());
143- };
144-
145- Ok(vec![
146- voice_muted(Some(community_id), user_id, false, conn).await?,
147- ])
148-}
149-
150 pub(crate) async fn voice_muted(88 pub(crate) async fn voice_muted(
151 community_id: Option<String>,89 community_id: Option<String>,
152 user_id: &str,90 user_id: &str,
@@ -168,22 +106,6 @@ pub(crate) async fn voice_muted(
168 Ok(Broadcast::new(To::Users(user_ids), event))106 Ok(Broadcast::new(To::Users(user_ids), event))
169 }107 }
170 108
171-pub(crate) async fn voice_silenced(
172- rooms: &Rooms,
173- community_id: &str,
174- conn: &Connection,
175-) -> Result<Vec<Broadcast>, ServerError> {
176- let mut broadcasts = Vec::new();
177- for user_id in rooms.room_users(community_id) {
178- if permission::is_builder(user::read(&user_id, conn).await?.role) {
179- continue;
180- }
181- broadcasts.extend(leave_room_voice(rooms, community_id, &user_id, conn).await?);
182- }
183-
184- Ok(broadcasts)
185-}
186-
187 pub(crate) async fn voice_closed(109 pub(crate) async fn voice_closed(
188 rooms: &Rooms,110 rooms: &Rooms,
189 community_id: &str,111 community_id: &str,
@@ -271,13 +193,6 @@ pub(crate) async fn authenticated(client: &Client, conn: &Connection) -> Result<
271 user::read(user_id, conn).await193 user::read(user_id, conn).await
272 }194 }
273 195
274-pub(crate) async fn builder(client: &Client, conn: &Connection) -> Result<User, ServerError> {
275- let user = authenticated(client, conn).await?;
276- ensure(permission::is_builder(user.role))?;
277-
278- Ok(user)
279-}
280-
281 pub async fn actor_rank(196 pub async fn actor_rank(
282 me: &User,197 me: &User,
283 community_id: &str,198 community_id: &str,
@@ -385,9 +300,7 @@ pub(crate) async fn record_ghost_voice(
385 &AdminAction::GhostVoice { seconds },300 &AdminAction::GhostVoice { seconds },
386 conn,301 conn,
387 )302 )
388- .await?;303+ .await
389-
390- Ok(())
391 }304 }
392 305
393 #[cfg(test)]306 #[cfg(test)]
crates/server/src/rooms.rsmodified+52 -89
@@ -153,9 +153,7 @@ fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> {
153 true153 true
154 });154 });
155 155
156- let mut broadcasts: Vec<Broadcast> = layers_changed(sharer.conn, sharer.kind, sharing, before)156+ let mut broadcasts = Vec::from_iter(layers_changed(sharer.conn, sharer.kind, sharing, before));
157- .into_iter()
158- .collect();
159 broadcasts.extend(keyframes);157 broadcasts.extend(keyframes);
160 broadcasts.extend(stopped);158 broadcasts.extend(stopped);
161 159
@@ -335,16 +333,14 @@ impl Rooms {
335 let mut transferred = false;333 let mut transferred = false;
336 let mut joined_at = Instant::now();334 let mut joined_at = Instant::now();
337 if let Some(previous) = inner.seat_conn(user_id) {335 if let Some(previous) = inner.seat_conn(user_id) {
338- let same_room = inner.seat_of.get(&previous).map(String::as_str) == Some(community_id);336+ let kept = inner
339- let kept_ghost = inner
340 .rooms337 .rooms
341 .get(community_id)338 .get(community_id)
342 .and_then(|room| room.seats.get(&previous))339 .and_then(|room| room.seats.get(&previous))
343- .map(|seat| (seat.ghost, seat.joined_at));340+ .filter(|seat| seat.ghost == ghost)
344- transferred = same_room && kept_ghost.is_some_and(|(was, _)| was == ghost);341+ .map(|seat| seat.joined_at);
345- if let (true, Some((_, at))) = (transferred, kept_ghost) {342+ transferred = kept.is_some();
346- joined_at = at;343+ joined_at = kept.unwrap_or(joined_at);
347- }
348 departure = inner.take(previous, previous != client.id, transferred);344 departure = inner.take(previous, previous != client.id, transferred);
349 }345 }
350 let room = inner346 let room = inner
@@ -398,19 +394,19 @@ impl Rooms {
398 394
399 pub fn close_room(&self, community_id: &str) -> Vec<Departure> {395 pub fn close_room(&self, community_id: &str) -> Vec<Departure> {
400 let mut inner = self.0.lock().unwrap();396 let mut inner = self.0.lock().unwrap();
401- let Some(room) = inner.rooms.get(community_id) else {397+ let ids: Vec<ConnId> = inner
402- return Vec::new();398+ .rooms
403- };399+ .get(community_id)
404- let ids: Vec<ConnId> = room.seats.keys().copied().collect();400+ .map(|room| room.seats.keys().copied().collect())
405- let mut departures: Vec<Departure> = ids401+ .unwrap_or_default();
406- .into_iter()
407- .filter_map(|id| inner.take(id, true, false))
408- .collect();
409- for departure in &mut departures {
410- departure.call_log = None;
411- }
412 402
413- departures403+ ids.into_iter()
404+ .filter_map(|id| inner.take(id, true, false))
405+ .map(|departure| Departure {
406+ call_log: None,
407+ ..departure
408+ })
409+ .collect()
414 }410 }
415 411
416 pub fn decline(&self, community_id: &str) {412 pub fn decline(&self, community_id: &str) {
@@ -425,17 +421,15 @@ impl Rooms {
425 let mut inner = self.0.lock().unwrap();421 let mut inner = self.0.lock().unwrap();
426 let id = inner.seat_conn(user_id)?;422 let id = inner.seat_conn(user_id)?;
427 let (community_id, room) = inner.seat_mut(id)?;423 let (community_id, room) = inner.seat_mut(id)?;
428- let community_id = community_id.to_string();
429 room.seats.get_mut(&id)?.muted = muted;424 room.seats.get_mut(&id)?.muted = muted;
430 425
431- Some(community_id)426+ Some(community_id.to_string())
432 }427 }
433 428
434 pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Departure> {429 pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Departure> {
435 let mut inner = self.0.lock().unwrap();430 let mut inner = self.0.lock().unwrap();
436 let id = inner.seat_conn(user_id)?;431 let id = inner.seat_conn(user_id)?;
437 let (community_id, room) = inner.seat_mut(id)?;432 let (community_id, room) = inner.seat_mut(id)?;
438- let community_id = community_id.to_string();
439 if room.seats.get(&id)?.ghost == ghost {433 if room.seats.get(&id)?.ghost == ghost {
440 return None;434 return None;
441 }435 }
@@ -446,22 +440,20 @@ impl Rooms {
446 let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs());440 let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs());
447 seat.ghost = ghost;441 seat.ghost = ghost;
448 seat.joined_at = Instant::now();442 seat.joined_at = Instant::now();
449- let shares: Vec<Kind> = if ghost {443+ let (shares, media) = if ghost {
450- std::mem::take(&mut seat.shares).into_keys().collect()444+ (
445+ std::mem::take(&mut seat.shares).into_keys().collect(),
446+ room.drop_viewer(user_id),
447+ )
451 } else {448 } else {
452- Vec::new()449+ (Vec::new(), Vec::new())
453- };
454- let media = if ghost {
455- room.drop_viewer(user_id)
456- } else {
457- Vec::new()
458 };450 };
459 let call_log = (ghost && !room.occupied())451 let call_log = (ghost && !room.occupied())
460 .then(|| room.call_log())452 .then(|| room.call_log())
461 .flatten();453 .flatten();
462 454
463 Some(Departure {455 Some(Departure {
464- community_id,456+ community_id: community_id.to_string(),
465 user_id: user_id.to_string(),457 user_id: user_id.to_string(),
466 ghost_seconds,458 ghost_seconds,
467 call_log,459 call_log,
@@ -542,37 +534,28 @@ impl Rooms {
542 pub fn start_share(&self, id: ConnId, kind: Kind, source: Source) -> Option<Vec<Broadcast>> {534 pub fn start_share(&self, id: ConnId, kind: Kind, source: Source) -> Option<Vec<Broadcast>> {
543 let mut inner = self.0.lock().unwrap();535 let mut inner = self.0.lock().unwrap();
544 let (community_id, room) = inner.seat_mut(id)?;536 let (community_id, room) = inner.seat_mut(id)?;
545- let community_id = community_id.to_string();
546 let seat = room.seats.get_mut(&id)?;537 let seat = room.seats.get_mut(&id)?;
547- let user_id = seat.user_id.clone();
548 let sharer = Sharer {538 let sharer = Sharer {
549 conn: id,539 conn: id,
550- user_id: &user_id,540+ user_id: &seat.user_id,
551- community_id: &community_id,541+ community_id,
552 kind,542 kind,
553 };543 };
554- if let Some(sharing) = seat.shares.get_mut(&kind) {544+ let sharing = seat.shares.entry(kind).or_insert_with(|| Sharing {
555- sharing.source = source;545+ source: source.clone(),
556- return Some(reroute(&sharer, sharing));546+ viewers: Vec::new(),
557- }547+ });
558- seat.shares.insert(548+ sharing.source = source;
559- kind,
560- Sharing {
561- source,
562- viewers: Vec::new(),
563- },
564- );
565 549
566- Some(Vec::new())550+ Some(reroute(&sharer, sharing))
567 }551 }
568 552
569 pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option<String> {553 pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option<String> {
570 let mut inner = self.0.lock().unwrap();554 let mut inner = self.0.lock().unwrap();
571 let (community_id, room) = inner.seat_mut(id)?;555 let (community_id, room) = inner.seat_mut(id)?;
572- let community_id = community_id.to_string();
573 room.seats.get_mut(&id)?.shares.remove(&kind)?;556 room.seats.get_mut(&id)?.shares.remove(&kind)?;
574 557
575- Some(community_id)558+ Some(community_id.to_string())
576 }559 }
577 560
578 pub fn watch(561 pub fn watch(
@@ -605,9 +588,7 @@ impl Rooms {
605 decode: decode.to_vec(),588 decode: decode.to_vec(),
606 forward,589 forward,
607 });590 });
608- let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_conn, kind, sharing, before)591+ let mut broadcasts = Vec::from_iter(layers_changed(sharer_conn, kind, sharing, before));
609- .into_iter()
610- .collect();
611 broadcasts.push(Broadcast::media(592 broadcasts.push(Broadcast::media(
612 sharer_conn,593 sharer_conn,
613 Media::Keyframe { kind, layer },594 Media::Keyframe { kind, layer },
@@ -616,24 +597,14 @@ impl Rooms {
616 Some(broadcasts)597 Some(broadcasts)
617 }598 }
618 599
619- pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Vec<Broadcast> {600+ pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> {
620 let mut inner = self.0.lock().unwrap();601 let mut inner = self.0.lock().unwrap();
621- let Some(sharer_conn) = inner.seat_conn(sharer_id) else {602+ let sharer_conn = inner.seat_conn(sharer_id)?;
622- return Vec::new();603+ let (_, room) = inner.seat_mut(id)?;
623- };604+ let viewer_id = room.seats.get(&id)?.user_id.clone();
624- let Some((_, room)) = inner.seat_mut(id) else {605+ let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?;
625- return Vec::new();
626- };
627- let Some(viewer_id) = room.seats.get(&id).map(|seat| seat.user_id.clone()) else {
628- return Vec::new();
629- };
630 606
631- room.seats607+ remove_viewer(sharer_conn, kind, sharing, &viewer_id)
632- .get_mut(&sharer_conn)
633- .and_then(|seat| seat.shares.get_mut(&kind))
634- .and_then(|sharing| remove_viewer(sharer_conn, kind, sharing, &viewer_id))
635- .into_iter()
636- .collect()
637 }608 }
638 609
639 pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> {610 pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> {
@@ -658,9 +629,6 @@ impl Rooms {
658 }629 }
659 630
660 pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec<Broadcast> {631 pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec<Broadcast> {
661- if from.me.is_none() {
662- return Vec::new();
663- }
664 let mut inner = self.0.lock().unwrap();632 let mut inner = self.0.lock().unwrap();
665 let Some((_, room)) = inner.seat_mut(from.id) else {633 let Some((_, room)) = inner.seat_mut(from.id) else {
666 return Vec::new();634 return Vec::new();
@@ -671,17 +639,19 @@ impl Rooms {
671 match Packet::decode(packet) {639 match Packet::decode(packet) {
672 Some(Packet::Voice { seq, .. }) => relay_voice(room, from.id, seq, packet),640 Some(Packet::Voice { seq, .. }) => relay_voice(room, from.id, seq, packet),
673 Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet),641 Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet),
674- _ => Vec::new(),642+ _ => {}
675 }643 }
644+
645+ Vec::new()
676 }646 }
677 }647 }
678 648
679-fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) -> Vec<Broadcast> {649+fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) {
680 let Some(sender) = room.seats.get(&id) else {650 let Some(sender) = room.seats.get(&id) else {
681- return Vec::new();651+ return;
682 };652 };
683 if sender.muted {653 if sender.muted {
684- return Vec::new();654+ return;
685 }655 }
686 let mut echo = Vec::new();656 let mut echo = Vec::new();
687 Packet::Voice { seq, opus: &[] }.encode(&mut echo);657 Packet::Voice { seq, opus: &[] }.encode(&mut echo);
@@ -692,23 +662,19 @@ fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) -> Vec<Broadcas
692 datagram::send(&seat.connection, bytes.clone());662 datagram::send(&seat.connection, bytes.clone());
693 }663 }
694 }664 }
695-
696- Vec::new()
697 }665 }
698 666
699-fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) -> Vec<Broadcast> {667+fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) {
700 let Some(seat) = room.seats.get(&id) else {668 let Some(seat) = room.seats.get(&id) else {
701- return Vec::new();669+ return;
702 };670 };
703 let Some(sharing) = seat.shares.get(&Kind::Screen) else {671 let Some(sharing) = seat.shares.get(&Kind::Screen) else {
704- return Vec::new();672+ return;
705 };673 };
706 let bytes = relayed(&seat.uuid, packet);674 let bytes = relayed(&seat.uuid, packet);
707 for viewer in &sharing.viewers {675 for viewer in &sharing.viewers {
708 datagram::send(&viewer.connection, bytes.clone());676 datagram::send(&viewer.connection, bytes.clone());
709 }677 }
710-
711- Vec::new()
712 }678 }
713 679
714 fn relay_video(680 fn relay_video(
@@ -736,8 +702,5 @@ fn relay_video(
736 }702 }
737 }703 }
738 704
739- before705+ Vec::from_iter(before.and_then(|before| layers_changed(id, kind, sharing, before)))
740- .and_then(|before| layers_changed(id, kind, sharing, before))
741- .into_iter()
742- .collect()
743 }706 }