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 @@
1 use common::{1 use common::{
2 constant::AVATAR_SIZE,2 constant::AVATAR_SIZE,
3- error::{Error, InvalidInput},3+ error::{Error, Field, InvalidInput},
4 };4 };
5 use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};5 use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
6 6
@@ -20,10 +20,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {
20 }20 }
21 }21 }
22 22
23- Err(Error::Avatar(InvalidInput::TooLarge {23+ Err(Error::Invalid {
24- maximum,24+ field: Field::Avatar,
25- actual: encoded.len() as u64,25+ input: InvalidInput::TooLarge {
26- }))26+ maximum,
27+ actual: encoded.len() as u64,
28+ },
29+ })
27 }30 }
28 31
29 fn center_square(image: DynamicImage) -> DynamicImage {32 fn center_square(image: DynamicImage) -> DynamicImage {
@@ -64,13 +67,14 @@ pub fn dominant_hue(bytes: &[u8]) -> Option<f32> {
64 if chroma < 0.15 {67 if chroma < 0.15 {
65 continue;68 continue;
66 }69 }
67- let hue = if max == r {70+ let sector = if max == r {
68 ((g - b) / chroma).rem_euclid(6.)71 ((g - b) / chroma).rem_euclid(6.)
69 } else if max == g {72 } else if max == g {
70 (b - r) / chroma + 2.73 (b - r) / chroma + 2.
71 } else {74 } else {
72 (r - g) / chroma + 4.75 (r - g) / chroma + 4.
73- } / 6.;76+ };
77+ let hue = sector / 6.;
74 let angle = hue * std::f32::consts::TAU;78 let angle = hue * std::f32::consts::TAU;
75 let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS];79 let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS];
76 bin.0 += chroma;80 bin.0 += chroma;
@@ -78,9 +82,10 @@ pub fn dominant_hue(bytes: &[u8]) -> Option<f32> {
78 bin.2 += angle.sin() * chroma;82 bin.2 += angle.sin() * chroma;
79 }83 }
80 84
85+ let pixels = image.pixels().len();
81 let total: f32 = bins.iter().map(|bin| bin.0).sum();86 let total: f32 = bins.iter().map(|bin| bin.0).sum();
82 let (weight, x, y) = bins.into_iter().max_by(|a, b| a.0.total_cmp(&b.0))?;87 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 {
84 return None;89 return None;
85 }90 }
86 91
crates/client/src/gui.rsmodified+4 -3
@@ -1052,9 +1052,10 @@ impl Yumush {
1052 }1052 }
1053 1053
1054 pub(super) fn is_direct(&self, community_id: &str) -> bool {1054 pub(super) fn is_direct(&self, community_id: &str) -> bool {
1055- self.chat.communities().iter().any(|community| {1055+ self.chat
1056- community.id == community_id && community.kind.is_direct()1056+ .communities()
1057- })1057+ .iter()
1058+ .any(|community| community.id == community_id && community.kind.is_direct())
1058 }1059 }
1059 1060
1060 fn is_me(&self, user_id: &str) -> bool {1061 fn is_me(&self, user_id: &str) -> bool {
crates/client/src/gui/builder.rsmodified+5 -2
@@ -13,7 +13,10 @@ mod voice;
13 13
14 use std::{fmt::Display, future::Future};14 use std::{fmt::Display, future::Future};
15 15
16-use common::model::{CommunityKind, Member, Role};16+use common::{
17+ model::{CommunityKind, Member, Role},
18+ permission,
19+};
17 use gpui_kit::{20 use gpui_kit::{
18 AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,21 AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,
19 StatefulInteractiveElement, Styled, Window,22 StatefulInteractiveElement, Styled, Window,
@@ -292,7 +295,7 @@ impl Yumush {
292 pub(super) fn is_builder(&self) -> bool {295 pub(super) fn is_builder(&self) -> bool {
293 self.user296 self.user
294 .as_ref()297 .as_ref()
295- .is_some_and(|me| me.role == Role::Builder)298+ .is_some_and(|me| permission::is_builder(me.role))
296 }299 }
297 300
298 pub(super) fn load_builder(&self, window: &mut Window, cx: &mut Context<Self>) {301 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::{
12 };12 };
13 use jiff::Timestamp;13 use jiff::Timestamp;
14 14
15-use super::ui::{15+use super::ui::{accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar};
16- accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar,
17-};
18 use crate::gui::STAMP;16 use crate::gui::STAMP;
19 use crate::gui::{17 use crate::gui::{
20 Palette, Yumush,18 Palette, Yumush,
21 auth::field,19 auth::field,
22 community_settings::{search_text, user_name},20 community_settings::{search_text, user_name},
23- entity_action, id_time, millis_time, notify_error, text,21+ entity_action, id_time, millis_time, text,
24 };22 };
25 23
26 fn builder_log_text(entry: &AdminLogEntry) -> String {24 fn builder_log_text(entry: &AdminLogEntry) -> String {
@@ -224,26 +222,19 @@ impl Yumush {
224 .map(str::to_string);222 .map(str::to_string);
225 let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx));223 let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx));
226 let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx));224 let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx));
227- let network = self.network.clone();225+ self.fetch_builder(
228-226+ window,
229- cx.spawn_in(window, async move |this, cx| {227+ cx,
230- let entries = match network228+ move |network| async move {
231- .admin_logs(actor_id, target_id, action, after_ms, before_ms)229+ network
232- .await230+ .admin_logs(actor_id, target_id, action, after_ms, before_ms)
233- {231+ .await
234- Ok(entries) => entries,232+ },
235- Err(error) => {233+ |yumush, entries, cx| {
236- notify_error(&this, cx, error);
237- return;
238- }
239- };
240-
241- let _ = this.update(cx, |yumush, cx| {
242 yumush.chat.builder_logs = entries;234 yumush.chat.builder_logs = entries;
243 cx.notify();235 cx.notify();
244- });236+ },
245- })237+ );
246- .detach();
247 }238 }
248 239
249 pub(super) fn log_user(&self, input: &Entity<InputState>, cx: &App) -> Option<Option<String>> {240 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::{
4 };4 };
5 5
6 use super::ui::{field_row, list_card, number, to_bytes, to_units};6 use super::ui::{field_row, list_card, number, to_bytes, to_units};
7-use crate::gui::{7+use crate::gui::{KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented};
8- KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented,
9-};
10 8
11 fn input_text(input: &Entity<InputState>, cx: &App) -> String {9 fn input_text(input: &Entity<InputState>, cx: &App) -> String {
12 input.read(cx).text().to_string()10 input.read(cx).text().to_string()
@@ -16,6 +14,10 @@ fn input_number(input: &Entity<InputState>, cx: &App) -> u32 {
16 number(&input_text(input, cx))14 number(&input_text(input, cx))
17 }15 }
18 16
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+
19 impl Yumush {21 impl Yumush {
20 pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {22 pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {
21 let Some(settings) = self.server.clone() else {23 let Some(settings) = self.server.clone() else {
@@ -23,78 +25,74 @@ impl Yumush {
23 };25 };
24 self.chat.server_registration_open = settings.registration_open;26 self.chat.server_registration_open = settings.registration_open;
25 self.chat.server_maintenance = settings.maintenance;27 self.chat.server_maintenance = settings.maintenance;
26- self.chat.server_name.update(cx, |input, cx| {28+ let chat = &self.chat;
27- input.set_value(settings.name.as_str(), window, cx)29+ set_input(&chat.server_name, &settings.name, window, cx);
28- });30+ set_input(
29- self.chat.server_limit.update(cx, |input, cx| {31+ &chat.server_limit,
30- input.set_value(32+ &to_units(settings.max_attachment_bytes, MB as u64),
31- to_units(settings.max_attachment_bytes, MB as u64).as_str(),33+ window,
32- window,34+ cx,
33- cx,35+ );
34- )36+ set_input(
35- });37+ &chat.server_user_quota,
36- self.chat.server_user_quota.update(cx, |input, cx| {38+ &to_units(settings.user_quota_bytes, MB as u64),
37- input.set_value(39+ window,
38- to_units(settings.user_quota_bytes, MB as u64).as_str(),40+ cx,
39- window,41+ );
40- cx,42+ set_input(
41- )43+ &chat.server_community_quota,
42- });44+ &to_units(settings.community_quota_bytes, MB as u64),
43- self.chat.server_community_quota.update(cx, |input, cx| {45+ window,
44- input.set_value(46+ cx,
45- to_units(settings.community_quota_bytes, MB as u64).as_str(),47+ );
46- window,48+ set_input(
47- cx,49+ &chat.server_message_retention,
48- )50+ &settings.message_retention_days.to_string(),
49- });51+ window,
50- self.chat.server_message_retention.update(cx, |input, cx| {52+ cx,
51- input.set_value(53+ );
52- settings.message_retention_days.to_string().as_str(),54+ set_input(
53- window,55+ &chat.server_attachment_retention,
54- cx,56+ &settings.attachment_retention_days.to_string(),
55- )57+ window,
56- });58+ cx,
57- self.chat59+ );
58- .server_attachment_retention60+ set_input(
59- .update(cx, |input, cx| {61+ &chat.server_announcement,
60- input.set_value(62+ &settings.announcement,
61- settings.attachment_retention_days.to_string().as_str(),63+ window,
62- window,64+ cx,
63- cx,65+ );
64- )66+ set_input(
65- });67+ &chat.server_max_communities,
66- self.chat.server_announcement.update(cx, |input, cx| {68+ &settings.max_communities_per_user.to_string(),
67- input.set_value(settings.announcement.as_str(), window, cx)69+ window,
68- });70+ cx,
69- self.chat.server_max_communities.update(cx, |input, cx| {71+ );
70- input.set_value(72+ set_input(
71- settings.max_communities_per_user.to_string().as_str(),73+ &chat.server_max_message_length,
72- window,74+ &settings.max_message_length.to_string(),
73- cx,75+ window,
74- )76+ cx,
75- });77+ );
76- self.chat.server_max_message_length.update(cx, |input, cx| {78+ set_input(
77- input.set_value(settings.max_message_length.to_string().as_str(), window, cx)79+ &chat.server_max_avatar,
78- });80+ &to_units(settings.max_avatar_bytes, KB as u64),
79- self.chat.server_max_avatar.update(cx, |input, cx| {81+ window,
80- input.set_value(82+ cx,
81- to_units(settings.max_avatar_bytes, KB as u64).as_str(),83+ );
82- window,84+ set_input(
83- cx,85+ &chat.server_messages_per_minute,
84- )86+ &settings.messages_per_minute.to_string(),
85- });87+ window,
86- self.chat88+ cx,
87- .server_messages_per_minute89+ );
88- .update(cx, |input, cx| {90+ set_input(
89- input.set_value(91+ &chat.server_logins_per_minute,
90- settings.messages_per_minute.to_string().as_str(),92+ &settings.logins_per_minute.to_string(),
91- window,93+ window,
92- cx,94+ cx,
93- )95+ );
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- });
98 }96 }
99 97
100 pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {98 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 {
259 }259 }
260 self.search_attachments(window, cx);260 self.search_attachments(window, cx);
261 self.load_backups(window, cx);261 self.load_backups(window, cx);
262- let network = self.network.clone();262+ self.fetch_builder(
263-263+ window,
264- cx.spawn_in(window, async move |this, cx| {264+ cx,
265- let (users, communities) = match network.storage_usage().await {265+ |network| async move { network.storage_usage().await },
266- Ok(usage) => usage,266+ |yumush, (users, communities), cx| {
267- Err(error) => {
268- notify_error(&this, cx, error);
269- return;
270- }
271- };
272-
273- let _ = this.update(cx, |yumush, cx| {
274 yumush.chat.builder_usage_users = users;267 yumush.chat.builder_usage_users = users;
275 yumush.chat.builder_usage_communities = communities;268 yumush.chat.builder_usage_communities = communities;
276 cx.notify();269 cx.notify();
277- });270+ },
278- })271+ );
279- .detach();
280 }272 }
281 273
282 pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context<Self>) {274 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 {
366 SelectState::new(366 SelectState::new(
367 SearchableVec::new(367 SearchableVec::new(
368 std::iter::once("All")368 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+ )
370 .collect::<Vec<_>>(),374 .collect::<Vec<_>>(),
371 ),375 ),
372 Some(IndexPath::new(0)),376 Some(IndexPath::new(0)),
@@ -1198,16 +1202,14 @@ impl Yumush {
1198 let text = self.announcement()?;1202 let text = self.announcement()?;
1199 1203
1200 Some(1204 Some(
1201- accent_bar(palette)1205+ accent_bar(palette).child(text.to_string()).child(
1202- .child(text.to_string())1206+ clickable(
1203- .child(1207+ "dismiss_announcement",
1204- clickable(1208+ palette,
1205- "dismiss_announcement",1209+ entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)),
1206- palette,1210+ )
1207- entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)),1211+ .child("×"),
1208- )1212+ ),
1209- .child("×"),
1210- ),
1211 )1213 )
1212 }1214 }
1213 1215
@@ -1907,9 +1909,8 @@ impl Yumush {
1907 Ok(participants) => {1909 Ok(participants) => {
1908 network.set_deafened(deafened);1910 network.set_deafened(deafened);
1909 let _ = this.update_in(cx, |yumush, _, cx| {1911 let _ = this.update_in(cx, |yumush, _, cx| {
1910- let muted = muted1912+ let muted =
1911- || yumush.is_server_muted()1913+ muted || yumush.is_server_muted() || yumush.hidden_in(&community_id);
1912- || yumush.hidden_in(&community_id);
1913 yumush.network.set_muted(muted);1914 yumush.network.set_muted(muted);
1914 yumush.chat.voice.insert(community_id.clone(), participants);1915 yumush.chat.voice.insert(community_id.clone(), participants);
1915 yumush.chat.voice_state = VoiceState::In {1916 yumush.chat.voice_state = VoiceState::In {
@@ -2486,71 +2487,73 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -
2486 .border_1()2487 .border_1()
2487 .border_color(palette.border)2488 .border_color(palette.border)
2488 .bg(palette.panel)2489 .bg(palette.panel)
2489- .children(2490+ .children(members.iter().map(
2490- members2491+ |MemberRow {
2491- .iter()2492+ user,
2492- .map(|MemberRow { user, rank, in_voice, muted, presence }| {2493+ rank,
2493- profile_popover(2494+ in_voice,
2494- format!("member_{}", user.id),2495+ muted,
2495- Anchor::TopRight,2496+ presence,
2496- user,2497+ }| {
2497- &entity,2498+ profile_popover(
2498- hoverable(2499+ format!("member_{}", user.id),
2499- format!("member_trigger_{}", user.id),2500+ Anchor::TopRight,
2500- div()2501+ user,
2501- .h(px(30.))2502+ &entity,
2502- .px(px(8.))2503+ hoverable(
2503- .flex()2504+ format!("member_trigger_{}", user.id),
2504- .items_center()2505+ div()
2505- .gap(px(8.))2506+ .h(px(30.))
2506- .rounded(px(6.))2507+ .px(px(8.))
2507- .child(presence_avatar(2508+ .flex()
2508- avatar(palette, user, px(18.), text(9.), &avatars),2509+ .items_center()
2509- *presence,2510+ .gap(px(8.))
2510- px(18.),2511+ .rounded(px(6.))
2511- palette,2512+ .child(presence_avatar(
2512- ))2513+ avatar(palette, user, px(18.), text(9.), &avatars),
2513- .child(2514+ *presence,
2514- div()2515+ px(18.),
2515- .flex_1()2516+ palette,
2516- .min_w_0()2517+ ))
2517- .flex()2518+ .child(
2518- .flex_col()2519+ div()
2519- .child(2520+ .flex_1()
2520- div()2521+ .min_w_0()
2521- .flex()2522+ .flex()
2522- .items_center()2523+ .flex_col()
2523- .gap(px(6.))2524+ .child(
2524- .child(user.username.clone())2525+ div()
2525- .children(rank_tag(*rank, palette))2526+ .flex()
2526- .children(in_voice.then(|| {2527+ .items_center()
2527- Icon::new(IconName::Headphones)2528+ .gap(px(6.))
2528- .w(px(12.))2529+ .child(user.username.clone())
2529- .h(px(12.))2530+ .children(rank_tag(*rank, palette))
2530- .text_color(palette.muted)2531+ .children(in_voice.then(|| {
2531- }))2532+ Icon::new(IconName::Headphones)
2532- .children(muted.then(|| {2533+ .w(px(12.))
2533- Icon::new(IconName::MicOff)2534+ .h(px(12.))
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.))
2543 .text_color(palette.muted)2535 .text_color(palette.muted)
2544- .truncate()2536+ }))
2545- .child(user.status.clone())2537+ .children(muted.then(|| {
2546- },2538+ Icon::new(IconName::MicOff)
2547- )),2539+ .w(px(12.))
2548- ),2540+ .h(px(12.))
2549- palette,2541+ .text_color(palette.danger)
2550- ),2542+ })),
2551- )2543+ )
2552- }),2544+ .children((!user.status.is_empty()).then(|| {
2553- ),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+ )),
2554 Anchor::TopRight,2557 Anchor::TopRight,
2555 )2558 )
2556 })2559 })
crates/client/src/gui/composer.rsmodified+6 -1
@@ -552,7 +552,12 @@ pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i
552 Popover::new("poll_popover")552 Popover::new("poll_popover")
553 .anchor(Anchor::BottomLeft)553 .anchor(Anchor::BottomLeft)
554 .appearance(false)554 .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+ ))
556 .content(move |_, _, cx| {561 .content(move |_, _, cx| {
557 let popover = cx.entity();562 let popover = cx.entity();
558 let toggle = entity.clone();563 let toggle = entity.clone();
crates/client/src/gui/forward.rsmodified+3 -5
@@ -11,9 +11,9 @@ use gpui_kit::{
11 };11 };
12 12
13 use super::{13 use super::{
14- Yumush, clickable,14+ Yumush, clickable, community_name,
15 composer::{Composer, poll_field},15 composer::{Composer, poll_field},
16- community_name, notify_error, palette,16+ notify_error, palette,
17 };17 };
18 18
19 pub struct Forward {19 pub struct Forward {
@@ -100,9 +100,7 @@ impl Render for Forward {
100 .flex()100 .flex()
101 .flex_col()101 .flex_col()
102 .gap(px(10.))102 .gap(px(10.))
103- .child(103+ .child(poll_field(&self.filter, palette))
104- poll_field(&self.filter, palette),
105- )
106 .child(104 .child(
107 Checkbox::new("keep_authors")105 Checkbox::new("keep_authors")
108 .label("Keep authors")106 .label("Keep authors")
crates/client/src/gui/media_view.rsmodified+2 -8
@@ -295,8 +295,7 @@ impl Yumush {
295 return;295 return;
296 };296 };
297 for path in paths {297 for path in paths {
298- let result =298+ let result = upload_file(&this, &network, &community_id, path, maximum, cx).await;
299- upload_file(&this, &network, &community_id, path, maximum, cx).await;
300 let _ = this.update(cx, |yumush, cx| {299 let _ = this.update(cx, |yumush, cx| {
301 if let Ok(attachment) = &result {300 if let Ok(attachment) = &result {
302 yumush.chat.media.pending.push(attachment.clone());301 yumush.chat.media.pending.push(attachment.clone());
@@ -442,12 +441,7 @@ impl Yumush {
442 cx: &mut Context<Self>,441 cx: &mut Context<Self>,
443 ) {442 ) {
444 let duration = duration_secs(&player);443 let duration = duration_secs(&player);
445- let seek = cx.new(|_| {444+ let seek = cx.new(|_| SliderState::new().min(0.).max(duration).default_value(0.));
446- SliderState::new()
447- .min(0.)
448- .max(duration)
449- .default_value(0.)
450- });
451 let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {445 let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {
452 let SliderEvent::Release(value) = event else {446 let SliderEvent::Release(value) = event else {
453 return;447 return;
crates/client/src/gui/message_actions.rsmodified+9 -3
@@ -18,8 +18,9 @@ use super::{
18 auth::field,18 auth::field,
19 avatar,19 avatar,
20 chat::{Chat, ReportTarget},20 chat::{Chat, ReportTarget},
21- clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in,21+ clickable,
22- primary_button, sidebar,22+ composer::trigger_icon,
23+ entity_action, id_time, notify_error, pop_in, primary_button, sidebar,
23 };24 };
24 25
25 pub fn reactions(26 pub fn reactions(
@@ -234,7 +235,12 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) ->
234 Popover::new("search_popover")235 Popover::new("search_popover")
235 .anchor(Anchor::TopRight)236 .anchor(Anchor::TopRight)
236 .appearance(false)237 .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+ ))
238 .content(move |_, _, cx| {244 .content(move |_, _, cx| {
239 let popover = cx.entity();245 let popover = cx.entity();
240 pop_in(246 pop_in(
crates/client/src/gui/poll.rsmodified+1 -1
@@ -153,7 +153,7 @@ pub fn poll_card(
153 .flex()153 .flex()
154 .items_center()154 .items_center()
155 .gap(px(8.))155 .gap(px(8.))
156- .children(poll.closed.then(|| "Closed"))156+ .children(poll.closed.then_some("Closed"))
157 .children(close_id.map(|close_id| {157 .children(close_id.map(|close_id| {
158 let close_entity = entity.clone();158 let close_entity = entity.clone();
159 clickable(159 clickable(
crates/client/src/gui/settings_page.rsmodified+2 -8
@@ -249,11 +249,7 @@ impl Yumush {
249 }249 }
250 }250 }
251 251
252-fn apply_user(252+fn apply_user(this: &WeakEntity<Yumush>, cx: &mut AsyncWindowContext, result: Result<User, Error>) {
253- this: &WeakEntity<Yumush>,
254- cx: &mut AsyncWindowContext,
255- result: Result<User, Error>,
256-) {
257 match result {253 match result {
258 Ok(user) => {254 Ok(user) => {
259 let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));255 let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
@@ -278,9 +274,7 @@ pub(super) fn picked_avatar(
278 let Ok(Ok(Some(paths))) = picked.await else {274 let Ok(Ok(Some(paths))) = picked.await else {
279 return None;275 return None;
280 };276 };
281- let Some(path) = paths.into_iter().next() else {277+ let path = paths.into_iter().next()?;
282- return None;
283- };
284 Some(278 Some(
285 executor279 executor
286 .spawn(async move { read_avatar_file(&path, maximum) })280 .spawn(async move { read_avatar_file(&path, maximum) })
crates/client/src/gui/sidebar.rsmodified+5 -1
@@ -284,7 +284,11 @@ impl Yumush {
284 let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;284 let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;
285 let direct = self.chat.unread_direct();285 let direct = self.chat.unread_direct();
286 let tabs = [286 let tabs = [
287- (SidebarTab::Communities, "Communities", self.chat.unread_groups()),287+ (
288+ SidebarTab::Communities,
289+ "Communities",
290+ self.chat.unread_groups(),
291+ ),
288 (292 (
289 SidebarTab::Messages,293 SidebarTab::Messages,
290 "Messages",294 "Messages",
crates/client/src/gui/voice_note.rsmodified+8 -7
@@ -15,7 +15,9 @@ use gpui_kit::{
15 use rtrb::{Consumer, RingBuffer};15 use rtrb::{Consumer, RingBuffer};
16 16
17 use super::{17 use super::{
18- Palette, Tooltip as _, Yumush, chat::VoiceState, clickable,18+ Palette, Tooltip as _, Yumush,
19+ chat::VoiceState,
20+ clickable,
19 media_view::{time_text, upload_file},21 media_view::{time_text, upload_file},
20 notify_error, primary_button, text,22 notify_error, primary_button, text,
21 };23 };
@@ -263,12 +265,11 @@ impl Yumush {
263 else {265 else {
264 return;266 return;
265 };267 };
266- let attachment = match upload_file(&this, &network, &community_id, path, maximum, cx)268+ let attachment =
267- .await269+ match upload_file(&this, &network, &community_id, path, maximum, cx).await {
268- {270+ Ok(attachment) => attachment,
269- Ok(attachment) => attachment,271+ Err(error) => return notify_error(&this, cx, error),
270- Err(error) => return notify_error(&this, cx, error),272+ };
271- };
272 if let Err(error) = network273 if let Err(error) = network
273 .create_message(&community_id, "", vec![attachment.id], None)274 .create_message(&community_id, "", vec![attachment.id], None)
274 .await275 .await
crates/client/src/mutes.rsmodified+1 -2
@@ -9,8 +9,7 @@ fn prefix(account_user_id: &str) -> String {
9 }9 }
10 10
11 pub fn load(account_user_id: &str) -> HashSet<String> {11 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())12+ let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) else {
13- else {
14 return HashSet::new();13 return HashSet::new();
15 };14 };
16 let prefix = prefix(account_user_id);15 let prefix = prefix(account_user_id);
crates/client/src/network.rsmodified+32 -58
@@ -18,9 +18,8 @@ use common::{
18 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,18 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
19 },19 },
20 network::{20 network::{
21- DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,21+ RESPONSE_MAX_READ_LENGTH, StreamKind, open_download, receive_decoded, receive_event,
22- receive_download_status, receive_event, send_encoded, send_request,22+ send_request, send_stream_kind, send_upload_header,
23- send_stream_kind, send_upload_header,
24 },23 },
25 request::{DownloadRequest, Request, UploadHeader},24 request::{DownloadRequest, Request, UploadHeader},
26 response::Response,25 response::Response,
@@ -145,7 +144,11 @@ impl NetworkHandle {
145 Response::Session { user, token } => (user, token),144 Response::Session { user, token } => (user, token),
146 _ => return Err(Error::Server),145 _ => return Err(Error::Server),
147 };146 };
148- let _ = self.done(Request::SetDevice { name: device_name() }).await;147+ let _ = self
148+ .done(Request::SetDevice {
149+ name: device_name(),
150+ })
151+ .await;
149 152
150 Ok(session)153 Ok(session)
151 }154 }
@@ -1506,37 +1509,21 @@ async fn backup_download(
1506 name: &str,1509 name: &str,
1507 path: &Path,1510 path: &Path,
1508 ) -> Result<(), Error> {1511 ) -> Result<(), Error> {
1509- let (mut send_stream, mut receive_stream) = connection.open_bi().await?;1512+ let request = Request::DownloadBackup {
1510- send_stream_kind(StreamKind::Backup, &mut send_stream).await?;1513+ name: name.to_string(),
1511- send_encoded(1514+ };
1512- &Request::DownloadBackup {1515+ let (mut receive_stream, length) =
1513- name: name.to_string(),1516+ open_download(connection, StreamKind::Backup, &request).await?;
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- }
1536 1517
1537- Ok(())1518+ let mut file = tokio::fs::File::create(path).await?;
1538- }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+ )));
1539 }1524 }
1525+
1526+ Ok(())
1540 }1527 }
1541 1528
1542 async fn download(1529 async fn download(
@@ -1544,37 +1531,24 @@ async fn download(
1544 attachment_id: &str,1531 attachment_id: &str,
1545 thumbnail: bool,1532 thumbnail: bool,
1546 ) -> Result<Vec<u8>, Error> {1533 ) -> 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?;
1549 let request = DownloadRequest {1534 let request = DownloadRequest {
1550 attachment_id: attachment_id.to_string(),1535 attachment_id: attachment_id.to_string(),
1551 thumbnail,1536 thumbnail,
1552 };1537 };
1553- send_encoded(&request, &mut send_stream).await?;1538+ let (mut receive_stream, length) =
1554- send_stream.finish()?;1539+ open_download(connection, StreamKind::Download, &request).await?;
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?;
1574 1540
1575- Ok(bytes)1541+ if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
1576- }1542+ return Err(Error::ReadBoundExceed {
1543+ actual: length as usize,
1544+ maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize,
1545+ });
1577 }1546 }
1547+
1548+ let mut bytes = vec![0u8; length as usize];
1549+ receive_stream.read_exact(&mut bytes).await?;
1550+
1551+ Ok(bytes)
1578 }1552 }
1579 1553
1580 async fn dispatch(1554 async fn dispatch(
crates/client/src/voice/audio.rsmodified+8 -6
@@ -22,6 +22,14 @@ mod backend;
22 #[cfg(target_os = "windows")]22 #[cfg(target_os = "windows")]
23 #[path = "audio/wasapi.rs"]23 #[path = "audio/wasapi.rs"]
24 mod backend;24 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+}
25 33
26 const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);34 const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);
27 const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100);35 const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100);
@@ -88,7 +96,6 @@ fn device(_: Option<Capture>, _: Playback, _: Choice) -> Audio {
88 Audio::Silent96 Audio::Silent
89 }97 }
90 98
91-#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
92 pub fn devices() -> Devices {99 pub fn devices() -> Devices {
93 match mode() {100 match mode() {
94 Mode::Off | Mode::Tone => Devices::default(),101 Mode::Off | Mode::Tone => Devices::default(),
@@ -96,11 +103,6 @@ pub fn devices() -> Devices {
96 }103 }
97 }104 }
98 105
99-#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
100-pub fn devices() -> Devices {
101- Devices::default()
102-}
103-
104 pub fn record(capture: &Capture, samples: impl IntoIterator<Item = f32>) {106 pub fn record(capture: &Capture, samples: impl IntoIterator<Item = f32>) {
105 let Ok(mut capture) = capture.try_lock() else {107 let Ok(mut capture) = capture.try_lock() else {
106 return;108 return;
crates/common/src/error.rsmodified+44 -30
@@ -100,6 +100,48 @@ impl Display for InvalidInput {
100 }100 }
101 }101 }
102 102
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+
103 #[derive(Debug, Clone, Encode, Decode, thiserror::Error)]145 #[derive(Debug, Clone, Encode, Decode, thiserror::Error)]
104 pub enum Error {146 pub enum Error {
105 #[error("unauthenticated")]147 #[error("unauthenticated")]
@@ -124,26 +166,8 @@ pub enum Error {
124 Decode(String),166 Decode(String),
125 #[error("read bound exceeded ({actual} > {maximum})")]167 #[error("read bound exceeded ({actual} > {maximum})")]
126 ReadBoundExceed { actual: usize, maximum: usize },168 ReadBoundExceed { actual: usize, maximum: usize },
127- #[error("username: {0}")]169+ #[error("{field} {input}")]
128- User(InvalidInput),170+ Invalid { field: Field, input: 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),
147 #[error("upload: {0}")]171 #[error("upload: {0}")]
148 Upload(String),172 Upload(String),
149 #[error("certificate: {0}")]173 #[error("certificate: {0}")]
@@ -156,22 +180,12 @@ pub enum Error {
156 Suspended,180 Suspended,
157 #[error("registration closed")]181 #[error("registration closed")]
158 RegistrationClosed,182 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),
165 #[error("banned")]183 #[error("banned")]
166 Banned,184 Banned,
167 #[error("maintenance")]185 #[error("maintenance")]
168 Maintenance,186 Maintenance,
169 #[error("storage quota exceeded")]187 #[error("storage quota exceeded")]
170 QuotaExceeded,188 QuotaExceeded,
171- #[error("quota: {0}")]
172- Quota(InvalidInput),
173- #[error("announcement: {0}")]
174- Announcement(InvalidInput),
175 #[error("limit reached")]189 #[error("limit reached")]
176 LimitReached,190 LimitReached,
177 #[error("too many requests, retry in {retry_after_seconds}s")]191 #[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(
90 DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))90 DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))
91 }91 }
92 92
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+
93 async fn send_framed<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {115 async fn send_framed<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
94 let payload = bitcode::encode(value);116 let payload = bitcode::encode(value);
95 send_stream117 send_stream
crates/common/src/validate.rsmodified+35 -28
@@ -11,10 +11,14 @@ use crate::{
11 MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS,11 MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS,
12 MINIMUM_USERNAME_LENGTH, REACTIONS,12 MINIMUM_USERNAME_LENGTH, REACTIONS,
13 },13 },
14- error::{Error, InvalidInput},14+ error::{Error, Field, InvalidInput},
15 model::{Poll, ServerSettings},15 model::{Poll, ServerSettings},
16 };16 };
17 17
18+fn invalid(field: Field) -> impl Fn(InvalidInput) -> Error {
19+ move |input| Error::Invalid { field, input }
20+}
21+
18 fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {22 fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
19 if actual < minimum {23 if actual < minimum {
20 return Err(InvalidInput::TooShort { minimum, actual });24 return Err(InvalidInput::TooShort { minimum, actual });
@@ -51,7 +55,7 @@ pub fn validate_username(username: &str) -> Result<(), Error> {
51 MAXIMUM_USERNAME_LENGTH,55 MAXIMUM_USERNAME_LENGTH,
52 true,56 true,
53 )57 )
54- .map_err(Error::User)58+ .map_err(invalid(Field::User))
55 }59 }
56 60
57 pub fn validate_password(password: &str) -> Result<(), Error> {61 pub fn validate_password(password: &str) -> Result<(), Error> {
@@ -61,7 +65,7 @@ pub fn validate_password(password: &str) -> Result<(), Error> {
61 MAXIMUM_PASSWORD_LENGTH,65 MAXIMUM_PASSWORD_LENGTH,
62 false,66 false,
63 )67 )
64- .map_err(Error::Password)68+ .map_err(invalid(Field::Password))
65 }69 }
66 70
67 pub fn validate_community_name(name: &str) -> Result<(), Error> {71 pub fn validate_community_name(name: &str) -> Result<(), Error> {
@@ -71,11 +75,11 @@ pub fn validate_community_name(name: &str) -> Result<(), Error> {
71 MAXIMUM_COMMUNITY_NAME_LENGTH,75 MAXIMUM_COMMUNITY_NAME_LENGTH,
72 true,76 true,
73 )77 )
74- .map_err(Error::Community)78+ .map_err(invalid(Field::Community))
75 }79 }
76 80
77 pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> {81 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))
79 }83 }
80 84
81 pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> {85 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
84 } else {88 } else {
85 089 0
86 };90 };
87- check(body, minimum, maximum, false).map_err(Error::Message)91+ check(body, minimum, maximum, false).map_err(invalid(Field::Message))
88 }92 }
89 93
90 pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {94 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))?;
92 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)96 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)
93- .map_err(Error::Message)?;97+ .map_err(invalid(Field::Message))?;
94 for option in options {98 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))?;
96 }100 }
97 101
98 Ok(())102 Ok(())
@@ -116,14 +120,16 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> {
116 return Ok(());120 return Ok(());
117 }121 }
118 122
119- Err(Error::Message(InvalidInput::ForbiddenCharacter))123+ Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter))
120 }124 }
121 125
122 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {126 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))?;
124 128
125 if name.contains(['/', '\\']) || name.chars().any(char::is_control) {129 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+ ));
127 }133 }
128 134
129 Ok(())135 Ok(())
@@ -136,7 +142,7 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> {
136 character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')142 character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
137 })143 })
138 {144 {
139- return Err(Error::BackupName(InvalidInput::ForbiddenCharacter));145+ return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter));
140 }146 }
141 147
142 Ok(())148 Ok(())
@@ -151,19 +157,19 @@ fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {
151 }157 }
152 158
153 pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> {159 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))
155 }161 }
156 162
157 pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {163 pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {
158 match limit {164 match limit {
159 limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => {165 limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => {
160- Err(Error::AttachmentLimit(InvalidInput::TooSmall {166+ Err(invalid(Field::AttachmentLimit)(InvalidInput::TooSmall {
161 minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES,167 minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES,
162 actual: limit,168 actual: limit,
163 }))169 }))
164 }170 }
165 limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => {171 limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => {
166- Err(Error::AttachmentLimit(InvalidInput::TooLarge {172+ Err(invalid(Field::AttachmentLimit)(InvalidInput::TooLarge {
167 maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES,173 maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES,
168 actual: limit,174 actual: limit,
169 }))175 }))
@@ -174,7 +180,7 @@ pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {
174 180
175 fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {181 fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
176 if quota != 0 && quota < minimum {182 if quota != 0 && quota < minimum {
177- return Err(Error::Quota(InvalidInput::TooSmall {183+ return Err(invalid(Field::Quota)(InvalidInput::TooSmall {
178 minimum,184 minimum,
179 actual: quota,185 actual: quota,
180 }));186 }));
@@ -185,10 +191,10 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
185 191
186 pub fn validate_announcement(text: &str) -> Result<(), Error> {192 pub fn validate_announcement(text: &str) -> Result<(), Error> {
187 if text.contains(['\n', '\r']) {193 if text.contains(['\n', '\r']) {
188- return Err(Error::Announcement(InvalidInput::MultiLine));194+ return Err(invalid(Field::Announcement)(InvalidInput::MultiLine));
189 }195 }
190 196
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))
192 }198 }
193 199
194 pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> {200 pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> {
@@ -205,8 +211,9 @@ pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error>
205 MINIMUM_MESSAGE_LENGTH,211 MINIMUM_MESSAGE_LENGTH,
206 MAXIMUM_MESSAGE_LENGTH,212 MAXIMUM_MESSAGE_LENGTH,
207 )213 )
208- .map_err(Error::Message)?;214+ .map_err(invalid(Field::Message))?;
209- check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64).map_err(Error::Avatar)215+ check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64)
216+ .map_err(invalid(Field::Avatar))
210 }217 }
211 218
212 pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {219 pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
@@ -214,27 +221,27 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
214 return Ok(());221 return Ok(());
215 };222 };
216 if reason.contains(['\n', '\r']) {223 if reason.contains(['\n', '\r']) {
217- return Err(Error::Reason(InvalidInput::MultiLine));224+ return Err(invalid(Field::Reason)(InvalidInput::MultiLine));
218 }225 }
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))
220 }227 }
221 228
222 pub fn validate_forward(count: usize) -> Result<(), Error> {229 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))
224 }231 }
225 232
226 pub fn validate_status(status: &str) -> Result<(), Error> {233 pub fn validate_status(status: &str) -> Result<(), Error> {
227 if status.contains(['\n', '\r']) {234 if status.contains(['\n', '\r']) {
228- return Err(Error::Status(InvalidInput::MultiLine));235+ return Err(invalid(Field::Status)(InvalidInput::MultiLine));
229 }236 }
230 237
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))
232 }239 }
233 240
234 pub fn validate_device(name: &str) -> Result<(), Error> {241 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))
236 }243 }
237 244
238 pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> {245 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))
240 }247 }
crates/server/src/admin_log.rsmodified+33 -34
@@ -1,6 +1,6 @@
1 use common::{1 use common::{
2 constant::LOG_PAGE_LIMIT,2 constant::LOG_PAGE_LIMIT,
3- model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail},3+ model::{AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail},
4 time,4 time,
5 };5 };
6 use turso::Connection;6 use turso::Connection;
@@ -8,53 +8,52 @@ use turso::Connection;
8 use crate::{database::new_id, error::Error, user};8 use crate::{database::new_id, error::Error, user};
9 9
10 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {10 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {
11- Some(match text {11+ Some(match AdminActionKind::parse(text)? {
12- "role_changed" => AdminAction::RoleChanged {12+ AdminActionKind::RoleChanged => AdminAction::RoleChanged {
13 role: Role::parse(&detail?)?,13 role: Role::parse(&detail?)?,
14 },14 },
15- "user_deleted" => AdminAction::UserDeleted,15+ AdminActionKind::UserDeleted => AdminAction::UserDeleted,
16- "user_suspended" => AdminAction::UserSuspended,16+ AdminActionKind::UserSuspended => AdminAction::UserSuspended,
17- "user_unsuspended" => AdminAction::UserUnsuspended,17+ AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended,
18- "sessions_revoked" => AdminAction::SessionsRevoked,18+ AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked,
19- "password_reset" => AdminAction::PasswordReset,19+ AdminActionKind::PasswordReset => AdminAction::PasswordReset,
20- "profile_cleared" => AdminAction::ProfileCleared,20+ AdminActionKind::ProfileCleared => AdminAction::ProfileCleared,
21- "user_created" => AdminAction::UserCreated,21+ AdminActionKind::UserCreated => AdminAction::UserCreated,
22- "community_deleted" => AdminAction::CommunityDeleted,22+ AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted,
23- "ownership_transferred" => AdminAction::OwnershipTransferred,23+ AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred,
24- "settings_changed" => AdminAction::SettingsChanged,24+ AdminActionKind::SettingsChanged => AdminAction::SettingsChanged,
25- "user_renamed" => AdminAction::UserRenamed { from: detail? },25+ AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? },
26- "user_timed_out" => AdminAction::UserTimedOut {26+ AdminActionKind::UserTimedOut => AdminAction::UserTimedOut {
27 minutes: detail?.parse().ok()?,27 minutes: detail?.parse().ok()?,
28 },28 },
29- "user_banned" => AdminAction::UserBanned { reason: detail },29+ AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail },
30- "ban_removed" => AdminAction::BanRemoved,30+ AdminActionKind::BanRemoved => AdminAction::BanRemoved,
31- "invite_created" => AdminAction::InviteCreated,31+ AdminActionKind::InviteCreated => AdminAction::InviteCreated,
32- "invite_deleted" => AdminAction::InviteDeleted,32+ AdminActionKind::InviteDeleted => AdminAction::InviteDeleted,
33- "report_handled" => AdminAction::ReportHandled {33+ AdminActionKind::ReportHandled => AdminAction::ReportHandled {
34 status: ReportStatus::parse(&detail?)?,34 status: ReportStatus::parse(&detail?)?,
35 },35 },
36- "message_deleted" => AdminAction::MessageDeleted,36+ AdminActionKind::MessageDeleted => AdminAction::MessageDeleted,
37- "user_purged" => AdminAction::UserPurged {37+ AdminActionKind::UserPurged => AdminAction::UserPurged {
38 messages: detail?.parse().ok()?,38 messages: detail?.parse().ok()?,
39 },39 },
40- "voice_kicked" => AdminAction::VoiceKicked,40+ AdminActionKind::VoiceKicked => AdminAction::VoiceKicked,
41- "voice_muted" => AdminAction::VoiceMuted {41+ AdminActionKind::VoiceMuted => AdminAction::VoiceMuted {
42 muted: detail?.parse().ok()?,42 muted: detail?.parse().ok()?,
43 },43 },
44- "community_voice_set" => AdminAction::CommunityVoiceSet {44+ AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet {
45 enabled: detail?.parse().ok()?,45 enabled: detail?.parse().ok()?,
46 },46 },
47- "attachment_deleted" => AdminAction::AttachmentDeleted,47+ AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted,
48- "ghost_enabled" => AdminAction::GhostEnabled,48+ AdminActionKind::GhostEnabled => AdminAction::GhostEnabled,
49- "ghost_disabled" => AdminAction::GhostDisabled,49+ AdminActionKind::GhostDisabled => AdminAction::GhostDisabled,
50- "ghost_visit" => AdminAction::GhostVisit,50+ AdminActionKind::GhostVisit => AdminAction::GhostVisit,
51- "ghost_voice" => AdminAction::GhostVoice {51+ AdminActionKind::GhostVoice => AdminAction::GhostVoice {
52 seconds: detail?.parse().ok()?,52 seconds: detail?.parse().ok()?,
53 },53 },
54- "backup_created" => AdminAction::BackupCreated { name: detail? },54+ AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? },
55- "backup_deleted" => AdminAction::BackupDeleted { name: detail? },55+ AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? },
56- "backup_downloaded" => AdminAction::BackupDownloaded { name: detail? },56+ AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? },
57- _ => return None,
58 })57 })
59 }58 }
60 59
crates/server/src/attachment.rsmodified+0 -14
@@ -57,20 +57,6 @@ pub struct Stored {
57 pub message_id: Option<String>,57 pub message_id: Option<String>,
58 }58 }
59 59
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-
74 fn from_row(row: &Row) -> Result<Attachment, Error> {60 fn from_row(row: &Row) -> Result<Attachment, Error> {
75 let size: i64 = row.get(2)?;61 let size: i64 = row.get(2)?;
76 let kind: String = row.get(3)?;62 let kind: String = row.get(3)?;
crates/server/src/backup.rsmodified+1 -5
@@ -26,10 +26,6 @@ use crate::{
26 const PREFIX: &str = "yumush-";26 const PREFIX: &str = "yumush-";
27 const EXTENSION: &str = ".db";27 const EXTENSION: &str = ".db";
28 28
29-pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
30- attachment::sibling_directory(database_path, "backups")
31-}
32-
33 fn created_secs(name: &str) -> Option<u64> {29 fn created_secs(name: &str) -> Option<u64> {
34 name.strip_prefix(PREFIX)?30 name.strip_prefix(PREFIX)?
35 .strip_suffix(EXTENSION)?31 .strip_suffix(EXTENSION)?
@@ -75,7 +71,7 @@ pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> {
75 backups.push(info(directory, &name)?);71 backups.push(info(directory, &name)?);
76 }72 }
77 }73 }
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));
79 75
80 Ok(backups)76 Ok(backups)
81 }77 }
crates/server/src/lib.rsmodified+14 -2
@@ -29,6 +29,8 @@ pub mod voice;
29 #[cfg(test)]29 #[cfg(test)]
30 mod test;30 mod test;
31 31
32+use std::path::{Path, PathBuf};
33+
32 use common::{config::Config, error::Error as CommonError, model::Role};34 use common::{config::Config, error::Error as CommonError, model::Role};
33 35
34 use crate::error::Error;36 use crate::error::Error;
@@ -57,6 +59,16 @@ fn load_config() -> Result<ServerConfig, Error> {
57 })59 })
58 }60 }
59 61
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+
60 pub async fn showtime() -> Result<(), Error> {72 pub async fn showtime() -> Result<(), Error> {
61 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();73 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
62 74
@@ -64,8 +76,8 @@ pub async fn showtime() -> Result<(), Error> {
64 76
65 let database = database::open(&config.database_path).await?;77 let database = database::open(&config.database_path).await?;
66 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;78 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;
67- let attachments = attachment::directory(&config.database_path)?;79+ let attachments = sibling_directory(&config.database_path, "attachments")?;
68- let backups = backup::directory(&config.database_path)?;80+ let backups = sibling_directory(&config.database_path, "backups")?;
69 tokio::spawn(attachment::collect(database.clone(), attachments.clone()));81 tokio::spawn(attachment::collect(database.clone(), attachments.clone()));
70 tokio::spawn(retention::collect(database.clone(), attachments.clone()));82 tokio::spawn(retention::collect(database.clone(), attachments.clone()));
71 83
crates/server/src/message.rsmodified+9 -12
@@ -1,16 +1,13 @@
1 use std::{collections::HashMap, path::Path};1 use std::{collections::HashMap, path::Path};
2 2
3 use common::{3 use common::{
4- constant::{4+ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
5- MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT,5+ error::{Error as CommonError, Field, InvalidInput},
6- },
7- error::{Error as CommonError, InvalidInput},
8 model::{6 model::{
9 CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage,7 CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage,
10 User,8 User,
11 },9 },
12 time,10 time,
13- validate::{validate_message_body, validate_new_message},
14 };11 };
15 use turso::{Connection, Row};12 use turso::{Connection, Row};
16 13
@@ -326,7 +323,6 @@ pub async fn create(
326 reply_to: Option<&str>,323 reply_to: Option<&str>,
327 conn: &Connection,324 conn: &Connection,
328 ) -> Result<Message, Error> {325 ) -> Result<Message, Error> {
329- validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
330 if let Some(reply_to) = reply_to {326 if let Some(reply_to) = reply_to {
331 ensure_in_community(reply_to, community_id, conn).await?;327 ensure_in_community(reply_to, community_id, conn).await?;
332 }328 }
@@ -485,8 +481,6 @@ pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message
485 }481 }
486 482
487 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {483 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {
488- validate_message_body(body, MAXIMUM_MESSAGE_LENGTH)?;
489-
490 let updated = conn484 let updated = conn
491 .execute(485 .execute(
492 "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",486 "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",
@@ -698,10 +692,13 @@ pub async fn forward(
698 }692 }
699 }693 }
700 if entries.len() > MAXIMUM_FORWARD_MESSAGES {694 if entries.len() > MAXIMUM_FORWARD_MESSAGES {
701- return Err(CommonError::Forward(InvalidInput::TooLong {695+ return Err(CommonError::Invalid {
702- maximum: MAXIMUM_FORWARD_MESSAGES,696+ field: Field::Forward,
703- actual: entries.len(),697+ input: InvalidInput::TooLong {
704- })698+ maximum: MAXIMUM_FORWARD_MESSAGES,
699+ actual: entries.len(),
700+ },
701+ }
705 .into());702 .into());
706 }703 }
707 704
crates/server/src/network.rsmodified+1 -2
@@ -12,7 +12,6 @@ use common::{
12 send_response,12 send_response,
13 },13 },
14 request::Request,14 request::Request,
15- voice::decode_packet,
16 };15 };
17 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};16 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
18 use tokio::{sync::mpsc, task::JoinHandle};17 use tokio::{sync::mpsc, task::JoinHandle};
@@ -280,7 +279,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
280 279
281 async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, voice: Voice) {280 async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, voice: Voice) {
282 while let Ok(bytes) = connection.read_datagram().await {281 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() {
284 voice.relay(connection.stable_id(), &bytes);283 voice.relay(connection.stable_id(), &bytes);
285 }284 }
286 }285 }
crates/server/src/request.rsmodified+68 -104
@@ -471,7 +471,10 @@ async fn dispatch(
471 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;471 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
472 let members = user_community::members(&community_id, &conn).await?;472 let members = user_community::members(&community_id, &conn).await?;
473 let event = Event::CommunityUpdated(updated.clone());473 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+ )
475 }478 }
476 Request::UpdateCommunityAvatar {479 Request::UpdateCommunityAvatar {
477 community_id,480 community_id,
@@ -493,7 +496,10 @@ async fn dispatch(
493 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;496 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
494 let members = user_community::members(&community_id, &conn).await?;497 let members = user_community::members(&community_id, &conn).await?;
495 let event = Event::CommunityUpdated(updated.clone());498 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+ )
497 }503 }
498 Request::DeleteCommunity { community_id } => {504 Request::DeleteCommunity { community_id } => {
499 let me = authenticated(state, &conn).await?;505 let me = authenticated(state, &conn).await?;
@@ -1143,7 +1149,13 @@ async fn dispatch(
1143 } => {1149 } => {
1144 let me = authenticated(state, &conn).await?;1150 let me = authenticated(state, &conn).await?;
1145 ensure_editable(&community_id, &conn).await?;1151 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?;
1147 let tx = conn.transaction().await?;1159 let tx = conn.transaction().await?;
1148 let members = user_community::members(&community_id, &tx).await?;1160 let members = user_community::members(&community_id, &tx).await?;
1149 let target = members1161 let target = members
@@ -2128,9 +2140,28 @@ mod tests {
2128 test,2140 test,
2129 };2141 };
2130 2142
2131- async fn signed_in(username: &str, db: &DB) -> Mutex<State> {2143+ async fn send(
2132- let state = Mutex::new(State::Anonymous);2144+ request: Request,
2145+ state: &Mutex<State>,
2146+ db: &DB,
2147+ services: &Services,
2148+ ) -> Response {
2133 handle(2149 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(
2134 Request::Register {2165 Request::Register {
2135 username: username.to_string(),2166 username: username.to_string(),
2136 password: "password".to_string(),2167 password: "password".to_string(),
@@ -2138,10 +2169,7 @@ mod tests {
2138 },2169 },
2139 &state,2170 &state,
2140 db,2171 db,
2141- &Services::default(),2172+ services,
2142- None,
2143- &test::directory(),
2144- &test::directory(),
2145 )2173 )
2146 .await;2174 .await;
2147 2175
@@ -2154,46 +2182,37 @@ mod tests {
2154 member: &Mutex<State>,2182 member: &Mutex<State>,
2155 username: &str,2183 username: &str,
2156 db: &DB,2184 db: &DB,
2185+ services: &Services,
2157 ) {2186 ) {
2158- let services = Services::default();2187+ let Response::User(member_user) = send(
2159- let (Response::User(member_user), _) = handle(
2160 Request::FindUser {2188 Request::FindUser {
2161 username: username.to_string(),2189 username: username.to_string(),
2162 },2190 },
2163 owner,2191 owner,
2164 db,2192 db,
2165- &services,2193+ services,
2166- None,
2167- &test::directory(),
2168- &test::directory(),
2169 )2194 )
2170 .await2195 .await
2171 else {2196 else {
2172 panic!("user not found");2197 panic!("user not found");
2173 };2198 };
2174- handle(2199+ send(
2175 Request::Invite {2200 Request::Invite {
2176 community_id: community_id.to_string(),2201 community_id: community_id.to_string(),
2177 user_id: member_user.id,2202 user_id: member_user.id,
2178 },2203 },
2179 owner,2204 owner,
2180 db,2205 db,
2181- &services,2206+ services,
2182- None,
2183- &test::directory(),
2184- &test::directory(),
2185 )2207 )
2186 .await;2208 .await;
2187- handle(2209+ send(
2188 Request::AcceptInvitation {2210 Request::AcceptInvitation {
2189 community_id: community_id.to_string(),2211 community_id: community_id.to_string(),
2190 },2212 },
2191 member,2213 member,
2192 db,2214 db,
2193- &services,2215+ services,
2194- None,
2195- &test::directory(),
2196- &test::directory(),
2197 )2216 )
2198 .await;2217 .await;
2199 }2218 }
@@ -2202,26 +2221,23 @@ mod tests {
2202 async fn plain_member_cannot_rename() {2221 async fn plain_member_cannot_rename() {
2203 let db = test::get_database().await;2222 let db = test::get_database().await;
2204 let services = Services::default();2223 let services = Services::default();
2205- let owner = signed_in("Owner", &db).await;2224+ let owner = signed_in("Owner", &db, &services).await;
2206- let member = signed_in("Member", &db).await;2225+ let member = signed_in("Member", &db, &services).await;
2207- let (Response::Community(community), _) = handle(2226+ let Response::Community(community) = send(
2208 Request::CreateCommunity {2227 Request::CreateCommunity {
2209 name: "The Community".to_string(),2228 name: "The Community".to_string(),
2210 },2229 },
2211 &owner,2230 &owner,
2212 &db,2231 &db,
2213 &services,2232 &services,
2214- None,
2215- &test::directory(),
2216- &test::directory(),
2217 )2233 )
2218 .await2234 .await
2219 else {2235 else {
2220 panic!("community not created");2236 panic!("community not created");
2221 };2237 };
2222- invite_and_accept(&community.id, &owner, &member, "Member", &db).await;2238+ invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2223 2239
2224- let (response, _) = handle(2240+ let response = send(
2225 Request::UpdateCommunity {2241 Request::UpdateCommunity {
2226 community_id: community.id,2242 community_id: community.id,
2227 name: "Renamed".to_string(),2243 name: "Renamed".to_string(),
@@ -2229,9 +2245,6 @@ mod tests {
2229 &member,2245 &member,
2230 &db,2246 &db,
2231 &services,2247 &services,
2232- None,
2233- &test::directory(),
2234- &test::directory(),
2235 )2248 )
2236 .await;2249 .await;
2237 2250
@@ -2242,86 +2255,57 @@ mod tests {
2242 async fn accepted_friend_request_befriends_both() {2255 async fn accepted_friend_request_befriends_both() {
2243 let db = test::get_database().await;2256 let db = test::get_database().await;
2244 let services = Services::default();2257 let services = Services::default();
2245- let first = signed_in("First", &db).await;2258+ let first = signed_in("First", &db, &services).await;
2246- let second = signed_in("Second", &db).await;2259+ let second = signed_in("Second", &db, &services).await;
2247- let (Response::User(first_user), _) = handle(2260+ let Response::User(first_user) = send(
2248 Request::FindUser {2261 Request::FindUser {
2249 username: "First".to_string(),2262 username: "First".to_string(),
2250 },2263 },
2251 &second,2264 &second,
2252 &db,2265 &db,
2253 &services,2266 &services,
2254- None,
2255- &test::directory(),
2256- &test::directory(),
2257 )2267 )
2258 .await2268 .await
2259 else {2269 else {
2260 panic!("user not found");2270 panic!("user not found");
2261 };2271 };
2262- let (Response::User(second_user), _) = handle(2272+ let Response::User(second_user) = send(
2263 Request::FindUser {2273 Request::FindUser {
2264 username: "Second".to_string(),2274 username: "Second".to_string(),
2265 },2275 },
2266 &first,2276 &first,
2267 &db,2277 &db,
2268 &services,2278 &services,
2269- None,
2270- &test::directory(),
2271- &test::directory(),
2272 )2279 )
2273 .await2280 .await
2274 else {2281 else {
2275 panic!("user not found");2282 panic!("user not found");
2276 };2283 };
2277- handle(2284+ send(
2278 Request::AddFriend {2285 Request::AddFriend {
2279 user_id: second_user.id.clone(),2286 user_id: second_user.id.clone(),
2280 },2287 },
2281 &first,2288 &first,
2282 &db,2289 &db,
2283 &services,2290 &services,
2284- None,
2285- &test::directory(),
2286- &test::directory(),
2287 )2291 )
2288 .await;2292 .await;
2289- handle(2293+ send(
2290 Request::AcceptFriend {2294 Request::AcceptFriend {
2291 user_id: first_user.id.clone(),2295 user_id: first_user.id.clone(),
2292 },2296 },
2293 &second,2297 &second,
2294 &db,2298 &db,
2295 &services,2299 &services,
2296- None,
2297- &test::directory(),
2298- &test::directory(),
2299 )2300 )
2300 .await;2301 .await;
2301 2302
2302- let (Response::Friends(first_friends), _) = handle(2303+ let Response::Friends(first_friends) = send(Request::Friends, &first, &db, &services).await
2303- Request::Friends,
2304- &first,
2305- &db,
2306- &services,
2307- None,
2308- &test::directory(),
2309- &test::directory(),
2310- )
2311- .await
2312 else {2304 else {
2313 panic!("friends not read");2305 panic!("friends not read");
2314 };2306 };
2315- let (Response::Friends(second_friends), _) = handle(2307+ let Response::Friends(second_friends) =
2316- Request::Friends,2308+ send(Request::Friends, &second, &db, &services).await
2317- &second,
2318- &db,
2319- &services,
2320- None,
2321- &test::directory(),
2322- &test::directory(),
2323- )
2324- .await
2325 else {2309 else {
2326 panic!("friends not read");2310 panic!("friends not read");
2327 };2311 };
@@ -2334,36 +2318,25 @@ mod tests {
2334 async fn invite_and_accept_makes_member() {2318 async fn invite_and_accept_makes_member() {
2335 let db = test::get_database().await;2319 let db = test::get_database().await;
2336 let services = Services::default();2320 let services = Services::default();
2337- let owner = signed_in("Owner", &db).await;2321+ let owner = signed_in("Owner", &db, &services).await;
2338- let member = signed_in("Member", &db).await;2322+ let member = signed_in("Member", &db, &services).await;
2339- let (Response::Community(community), _) = handle(2323+ let Response::Community(community) = send(
2340 Request::CreateCommunity {2324 Request::CreateCommunity {
2341 name: "The Community".to_string(),2325 name: "The Community".to_string(),
2342 },2326 },
2343 &owner,2327 &owner,
2344 &db,2328 &db,
2345 &services,2329 &services,
2346- None,
2347- &test::directory(),
2348- &test::directory(),
2349 )2330 )
2350 .await2331 .await
2351 else {2332 else {
2352 panic!("community not created");2333 panic!("community not created");
2353 };2334 };
2354 2335
2355- invite_and_accept(&community.id, &owner, &member, "Member", &db).await;2336+ invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2356 2337
2357- let (Response::Communities(communities), _) = handle(2338+ let Response::Communities(communities) =
2358- Request::Communities,2339+ send(Request::Communities, &member, &db, &services).await
2359- &member,
2360- &db,
2361- &services,
2362- None,
2363- &test::directory(),
2364- &test::directory(),
2365- )
2366- .await
2367 else {2340 else {
2368 panic!("communities not read");2341 panic!("communities not read");
2369 };2342 };
@@ -2374,23 +2347,20 @@ mod tests {
2374 async fn delete_community_removes_messages() {2347 async fn delete_community_removes_messages() {
2375 let db = test::get_database().await;2348 let db = test::get_database().await;
2376 let services = Services::default();2349 let services = Services::default();
2377- let owner = signed_in("Owner", &db).await;2350+ let owner = signed_in("Owner", &db, &services).await;
2378- let (Response::Community(community), _) = handle(2351+ let Response::Community(community) = send(
2379 Request::CreateCommunity {2352 Request::CreateCommunity {
2380 name: "The Community".to_string(),2353 name: "The Community".to_string(),
2381 },2354 },
2382 &owner,2355 &owner,
2383 &db,2356 &db,
2384 &services,2357 &services,
2385- None,
2386- &test::directory(),
2387- &test::directory(),
2388 )2358 )
2389 .await2359 .await
2390 else {2360 else {
2391 panic!("community not created");2361 panic!("community not created");
2392 };2362 };
2393- handle(2363+ send(
2394 Request::CreateMessage {2364 Request::CreateMessage {
2395 community_id: community.id.clone(),2365 community_id: community.id.clone(),
2396 body: "Tahinli".to_string(),2366 body: "Tahinli".to_string(),
@@ -2400,22 +2370,16 @@ mod tests {
2400 &owner,2370 &owner,
2401 &db,2371 &db,
2402 &services,2372 &services,
2403- None,
2404- &test::directory(),
2405- &test::directory(),
2406 )2373 )
2407 .await;2374 .await;
2408 2375
2409- handle(2376+ send(
2410 Request::DeleteCommunity {2377 Request::DeleteCommunity {
2411 community_id: community.id.clone(),2378 community_id: community.id.clone(),
2412 },2379 },
2413 &owner,2380 &owner,
2414 &db,2381 &db,
2415 &services,2382 &services,
2416- None,
2417- &test::directory(),
2418- &test::directory(),
2419 )2383 )
2420 .await;2384 .await;
2421 2385
crates/server/src/user.rsmodified+30 -10
@@ -1,6 +1,6 @@
1 use common::{1 use common::{
2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3- error::{Error as CommonError, InvalidInput},3+ error::{Error as CommonError, Field, InvalidInput},
4 model::{Account, Presence, Role, User},4 model::{Account, Presence, Role, User},
5 permission, time,5 permission, time,
6 validate::{validate_avatar_size, validate_status, validate_username},6 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
167 167
168 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {168 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
169 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;169 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
170- let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg)170+ let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| {
171- .map_err(|_| CommonError::Avatar(InvalidInput::NotJpeg))?;171+ CommonError::Invalid {
172+ field: Field::Avatar,
173+ input: InvalidInput::NotJpeg,
174+ }
175+ })?;
172 if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE {176 if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE {
173- return Err(CommonError::Avatar(InvalidInput::Dimensions {177+ return Err(CommonError::Invalid {
174- expected: AVATAR_SIZE,178+ field: Field::Avatar,
175- })179+ input: InvalidInput::Dimensions {
180+ expected: AVATAR_SIZE,
181+ },
182+ }
176 .into());183 .into());
177 }184 }
178 185
@@ -435,7 +442,10 @@ pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
435 mod tests {442 mod tests {
436 use std::io::Cursor;443 use std::io::Cursor;
437 444
438- use common::{constant::AVATAR_SIZE, error::Error as CommonError};445+ use common::{
446+ constant::AVATAR_SIZE,
447+ error::{Error as CommonError, Field},
448+ };
439 use image::{ImageFormat, RgbImage};449 use image::{ImageFormat, RgbImage};
440 450
441 use crate::{database, error::Error, test, user};451 use crate::{database, error::Error, test, user};
@@ -455,16 +465,26 @@ mod tests {
455 let mut conn = database::connect(&db).await.unwrap();465 let mut conn = database::connect(&db).await.unwrap();
456 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();466 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
457 467
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;
459 let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await;470 let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await;
460 let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn)471 let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn)
461 .await472 .await
462 .unwrap();473 .unwrap();
463 474
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+ ));
465 assert!(matches!(482 assert!(matches!(
466 not_jpeg,483 not_jpeg,
467- Err(Error::Common(CommonError::Avatar(_)))484+ Err(Error::Common(CommonError::Invalid {
485+ field: Field::Avatar,
486+ ..
487+ }))
468 ));488 ));
469 let avatar_id = valid.avatar_id.unwrap();489 let avatar_id = valid.avatar_id.unwrap();
470 assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty());490 assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty());
crates/server/src/voice.rsmodified+10 -3
@@ -7,7 +7,7 @@ use std::{
7 use bytes::Bytes;7 use bytes::Bytes;
8 use common::{8 use common::{
9 time,9 time,
10- voice::{SEQUENCE_LENGTH, encode_relay},10+ voice::{decode_packet, encode_relay},
11 };11 };
12 use quinn::Connection;12 use quinn::Connection;
13 13
@@ -247,6 +247,9 @@ impl Voice {
247 }247 }
248 248
249 pub fn relay(&self, connection_id: usize, packet: &[u8]) {249 pub fn relay(&self, connection_id: usize, packet: &[u8]) {
250+ let Some((sequence, _)) = decode_packet(packet) else {
251+ return;
252+ };
250 let rooms = self.0.lock().unwrap();253 let rooms = self.0.lock().unwrap();
251 let Some(room) = rooms.values().find(|room| {254 let Some(room) = rooms.values().find(|room| {
252 room.participants255 room.participants
@@ -255,7 +258,11 @@ impl Voice {
255 }) else {258 }) else {
256 return;259 return;
257 };260 };
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 {
259 return;266 return;
260 };267 };
261 if sender.muted {268 if sender.muted {
@@ -263,7 +270,7 @@ impl Voice {
263 }270 }
264 let (Some(relay), Some(echo)) = (271 let (Some(relay), Some(echo)) = (
265 encode_relay(&sender.user_id, packet),272 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()),
267 ) else {274 ) else {
268 return;275 return;
269 };276 };