diff --git a/crates/client/src/avatar.rs b/crates/client/src/avatar.rs index 8dc143b..5309e00 100644 --- a/crates/client/src/avatar.rs +++ b/crates/client/src/avatar.rs @@ -1,6 +1,6 @@ use common::{ constant::AVATAR_SIZE, - error::{Error, InvalidInput}, + error::{Error, Field, InvalidInput}, }; use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; @@ -20,10 +20,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result, Error> { } } - Err(Error::Avatar(InvalidInput::TooLarge { - maximum, - actual: encoded.len() as u64, - })) + Err(Error::Invalid { + field: Field::Avatar, + input: InvalidInput::TooLarge { + maximum, + actual: encoded.len() as u64, + }, + }) } fn center_square(image: DynamicImage) -> DynamicImage { @@ -64,13 +67,14 @@ pub fn dominant_hue(bytes: &[u8]) -> Option { if chroma < 0.15 { continue; } - let hue = if max == r { + let sector = if max == r { ((g - b) / chroma).rem_euclid(6.) } else if max == g { (b - r) / chroma + 2. } else { (r - g) / chroma + 4. - } / 6.; + }; + let hue = sector / 6.; let angle = hue * std::f32::consts::TAU; let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS]; bin.0 += chroma; @@ -78,9 +82,10 @@ pub fn dominant_hue(bytes: &[u8]) -> Option { bin.2 += angle.sin() * chroma; } + let pixels = image.pixels().len(); let total: f32 = bins.iter().map(|bin| bin.0).sum(); let (weight, x, y) = bins.into_iter().max_by(|a, b| a.0.total_cmp(&b.0))?; - if weight < total * 0.05 || total < (image.len() / 3) as f32 * 0.03 { + if weight < total * 0.05 || total < pixels as f32 * 0.03 { return None; } diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index ad38945..9c330c6 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1052,9 +1052,10 @@ impl Yumush { } pub(super) fn is_direct(&self, community_id: &str) -> bool { - self.chat.communities().iter().any(|community| { - community.id == community_id && community.kind.is_direct() - }) + self.chat + .communities() + .iter() + .any(|community| community.id == community_id && community.kind.is_direct()) } fn is_me(&self, user_id: &str) -> bool { diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 072d8a0..d3b66da 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -13,7 +13,10 @@ mod voice; use std::{fmt::Display, future::Future}; -use common::model::{CommunityKind, Member, Role}; +use common::{ + model::{CommunityKind, Member, Role}, + permission, +}; use gpui_kit::{ AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, @@ -292,7 +295,7 @@ impl Yumush { pub(super) fn is_builder(&self) -> bool { self.user .as_ref() - .is_some_and(|me| me.role == Role::Builder) + .is_some_and(|me| permission::is_builder(me.role)) } pub(super) fn load_builder(&self, window: &mut Window, cx: &mut Context) { diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 9e600fc..6ee1ea7 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -12,15 +12,13 @@ use gpui_kit::{ }; use jiff::Timestamp; -use super::ui::{ - accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar, -}; +use super::ui::{accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar}; use crate::gui::STAMP; use crate::gui::{ Palette, Yumush, auth::field, community_settings::{search_text, user_name}, - entity_action, id_time, millis_time, notify_error, text, + entity_action, id_time, millis_time, text, }; fn builder_log_text(entry: &AdminLogEntry) -> String { @@ -224,26 +222,19 @@ impl Yumush { .map(str::to_string); let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let entries = match network - .admin_logs(actor_id, target_id, action, after_ms, before_ms) - .await - { - Ok(entries) => entries, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + move |network| async move { + network + .admin_logs(actor_id, target_id, action, after_ms, before_ms) + .await + }, + |yumush, entries, cx| { yumush.chat.builder_logs = entries; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn log_user(&self, input: &Entity, cx: &App) -> Option> { diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index 295fea7..cb420a5 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -4,9 +4,7 @@ use gpui_kit::{ }; use super::ui::{field_row, list_card, number, to_bytes, to_units}; -use crate::gui::{ - KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented, -}; +use crate::gui::{KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented}; fn input_text(input: &Entity, cx: &App) -> String { input.read(cx).text().to_string() @@ -16,6 +14,10 @@ fn input_number(input: &Entity, cx: &App) -> u32 { number(&input_text(input, cx)) } +fn set_input(input: &Entity, text: &str, window: &mut Window, cx: &mut App) { + input.update(cx, |input, cx| input.set_value(text, window, cx)); +} + impl Yumush { pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context) { let Some(settings) = self.server.clone() else { @@ -23,78 +25,74 @@ impl Yumush { }; self.chat.server_registration_open = settings.registration_open; self.chat.server_maintenance = settings.maintenance; - self.chat.server_name.update(cx, |input, cx| { - input.set_value(settings.name.as_str(), window, cx) - }); - self.chat.server_limit.update(cx, |input, cx| { - input.set_value( - to_units(settings.max_attachment_bytes, MB as u64).as_str(), - window, - cx, - ) - }); - self.chat.server_user_quota.update(cx, |input, cx| { - input.set_value( - to_units(settings.user_quota_bytes, MB as u64).as_str(), - window, - cx, - ) - }); - self.chat.server_community_quota.update(cx, |input, cx| { - input.set_value( - to_units(settings.community_quota_bytes, MB as u64).as_str(), - window, - cx, - ) - }); - self.chat.server_message_retention.update(cx, |input, cx| { - input.set_value( - settings.message_retention_days.to_string().as_str(), - window, - cx, - ) - }); - self.chat - .server_attachment_retention - .update(cx, |input, cx| { - input.set_value( - settings.attachment_retention_days.to_string().as_str(), - window, - cx, - ) - }); - self.chat.server_announcement.update(cx, |input, cx| { - input.set_value(settings.announcement.as_str(), window, cx) - }); - self.chat.server_max_communities.update(cx, |input, cx| { - input.set_value( - settings.max_communities_per_user.to_string().as_str(), - window, - cx, - ) - }); - self.chat.server_max_message_length.update(cx, |input, cx| { - input.set_value(settings.max_message_length.to_string().as_str(), window, cx) - }); - self.chat.server_max_avatar.update(cx, |input, cx| { - input.set_value( - to_units(settings.max_avatar_bytes, KB as u64).as_str(), - window, - cx, - ) - }); - self.chat - .server_messages_per_minute - .update(cx, |input, cx| { - input.set_value( - settings.messages_per_minute.to_string().as_str(), - window, - cx, - ) - }); - self.chat.server_logins_per_minute.update(cx, |input, cx| { - input.set_value(settings.logins_per_minute.to_string().as_str(), window, cx) - }); + let chat = &self.chat; + set_input(&chat.server_name, &settings.name, window, cx); + set_input( + &chat.server_limit, + &to_units(settings.max_attachment_bytes, MB as u64), + window, + cx, + ); + set_input( + &chat.server_user_quota, + &to_units(settings.user_quota_bytes, MB as u64), + window, + cx, + ); + set_input( + &chat.server_community_quota, + &to_units(settings.community_quota_bytes, MB as u64), + window, + cx, + ); + set_input( + &chat.server_message_retention, + &settings.message_retention_days.to_string(), + window, + cx, + ); + set_input( + &chat.server_attachment_retention, + &settings.attachment_retention_days.to_string(), + window, + cx, + ); + set_input( + &chat.server_announcement, + &settings.announcement, + window, + cx, + ); + set_input( + &chat.server_max_communities, + &settings.max_communities_per_user.to_string(), + window, + cx, + ); + set_input( + &chat.server_max_message_length, + &settings.max_message_length.to_string(), + window, + cx, + ); + set_input( + &chat.server_max_avatar, + &to_units(settings.max_avatar_bytes, KB as u64), + window, + cx, + ); + set_input( + &chat.server_messages_per_minute, + &settings.messages_per_minute.to_string(), + window, + cx, + ); + set_input( + &chat.server_logins_per_minute, + &settings.logins_per_minute.to_string(), + window, + cx, + ); } pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index bc3f570..74885b4 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -259,24 +259,16 @@ impl Yumush { } self.search_attachments(window, cx); self.load_backups(window, cx); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let (users, communities) = match network.storage_usage().await { - Ok(usage) => usage, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.storage_usage().await }, + |yumush, (users, communities), cx| { yumush.chat.builder_usage_users = users; yumush.chat.builder_usage_communities = communities; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context) { diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 247c65b..041813f 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -366,7 +366,11 @@ impl Chat { SelectState::new( SearchableVec::new( std::iter::once("All") - .chain(AdminActionKind::ALL.into_iter().map(AdminActionKind::as_str)) + .chain( + AdminActionKind::ALL + .into_iter() + .map(AdminActionKind::as_str), + ) .collect::>(), ), Some(IndexPath::new(0)), @@ -1198,16 +1202,14 @@ impl Yumush { let text = self.announcement()?; Some( - accent_bar(palette) - .child(text.to_string()) - .child( - clickable( - "dismiss_announcement", - palette, - entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), - ) - .child("×"), - ), + accent_bar(palette).child(text.to_string()).child( + clickable( + "dismiss_announcement", + palette, + entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), + ) + .child("×"), + ), ) } @@ -1907,9 +1909,8 @@ impl Yumush { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { - let muted = muted - || yumush.is_server_muted() - || yumush.hidden_in(&community_id); + let muted = + muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); yumush.network.set_muted(muted); yumush.chat.voice.insert(community_id.clone(), participants); yumush.chat.voice_state = VoiceState::In { @@ -2486,71 +2487,73 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - .border_1() .border_color(palette.border) .bg(palette.panel) - .children( - members - .iter() - .map(|MemberRow { user, rank, in_voice, muted, presence }| { - profile_popover( - format!("member_{}", user.id), - Anchor::TopRight, - user, - &entity, - hoverable( - format!("member_trigger_{}", user.id), - div() - .h(px(30.)) - .px(px(8.)) - .flex() - .items_center() - .gap(px(8.)) - .rounded(px(6.)) - .child(presence_avatar( - avatar(palette, user, px(18.), text(9.), &avatars), - *presence, - px(18.), - palette, - )) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .flex() - .items_center() - .gap(px(6.)) - .child(user.username.clone()) - .children(rank_tag(*rank, palette)) - .children(in_voice.then(|| { - Icon::new(IconName::Headphones) - .w(px(12.)) - .h(px(12.)) - .text_color(palette.muted) - })) - .children(muted.then(|| { - Icon::new(IconName::MicOff) - .w(px(12.)) - .h(px(12.)) - .text_color(palette.danger) - })), - ) - .children((!user.status.is_empty()).then( - || { - div() - .text_size(text(11.)) + .children(members.iter().map( + |MemberRow { + user, + rank, + in_voice, + muted, + presence, + }| { + profile_popover( + format!("member_{}", user.id), + Anchor::TopRight, + user, + &entity, + hoverable( + format!("member_trigger_{}", user.id), + div() + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .child(presence_avatar( + avatar(palette, user, px(18.), text(9.), &avatars), + *presence, + px(18.), + palette, + )) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(user.username.clone()) + .children(rank_tag(*rank, palette)) + .children(in_voice.then(|| { + Icon::new(IconName::Headphones) + .w(px(12.)) + .h(px(12.)) .text_color(palette.muted) - .truncate() - .child(user.status.clone()) - }, - )), - ), - palette, - ), - ) - }), - ), + })) + .children(muted.then(|| { + Icon::new(IconName::MicOff) + .w(px(12.)) + .h(px(12.)) + .text_color(palette.danger) + })), + ) + .children((!user.status.is_empty()).then(|| { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(user.status.clone()) + })), + ), + palette, + ), + ) + }, + )), Anchor::TopRight, ) }) diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index a3381f9..d8a9ed6 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -552,7 +552,12 @@ pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i Popover::new("poll_popover") .anchor(Anchor::BottomLeft) .appearance(false) - .trigger(trigger_icon("poll_trigger", IconName::ChartBar, 28., palette)) + .trigger(trigger_icon( + "poll_trigger", + IconName::ChartBar, + 28., + palette, + )) .content(move |_, _, cx| { let popover = cx.entity(); let toggle = entity.clone(); diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index a1286c3..80ff71f 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -11,9 +11,9 @@ use gpui_kit::{ }; use super::{ - Yumush, clickable, + Yumush, clickable, community_name, composer::{Composer, poll_field}, - community_name, notify_error, palette, + notify_error, palette, }; pub struct Forward { @@ -100,9 +100,7 @@ impl Render for Forward { .flex() .flex_col() .gap(px(10.)) - .child( - poll_field(&self.filter, palette), - ) + .child(poll_field(&self.filter, palette)) .child( Checkbox::new("keep_authors") .label("Keep authors") diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index 5b32852..ca68023 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -295,8 +295,7 @@ impl Yumush { return; }; for path in paths { - let result = - upload_file(&this, &network, &community_id, path, maximum, cx).await; + let result = upload_file(&this, &network, &community_id, path, maximum, cx).await; let _ = this.update(cx, |yumush, cx| { if let Ok(attachment) = &result { yumush.chat.media.pending.push(attachment.clone()); @@ -442,12 +441,7 @@ impl Yumush { cx: &mut Context, ) { let duration = duration_secs(&player); - let seek = cx.new(|_| { - SliderState::new() - .min(0.) - .max(duration) - .default_value(0.) - }); + let seek = cx.new(|_| SliderState::new().min(0.).max(duration).default_value(0.)); let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| { let SliderEvent::Release(value) = event else { return; diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index 9d734ab..acbd672 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -18,8 +18,9 @@ use super::{ auth::field, avatar, chat::{Chat, ReportTarget}, - clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in, - primary_button, sidebar, + clickable, + composer::trigger_icon, + entity_action, id_time, notify_error, pop_in, primary_button, sidebar, }; pub fn reactions( @@ -234,7 +235,12 @@ pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> Popover::new("search_popover") .anchor(Anchor::TopRight) .appearance(false) - .trigger(trigger_icon("search_trigger", IconName::Search, 24., palette)) + .trigger(trigger_icon( + "search_trigger", + IconName::Search, + 24., + palette, + )) .content(move |_, _, cx| { let popover = cx.entity(); pop_in( diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 2437cf9..e31a1dd 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -153,7 +153,7 @@ pub fn poll_card( .flex() .items_center() .gap(px(8.)) - .children(poll.closed.then(|| "Closed")) + .children(poll.closed.then_some("Closed")) .children(close_id.map(|close_id| { let close_entity = entity.clone(); clickable( diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 9a526a5..2041930 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -249,11 +249,7 @@ impl Yumush { } } -fn apply_user( - this: &WeakEntity, - cx: &mut AsyncWindowContext, - result: Result, -) { +fn apply_user(this: &WeakEntity, cx: &mut AsyncWindowContext, result: Result) { match result { Ok(user) => { let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); @@ -278,9 +274,7 @@ pub(super) fn picked_avatar( let Ok(Ok(Some(paths))) = picked.await else { return None; }; - let Some(path) = paths.into_iter().next() else { - return None; - }; + let path = paths.into_iter().next()?; Some( executor .spawn(async move { read_avatar_file(&path, maximum) }) diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 57f5ac7..2784521 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -284,7 +284,11 @@ impl Yumush { let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32; let direct = self.chat.unread_direct(); let tabs = [ - (SidebarTab::Communities, "Communities", self.chat.unread_groups()), + ( + SidebarTab::Communities, + "Communities", + self.chat.unread_groups(), + ), ( SidebarTab::Messages, "Messages", diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index b30bdf2..34afec1 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -15,7 +15,9 @@ use gpui_kit::{ use rtrb::{Consumer, RingBuffer}; use super::{ - Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, + Palette, Tooltip as _, Yumush, + chat::VoiceState, + clickable, media_view::{time_text, upload_file}, notify_error, primary_button, text, }; @@ -263,12 +265,11 @@ impl Yumush { else { return; }; - let attachment = match upload_file(&this, &network, &community_id, path, maximum, cx) - .await - { - Ok(attachment) => attachment, - Err(error) => return notify_error(&this, cx, error), - }; + let attachment = + match upload_file(&this, &network, &community_id, path, maximum, cx).await { + Ok(attachment) => attachment, + Err(error) => return notify_error(&this, cx, error), + }; if let Err(error) = network .create_message(&community_id, "", vec![attachment.id], None) .await diff --git a/crates/client/src/mutes.rs b/crates/client/src/mutes.rs index aa54ca0..79f77c4 100644 --- a/crates/client/src/mutes.rs +++ b/crates/client/src/mutes.rs @@ -9,8 +9,7 @@ fn prefix(account_user_id: &str) -> String { } pub fn load(account_user_id: &str) -> HashSet { - let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) - else { + let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) else { return HashSet::new(); }; let prefix = prefix(account_user_id); diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 6ea606c..2942cc6 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -18,9 +18,8 @@ use common::{ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, network::{ - DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded, - receive_download_status, receive_event, send_encoded, send_request, - send_stream_kind, send_upload_header, + RESPONSE_MAX_READ_LENGTH, StreamKind, open_download, receive_decoded, receive_event, + send_request, send_stream_kind, send_upload_header, }, request::{DownloadRequest, Request, UploadHeader}, response::Response, @@ -145,7 +144,11 @@ impl NetworkHandle { Response::Session { user, token } => (user, token), _ => return Err(Error::Server), }; - let _ = self.done(Request::SetDevice { name: device_name() }).await; + let _ = self + .done(Request::SetDevice { + name: device_name(), + }) + .await; Ok(session) } @@ -1506,37 +1509,21 @@ async fn backup_download( name: &str, path: &Path, ) -> Result<(), Error> { - let (mut send_stream, mut receive_stream) = connection.open_bi().await?; - send_stream_kind(StreamKind::Backup, &mut send_stream).await?; - send_encoded( - &Request::DownloadBackup { - name: name.to_string(), - }, - &mut send_stream, - ) - .await?; - send_stream.finish()?; - - match receive_download_status(&mut receive_stream).await? { - DownloadStatus::Error => { - Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?) - } - DownloadStatus::Ok => { - let mut length_bytes = [0u8; 8]; - receive_stream.read_exact(&mut length_bytes).await?; - let length = u64::from_le_bytes(length_bytes); - - let mut file = tokio::fs::File::create(path).await?; - let copied = tokio::io::copy(&mut receive_stream, &mut file).await?; - if copied != length { - return Err(Error::Network(format!( - "backup truncated ({copied} < {length})" - ))); - } + let request = Request::DownloadBackup { + name: name.to_string(), + }; + let (mut receive_stream, length) = + open_download(connection, StreamKind::Backup, &request).await?; - Ok(()) - } + let mut file = tokio::fs::File::create(path).await?; + let copied = tokio::io::copy(&mut receive_stream, &mut file).await?; + if copied != length { + return Err(Error::Network(format!( + "backup truncated ({copied} < {length})" + ))); } + + Ok(()) } async fn download( @@ -1544,37 +1531,24 @@ async fn download( attachment_id: &str, thumbnail: bool, ) -> Result, Error> { - let (mut send_stream, mut receive_stream) = connection.open_bi().await?; - send_stream_kind(StreamKind::Download, &mut send_stream).await?; let request = DownloadRequest { attachment_id: attachment_id.to_string(), thumbnail, }; - send_encoded(&request, &mut send_stream).await?; - send_stream.finish()?; - - match receive_download_status(&mut receive_stream).await? { - DownloadStatus::Error => { - Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?) - } - DownloadStatus::Ok => { - let mut length_bytes = [0u8; 8]; - receive_stream.read_exact(&mut length_bytes).await?; - - let length = u64::from_le_bytes(length_bytes); - if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES { - return Err(Error::ReadBoundExceed { - actual: length as usize, - maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize, - }); - } - - let mut bytes = vec![0u8; length as usize]; - receive_stream.read_exact(&mut bytes).await?; + let (mut receive_stream, length) = + open_download(connection, StreamKind::Download, &request).await?; - Ok(bytes) - } + if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES { + return Err(Error::ReadBoundExceed { + actual: length as usize, + maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize, + }); } + + let mut bytes = vec![0u8; length as usize]; + receive_stream.read_exact(&mut bytes).await?; + + Ok(bytes) } async fn dispatch( diff --git a/crates/client/src/voice/audio.rs b/crates/client/src/voice/audio.rs index f9cd2de..d348e57 100644 --- a/crates/client/src/voice/audio.rs +++ b/crates/client/src/voice/audio.rs @@ -22,6 +22,14 @@ mod backend; #[cfg(target_os = "windows")] #[path = "audio/wasapi.rs"] mod backend; +#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] +mod backend { + use super::Devices; + + pub fn devices() -> Devices { + Devices::default() + } +} const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); @@ -88,7 +96,6 @@ fn device(_: Option, _: Playback, _: Choice) -> Audio { Audio::Silent } -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] pub fn devices() -> Devices { match mode() { Mode::Off | Mode::Tone => Devices::default(), @@ -96,11 +103,6 @@ pub fn devices() -> Devices { } } -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] -pub fn devices() -> Devices { - Devices::default() -} - pub fn record(capture: &Capture, samples: impl IntoIterator) { let Ok(mut capture) = capture.try_lock() else { return; diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index 271e666..25f7e3d 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -100,6 +100,48 @@ impl Display for InvalidInput { } } +#[derive(Debug, Clone, Copy, Encode, Decode)] +pub enum Field { + User, + Password, + Community, + Message, + Status, + Avatar, + Attachment, + AttachmentName, + Reason, + Forward, + AttachmentLimit, + Device, + BackupName, + Quota, + Announcement, +} + +impl Display for Field { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let label = match self { + Field::User => "username:", + Field::Password => "password:", + Field::Community => "community name:", + Field::Message => "message:", + Field::Status => "status:", + Field::Avatar => "avatar:", + Field::Attachment => "file", + Field::AttachmentName => "file name:", + Field::Reason => "reason:", + Field::Forward => "forward:", + Field::AttachmentLimit => "max attachment size:", + Field::Device => "device:", + Field::BackupName => "backup name:", + Field::Quota => "quota:", + Field::Announcement => "announcement:", + }; + write!(f, "{label}") + } +} + #[derive(Debug, Clone, Encode, Decode, thiserror::Error)] pub enum Error { #[error("unauthenticated")] @@ -124,26 +166,8 @@ pub enum Error { Decode(String), #[error("read bound exceeded ({actual} > {maximum})")] ReadBoundExceed { actual: usize, maximum: usize }, - #[error("username: {0}")] - User(InvalidInput), - #[error("password: {0}")] - Password(InvalidInput), - #[error("community name: {0}")] - Community(InvalidInput), - #[error("message: {0}")] - Message(InvalidInput), - #[error("status: {0}")] - Status(InvalidInput), - #[error("avatar: {0}")] - Avatar(InvalidInput), - #[error("file {0}")] - Attachment(InvalidInput), - #[error("file name: {0}")] - AttachmentName(InvalidInput), - #[error("reason: {0}")] - Reason(InvalidInput), - #[error("forward: {0}")] - Forward(InvalidInput), + #[error("{field} {input}")] + Invalid { field: Field, input: InvalidInput }, #[error("upload: {0}")] Upload(String), #[error("certificate: {0}")] @@ -156,22 +180,12 @@ pub enum Error { Suspended, #[error("registration closed")] RegistrationClosed, - #[error("max attachment size: {0}")] - AttachmentLimit(InvalidInput), - #[error("device: {0}")] - Device(InvalidInput), - #[error("backup name: {0}")] - BackupName(InvalidInput), #[error("banned")] Banned, #[error("maintenance")] Maintenance, #[error("storage quota exceeded")] QuotaExceeded, - #[error("quota: {0}")] - Quota(InvalidInput), - #[error("announcement: {0}")] - Announcement(InvalidInput), #[error("limit reached")] LimitReached, #[error("too many requests, retry in {retry_after_seconds}s")] diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index 6da7d44..4fcaac8 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -90,6 +90,28 @@ pub async fn receive_download_status( DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0]))) } +pub async fn open_download( + connection: &quinn::Connection, + kind: StreamKind, + request: &T, +) -> Result<(RecvStream, u64), Error> { + let (mut send_stream, mut receive_stream) = connection.open_bi().await?; + send_stream_kind(kind, &mut send_stream).await?; + send_encoded(request, &mut send_stream).await?; + send_stream.finish()?; + + match receive_download_status(&mut receive_stream).await? { + DownloadStatus::Error => { + Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?) + } + DownloadStatus::Ok => { + let mut length_bytes = [0u8; 8]; + receive_stream.read_exact(&mut length_bytes).await?; + Ok((receive_stream, u64::from_le_bytes(length_bytes))) + } + } +} + async fn send_framed(value: &T, send_stream: &mut SendStream) -> Result<(), Error> { let payload = bitcode::encode(value); send_stream diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 04d869e..e2606e7 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -11,10 +11,14 @@ use crate::{ MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS, MINIMUM_USERNAME_LENGTH, REACTIONS, }, - error::{Error, InvalidInput}, + error::{Error, Field, InvalidInput}, model::{Poll, ServerSettings}, }; +fn invalid(field: Field) -> impl Fn(InvalidInput) -> Error { + move |input| Error::Invalid { field, input } +} + fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { if actual < minimum { return Err(InvalidInput::TooShort { minimum, actual }); @@ -51,7 +55,7 @@ pub fn validate_username(username: &str) -> Result<(), Error> { MAXIMUM_USERNAME_LENGTH, true, ) - .map_err(Error::User) + .map_err(invalid(Field::User)) } pub fn validate_password(password: &str) -> Result<(), Error> { @@ -61,7 +65,7 @@ pub fn validate_password(password: &str) -> Result<(), Error> { MAXIMUM_PASSWORD_LENGTH, false, ) - .map_err(Error::Password) + .map_err(invalid(Field::Password)) } pub fn validate_community_name(name: &str) -> Result<(), Error> { @@ -71,11 +75,11 @@ pub fn validate_community_name(name: &str) -> Result<(), Error> { MAXIMUM_COMMUNITY_NAME_LENGTH, true, ) - .map_err(Error::Community) + .map_err(invalid(Field::Community)) } pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> { - check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(Error::Message) + check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(invalid(Field::Message)) } 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 } else { 0 }; - check(body, minimum, maximum, false).map_err(Error::Message) + check(body, minimum, maximum, false).map_err(invalid(Field::Message)) } pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { - check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(Error::Message)?; + check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Message))?; check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS) - .map_err(Error::Message)?; + .map_err(invalid(Field::Message))?; for option in options { - check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(Error::Message)?; + check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Message))?; } Ok(()) @@ -116,14 +120,16 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> { return Ok(()); } - Err(Error::Message(InvalidInput::ForbiddenCharacter)) + Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter)) } pub fn validate_attachment_name(name: &str) -> Result<(), Error> { - check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(Error::AttachmentName)?; + check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(invalid(Field::AttachmentName))?; if name.contains(['/', '\\']) || name.chars().any(char::is_control) { - return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter)); + return Err(invalid(Field::AttachmentName)( + InvalidInput::ForbiddenCharacter, + )); } Ok(()) @@ -136,7 +142,7 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> { character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') }) { - return Err(Error::BackupName(InvalidInput::ForbiddenCharacter)); + return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter)); } Ok(()) @@ -151,19 +157,19 @@ fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> { } pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> { - check_size(size, maximum).map_err(Error::Attachment) + check_size(size, maximum).map_err(invalid(Field::Attachment)) } pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> { match limit { limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => { - Err(Error::AttachmentLimit(InvalidInput::TooSmall { + Err(invalid(Field::AttachmentLimit)(InvalidInput::TooSmall { minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES, actual: limit, })) } limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => { - Err(Error::AttachmentLimit(InvalidInput::TooLarge { + Err(invalid(Field::AttachmentLimit)(InvalidInput::TooLarge { maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES, actual: limit, })) @@ -174,7 +180,7 @@ pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> { fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { if quota != 0 && quota < minimum { - return Err(Error::Quota(InvalidInput::TooSmall { + return Err(invalid(Field::Quota)(InvalidInput::TooSmall { minimum, actual: quota, })); @@ -185,10 +191,10 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { pub fn validate_announcement(text: &str) -> Result<(), Error> { if text.contains(['\n', '\r']) { - return Err(Error::Announcement(InvalidInput::MultiLine)); + return Err(invalid(Field::Announcement)(InvalidInput::MultiLine)); } - check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement) + check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement)) } pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> { @@ -205,8 +211,9 @@ pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> MINIMUM_MESSAGE_LENGTH, MAXIMUM_MESSAGE_LENGTH, ) - .map_err(Error::Message)?; - check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64).map_err(Error::Avatar) + .map_err(invalid(Field::Message))?; + check_size(settings.max_avatar_bytes, MAXIMUM_AVATAR_BYTES as u64) + .map_err(invalid(Field::Avatar)) } pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> { @@ -214,27 +221,27 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> { return Ok(()); }; if reason.contains(['\n', '\r']) { - return Err(Error::Reason(InvalidInput::MultiLine)); + return Err(invalid(Field::Reason)(InvalidInput::MultiLine)); } - check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason) + check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason)) } pub fn validate_forward(count: usize) -> Result<(), Error> { - check_length(count, 1, MAXIMUM_FORWARD_MESSAGES).map_err(Error::Forward) + check_length(count, 1, MAXIMUM_FORWARD_MESSAGES).map_err(invalid(Field::Forward)) } pub fn validate_status(status: &str) -> Result<(), Error> { if status.contains(['\n', '\r']) { - return Err(Error::Status(InvalidInput::MultiLine)); + return Err(invalid(Field::Status)(InvalidInput::MultiLine)); } - check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status) + check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status)) } pub fn validate_device(name: &str) -> Result<(), Error> { - check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device) + check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(invalid(Field::Device)) } pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> { - check_size(bytes.len() as u64, maximum).map_err(Error::Avatar) + check_size(bytes.len() as u64, maximum).map_err(invalid(Field::Avatar)) } diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs index df8647b..d6b27e3 100644 --- a/crates/server/src/admin_log.rs +++ b/crates/server/src/admin_log.rs @@ -1,6 +1,6 @@ use common::{ constant::LOG_PAGE_LIMIT, - model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail}, + model::{AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail}, time, }; use turso::Connection; @@ -8,53 +8,52 @@ use turso::Connection; use crate::{database::new_id, error::Error, user}; fn action_of(text: &str, detail: Option) -> Option { - Some(match text { - "role_changed" => AdminAction::RoleChanged { + Some(match AdminActionKind::parse(text)? { + AdminActionKind::RoleChanged => AdminAction::RoleChanged { role: Role::parse(&detail?)?, }, - "user_deleted" => AdminAction::UserDeleted, - "user_suspended" => AdminAction::UserSuspended, - "user_unsuspended" => AdminAction::UserUnsuspended, - "sessions_revoked" => AdminAction::SessionsRevoked, - "password_reset" => AdminAction::PasswordReset, - "profile_cleared" => AdminAction::ProfileCleared, - "user_created" => AdminAction::UserCreated, - "community_deleted" => AdminAction::CommunityDeleted, - "ownership_transferred" => AdminAction::OwnershipTransferred, - "settings_changed" => AdminAction::SettingsChanged, - "user_renamed" => AdminAction::UserRenamed { from: detail? }, - "user_timed_out" => AdminAction::UserTimedOut { + AdminActionKind::UserDeleted => AdminAction::UserDeleted, + AdminActionKind::UserSuspended => AdminAction::UserSuspended, + AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended, + AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked, + AdminActionKind::PasswordReset => AdminAction::PasswordReset, + AdminActionKind::ProfileCleared => AdminAction::ProfileCleared, + AdminActionKind::UserCreated => AdminAction::UserCreated, + AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted, + AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred, + AdminActionKind::SettingsChanged => AdminAction::SettingsChanged, + AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? }, + AdminActionKind::UserTimedOut => AdminAction::UserTimedOut { minutes: detail?.parse().ok()?, }, - "user_banned" => AdminAction::UserBanned { reason: detail }, - "ban_removed" => AdminAction::BanRemoved, - "invite_created" => AdminAction::InviteCreated, - "invite_deleted" => AdminAction::InviteDeleted, - "report_handled" => AdminAction::ReportHandled { + AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail }, + AdminActionKind::BanRemoved => AdminAction::BanRemoved, + AdminActionKind::InviteCreated => AdminAction::InviteCreated, + AdminActionKind::InviteDeleted => AdminAction::InviteDeleted, + AdminActionKind::ReportHandled => AdminAction::ReportHandled { status: ReportStatus::parse(&detail?)?, }, - "message_deleted" => AdminAction::MessageDeleted, - "user_purged" => AdminAction::UserPurged { + AdminActionKind::MessageDeleted => AdminAction::MessageDeleted, + AdminActionKind::UserPurged => AdminAction::UserPurged { messages: detail?.parse().ok()?, }, - "voice_kicked" => AdminAction::VoiceKicked, - "voice_muted" => AdminAction::VoiceMuted { + AdminActionKind::VoiceKicked => AdminAction::VoiceKicked, + AdminActionKind::VoiceMuted => AdminAction::VoiceMuted { muted: detail?.parse().ok()?, }, - "community_voice_set" => AdminAction::CommunityVoiceSet { + AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet { enabled: detail?.parse().ok()?, }, - "attachment_deleted" => AdminAction::AttachmentDeleted, - "ghost_enabled" => AdminAction::GhostEnabled, - "ghost_disabled" => AdminAction::GhostDisabled, - "ghost_visit" => AdminAction::GhostVisit, - "ghost_voice" => AdminAction::GhostVoice { + AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted, + AdminActionKind::GhostEnabled => AdminAction::GhostEnabled, + AdminActionKind::GhostDisabled => AdminAction::GhostDisabled, + AdminActionKind::GhostVisit => AdminAction::GhostVisit, + AdminActionKind::GhostVoice => AdminAction::GhostVoice { seconds: detail?.parse().ok()?, }, - "backup_created" => AdminAction::BackupCreated { name: detail? }, - "backup_deleted" => AdminAction::BackupDeleted { name: detail? }, - "backup_downloaded" => AdminAction::BackupDownloaded { name: detail? }, - _ => return None, + AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? }, + AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? }, + AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? }, }) } diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index ece590e..063888f 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -57,20 +57,6 @@ pub struct Stored { pub message_id: Option, } -pub fn sibling_directory(database_path: &str, name: &str) -> Result { - let directory = Path::new(database_path) - .parent() - .unwrap_or_else(|| Path::new("")) - .join(name); - std::fs::create_dir_all(&directory)?; - - Ok(directory) -} - -pub fn directory(database_path: &str) -> Result { - sibling_directory(database_path, "attachments") -} - fn from_row(row: &Row) -> Result { let size: i64 = row.get(2)?; let kind: String = row.get(3)?; diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index 3474ef4..345cfe6 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -26,10 +26,6 @@ use crate::{ const PREFIX: &str = "yumush-"; const EXTENSION: &str = ".db"; -pub fn directory(database_path: &str) -> Result { - attachment::sibling_directory(database_path, "backups") -} - fn created_secs(name: &str) -> Option { name.strip_prefix(PREFIX)? .strip_suffix(EXTENSION)? @@ -75,7 +71,7 @@ pub fn list(directory: &Path) -> Result, Error> { backups.push(info(directory, &name)?); } } - backups.sort_by(|left, right| right.created_ms.cmp(&left.created_ms)); + backups.sort_by_key(|backup| std::cmp::Reverse(backup.created_ms)); Ok(backups) } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 74cdf85..c5921fd 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -29,6 +29,8 @@ pub mod voice; #[cfg(test)] mod test; +use std::path::{Path, PathBuf}; + use common::{config::Config, error::Error as CommonError, model::Role}; use crate::error::Error; @@ -57,6 +59,16 @@ fn load_config() -> Result { }) } +fn sibling_directory(database_path: &str, name: &str) -> Result { + let directory = Path::new(database_path) + .parent() + .unwrap_or_else(|| Path::new("")) + .join(name); + std::fs::create_dir_all(&directory)?; + + Ok(directory) +} + pub async fn showtime() -> Result<(), Error> { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); @@ -64,8 +76,8 @@ pub async fn showtime() -> Result<(), Error> { let database = database::open(&config.database_path).await?; let certificate = certificate::load(&config.certificate_path, &config.key_path)?; - let attachments = attachment::directory(&config.database_path)?; - let backups = backup::directory(&config.database_path)?; + let attachments = sibling_directory(&config.database_path, "attachments")?; + let backups = sibling_directory(&config.database_path, "backups")?; tokio::spawn(attachment::collect(database.clone(), attachments.clone())); tokio::spawn(retention::collect(database.clone(), attachments.clone())); diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index c553b91..5863d4a 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -1,16 +1,13 @@ use std::{collections::HashMap, path::Path}; use common::{ - constant::{ - MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT, - }, - error::{Error as CommonError, InvalidInput}, + constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, + error::{Error as CommonError, Field, InvalidInput}, model::{ CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, User, }, time, - validate::{validate_message_body, validate_new_message}, }; use turso::{Connection, Row}; @@ -326,7 +323,6 @@ pub async fn create( reply_to: Option<&str>, conn: &Connection, ) -> Result { - validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; if let Some(reply_to) = reply_to { ensure_in_community(reply_to, community_id, conn).await?; } @@ -485,8 +481,6 @@ pub async fn pinned(community_id: &str, conn: &Connection) -> Result Result { - validate_message_body(body, MAXIMUM_MESSAGE_LENGTH)?; - let updated = conn .execute( "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", @@ -698,10 +692,13 @@ pub async fn forward( } } if entries.len() > MAXIMUM_FORWARD_MESSAGES { - return Err(CommonError::Forward(InvalidInput::TooLong { - maximum: MAXIMUM_FORWARD_MESSAGES, - actual: entries.len(), - }) + return Err(CommonError::Invalid { + field: Field::Forward, + input: InvalidInput::TooLong { + maximum: MAXIMUM_FORWARD_MESSAGES, + actual: entries.len(), + }, + } .into()); } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index b59c439..5d8fbfd 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -12,7 +12,6 @@ use common::{ send_response, }, request::Request, - voice::decode_packet, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; use tokio::{sync::mpsc, task::JoinHandle}; @@ -280,7 +279,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro async fn relay_datagrams(connection: Connection, state: Arc>, voice: Voice) { while let Ok(bytes) = connection.read_datagram().await { - if signed_user_id(&state).is_some() && decode_packet(&bytes).is_some() { + if signed_user_id(&state).is_some() { voice.relay(connection.stable_id(), &bytes); } } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 74fa066..1546466 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -471,7 +471,10 @@ async fn dispatch( log::record(&community_id, Some(&me.id), None, &action, &conn).await?; let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); - (Response::Community(updated), vec![broadcast(event, &members)]) + ( + Response::Community(updated), + vec![broadcast(event, &members)], + ) } Request::UpdateCommunityAvatar { community_id, @@ -493,7 +496,10 @@ async fn dispatch( log::record(&community_id, Some(&me.id), None, &action, &conn).await?; let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); - (Response::Community(updated), vec![broadcast(event, &members)]) + ( + Response::Community(updated), + vec![broadcast(event, &members)], + ) } Request::DeleteCommunity { community_id } => { let me = authenticated(state, &conn).await?; @@ -1143,7 +1149,13 @@ async fn dispatch( } => { let me = authenticated(state, &conn).await?; ensure_editable(&community_id, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_transfer_ownership).await?; + allowed( + &me, + &community_id, + &conn, + permission::can_transfer_ownership, + ) + .await?; let tx = conn.transaction().await?; let members = user_community::members(&community_id, &tx).await?; let target = members @@ -2128,9 +2140,28 @@ mod tests { test, }; - async fn signed_in(username: &str, db: &DB) -> Mutex { - let state = Mutex::new(State::Anonymous); + async fn send( + request: Request, + state: &Mutex, + db: &DB, + services: &Services, + ) -> Response { handle( + request, + state, + db, + services, + None, + &test::directory(), + &test::directory(), + ) + .await + .0 + } + + async fn signed_in(username: &str, db: &DB, services: &Services) -> Mutex { + let state = Mutex::new(State::Anonymous); + send( Request::Register { username: username.to_string(), password: "password".to_string(), @@ -2138,10 +2169,7 @@ mod tests { }, &state, db, - &Services::default(), - None, - &test::directory(), - &test::directory(), + services, ) .await; @@ -2154,46 +2182,37 @@ mod tests { member: &Mutex, username: &str, db: &DB, + services: &Services, ) { - let services = Services::default(); - let (Response::User(member_user), _) = handle( + let Response::User(member_user) = send( Request::FindUser { username: username.to_string(), }, owner, db, - &services, - None, - &test::directory(), - &test::directory(), + services, ) .await else { panic!("user not found"); }; - handle( + send( Request::Invite { community_id: community_id.to_string(), user_id: member_user.id, }, owner, db, - &services, - None, - &test::directory(), - &test::directory(), + services, ) .await; - handle( + send( Request::AcceptInvitation { community_id: community_id.to_string(), }, member, db, - &services, - None, - &test::directory(), - &test::directory(), + services, ) .await; } @@ -2202,26 +2221,23 @@ mod tests { async fn plain_member_cannot_rename() { let db = test::get_database().await; let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let member = signed_in("Member", &db).await; - let (Response::Community(community), _) = handle( + let owner = signed_in("Owner", &db, &services).await; + let member = signed_in("Member", &db, &services).await; + let Response::Community(community) = send( Request::CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await else { panic!("community not created"); }; - invite_and_accept(&community.id, &owner, &member, "Member", &db).await; + invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; - let (response, _) = handle( + let response = send( Request::UpdateCommunity { community_id: community.id, name: "Renamed".to_string(), @@ -2229,9 +2245,6 @@ mod tests { &member, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await; @@ -2242,86 +2255,57 @@ mod tests { async fn accepted_friend_request_befriends_both() { let db = test::get_database().await; let services = Services::default(); - let first = signed_in("First", &db).await; - let second = signed_in("Second", &db).await; - let (Response::User(first_user), _) = handle( + let first = signed_in("First", &db, &services).await; + let second = signed_in("Second", &db, &services).await; + let Response::User(first_user) = send( Request::FindUser { username: "First".to_string(), }, &second, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await else { panic!("user not found"); }; - let (Response::User(second_user), _) = handle( + let Response::User(second_user) = send( Request::FindUser { username: "Second".to_string(), }, &first, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await else { panic!("user not found"); }; - handle( + send( Request::AddFriend { user_id: second_user.id.clone(), }, &first, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await; - handle( + send( Request::AcceptFriend { user_id: first_user.id.clone(), }, &second, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await; - let (Response::Friends(first_friends), _) = handle( - Request::Friends, - &first, - &db, - &services, - None, - &test::directory(), - &test::directory(), - ) - .await + let Response::Friends(first_friends) = send(Request::Friends, &first, &db, &services).await else { panic!("friends not read"); }; - let (Response::Friends(second_friends), _) = handle( - Request::Friends, - &second, - &db, - &services, - None, - &test::directory(), - &test::directory(), - ) - .await + let Response::Friends(second_friends) = + send(Request::Friends, &second, &db, &services).await else { panic!("friends not read"); }; @@ -2334,36 +2318,25 @@ mod tests { async fn invite_and_accept_makes_member() { let db = test::get_database().await; let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let member = signed_in("Member", &db).await; - let (Response::Community(community), _) = handle( + let owner = signed_in("Owner", &db, &services).await; + let member = signed_in("Member", &db, &services).await; + let Response::Community(community) = send( Request::CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await else { panic!("community not created"); }; - invite_and_accept(&community.id, &owner, &member, "Member", &db).await; + invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; - let (Response::Communities(communities), _) = handle( - Request::Communities, - &member, - &db, - &services, - None, - &test::directory(), - &test::directory(), - ) - .await + let Response::Communities(communities) = + send(Request::Communities, &member, &db, &services).await else { panic!("communities not read"); }; @@ -2374,23 +2347,20 @@ mod tests { async fn delete_community_removes_messages() { let db = test::get_database().await; let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let (Response::Community(community), _) = handle( + let owner = signed_in("Owner", &db, &services).await; + let Response::Community(community) = send( Request::CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await else { panic!("community not created"); }; - handle( + send( Request::CreateMessage { community_id: community.id.clone(), body: "Tahinli".to_string(), @@ -2400,22 +2370,16 @@ mod tests { &owner, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await; - handle( + send( Request::DeleteCommunity { community_id: community.id.clone(), }, &owner, &db, &services, - None, - &test::directory(), - &test::directory(), ) .await; diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index b78cae3..ca4d617 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -1,6 +1,6 @@ use common::{ constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, - error::{Error as CommonError, InvalidInput}, + error::{Error as CommonError, Field, InvalidInput}, model::{Account, Presence, Role, User}, permission, time, 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 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; - let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg) - .map_err(|_| CommonError::Avatar(InvalidInput::NotJpeg))?; + let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { + CommonError::Invalid { + field: Field::Avatar, + input: InvalidInput::NotJpeg, + } + })?; if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { - return Err(CommonError::Avatar(InvalidInput::Dimensions { - expected: AVATAR_SIZE, - }) + return Err(CommonError::Invalid { + field: Field::Avatar, + input: InvalidInput::Dimensions { + expected: AVATAR_SIZE, + }, + } .into()); } @@ -435,7 +442,10 @@ pub async fn delete(user_id: &str, conn: &Connection) -> Result { mod tests { use std::io::Cursor; - use common::{constant::AVATAR_SIZE, error::Error as CommonError}; + use common::{ + constant::AVATAR_SIZE, + error::{Error as CommonError, Field}, + }; use image::{ImageFormat, RgbImage}; use crate::{database, error::Error, test, user}; @@ -455,16 +465,26 @@ mod tests { let mut conn = database::connect(&db).await.unwrap(); let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let small = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await; + let small = + user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await; let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await; let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn) .await .unwrap(); - assert!(matches!(small, Err(Error::Common(CommonError::Avatar(_))))); + assert!(matches!( + small, + Err(Error::Common(CommonError::Invalid { + field: Field::Avatar, + .. + })) + )); assert!(matches!( not_jpeg, - Err(Error::Common(CommonError::Avatar(_))) + Err(Error::Common(CommonError::Invalid { + field: Field::Avatar, + .. + })) )); let avatar_id = valid.avatar_id.unwrap(); assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty()); diff --git a/crates/server/src/voice.rs b/crates/server/src/voice.rs index 063cd3a..6e81943 100644 --- a/crates/server/src/voice.rs +++ b/crates/server/src/voice.rs @@ -7,7 +7,7 @@ use std::{ use bytes::Bytes; use common::{ time, - voice::{SEQUENCE_LENGTH, encode_relay}, + voice::{decode_packet, encode_relay}, }; use quinn::Connection; @@ -247,6 +247,9 @@ impl Voice { } pub fn relay(&self, connection_id: usize, packet: &[u8]) { + let Some((sequence, _)) = decode_packet(packet) else { + return; + }; let rooms = self.0.lock().unwrap(); let Some(room) = rooms.values().find(|room| { room.participants @@ -255,7 +258,11 @@ impl Voice { }) else { return; }; - let Some(sender) = find(&rooms, connection_id) else { + let Some(sender) = room + .participants + .iter() + .find(|participant| participant.connection.stable_id() == connection_id) + else { return; }; if sender.muted { @@ -263,7 +270,7 @@ impl Voice { } let (Some(relay), Some(echo)) = ( encode_relay(&sender.user_id, packet), - encode_relay(&sender.user_id, &packet[..SEQUENCE_LENGTH]), + encode_relay(&sender.user_id, &sequence.to_be_bytes()), ) else { return; };