forge
Explore
Log in

Don't you dare go Hollow

Finish ssot cleanup for errors, admin actions and leftovers

Browse files at this commit

eed0fda09668143fefcef6260e25865b761e9b5cAhmet Kaan GümüşParent: f8f75cb
  • refactor
    • finish ssot cleanup for errors, admin actions and leftovers
Show full message
♻️ refactor: finish ssot cleanup for errors, admin actions and leftovers
crates/client/src/avatar.rsmodified+13 -8
@@ -1,6 +1,6 @@
11 use common::{
22 constant::AVATAR_SIZE,
3- error::{Error, InvalidInput},
3+ error::{Error, Field, InvalidInput},
44 };
55 use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
66
@@ -20,10 +20,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {
2020 }
2121 }
2222
23- Err(Error::Avatar(InvalidInput::TooLarge {
24- maximum,
25- actual: encoded.len() as u64,
26- }))
23+ Err(Error::Invalid {
24+ field: Field::Avatar,
25+ input: InvalidInput::TooLarge {
26+ maximum,
27+ actual: encoded.len() as u64,
28+ },
29+ })
2730 }
2831
2932 fn center_square(image: DynamicImage) -> DynamicImage {
@@ -64,13 +67,14 @@ pub fn dominant_hue(bytes: &[u8]) -> Option<f32> {
6467 if chroma < 0.15 {
6568 continue;
6669 }
67- let hue = if max == r {
70+ let sector = if max == r {
6871 ((g - b) / chroma).rem_euclid(6.)
6972 } else if max == g {
7073 (b - r) / chroma + 2.
7174 } else {
7275 (r - g) / chroma + 4.
73- } / 6.;
76+ };
77+ let hue = sector / 6.;
7478 let angle = hue * std::f32::consts::TAU;
7579 let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS];
7680 bin.0 += chroma;
@@ -78,9 +82,10 @@ pub fn dominant_hue(bytes: &[u8]) -> Option<f32> {
7882 bin.2 += angle.sin() * chroma;
7983 }
8084
85+ let pixels = image.pixels().len();
8186 let total: f32 = bins.iter().map(|bin| bin.0).sum();
8287 let (weight, x, y) = bins.into_iter().max_by(|a, b| a.0.total_cmp(&b.0))?;
83- if weight < total * 0.05 || total < (image.len() / 3) as f32 * 0.03 {
88+ if weight < total * 0.05 || total < pixels as f32 * 0.03 {
8489 return None;
8590 }
8691
crates/client/src/gui.rsmodified+4 -3
@@ -1052,9 +1052,10 @@ impl Yumush {
10521052 }
10531053
10541054 pub(super) fn is_direct(&self, community_id: &str) -> bool {
1055- self.chat.communities().iter().any(|community| {
1056- community.id == community_id && community.kind.is_direct()
1057- })
1055+ self.chat
1056+ .communities()
1057+ .iter()
1058+ .any(|community| community.id == community_id && community.kind.is_direct())
10581059 }
10591060
10601061 fn is_me(&self, user_id: &str) -> bool {
crates/client/src/gui/builder.rsmodified+5 -2
@@ -13,7 +13,10 @@ mod voice;
1313
1414 use std::{fmt::Display, future::Future};
1515
16-use common::model::{CommunityKind, Member, Role};
16+use common::{
17+ model::{CommunityKind, Member, Role},
18+ permission,
19+};
1720 use gpui_kit::{
1821 AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,
1922 StatefulInteractiveElement, Styled, Window,
@@ -292,7 +295,7 @@ impl Yumush {
292295 pub(super) fn is_builder(&self) -> bool {
293296 self.user
294297 .as_ref()
295- .is_some_and(|me| me.role == Role::Builder)
298+ .is_some_and(|me| permission::is_builder(me.role))
296299 }
297300
298301 pub(super) fn load_builder(&self, window: &mut Window, cx: &mut Context<Self>) {
crates/client/src/gui/builder/log.rsmodified+13 -22
@@ -12,15 +12,13 @@ use gpui_kit::{
1212 };
1313 use jiff::Timestamp;
1414
15-use super::ui::{
16- accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar,
17-};
15+use super::ui::{accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar};
1816 use crate::gui::STAMP;
1917 use crate::gui::{
2018 Palette, Yumush,
2119 auth::field,
2220 community_settings::{search_text, user_name},
23- entity_action, id_time, millis_time, notify_error, text,
21+ entity_action, id_time, millis_time, text,
2422 };
2523
2624 fn builder_log_text(entry: &AdminLogEntry) -> String {
@@ -224,26 +222,19 @@ impl Yumush {
224222 .map(str::to_string);
225223 let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx));
226224 let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx));
227- let network = self.network.clone();
228-
229- cx.spawn_in(window, async move |this, cx| {
230- let entries = match network
231- .admin_logs(actor_id, target_id, action, after_ms, before_ms)
232- .await
233- {
234- Ok(entries) => entries,
235- Err(error) => {
236- notify_error(&this, cx, error);
237- return;
238- }
239- };
240-
241- let _ = this.update(cx, |yumush, cx| {
225+ self.fetch_builder(
226+ window,
227+ cx,
228+ move |network| async move {
229+ network
230+ .admin_logs(actor_id, target_id, action, after_ms, before_ms)
231+ .await
232+ },
233+ |yumush, entries, cx| {
242234 yumush.chat.builder_logs = entries;
243235 cx.notify();
244- });
245- })
246- .detach();
236+ },
237+ );
247238 }
248239
249240 pub(super) fn log_user(&self, input: &Entity<InputState>, cx: &App) -> Option<Option<String>> {
crates/client/src/gui/builder/server.rsmodified+73 -75
@@ -4,9 +4,7 @@ use gpui_kit::{
44 };
55
66 use super::ui::{field_row, list_card, number, to_bytes, to_units};
7-use crate::gui::{
8- KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented,
9-};
7+use crate::gui::{KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented};
108
119 fn input_text(input: &Entity<InputState>, cx: &App) -> String {
1210 input.read(cx).text().to_string()
@@ -16,6 +14,10 @@ fn input_number(input: &Entity<InputState>, cx: &App) -> u32 {
1614 number(&input_text(input, cx))
1715 }
1816
17+fn set_input(input: &Entity<InputState>, text: &str, window: &mut Window, cx: &mut App) {
18+ input.update(cx, |input, cx| input.set_value(text, window, cx));
19+}
20+
1921 impl Yumush {
2022 pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2123 let Some(settings) = self.server.clone() else {
@@ -23,78 +25,74 @@ impl Yumush {
2325 };
2426 self.chat.server_registration_open = settings.registration_open;
2527 self.chat.server_maintenance = settings.maintenance;
26- self.chat.server_name.update(cx, |input, cx| {
27- input.set_value(settings.name.as_str(), window, cx)
28- });
29- self.chat.server_limit.update(cx, |input, cx| {
30- input.set_value(
31- to_units(settings.max_attachment_bytes, MB as u64).as_str(),
32- window,
33- cx,
34- )
35- });
36- self.chat.server_user_quota.update(cx, |input, cx| {
37- input.set_value(
38- to_units(settings.user_quota_bytes, MB as u64).as_str(),
39- window,
40- cx,
41- )
42- });
43- self.chat.server_community_quota.update(cx, |input, cx| {
44- input.set_value(
45- to_units(settings.community_quota_bytes, MB as u64).as_str(),
46- window,
47- cx,
48- )
49- });
50- self.chat.server_message_retention.update(cx, |input, cx| {
51- input.set_value(
52- settings.message_retention_days.to_string().as_str(),
53- window,
54- cx,
55- )
56- });
57- self.chat
58- .server_attachment_retention
59- .update(cx, |input, cx| {
60- input.set_value(
61- settings.attachment_retention_days.to_string().as_str(),
62- window,
63- cx,
64- )
65- });
66- self.chat.server_announcement.update(cx, |input, cx| {
67- input.set_value(settings.announcement.as_str(), window, cx)
68- });
69- self.chat.server_max_communities.update(cx, |input, cx| {
70- input.set_value(
71- settings.max_communities_per_user.to_string().as_str(),
72- window,
73- cx,
74- )
75- });
76- self.chat.server_max_message_length.update(cx, |input, cx| {
77- input.set_value(settings.max_message_length.to_string().as_str(), window, cx)
78- });
79- self.chat.server_max_avatar.update(cx, |input, cx| {
80- input.set_value(
81- to_units(settings.max_avatar_bytes, KB as u64).as_str(),
82- window,
83- cx,
84- )
85- });
86- self.chat
87- .server_messages_per_minute
88- .update(cx, |input, cx| {
89- input.set_value(
90- settings.messages_per_minute.to_string().as_str(),
91- window,
92- cx,
93- )
94- });
95- self.chat.server_logins_per_minute.update(cx, |input, cx| {
96- input.set_value(settings.logins_per_minute.to_string().as_str(), window, cx)
97- });
28+ let chat = &self.chat;
29+ set_input(&chat.server_name, &settings.name, window, cx);
30+ set_input(
31+ &chat.server_limit,
32+ &to_units(settings.max_attachment_bytes, MB as u64),
33+ window,
34+ cx,
35+ );
36+ set_input(
37+ &chat.server_user_quota,
38+ &to_units(settings.user_quota_bytes, MB as u64),
39+ window,
40+ cx,
41+ );
42+ set_input(
43+ &chat.server_community_quota,
44+ &to_units(settings.community_quota_bytes, MB as u64),
45+ window,
46+ cx,
47+ );
48+ set_input(
49+ &chat.server_message_retention,
50+ &settings.message_retention_days.to_string(),
51+ window,
52+ cx,
53+ );
54+ set_input(
55+ &chat.server_attachment_retention,
56+ &settings.attachment_retention_days.to_string(),
57+ window,
58+ cx,
59+ );
60+ set_input(
61+ &chat.server_announcement,
62+ &settings.announcement,
63+ window,
64+ cx,
65+ );
66+ set_input(
67+ &chat.server_max_communities,
68+ &settings.max_communities_per_user.to_string(),
69+ window,
70+ cx,
71+ );
72+ set_input(
73+ &chat.server_max_message_length,
74+ &settings.max_message_length.to_string(),
75+ window,
76+ cx,
77+ );
78+ set_input(
79+ &chat.server_max_avatar,
80+ &to_units(settings.max_avatar_bytes, KB as u64),
81+ window,
82+ cx,
83+ );
84+ set_input(
85+ &chat.server_messages_per_minute,
86+ &settings.messages_per_minute.to_string(),
87+ window,
88+ cx,
89+ );
90+ set_input(
91+ &chat.server_logins_per_minute,
92+ &settings.logins_per_minute.to_string(),
93+ window,
94+ cx,
95+ );
9896 }
9997
10098 pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
crates/client/src/gui/builder/storage.rsmodified+7 -15
@@ -259,24 +259,16 @@ impl Yumush {
259259 }
260260 self.search_attachments(window, cx);
261261 self.load_backups(window, cx);
262- let network = self.network.clone();
263-
264- cx.spawn_in(window, async move |this, cx| {
265- let (users, communities) = match network.storage_usage().await {
266- Ok(usage) => usage,
267- Err(error) => {
268- notify_error(&this, cx, error);
269- return;
270- }
271- };
272-
273- let _ = this.update(cx, |yumush, cx| {
262+ self.fetch_builder(
263+ window,
264+ cx,
265+ |network| async move { network.storage_usage().await },
266+ |yumush, (users, communities), cx| {
274267 yumush.chat.builder_usage_users = users;
275268 yumush.chat.builder_usage_communities = communities;
276269 cx.notify();
277- });
278- })
279- .detach();
270+ },
271+ );
280272 }
281273
282274 pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context<Self>) {
crates/client/src/gui/chat.rsmodified+81 -78
@@ -366,7 +366,11 @@ impl Chat {
366366 SelectState::new(
367367 SearchableVec::new(
368368 std::iter::once("All")
369- .chain(AdminActionKind::ALL.into_iter().map(AdminActionKind::as_str))
369+ .chain(
370+ AdminActionKind::ALL
371+ .into_iter()
372+ .map(AdminActionKind::as_str),
373+ )
370374 .collect::<Vec<_>>(),
371375 ),
372376 Some(IndexPath::new(0)),
@@ -1198,16 +1202,14 @@ impl Yumush {
11981202 let text = self.announcement()?;
11991203
12001204 Some(
1201- accent_bar(palette)
1202- .child(text.to_string())
1203- .child(
1204- clickable(
1205- "dismiss_announcement",
1206- palette,
1207- entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)),
1208- )
1209- .child("×"),
1210- ),
1205+ accent_bar(palette).child(text.to_string()).child(
1206+ clickable(
1207+ "dismiss_announcement",
1208+ palette,
1209+ entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)),
1210+ )
1211+ .child("×"),
1212+ ),
12111213 )
12121214 }
12131215
@@ -1907,9 +1909,8 @@ impl Yumush {
19071909 Ok(participants) => {
19081910 network.set_deafened(deafened);
19091911 let _ = this.update_in(cx, |yumush, _, cx| {
1910- let muted = muted
1911- || yumush.is_server_muted()
1912- || yumush.hidden_in(&community_id);
1912+ let muted =
1913+ muted || yumush.is_server_muted() || yumush.hidden_in(&community_id);
19131914 yumush.network.set_muted(muted);
19141915 yumush.chat.voice.insert(community_id.clone(), participants);
19151916 yumush.chat.voice_state = VoiceState::In {
@@ -2486,71 +2487,73 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -
24862487 .border_1()
24872488 .border_color(palette.border)
24882489 .bg(palette.panel)
2489- .children(
2490- members
2491- .iter()
2492- .map(|MemberRow { user, rank, in_voice, muted, presence }| {
2493- profile_popover(
2494- format!("member_{}", user.id),
2495- Anchor::TopRight,
2496- user,
2497- &entity,
2498- hoverable(
2499- format!("member_trigger_{}", user.id),
2500- div()
2501- .h(px(30.))
2502- .px(px(8.))
2503- .flex()
2504- .items_center()
2505- .gap(px(8.))
2506- .rounded(px(6.))
2507- .child(presence_avatar(
2508- avatar(palette, user, px(18.), text(9.), &avatars),
2509- *presence,
2510- px(18.),
2511- palette,
2512- ))
2513- .child(
2514- div()
2515- .flex_1()
2516- .min_w_0()
2517- .flex()
2518- .flex_col()
2519- .child(
2520- div()
2521- .flex()
2522- .items_center()
2523- .gap(px(6.))
2524- .child(user.username.clone())
2525- .children(rank_tag(*rank, palette))
2526- .children(in_voice.then(|| {
2527- Icon::new(IconName::Headphones)
2528- .w(px(12.))
2529- .h(px(12.))
2530- .text_color(palette.muted)
2531- }))
2532- .children(muted.then(|| {
2533- Icon::new(IconName::MicOff)
2534- .w(px(12.))
2535- .h(px(12.))
2536- .text_color(palette.danger)
2537- })),
2538- )
2539- .children((!user.status.is_empty()).then(
2540- || {
2541- div()
2542- .text_size(text(11.))
2490+ .children(members.iter().map(
2491+ |MemberRow {
2492+ user,
2493+ rank,
2494+ in_voice,
2495+ muted,
2496+ presence,
2497+ }| {
2498+ profile_popover(
2499+ format!("member_{}", user.id),
2500+ Anchor::TopRight,
2501+ user,
2502+ &entity,
2503+ hoverable(
2504+ format!("member_trigger_{}", user.id),
2505+ div()
2506+ .h(px(30.))
2507+ .px(px(8.))
2508+ .flex()
2509+ .items_center()
2510+ .gap(px(8.))
2511+ .rounded(px(6.))
2512+ .child(presence_avatar(
2513+ avatar(palette, user, px(18.), text(9.), &avatars),
2514+ *presence,
2515+ px(18.),
2516+ palette,
2517+ ))
2518+ .child(
2519+ div()
2520+ .flex_1()
2521+ .min_w_0()
2522+ .flex()
2523+ .flex_col()
2524+ .child(
2525+ div()
2526+ .flex()
2527+ .items_center()
2528+ .gap(px(6.))
2529+ .child(user.username.clone())
2530+ .children(rank_tag(*rank, palette))
2531+ .children(in_voice.then(|| {
2532+ Icon::new(IconName::Headphones)
2533+ .w(px(12.))
2534+ .h(px(12.))
25432535 .text_color(palette.muted)
2544- .truncate()
2545- .child(user.status.clone())
2546- },
2547- )),
2548- ),
2549- palette,
2550- ),
2551- )
2552- }),
2553- ),
2536+ }))
2537+ .children(muted.then(|| {
2538+ Icon::new(IconName::MicOff)
2539+ .w(px(12.))
2540+ .h(px(12.))
2541+ .text_color(palette.danger)
2542+ })),
2543+ )
2544+ .children((!user.status.is_empty()).then(|| {
2545+ div()
2546+ .text_size(text(11.))
2547+ .text_color(palette.muted)
2548+ .truncate()
2549+ .child(user.status.clone())
2550+ })),
2551+ ),
2552+ palette,
2553+ ),
2554+ )
2555+ },
2556+ )),
25542557 Anchor::TopRight,
25552558 )
25562559 })
crates/client/src/gui/composer.rsmodified+6 -1
@@ -552,7 +552,12 @@ pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i
552552 Popover::new("poll_popover")
553553 .anchor(Anchor::BottomLeft)
554554 .appearance(false)
555- .trigger(trigger_icon("poll_trigger", IconName::ChartBar, 28., palette))
555+ .trigger(trigger_icon(
556+ "poll_trigger",
557+ IconName::ChartBar,
558+ 28.,
559+ palette,
560+ ))
556561 .content(move |_, _, cx| {
557562 let popover = cx.entity();
558563 let toggle = entity.clone();
crates/client/src/gui/forward.rsmodified+3 -5
@@ -11,9 +11,9 @@ use gpui_kit::{
1111 };
1212
1313 use super::{
14- Yumush, clickable,
14+ Yumush, clickable, community_name,
1515 composer::{Composer, poll_field},
16- community_name, notify_error, palette,
16+ notify_error, palette,
1717 };
1818
1919 pub struct Forward {
@@ -100,9 +100,7 @@ impl Render for Forward {
100100 .flex()
101101 .flex_col()
102102 .gap(px(10.))
103- .child(
104- poll_field(&self.filter, palette),
105- )
103+ .child(poll_field(&self.filter, palette))
106104 .child(
107105 Checkbox::new("keep_authors")
108106 .label("Keep authors")
crates/client/src/gui/media_view.rsmodified+2 -8
@@ -295,8 +295,7 @@ impl Yumush {
295295 return;
296296 };
297297 for path in paths {
298- let result =
299- upload_file(&this, &network, &community_id, path, maximum, cx).await;
298+ let result = upload_file(&this, &network, &community_id, path, maximum, cx).await;
300299 let _ = this.update(cx, |yumush, cx| {
301300 if let Ok(attachment) = &result {
302301 yumush.chat.media.pending.push(attachment.clone());
@@ -442,12 +441,7 @@ impl Yumush {
442441 cx: &mut Context<Self>,
443442 ) {
444443 let duration = duration_secs(&player);
445- let seek = cx.new(|_| {
446- SliderState::new()
447- .min(0.)
448- .max(duration)
449- .default_value(0.)
450- });
444+ let seek = cx.new(|_| SliderState::new().min(0.).max(duration).default_value(0.));
451445 let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {
452446 let SliderEvent::Release(value) = event else {
453447 return;
crates/client/src/gui/message_actions.rsmodified+9 -3
@@ -18,8 +18,9 @@ use super::{
1818 auth::field,
1919 avatar,
2020 chat::{Chat, ReportTarget},
21- clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in,
22- primary_button, sidebar,
21+ clickable,
22+ composer::trigger_icon,
23+ entity_action, id_time, notify_error, pop_in, primary_button, sidebar,
2324 };
2425
2526 pub fn reactions(
@@ -234,7 +235,12 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) ->
234235 Popover::new("search_popover")
235236 .anchor(Anchor::TopRight)
236237 .appearance(false)
237- .trigger(trigger_icon("search_trigger", IconName::Search, 24., palette))
238+ .trigger(trigger_icon(
239+ "search_trigger",
240+ IconName::Search,
241+ 24.,
242+ palette,
243+ ))
238244 .content(move |_, _, cx| {
239245 let popover = cx.entity();
240246 pop_in(
crates/client/src/gui/poll.rsmodified+1 -1
@@ -153,7 +153,7 @@ pub fn poll_card(
153153 .flex()
154154 .items_center()
155155 .gap(px(8.))
156- .children(poll.closed.then(|| "Closed"))
156+ .children(poll.closed.then_some("Closed"))
157157 .children(close_id.map(|close_id| {
158158 let close_entity = entity.clone();
159159 clickable(
crates/client/src/gui/settings_page.rsmodified+2 -8
@@ -249,11 +249,7 @@ impl Yumush {
249249 }
250250 }
251251
252-fn apply_user(
253- this: &WeakEntity<Yumush>,
254- cx: &mut AsyncWindowContext,
255- result: Result<User, Error>,
256-) {
252+fn apply_user(this: &WeakEntity<Yumush>, cx: &mut AsyncWindowContext, result: Result<User, Error>) {
257253 match result {
258254 Ok(user) => {
259255 let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
@@ -278,9 +274,7 @@ pub(super) fn picked_avatar(
278274 let Ok(Ok(Some(paths))) = picked.await else {
279275 return None;
280276 };
281- let Some(path) = paths.into_iter().next() else {
282- return None;
283- };
277+ let path = paths.into_iter().next()?;
284278 Some(
285279 executor
286280 .spawn(async move { read_avatar_file(&path, maximum) })
crates/client/src/gui/sidebar.rsmodified+5 -1
@@ -284,7 +284,11 @@ impl Yumush {
284284 let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;
285285 let direct = self.chat.unread_direct();
286286 let tabs = [
287- (SidebarTab::Communities, "Communities", self.chat.unread_groups()),
287+ (
288+ SidebarTab::Communities,
289+ "Communities",
290+ self.chat.unread_groups(),
291+ ),
288292 (
289293 SidebarTab::Messages,
290294 "Messages",
crates/client/src/gui/voice_note.rsmodified+8 -7
@@ -15,7 +15,9 @@ use gpui_kit::{
1515 use rtrb::{Consumer, RingBuffer};
1616
1717 use super::{
18- Palette, Tooltip as _, Yumush, chat::VoiceState, clickable,
18+ Palette, Tooltip as _, Yumush,
19+ chat::VoiceState,
20+ clickable,
1921 media_view::{time_text, upload_file},
2022 notify_error, primary_button, text,
2123 };
@@ -263,12 +265,11 @@ impl Yumush {
263265 else {
264266 return;
265267 };
266- let attachment = match upload_file(&this, &network, &community_id, path, maximum, cx)
267- .await
268- {
269- Ok(attachment) => attachment,
270- Err(error) => return notify_error(&this, cx, error),
271- };
268+ let attachment =
269+ match upload_file(&this, &network, &community_id, path, maximum, cx).await {
270+ Ok(attachment) => attachment,
271+ Err(error) => return notify_error(&this, cx, error),
272+ };
272273 if let Err(error) = network
273274 .create_message(&community_id, "", vec![attachment.id], None)
274275 .await
crates/client/src/mutes.rsmodified+1 -2
@@ -9,8 +9,7 @@ fn prefix(account_user_id: &str) -> String {
99 }
1010
1111 pub fn load(account_user_id: &str) -> HashSet<String> {
12- let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok())
13- else {
12+ let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) else {
1413 return HashSet::new();
1514 };
1615 let prefix = prefix(account_user_id);
crates/client/src/network.rsmodified+32 -58
@@ -18,9 +18,8 @@ use common::{
1818 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
1919 },
2020 network::{
21- DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
22- receive_download_status, receive_event, send_encoded, send_request,
23- send_stream_kind, send_upload_header,
21+ RESPONSE_MAX_READ_LENGTH, StreamKind, open_download, receive_decoded, receive_event,
22+ send_request, send_stream_kind, send_upload_header,
2423 },
2524 request::{DownloadRequest, Request, UploadHeader},
2625 response::Response,
@@ -145,7 +144,11 @@ impl NetworkHandle {
145144 Response::Session { user, token } => (user, token),
146145 _ => return Err(Error::Server),
147146 };
148- let _ = self.done(Request::SetDevice { name: device_name() }).await;
147+ let _ = self
148+ .done(Request::SetDevice {
149+ name: device_name(),
150+ })
151+ .await;
149152
150153 Ok(session)
151154 }
@@ -1506,37 +1509,21 @@ async fn backup_download(
15061509 name: &str,
15071510 path: &Path,
15081511 ) -> Result<(), Error> {
1509- let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
1510- send_stream_kind(StreamKind::Backup, &mut send_stream).await?;
1511- send_encoded(
1512- &Request::DownloadBackup {
1513- name: name.to_string(),
1514- },
1515- &mut send_stream,
1516- )
1517- .await?;
1518- send_stream.finish()?;
1519-
1520- match receive_download_status(&mut receive_stream).await? {
1521- DownloadStatus::Error => {
1522- Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
1523- }
1524- DownloadStatus::Ok => {
1525- let mut length_bytes = [0u8; 8];
1526- receive_stream.read_exact(&mut length_bytes).await?;
1527- let length = u64::from_le_bytes(length_bytes);
1528-
1529- let mut file = tokio::fs::File::create(path).await?;
1530- let copied = tokio::io::copy(&mut receive_stream, &mut file).await?;
1531- if copied != length {
1532- return Err(Error::Network(format!(
1533- "backup truncated ({copied} < {length})"
1534- )));
1535- }
1512+ let request = Request::DownloadBackup {
1513+ name: name.to_string(),
1514+ };
1515+ let (mut receive_stream, length) =
1516+ open_download(connection, StreamKind::Backup, &request).await?;
15361517
1537- Ok(())
1538- }
1518+ let mut file = tokio::fs::File::create(path).await?;
1519+ let copied = tokio::io::copy(&mut receive_stream, &mut file).await?;
1520+ if copied != length {
1521+ return Err(Error::Network(format!(
1522+ "backup truncated ({copied} < {length})"
1523+ )));
15391524 }
1525+
1526+ Ok(())
15401527 }
15411528
15421529 async fn download(
@@ -1544,37 +1531,24 @@ async fn download(
15441531 attachment_id: &str,
15451532 thumbnail: bool,
15461533 ) -> Result<Vec<u8>, Error> {
1547- let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
1548- send_stream_kind(StreamKind::Download, &mut send_stream).await?;
15491534 let request = DownloadRequest {
15501535 attachment_id: attachment_id.to_string(),
15511536 thumbnail,
15521537 };
1553- send_encoded(&request, &mut send_stream).await?;
1554- send_stream.finish()?;
1555-
1556- match receive_download_status(&mut receive_stream).await? {
1557- DownloadStatus::Error => {
1558- Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
1559- }
1560- DownloadStatus::Ok => {
1561- let mut length_bytes = [0u8; 8];
1562- receive_stream.read_exact(&mut length_bytes).await?;
1563-
1564- let length = u64::from_le_bytes(length_bytes);
1565- if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
1566- return Err(Error::ReadBoundExceed {
1567- actual: length as usize,
1568- maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize,
1569- });
1570- }
1571-
1572- let mut bytes = vec![0u8; length as usize];
1573- receive_stream.read_exact(&mut bytes).await?;
1538+ let (mut receive_stream, length) =
1539+ open_download(connection, StreamKind::Download, &request).await?;
15741540
1575- Ok(bytes)
1576- }
1541+ if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
1542+ return Err(Error::ReadBoundExceed {
1543+ actual: length as usize,
1544+ maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize,
1545+ });
15771546 }
1547+
1548+ let mut bytes = vec![0u8; length as usize];
1549+ receive_stream.read_exact(&mut bytes).await?;
1550+
1551+ Ok(bytes)
15781552 }
15791553
15801554 async fn dispatch(
crates/client/src/voice/audio.rsmodified+8 -6
@@ -22,6 +22,14 @@ mod backend;
2222 #[cfg(target_os = "windows")]
2323 #[path = "audio/wasapi.rs"]
2424 mod backend;
25+#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
26+mod backend {
27+ use super::Devices;
28+
29+ pub fn devices() -> Devices {
30+ Devices::default()
31+ }
32+}
2533
2634 const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);
2735 const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100);
@@ -88,7 +96,6 @@ fn device(_: Option<Capture>, _: Playback, _: Choice) -> Audio {
8896 Audio::Silent
8997 }
9098
91-#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
9299 pub fn devices() -> Devices {
93100 match mode() {
94101 Mode::Off | Mode::Tone => Devices::default(),
@@ -96,11 +103,6 @@ pub fn devices() -> Devices {
96103 }
97104 }
98105
99-#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
100-pub fn devices() -> Devices {
101- Devices::default()
102-}
103-
104106 pub fn record(capture: &Capture, samples: impl IntoIterator<Item = f32>) {
105107 let Ok(mut capture) = capture.try_lock() else {
106108 return;
crates/common/src/error.rsmodified+44 -30
@@ -100,6 +100,48 @@ impl Display for InvalidInput {
100100 }
101101 }
102102
103+#[derive(Debug, Clone, Copy, Encode, Decode)]
104+pub enum Field {
105+ User,
106+ Password,
107+ Community,
108+ Message,
109+ Status,
110+ Avatar,
111+ Attachment,
112+ AttachmentName,
113+ Reason,
114+ Forward,
115+ AttachmentLimit,
116+ Device,
117+ BackupName,
118+ Quota,
119+ Announcement,
120+}
121+
122+impl Display for Field {
123+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124+ let label = match self {
125+ Field::User => "username:",
126+ Field::Password => "password:",
127+ Field::Community => "community name:",
128+ Field::Message => "message:",
129+ Field::Status => "status:",
130+ Field::Avatar => "avatar:",
131+ Field::Attachment => "file",
132+ Field::AttachmentName => "file name:",
133+ Field::Reason => "reason:",
134+ Field::Forward => "forward:",
135+ Field::AttachmentLimit => "max attachment size:",
136+ Field::Device => "device:",
137+ Field::BackupName => "backup name:",
138+ Field::Quota => "quota:",
139+ Field::Announcement => "announcement:",
140+ };
141+ write!(f, "{label}")
142+ }
143+}
144+
103145 #[derive(Debug, Clone, Encode, Decode, thiserror::Error)]
104146 pub enum Error {
105147 #[error("unauthenticated")]
@@ -124,26 +166,8 @@ pub enum Error {
124166 Decode(String),
125167 #[error("read bound exceeded ({actual} > {maximum})")]
126168 ReadBoundExceed { actual: usize, maximum: usize },
127- #[error("username: {0}")]
128- User(InvalidInput),
129- #[error("password: {0}")]
130- Password(InvalidInput),
131- #[error("community name: {0}")]
132- Community(InvalidInput),
133- #[error("message: {0}")]
134- Message(InvalidInput),
135- #[error("status: {0}")]
136- Status(InvalidInput),
137- #[error("avatar: {0}")]
138- Avatar(InvalidInput),
139- #[error("file {0}")]
140- Attachment(InvalidInput),
141- #[error("file name: {0}")]
142- AttachmentName(InvalidInput),
143- #[error("reason: {0}")]
144- Reason(InvalidInput),
145- #[error("forward: {0}")]
146- Forward(InvalidInput),
169+ #[error("{field} {input}")]
170+ Invalid { field: Field, input: InvalidInput },
147171 #[error("upload: {0}")]
148172 Upload(String),
149173 #[error("certificate: {0}")]
@@ -156,22 +180,12 @@ pub enum Error {
156180 Suspended,
157181 #[error("registration closed")]
158182 RegistrationClosed,
159- #[error("max attachment size: {0}")]
160- AttachmentLimit(InvalidInput),
161- #[error("device: {0}")]
162- Device(InvalidInput),
163- #[error("backup name: {0}")]
164- BackupName(InvalidInput),
165183 #[error("banned")]
166184 Banned,
167185 #[error("maintenance")]
168186 Maintenance,
169187 #[error("storage quota exceeded")]
170188 QuotaExceeded,
171- #[error("quota: {0}")]
172- Quota(InvalidInput),
173- #[error("announcement: {0}")]
174- Announcement(InvalidInput),
175189 #[error("limit reached")]
176190 LimitReached,
177191 #[error("too many requests, retry in {retry_after_seconds}s")]
crates/common/src/network.rsmodified+22 -0
@@ -90,6 +90,28 @@ pub async fn receive_download_status(
9090 DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))
9191 }
9292
93+pub async fn open_download<T: Encode>(
94+ connection: &quinn::Connection,
95+ kind: StreamKind,
96+ request: &T,
97+) -> Result<(RecvStream, u64), Error> {
98+ let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
99+ send_stream_kind(kind, &mut send_stream).await?;
100+ send_encoded(request, &mut send_stream).await?;
101+ send_stream.finish()?;
102+
103+ match receive_download_status(&mut receive_stream).await? {
104+ DownloadStatus::Error => {
105+ Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
106+ }
107+ DownloadStatus::Ok => {
108+ let mut length_bytes = [0u8; 8];
109+ receive_stream.read_exact(&mut length_bytes).await?;
110+ Ok((receive_stream, u64::from_le_bytes(length_bytes)))
111+ }
112+ }
113+}
114+
93115 async fn send_framed<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
94116 let payload = bitcode::encode(value);
95117 send_stream
crates/common/src/validate.rsmodified+35 -28
@@ -11,10 +11,14 @@ use crate::{
1111 MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS,
1212 MINIMUM_USERNAME_LENGTH, REACTIONS,
1313 },
14- error::{Error, InvalidInput},
14+ error::{Error, Field, InvalidInput},
1515 model::{Poll, ServerSettings},
1616 };
1717
18+fn invalid(field: Field) -> impl Fn(InvalidInput) -> Error {
19+ move |input| Error::Invalid { field, input }
20+}
21+
1822 fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
1923 if actual < minimum {
2024 return Err(InvalidInput::TooShort { minimum, actual });
@@ -51,7 +55,7 @@ pub fn validate_username(username: &str) -> Result<(), Error> {
5155 MAXIMUM_USERNAME_LENGTH,
5256 true,
5357 )
54- .map_err(Error::User)
58+ .map_err(invalid(Field::User))
5559 }
5660
5761 pub fn validate_password(password: &str) -> Result<(), Error> {
@@ -61,7 +65,7 @@ pub fn validate_password(password: &str) -> Result<(), Error> {
6165 MAXIMUM_PASSWORD_LENGTH,
6266 false,
6367 )
64- .map_err(Error::Password)
68+ .map_err(invalid(Field::Password))
6569 }
6670
6771 pub fn validate_community_name(name: &str) -> Result<(), Error> {
@@ -71,11 +75,11 @@ pub fn validate_community_name(name: &str) -> Result<(), Error> {
7175 MAXIMUM_COMMUNITY_NAME_LENGTH,
7276 true,
7377 )
74- .map_err(Error::Community)
78+ .map_err(invalid(Field::Community))
7579 }
7680
7781 pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> {
78- check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(Error::Message)
82+ check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(invalid(Field::Message))
7983 }
8084
8185 pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> {
@@ -84,15 +88,15 @@ pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> R
8488 } else {
8589 0
8690 };
87- check(body, minimum, maximum, false).map_err(Error::Message)
91+ check(body, minimum, maximum, false).map_err(invalid(Field::Message))
8892 }
8993
9094 pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {
91- check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(Error::Message)?;
95+ check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Message))?;
9296 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)
93- .map_err(Error::Message)?;
97+ .map_err(invalid(Field::Message))?;
9498 for option in options {
95- check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(Error::Message)?;
99+ check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Message))?;
96100 }
97101
98102 Ok(())
@@ -116,14 +120,16 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> {
116120 return Ok(());
117121 }
118122
119- Err(Error::Message(InvalidInput::ForbiddenCharacter))
123+ Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter))
120124 }
121125
122126 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
123- check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(Error::AttachmentName)?;
127+ check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(invalid(Field::AttachmentName))?;
124128
125129 if name.contains(['/', '\\']) || name.chars().any(char::is_control) {
126- return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter));
130+ return Err(invalid(Field::AttachmentName)(
131+ InvalidInput::ForbiddenCharacter,
132+ ));
127133 }
128134
129135 Ok(())
@@ -136,7 +142,7 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> {
136142 character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
137143 })
138144 {
139- return Err(Error::BackupName(InvalidInput::ForbiddenCharacter));
145+ return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter));
140146 }
141147
142148 Ok(())
@@ -151,19 +157,19 @@ fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {
151157 }
152158
153159 pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> {
154- check_size(size, maximum).map_err(Error::Attachment)
160+ check_size(size, maximum).map_err(invalid(Field::Attachment))
155161 }
156162
157163 pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {
158164 match limit {
159165 limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => {
160- Err(Error::AttachmentLimit(InvalidInput::TooSmall {
166+ Err(invalid(Field::AttachmentLimit)(InvalidInput::TooSmall {
161167 minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES,
162168 actual: limit,
163169 }))
164170 }
165171 limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => {
166- Err(Error::AttachmentLimit(InvalidInput::TooLarge {
172+ Err(invalid(Field::AttachmentLimit)(InvalidInput::TooLarge {
167173 maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES,
168174 actual: limit,
169175 }))
@@ -174,7 +180,7 @@ pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {
174180
175181 fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
176182 if quota != 0 && quota < minimum {
177- return Err(Error::Quota(InvalidInput::TooSmall {
183+ return Err(invalid(Field::Quota)(InvalidInput::TooSmall {
178184 minimum,
179185 actual: quota,
180186 }));
@@ -185,10 +191,10 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
185191
186192 pub fn validate_announcement(text: &str) -> Result<(), Error> {
187193 if text.contains(['\n', '\r']) {
188- return Err(Error::Announcement(InvalidInput::MultiLine));
194+ return Err(invalid(Field::Announcement)(InvalidInput::MultiLine));
189195 }
190196
191- check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement)
197+ check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement))
192198 }
193199
194200 pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> {
@@ -205,8 +211,9 @@ pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error>
205211 MINIMUM_MESSAGE_LENGTH,
206212 MAXIMUM_MESSAGE_LENGTH,
207213 )
208- .map_err(Error::Message)?;
209- check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64).map_err(Error::Avatar)
214+ .map_err(invalid(Field::Message))?;
215+ check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64)
216+ .map_err(invalid(Field::Avatar))
210217 }
211218
212219 pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
@@ -214,27 +221,27 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
214221 return Ok(());
215222 };
216223 if reason.contains(['\n', '\r']) {
217- return Err(Error::Reason(InvalidInput::MultiLine));
224+ return Err(invalid(Field::Reason)(InvalidInput::MultiLine));
218225 }
219- check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason)
226+ check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason))
220227 }
221228
222229 pub fn validate_forward(count: usize) -> Result<(), Error> {
223- check_length(count, 1, MAXIMUM_FORWARD_MESSAGES).map_err(Error::Forward)
230+ check_length(count, 1, MAXIMUM_FORWARD_MESSAGES).map_err(invalid(Field::Forward))
224231 }
225232
226233 pub fn validate_status(status: &str) -> Result<(), Error> {
227234 if status.contains(['\n', '\r']) {
228- return Err(Error::Status(InvalidInput::MultiLine));
235+ return Err(invalid(Field::Status)(InvalidInput::MultiLine));
229236 }
230237
231- check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status)
238+ check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status))
232239 }
233240
234241 pub fn validate_device(name: &str) -> Result<(), Error> {
235- check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device)
242+ check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(invalid(Field::Device))
236243 }
237244
238245 pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> {
239- check_size(bytes.len() as u64, maximum).map_err(Error::Avatar)
246+ check_size(bytes.len() as u64, maximum).map_err(invalid(Field::Avatar))
240247 }
crates/server/src/admin_log.rsmodified+33 -34
@@ -1,6 +1,6 @@
11 use common::{
22 constant::LOG_PAGE_LIMIT,
3- model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail},
3+ model::{AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail},
44 time,
55 };
66 use turso::Connection;
@@ -8,53 +8,52 @@ use turso::Connection;
88 use crate::{database::new_id, error::Error, user};
99
1010 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {
11- Some(match text {
12- "role_changed" => AdminAction::RoleChanged {
11+ Some(match AdminActionKind::parse(text)? {
12+ AdminActionKind::RoleChanged => AdminAction::RoleChanged {
1313 role: Role::parse(&detail?)?,
1414 },
15- "user_deleted" => AdminAction::UserDeleted,
16- "user_suspended" => AdminAction::UserSuspended,
17- "user_unsuspended" => AdminAction::UserUnsuspended,
18- "sessions_revoked" => AdminAction::SessionsRevoked,
19- "password_reset" => AdminAction::PasswordReset,
20- "profile_cleared" => AdminAction::ProfileCleared,
21- "user_created" => AdminAction::UserCreated,
22- "community_deleted" => AdminAction::CommunityDeleted,
23- "ownership_transferred" => AdminAction::OwnershipTransferred,
24- "settings_changed" => AdminAction::SettingsChanged,
25- "user_renamed" => AdminAction::UserRenamed { from: detail? },
26- "user_timed_out" => AdminAction::UserTimedOut {
15+ AdminActionKind::UserDeleted => AdminAction::UserDeleted,
16+ AdminActionKind::UserSuspended => AdminAction::UserSuspended,
17+ AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended,
18+ AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked,
19+ AdminActionKind::PasswordReset => AdminAction::PasswordReset,
20+ AdminActionKind::ProfileCleared => AdminAction::ProfileCleared,
21+ AdminActionKind::UserCreated => AdminAction::UserCreated,
22+ AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted,
23+ AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred,
24+ AdminActionKind::SettingsChanged => AdminAction::SettingsChanged,
25+ AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? },
26+ AdminActionKind::UserTimedOut => AdminAction::UserTimedOut {
2727 minutes: detail?.parse().ok()?,
2828 },
29- "user_banned" => AdminAction::UserBanned { reason: detail },
30- "ban_removed" => AdminAction::BanRemoved,
31- "invite_created" => AdminAction::InviteCreated,
32- "invite_deleted" => AdminAction::InviteDeleted,
33- "report_handled" => AdminAction::ReportHandled {
29+ AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail },
30+ AdminActionKind::BanRemoved => AdminAction::BanRemoved,
31+ AdminActionKind::InviteCreated => AdminAction::InviteCreated,
32+ AdminActionKind::InviteDeleted => AdminAction::InviteDeleted,
33+ AdminActionKind::ReportHandled => AdminAction::ReportHandled {
3434 status: ReportStatus::parse(&detail?)?,
3535 },
36- "message_deleted" => AdminAction::MessageDeleted,
37- "user_purged" => AdminAction::UserPurged {
36+ AdminActionKind::MessageDeleted => AdminAction::MessageDeleted,
37+ AdminActionKind::UserPurged => AdminAction::UserPurged {
3838 messages: detail?.parse().ok()?,
3939 },
40- "voice_kicked" => AdminAction::VoiceKicked,
41- "voice_muted" => AdminAction::VoiceMuted {
40+ AdminActionKind::VoiceKicked => AdminAction::VoiceKicked,
41+ AdminActionKind::VoiceMuted => AdminAction::VoiceMuted {
4242 muted: detail?.parse().ok()?,
4343 },
44- "community_voice_set" => AdminAction::CommunityVoiceSet {
44+ AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet {
4545 enabled: detail?.parse().ok()?,
4646 },
47- "attachment_deleted" => AdminAction::AttachmentDeleted,
48- "ghost_enabled" => AdminAction::GhostEnabled,
49- "ghost_disabled" => AdminAction::GhostDisabled,
50- "ghost_visit" => AdminAction::GhostVisit,
51- "ghost_voice" => AdminAction::GhostVoice {
47+ AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted,
48+ AdminActionKind::GhostEnabled => AdminAction::GhostEnabled,
49+ AdminActionKind::GhostDisabled => AdminAction::GhostDisabled,
50+ AdminActionKind::GhostVisit => AdminAction::GhostVisit,
51+ AdminActionKind::GhostVoice => AdminAction::GhostVoice {
5252 seconds: detail?.parse().ok()?,
5353 },
54- "backup_created" => AdminAction::BackupCreated { name: detail? },
55- "backup_deleted" => AdminAction::BackupDeleted { name: detail? },
56- "backup_downloaded" => AdminAction::BackupDownloaded { name: detail? },
57- _ => return None,
54+ AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? },
55+ AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? },
56+ AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? },
5857 })
5958 }
6059
crates/server/src/attachment.rsmodified+0 -14
@@ -57,20 +57,6 @@ pub struct Stored {
5757 pub message_id: Option<String>,
5858 }
5959
60-pub fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> {
61- let directory = Path::new(database_path)
62- .parent()
63- .unwrap_or_else(|| Path::new(""))
64- .join(name);
65- std::fs::create_dir_all(&directory)?;
66-
67- Ok(directory)
68-}
69-
70-pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
71- sibling_directory(database_path, "attachments")
72-}
73-
7460 fn from_row(row: &Row) -> Result<Attachment, Error> {
7561 let size: i64 = row.get(2)?;
7662 let kind: String = row.get(3)?;
crates/server/src/backup.rsmodified+1 -5
@@ -26,10 +26,6 @@ use crate::{
2626 const PREFIX: &str = "yumush-";
2727 const EXTENSION: &str = ".db";
2828
29-pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
30- attachment::sibling_directory(database_path, "backups")
31-}
32-
3329 fn created_secs(name: &str) -> Option<u64> {
3430 name.strip_prefix(PREFIX)?
3531 .strip_suffix(EXTENSION)?
@@ -75,7 +71,7 @@ pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> {
7571 backups.push(info(directory, &name)?);
7672 }
7773 }
78- backups.sort_by(|left, right| right.created_ms.cmp(&left.created_ms));
74+ backups.sort_by_key(|backup| std::cmp::Reverse(backup.created_ms));
7975
8076 Ok(backups)
8177 }
crates/server/src/lib.rsmodified+14 -2
@@ -29,6 +29,8 @@ pub mod voice;
2929 #[cfg(test)]
3030 mod test;
3131
32+use std::path::{Path, PathBuf};
33+
3234 use common::{config::Config, error::Error as CommonError, model::Role};
3335
3436 use crate::error::Error;
@@ -57,6 +59,16 @@ fn load_config() -> Result<ServerConfig, Error> {
5759 })
5860 }
5961
62+fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> {
63+ let directory = Path::new(database_path)
64+ .parent()
65+ .unwrap_or_else(|| Path::new(""))
66+ .join(name);
67+ std::fs::create_dir_all(&directory)?;
68+
69+ Ok(directory)
70+}
71+
6072 pub async fn showtime() -> Result<(), Error> {
6173 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
6274
@@ -64,8 +76,8 @@ pub async fn showtime() -> Result<(), Error> {
6476
6577 let database = database::open(&config.database_path).await?;
6678 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;
67- let attachments = attachment::directory(&config.database_path)?;
68- let backups = backup::directory(&config.database_path)?;
79+ let attachments = sibling_directory(&config.database_path, "attachments")?;
80+ let backups = sibling_directory(&config.database_path, "backups")?;
6981 tokio::spawn(attachment::collect(database.clone(), attachments.clone()));
7082 tokio::spawn(retention::collect(database.clone(), attachments.clone()));
7183
crates/server/src/message.rsmodified+9 -12
@@ -1,16 +1,13 @@
11 use std::{collections::HashMap, path::Path};
22
33 use common::{
4- constant::{
5- MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT,
6- },
7- error::{Error as CommonError, InvalidInput},
4+ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
5+ error::{Error as CommonError, Field, InvalidInput},
86 model::{
97 CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage,
108 User,
119 },
1210 time,
13- validate::{validate_message_body, validate_new_message},
1411 };
1512 use turso::{Connection, Row};
1613
@@ -326,7 +323,6 @@ pub async fn create(
326323 reply_to: Option<&str>,
327324 conn: &Connection,
328325 ) -> Result<Message, Error> {
329- validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
330326 if let Some(reply_to) = reply_to {
331327 ensure_in_community(reply_to, community_id, conn).await?;
332328 }
@@ -485,8 +481,6 @@ pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message
485481 }
486482
487483 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {
488- validate_message_body(body, MAXIMUM_MESSAGE_LENGTH)?;
489-
490484 let updated = conn
491485 .execute(
492486 "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",
@@ -698,10 +692,13 @@ pub async fn forward(
698692 }
699693 }
700694 if entries.len() > MAXIMUM_FORWARD_MESSAGES {
701- return Err(CommonError::Forward(InvalidInput::TooLong {
702- maximum: MAXIMUM_FORWARD_MESSAGES,
703- actual: entries.len(),
704- })
695+ return Err(CommonError::Invalid {
696+ field: Field::Forward,
697+ input: InvalidInput::TooLong {
698+ maximum: MAXIMUM_FORWARD_MESSAGES,
699+ actual: entries.len(),
700+ },
701+ }
705702 .into());
706703 }
707704
crates/server/src/network.rsmodified+1 -2
@@ -12,7 +12,6 @@ use common::{
1212 send_response,
1313 },
1414 request::Request,
15- voice::decode_packet,
1615 };
1716 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
1817 use tokio::{sync::mpsc, task::JoinHandle};
@@ -280,7 +279,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
280279
281280 async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, voice: Voice) {
282281 while let Ok(bytes) = connection.read_datagram().await {
283- if signed_user_id(&state).is_some() && decode_packet(&bytes).is_some() {
282+ if signed_user_id(&state).is_some() {
284283 voice.relay(connection.stable_id(), &bytes);
285284 }
286285 }
crates/server/src/request.rsmodified+68 -104
@@ -471,7 +471,10 @@ async fn dispatch(
471471 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
472472 let members = user_community::members(&community_id, &conn).await?;
473473 let event = Event::CommunityUpdated(updated.clone());
474- (Response::Community(updated), vec![broadcast(event, &members)])
474+ (
475+ Response::Community(updated),
476+ vec![broadcast(event, &members)],
477+ )
475478 }
476479 Request::UpdateCommunityAvatar {
477480 community_id,
@@ -493,7 +496,10 @@ async fn dispatch(
493496 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
494497 let members = user_community::members(&community_id, &conn).await?;
495498 let event = Event::CommunityUpdated(updated.clone());
496- (Response::Community(updated), vec![broadcast(event, &members)])
499+ (
500+ Response::Community(updated),
501+ vec![broadcast(event, &members)],
502+ )
497503 }
498504 Request::DeleteCommunity { community_id } => {
499505 let me = authenticated(state, &conn).await?;
@@ -1143,7 +1149,13 @@ async fn dispatch(
11431149 } => {
11441150 let me = authenticated(state, &conn).await?;
11451151 ensure_editable(&community_id, &conn).await?;
1146- allowed(&me, &community_id, &conn, permission::can_transfer_ownership).await?;
1152+ allowed(
1153+ &me,
1154+ &community_id,
1155+ &conn,
1156+ permission::can_transfer_ownership,
1157+ )
1158+ .await?;
11471159 let tx = conn.transaction().await?;
11481160 let members = user_community::members(&community_id, &tx).await?;
11491161 let target = members
@@ -2128,9 +2140,28 @@ mod tests {
21282140 test,
21292141 };
21302142
2131- async fn signed_in(username: &str, db: &DB) -> Mutex<State> {
2132- let state = Mutex::new(State::Anonymous);
2143+ async fn send(
2144+ request: Request,
2145+ state: &Mutex<State>,
2146+ db: &DB,
2147+ services: &Services,
2148+ ) -> Response {
21332149 handle(
2150+ request,
2151+ state,
2152+ db,
2153+ services,
2154+ None,
2155+ &test::directory(),
2156+ &test::directory(),
2157+ )
2158+ .await
2159+ .0
2160+ }
2161+
2162+ async fn signed_in(username: &str, db: &DB, services: &Services) -> Mutex<State> {
2163+ let state = Mutex::new(State::Anonymous);
2164+ send(
21342165 Request::Register {
21352166 username: username.to_string(),
21362167 password: "password".to_string(),
@@ -2138,10 +2169,7 @@ mod tests {
21382169 },
21392170 &state,
21402171 db,
2141- &Services::default(),
2142- None,
2143- &test::directory(),
2144- &test::directory(),
2172+ services,
21452173 )
21462174 .await;
21472175
@@ -2154,46 +2182,37 @@ mod tests {
21542182 member: &Mutex<State>,
21552183 username: &str,
21562184 db: &DB,
2185+ services: &Services,
21572186 ) {
2158- let services = Services::default();
2159- let (Response::User(member_user), _) = handle(
2187+ let Response::User(member_user) = send(
21602188 Request::FindUser {
21612189 username: username.to_string(),
21622190 },
21632191 owner,
21642192 db,
2165- &services,
2166- None,
2167- &test::directory(),
2168- &test::directory(),
2193+ services,
21692194 )
21702195 .await
21712196 else {
21722197 panic!("user not found");
21732198 };
2174- handle(
2199+ send(
21752200 Request::Invite {
21762201 community_id: community_id.to_string(),
21772202 user_id: member_user.id,
21782203 },
21792204 owner,
21802205 db,
2181- &services,
2182- None,
2183- &test::directory(),
2184- &test::directory(),
2206+ services,
21852207 )
21862208 .await;
2187- handle(
2209+ send(
21882210 Request::AcceptInvitation {
21892211 community_id: community_id.to_string(),
21902212 },
21912213 member,
21922214 db,
2193- &services,
2194- None,
2195- &test::directory(),
2196- &test::directory(),
2215+ services,
21972216 )
21982217 .await;
21992218 }
@@ -2202,26 +2221,23 @@ mod tests {
22022221 async fn plain_member_cannot_rename() {
22032222 let db = test::get_database().await;
22042223 let services = Services::default();
2205- let owner = signed_in("Owner", &db).await;
2206- let member = signed_in("Member", &db).await;
2207- let (Response::Community(community), _) = handle(
2224+ let owner = signed_in("Owner", &db, &services).await;
2225+ let member = signed_in("Member", &db, &services).await;
2226+ let Response::Community(community) = send(
22082227 Request::CreateCommunity {
22092228 name: "The Community".to_string(),
22102229 },
22112230 &owner,
22122231 &db,
22132232 &services,
2214- None,
2215- &test::directory(),
2216- &test::directory(),
22172233 )
22182234 .await
22192235 else {
22202236 panic!("community not created");
22212237 };
2222- invite_and_accept(&community.id, &owner, &member, "Member", &db).await;
2238+ invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
22232239
2224- let (response, _) = handle(
2240+ let response = send(
22252241 Request::UpdateCommunity {
22262242 community_id: community.id,
22272243 name: "Renamed".to_string(),
@@ -2229,9 +2245,6 @@ mod tests {
22292245 &member,
22302246 &db,
22312247 &services,
2232- None,
2233- &test::directory(),
2234- &test::directory(),
22352248 )
22362249 .await;
22372250
@@ -2242,86 +2255,57 @@ mod tests {
22422255 async fn accepted_friend_request_befriends_both() {
22432256 let db = test::get_database().await;
22442257 let services = Services::default();
2245- let first = signed_in("First", &db).await;
2246- let second = signed_in("Second", &db).await;
2247- let (Response::User(first_user), _) = handle(
2258+ let first = signed_in("First", &db, &services).await;
2259+ let second = signed_in("Second", &db, &services).await;
2260+ let Response::User(first_user) = send(
22482261 Request::FindUser {
22492262 username: "First".to_string(),
22502263 },
22512264 &second,
22522265 &db,
22532266 &services,
2254- None,
2255- &test::directory(),
2256- &test::directory(),
22572267 )
22582268 .await
22592269 else {
22602270 panic!("user not found");
22612271 };
2262- let (Response::User(second_user), _) = handle(
2272+ let Response::User(second_user) = send(
22632273 Request::FindUser {
22642274 username: "Second".to_string(),
22652275 },
22662276 &first,
22672277 &db,
22682278 &services,
2269- None,
2270- &test::directory(),
2271- &test::directory(),
22722279 )
22732280 .await
22742281 else {
22752282 panic!("user not found");
22762283 };
2277- handle(
2284+ send(
22782285 Request::AddFriend {
22792286 user_id: second_user.id.clone(),
22802287 },
22812288 &first,
22822289 &db,
22832290 &services,
2284- None,
2285- &test::directory(),
2286- &test::directory(),
22872291 )
22882292 .await;
2289- handle(
2293+ send(
22902294 Request::AcceptFriend {
22912295 user_id: first_user.id.clone(),
22922296 },
22932297 &second,
22942298 &db,
22952299 &services,
2296- None,
2297- &test::directory(),
2298- &test::directory(),
22992300 )
23002301 .await;
23012302
2302- let (Response::Friends(first_friends), _) = handle(
2303- Request::Friends,
2304- &first,
2305- &db,
2306- &services,
2307- None,
2308- &test::directory(),
2309- &test::directory(),
2310- )
2311- .await
2303+ let Response::Friends(first_friends) = send(Request::Friends, &first, &db, &services).await
23122304 else {
23132305 panic!("friends not read");
23142306 };
2315- let (Response::Friends(second_friends), _) = handle(
2316- Request::Friends,
2317- &second,
2318- &db,
2319- &services,
2320- None,
2321- &test::directory(),
2322- &test::directory(),
2323- )
2324- .await
2307+ let Response::Friends(second_friends) =
2308+ send(Request::Friends, &second, &db, &services).await
23252309 else {
23262310 panic!("friends not read");
23272311 };
@@ -2334,36 +2318,25 @@ mod tests {
23342318 async fn invite_and_accept_makes_member() {
23352319 let db = test::get_database().await;
23362320 let services = Services::default();
2337- let owner = signed_in("Owner", &db).await;
2338- let member = signed_in("Member", &db).await;
2339- let (Response::Community(community), _) = handle(
2321+ let owner = signed_in("Owner", &db, &services).await;
2322+ let member = signed_in("Member", &db, &services).await;
2323+ let Response::Community(community) = send(
23402324 Request::CreateCommunity {
23412325 name: "The Community".to_string(),
23422326 },
23432327 &owner,
23442328 &db,
23452329 &services,
2346- None,
2347- &test::directory(),
2348- &test::directory(),
23492330 )
23502331 .await
23512332 else {
23522333 panic!("community not created");
23532334 };
23542335
2355- invite_and_accept(&community.id, &owner, &member, "Member", &db).await;
2336+ invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
23562337
2357- let (Response::Communities(communities), _) = handle(
2358- Request::Communities,
2359- &member,
2360- &db,
2361- &services,
2362- None,
2363- &test::directory(),
2364- &test::directory(),
2365- )
2366- .await
2338+ let Response::Communities(communities) =
2339+ send(Request::Communities, &member, &db, &services).await
23672340 else {
23682341 panic!("communities not read");
23692342 };
@@ -2374,23 +2347,20 @@ mod tests {
23742347 async fn delete_community_removes_messages() {
23752348 let db = test::get_database().await;
23762349 let services = Services::default();
2377- let owner = signed_in("Owner", &db).await;
2378- let (Response::Community(community), _) = handle(
2350+ let owner = signed_in("Owner", &db, &services).await;
2351+ let Response::Community(community) = send(
23792352 Request::CreateCommunity {
23802353 name: "The Community".to_string(),
23812354 },
23822355 &owner,
23832356 &db,
23842357 &services,
2385- None,
2386- &test::directory(),
2387- &test::directory(),
23882358 )
23892359 .await
23902360 else {
23912361 panic!("community not created");
23922362 };
2393- handle(
2363+ send(
23942364 Request::CreateMessage {
23952365 community_id: community.id.clone(),
23962366 body: "Tahinli".to_string(),
@@ -2400,22 +2370,16 @@ mod tests {
24002370 &owner,
24012371 &db,
24022372 &services,
2403- None,
2404- &test::directory(),
2405- &test::directory(),
24062373 )
24072374 .await;
24082375
2409- handle(
2376+ send(
24102377 Request::DeleteCommunity {
24112378 community_id: community.id.clone(),
24122379 },
24132380 &owner,
24142381 &db,
24152382 &services,
2416- None,
2417- &test::directory(),
2418- &test::directory(),
24192383 )
24202384 .await;
24212385
crates/server/src/user.rsmodified+30 -10
@@ -1,6 +1,6 @@
11 use common::{
22 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3- error::{Error as CommonError, InvalidInput},
3+ error::{Error as CommonError, Field, InvalidInput},
44 model::{Account, Presence, Role, User},
55 permission, time,
66 validate::{validate_avatar_size, validate_status, validate_username},
@@ -167,12 +167,19 @@ pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Re
167167
168168 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
169169 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
170- let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg)
171- .map_err(|_| CommonError::Avatar(InvalidInput::NotJpeg))?;
170+ let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| {
171+ CommonError::Invalid {
172+ field: Field::Avatar,
173+ input: InvalidInput::NotJpeg,
174+ }
175+ })?;
172176 if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE {
173- return Err(CommonError::Avatar(InvalidInput::Dimensions {
174- expected: AVATAR_SIZE,
175- })
177+ return Err(CommonError::Invalid {
178+ field: Field::Avatar,
179+ input: InvalidInput::Dimensions {
180+ expected: AVATAR_SIZE,
181+ },
182+ }
176183 .into());
177184 }
178185
@@ -435,7 +442,10 @@ pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
435442 mod tests {
436443 use std::io::Cursor;
437444
438- use common::{constant::AVATAR_SIZE, error::Error as CommonError};
445+ use common::{
446+ constant::AVATAR_SIZE,
447+ error::{Error as CommonError, Field},
448+ };
439449 use image::{ImageFormat, RgbImage};
440450
441451 use crate::{database, error::Error, test, user};
@@ -455,16 +465,26 @@ mod tests {
455465 let mut conn = database::connect(&db).await.unwrap();
456466 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
457467
458- let small = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await;
468+ let small =
469+ user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await;
459470 let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await;
460471 let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn)
461472 .await
462473 .unwrap();
463474
464- assert!(matches!(small, Err(Error::Common(CommonError::Avatar(_)))));
475+ assert!(matches!(
476+ small,
477+ Err(Error::Common(CommonError::Invalid {
478+ field: Field::Avatar,
479+ ..
480+ }))
481+ ));
465482 assert!(matches!(
466483 not_jpeg,
467- Err(Error::Common(CommonError::Avatar(_)))
484+ Err(Error::Common(CommonError::Invalid {
485+ field: Field::Avatar,
486+ ..
487+ }))
468488 ));
469489 let avatar_id = valid.avatar_id.unwrap();
470490 assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty());
crates/server/src/voice.rsmodified+10 -3
@@ -7,7 +7,7 @@ use std::{
77 use bytes::Bytes;
88 use common::{
99 time,
10- voice::{SEQUENCE_LENGTH, encode_relay},
10+ voice::{decode_packet, encode_relay},
1111 };
1212 use quinn::Connection;
1313
@@ -247,6 +247,9 @@ impl Voice {
247247 }
248248
249249 pub fn relay(&self, connection_id: usize, packet: &[u8]) {
250+ let Some((sequence, _)) = decode_packet(packet) else {
251+ return;
252+ };
250253 let rooms = self.0.lock().unwrap();
251254 let Some(room) = rooms.values().find(|room| {
252255 room.participants
@@ -255,7 +258,11 @@ impl Voice {
255258 }) else {
256259 return;
257260 };
258- let Some(sender) = find(&rooms, connection_id) else {
261+ let Some(sender) = room
262+ .participants
263+ .iter()
264+ .find(|participant| participant.connection.stable_id() == connection_id)
265+ else {
259266 return;
260267 };
261268 if sender.muted {
@@ -263,7 +270,7 @@ impl Voice {
263270 }
264271 let (Some(relay), Some(echo)) = (
265272 encode_relay(&sender.user_id, packet),
266- encode_relay(&sender.user_id, &packet[..SEQUENCE_LENGTH]),
273+ encode_relay(&sender.user_id, &sequence.to_be_bytes()),
267274 ) else {
268275 return;
269276 };