diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 5bffcd5..9e2e848 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -7,6 +7,7 @@ use std::{ }; use common::{ + call::{GetAvatar, GetSettings, MarkRead}, constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, error::Error, event::Event, @@ -899,7 +900,11 @@ impl Yumush { let avatar_id = avatar_id.to_string(); cx.spawn(async move |this, cx| { - let result = network.read_avatar(&avatar_id).await; + let result = network + .call(GetAvatar { + avatar_id: avatar_id.clone(), + }) + .await; let _ = this.update(cx, |yumush, cx| { yumush.chat.avatar_requests.remove(&avatar_id); if let Ok(bytes) = result { @@ -971,7 +976,12 @@ impl Yumush { let message_id = message_id.to_string(); cx.spawn(async move |_, _| { - let _ = network.mark_read(&community_id, &message_id).await; + let _ = network + .call(MarkRead { + community_id, + message_id, + }) + .await; }) .detach(); } @@ -1103,7 +1113,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Ok(settings) = network.server_settings().await else { + let Ok(settings) = network.call(GetSettings).await else { return; }; let _ = this.update(cx, |yumush, cx| { diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 777eb8d..858a3bb 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -14,6 +14,7 @@ mod voice; use std::{fmt::Display, future::Future, path::PathBuf}; use common::{ + call::{ListUsers, SetGhost}, model::{CommunityKind, Member, Role}, permission, }; @@ -381,7 +382,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.users().await }, + |network| async move { network.call(ListUsers).await }, |yumush, accounts, cx| { for account in &accounts { yumush.request_user_avatar(&account.user, cx); @@ -466,7 +467,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.set_ghost(enabled).await { + match network.call(SetGhost { enabled }).await { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush.set_ghost_state(enabled); diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs index 7dae9ec..74222c4 100644 --- a/crates/client/src/gui/builder/access.rs +++ b/crates/client/src/gui/builder/access.rs @@ -1,4 +1,7 @@ -use common::model::{InviteCode, ServerBan, ServerBanKind}; +use common::{ + call::{CreateInviteCode, DeleteInviteCode, ListInviteCodes, ListServerBans, RemoveServerBan}, + model::{InviteCode, ServerBan, ServerBanKind}, +}; use gpui_kit::{ AnyElement, ClipboardItem, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px, @@ -155,7 +158,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.invite_codes().await }, + |network| async move { network.call(ListInviteCodes).await }, |yumush, codes, cx| { yumush.chat.builder_invites = codes; cx.notify(); @@ -167,7 +170,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.server_bans().await }, + |network| async move { network.call(ListServerBans).await }, |yumush, bans, cx| { yumush.chat.builder_bans = bans; cx.notify(); @@ -191,7 +194,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.create_invite_code(uses, hours).await { + match network.call(CreateInviteCode { uses, hours }).await { Ok(_) => { let _ = this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); @@ -216,7 +219,7 @@ impl Yumush { let code = code.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_invite_code(&code).await { + match network.call(DeleteInviteCode { code }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); @@ -236,7 +239,7 @@ impl Yumush { let id = id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.remove_server_ban(&id).await { + match network.call(RemoveServerBan { id }).await { Ok(()) => { let _ = this .update_in(cx, |yumush, window, cx| yumush.load_server_bans(window, cx)); diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs index d1550d9..9da8c1b 100644 --- a/crates/client/src/gui/builder/backups.rs +++ b/crates/client/src/gui/builder/backups.rs @@ -1,4 +1,7 @@ -use common::model::BackupInfo; +use common::{ + call::{CreateBackup, DeleteBackup, ListBackups}, + model::BackupInfo, +}; use gpui_kit::{ Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, @@ -118,7 +121,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.backups().await }, + |network| async move { network.call(ListBackups).await }, |yumush, backups, cx| { yumush.backups = backups; cx.notify(); @@ -130,7 +133,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.create_backup().await { + match network.call(CreateBackup).await { Ok(_) => { let _ = this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx)); @@ -150,7 +153,7 @@ impl Yumush { let name = name.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_backup(&name).await { + match network.call(DeleteBackup { name }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx)); diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index 7f3cd4d..f7efe47 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -1,4 +1,10 @@ -use common::model::{Community, CommunitySummary, Member, Rank}; +use common::{ + call::{ + DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice, + TransferOwnership, + }, + model::{Community, CommunitySummary, Member, Rank}, +}; use gpui_kit::{ AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px, @@ -25,7 +31,13 @@ impl Yumush { let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.set_community_voice(&community_id, enabled).await { + match network + .call(SetCommunityVoice { + community_id, + enabled, + }) + .await + { Ok(_) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.load_builder_communities(window, cx) @@ -41,7 +53,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.all_communities().await }, + |network| async move { network.call(ListAllCommunities).await }, |yumush, summaries, cx| { for summary in &summaries { if let Some(avatar_id) = &summary.community.avatar_id { @@ -71,7 +83,12 @@ impl Yumush { let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_community(&community_id).await { + match network + .call(DeleteCommunity { + community_id: community_id.clone(), + }) + .await + { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.remove_community(&community_id); @@ -118,7 +135,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let members = match network.members(&community_id).await { + let members = match network + .call(ListMembers { + community_id: community_id.clone(), + }) + .await + { Ok(members) => members, Err(error) => { notify_error(&this, cx, error); @@ -179,7 +201,13 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.transfer_ownership(&community_id, &user_id).await { + match network + .call(TransferOwnership { + community_id, + user_id, + }) + .await + { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.transfer = None; @@ -212,7 +240,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.read_community(&community_id).await { + match network.call(GetCommunity { community_id }).await { Ok(community) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.enter(community, voice, window, cx) diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 426ed09..e1c72b3 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -1,4 +1,5 @@ use common::{ + call::ListAdminLogs, model::{AdminAction, AdminLogEntry, action_detail}, time::{created_at_ms, now_ms}, }; @@ -222,7 +223,13 @@ impl Yumush { cx, move |network| async move { network - .admin_logs(actor_id, target_id, action, after_ms, before_ms) + .call(ListAdminLogs { + actor_id, + target_id, + action, + after_ms, + before_ms, + }) .await }, |yumush, entries, cx| { diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 4a3ae8f..84b734c 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -1,4 +1,7 @@ -use common::model::MessageHit; +use common::{ + call::{DeleteMessage, SearchMessages}, + model::MessageHit, +}; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, @@ -224,7 +227,13 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let hits = match network - .search_messages(text, user_id, community_id, after_ms, before_ms) + .call(SearchMessages { + text, + user_id, + community_id, + after_ms, + before_ms, + }) .await { Ok(hits) => hits, @@ -256,7 +265,12 @@ impl Yumush { let message_id = message_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_message(&message_id).await { + match network + .call(DeleteMessage { + message_id: message_id.clone(), + }) + .await + { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs index d1d3864..8c4b103 100644 --- a/crates/client/src/gui/builder/overview.rs +++ b/crates/client/src/gui/builder/overview.rs @@ -1,5 +1,9 @@ use crate::net::Fail; -use common::{model::DayStat, time::DAY_MILLIS}; +use common::{ + call::{GetDailyStats, GetOverview}, + model::DayStat, + time::DAY_MILLIS, +}; use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px}; use jiff::Timestamp; @@ -108,7 +112,10 @@ impl Yumush { window, cx, |network| async move { - Ok::<_, Fail>((network.overview().await?, network.daily_stats(30).await?)) + Ok::<_, Fail>(( + network.call(GetOverview).await?, + network.call(GetDailyStats { days: 30 }).await?, + )) }, |yumush, (overview, stats), cx| { yumush.chat.builder_overview = Some(overview); diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index c960041..138d603 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -1,6 +1,9 @@ use std::future::Future; -use common::model::{BanScope, Report, ReportStatus}; +use common::{ + call::{BanUser, DeleteMessage, HandleReport, ListReports, TimeoutUser}, + model::{BanScope, Report, ReportStatus}, +}; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, div, px, @@ -42,7 +45,9 @@ impl Yumush { cx, |network| async move { network - .reports(Some(ReportStatus::Open)) + .call(ListReports { + status: Some(ReportStatus::Open), + }) .await .map(|reports| reports.len()) }, @@ -58,7 +63,7 @@ impl Yumush { self.fetch_builder( window, cx, - move |network| async move { network.reports(status).await }, + move |network| async move { network.call(ListReports { status }).await }, |yumush, reports, cx| { yumush.chat.builder_reports = reports; cx.notify(); @@ -110,7 +115,7 @@ impl Yumush { ) { let report_id = report_id.to_string(); self.report_action(window, cx, move |network| async move { - network.handle_report(&report_id, status).await + network.call(HandleReport { report_id, status }).await }); } @@ -122,7 +127,7 @@ impl Yumush { ) { let message_id = message_id.to_string(); self.report_action(window, cx, move |network| async move { - network.delete_message(&message_id).await + network.call(DeleteMessage { message_id }).await }); } @@ -134,7 +139,12 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.report_action(window, cx, move |network| async move { - network.timeout_user(&user_id, 60).await + network + .call(TimeoutUser { + user_id, + minutes: 60, + }) + .await }); } @@ -149,7 +159,11 @@ impl Yumush { let reason = reason.to_string(); self.report_action(window, cx, move |network| async move { network - .ban_user(&user_id, Some(reason.as_str()), BanScope::Account) + .call(BanUser { + user_id, + reason: Some(reason), + scope: BanScope::Account, + }) .await }); } diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index be5bb8d..6a49478 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -1,4 +1,4 @@ -use common::model::ServerSettings; +use common::{call::UpdateServerSettings, model::ServerSettings}; use gpui_kit::{ AnyElement, App, Context, Entity, IntoElement, Window, component::{WindowExt, input::InputState, notification::Notification}, @@ -128,7 +128,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.update_server_settings(settings).await { + match network.call(UpdateServerSettings { settings }).await { Ok(settings) => { let _ = this.update(cx, |yumush, cx| { yumush.server = Some(settings); diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index 274bdb1..af30b98 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -1,4 +1,7 @@ -use common::model::AttachmentInfo; +use common::{ + call::{DeleteAttachment, ListAttachments}, + model::AttachmentInfo, +}; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, @@ -282,7 +285,13 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let attachments = match network.attachments(user_id, community_id).await { + let attachments = match network + .call(ListAttachments { + user_id, + community_id, + }) + .await + { Ok(attachments) => attachments, Err(error) => { notify_error(&this, cx, error); @@ -312,7 +321,7 @@ impl Yumush { let attachment_id = attachment_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_attachment(&attachment_id).await { + match network.call(DeleteAttachment { attachment_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.load_storage(window, cx); diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 8a431c9..49ebaad 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -1,6 +1,10 @@ use std::future::Future; use common::{ + call::{ + BanUser, ClearProfile, CreateUser, DeleteUser, ListSessions, PurgeUser, RenameUser, + ResetPassword, RevokeSession, RevokeSessions, SetRole, SuspendUser, TimeoutUser, + }, model::{Account, BanScope, Role, SessionInfo, User}, permission, time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, @@ -59,7 +63,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.create_user(&username, &password).await { + match network.call(CreateUser { username, password }).await { Ok(_) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush @@ -86,7 +90,7 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.set_role(&user_id, role).await { + match network.call(SetRole { user_id, role }).await { Ok(user) => { let _ = this.update(cx, |yumush, cx| { let index = yumush @@ -120,7 +124,12 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_user(&user_id).await { + match network + .call(DeleteUser { + user_id: user_id.clone(), + }) + .await + { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush @@ -164,7 +173,7 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { - network.suspend_user(&user_id, suspended).await + network.call(SuspendUser { user_id, suspended }).await }); } @@ -176,7 +185,7 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { - network.revoke_sessions(&user_id).await + network.call(RevokeSessions { user_id }).await }); } @@ -188,7 +197,7 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { - network.clear_profile(&user_id).await.map(|_| ()) + network.call(ClearProfile { user_id }).await.map(|_| ()) }); } @@ -210,7 +219,7 @@ impl Yumush { .builder_password .update(cx, |input, cx| input.set_value("", window, cx)); self.builder_user_action(window, cx, move |network| async move { - network.reset_password(&user_id, &password).await + network.call(ResetPassword { user_id, password }).await }); } @@ -223,7 +232,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.sessions(&user_id).await { + match network + .call(ListSessions { + user_id: user_id.clone(), + }) + .await + { Ok(sessions) => { let _ = this.update(cx, |yumush, cx| { yumush.chat.builder_sessions = Some((user_id, sessions)); @@ -267,7 +281,13 @@ impl Yumush { let session_id = session_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.revoke_session(&user_id, &session_id).await { + match network + .call(RevokeSession { + user_id: user_id.clone(), + session_id, + }) + .await + { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.load_sessions(user_id, window, cx) @@ -297,7 +317,10 @@ impl Yumush { .builder_rename .update(cx, |input, cx| input.set_value("", window, cx)); self.builder_user_action(window, cx, move |network| async move { - network.rename_user(&user_id, &username).await.map(|_| ()) + network + .call(RenameUser { user_id, username }) + .await + .map(|_| ()) }); } @@ -323,7 +346,7 @@ impl Yumush { .builder_timeout .update(cx, |input, cx| input.set_value("", window, cx)); self.builder_user_action(window, cx, move |network| async move { - network.timeout_user(&user_id, minutes).await + network.call(TimeoutUser { user_id, minutes }).await }); } @@ -356,7 +379,13 @@ impl Yumush { .builder_ban_reason .update(cx, |input, cx| input.set_value("", window, cx)); self.builder_user_action(window, cx, move |network| async move { - network.ban_user(&user_id, reason.as_deref(), scope).await + network + .call(BanUser { + user_id, + reason, + scope, + }) + .await }); } @@ -374,7 +403,12 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.purge_user(&user_id).await { + match network + .call(PurgeUser { + user_id: user_id.clone(), + }) + .await + { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index 89bb82a..58f2ef0 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -1,6 +1,9 @@ use std::future::Future; -use common::model::{User, VoiceRoom}; +use common::{ + call::{KickFromVoice, ListVoiceRooms, ServerMute}, + model::{User, VoiceRoom}, +}; use gpui_kit::{ AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, div, px, @@ -17,7 +20,7 @@ impl Yumush { self.fetch_builder( window, cx, - |network| async move { network.voice_rooms().await }, + |network| async move { network.call(ListVoiceRooms).await }, |yumush, rooms, cx| { yumush.chat.builder_voice_rooms = rooms; cx.notify(); @@ -54,7 +57,7 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.voice_action(window, cx, move |network| async move { - network.server_mute(&user_id, muted).await + network.call(ServerMute { user_id, muted }).await }); } @@ -66,7 +69,7 @@ impl Yumush { ) { let user_id = user_id.to_string(); self.voice_action(window, cx, move |network| async move { - network.kick_from_voice(&user_id).await + network.call(KickFromVoice { user_id }).await }); } diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index b1e0c73..64f5dc7 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -33,6 +33,11 @@ use crate::settings::VOLUME; use crate::share::session::ShareSample; use crate::voice::VoiceSample; use common::{ + call::{ + CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans, + ListCommunities, ListMembers, ListMessages, ListPins, ListUnreads, ListVoiceParticipants, + SearchCommunity, WatchCommunity, + }, constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ @@ -1168,7 +1173,8 @@ pub(super) fn create_community( let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(community) = ok_or_notify(network.create_community(&name).await, &this, cx) else { + let Some(community) = ok_or_notify(network.call(CreateCommunity { name }).await, &this, cx) + else { return; }; @@ -1635,10 +1641,11 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(communities) = ok_or_notify(network.communities().await, &this, cx) else { + let Some(communities) = ok_or_notify(network.call(ListCommunities).await, &this, cx) + else { return; }; - let unreads = network.unreads().await.unwrap_or_default(); + let unreads = network.call(ListUnreads).await.unwrap_or_default(); let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.unread = unreads @@ -1676,7 +1683,12 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let Some(hits) = ok_or_notify( - network.search_community(community_id.clone(), text).await, + network + .call(SearchCommunity { + community_id: community_id.clone(), + text, + }) + .await, &this, cx, ) else { @@ -1700,7 +1712,15 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(pins) = ok_or_notify(network.pins(&community_id).await, &this, cx) else { + let Some(pins) = ok_or_notify( + network + .call(ListPins { + community_id: community_id.clone(), + }) + .await, + &this, + cx, + ) else { return; }; @@ -1721,8 +1741,15 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(members) = ok_or_notify(network.members(&community_id).await, &this, cx) - else { + let Some(members) = ok_or_notify( + network + .call(ListMembers { + community_id: community_id.clone(), + }) + .await, + &this, + cx, + ) else { return; }; @@ -1755,7 +1782,7 @@ impl Yumush { cx.spawn(async move |this, cx| { for user_id in missing { - let Ok(user) = network.read_user(&user_id).await else { + let Ok(user) = network.call(GetUser { user_id }).await else { continue; }; let _ = this.update(cx, |yumush, cx| { @@ -1778,7 +1805,15 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(bans) = ok_or_notify(network.bans(&community_id).await, &this, cx) else { + let Some(bans) = ok_or_notify( + network + .call(ListBans { + community_id: community_id.clone(), + }) + .await, + &this, + cx, + ) else { return; }; @@ -1841,11 +1876,18 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { if before.is_none() { - let _ = network.watch_community(Some(&community_id)).await; + let _ = network + .call(WatchCommunity { + community_id: Some(community_id.clone()), + }) + .await; } let Some(page) = ok_or_notify( network - .read_messages(&community_id, before.as_deref()) + .call(ListMessages { + community_id: community_id.clone(), + before, + }) .await, &this, cx, @@ -1910,7 +1952,7 @@ impl Yumush { let message_id = message_id.to_string(); spawn_done(window, cx, async move { - network.delete_message(&message_id).await + network.call(DeleteMessage { message_id }).await }); } @@ -1923,7 +1965,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.leave_community(&community_id).await { + if let Err(error) = network + .call(LeaveCommunity { + community_id: community_id.clone(), + }) + .await + { notify_error(&this, cx, error); return; } @@ -1941,7 +1988,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn(async move |this, cx| { - let Ok(participants) = network.voice_participants(&community_id).await else { + let Ok(participants) = network + .call(ListVoiceParticipants { + community_id: community_id.clone(), + }) + .await + else { return; }; @@ -2423,7 +2475,7 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.decline_call(&community_id).await + network.call(DeclineCall { community_id }).await }); } diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index a045164..ca21a23 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -2,6 +2,9 @@ use std::{collections::HashMap, sync::Arc}; use crate::net::Fail; use common::{ + call::{ + DeleteCommunity, ListLogs, SetCommunityVoice, Unban, UpdateCommunity, UpdateCommunityAvatar, + }, model::{Ban, Community, LogAction, LogEntry, User}, permission, validate::validate_community_name, @@ -215,7 +218,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.set_community_voice(&community_id, enabled).await; + let result = network + .call(SetCommunityVoice { + community_id, + enabled, + }) + .await; apply_community(&this, cx, result); }) .detach(); @@ -242,7 +250,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.update_community(&community_id, &name).await; + let result = network.call(UpdateCommunity { community_id, name }).await; apply_community(&this, cx, result); }) .detach(); @@ -262,7 +270,10 @@ impl Yumush { let result = match prepared { Ok(bytes) => { network - .update_community_avatar(&community_id, Some(bytes)) + .call(UpdateCommunityAvatar { + community_id, + image: Some(bytes), + }) .await } Err(error) => Err(error), @@ -279,7 +290,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.update_community_avatar(&community_id, None).await; + let result = network + .call(UpdateCommunityAvatar { + community_id, + image: None, + }) + .await; apply_community(&this, cx, result); }) .detach(); @@ -295,7 +311,10 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.delete_community(&community_id).await { + let call = DeleteCommunity { + community_id: community_id.clone(), + }; + match network.call(call).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.remove_community(&community_id); @@ -316,7 +335,11 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.unban(&community_id, &user_id).await { + let call = Unban { + community_id, + user_id: user_id.clone(), + }; + match network.call(call).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.bans.retain(|ban| ban.user.id != user_id); @@ -415,7 +438,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let logs = match network.logs(&community_id).await { + let logs = match network.call(ListLogs { community_id }).await { Ok(logs) => logs, Err(error) => { notify_error(&this, cx, error); diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index d87c20b..b5c124d 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -4,6 +4,7 @@ use std::time::{Duration, Instant}; use crate::net::Fail; use common::{ + call::{CreateMessage, CreatePoll, Typing, UpdateMessage}, constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS}, error::Error, model::Attachment, @@ -232,7 +233,7 @@ impl Yumush { .insert(community_id.clone(), Instant::now()); let network = self.network.clone(); cx.spawn(async move |_, _| { - let _ = network.typing(&community_id).await; + let _ = network.call(Typing { community_id }).await; }) .detach(); } @@ -272,7 +273,12 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { match network - .create_message(&community_id, &body, attachments, reply) + .call(CreateMessage { + community_id: community_id.clone(), + body: body.clone(), + attachments, + reply_to: reply, + }) .await { Ok(_) => {} @@ -355,7 +361,13 @@ impl Yumush { let restore = input.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.update_message(&message_id, &body).await { + if let Err(error) = network + .call(UpdateMessage { + message_id: message_id.clone(), + body: body.clone(), + }) + .await + { let _ = this.update_in(cx, |yumush, window, cx| { if restore.read(cx).text().len() == 0 { restore.update(cx, |state, cx| state.set_value(body, window, cx)); @@ -697,7 +709,12 @@ impl Yumush { spawn_done(window, cx, async move { network - .create_poll(&community_id, &question, options, multiple) + .call(CreatePoll { + community_id, + question, + options, + multiple, + }) .await }); diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 41e7e7b..f7c3158 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -1,4 +1,5 @@ use super::text; +use common::call::ForwardMessages; use gpui_kit::{ AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, @@ -168,7 +169,11 @@ impl Yumush { spawn_done(window, cx, async move { network - .forward_messages(ids, &community_id, keep_authors) + .call(ForwardMessages { + message_ids: ids, + community_id, + snippet: keep_authors, + }) .await }); cx.notify(); diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index 3b2e3b4..8a183d3 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -1,5 +1,6 @@ use super::text; use common::{ + call::{Pin, React, ReportMessage, ReportUser}, constant::REACTIONS, model::{Message, User}, }; @@ -488,7 +489,12 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.pin(&message_id, !pinned).await + network + .call(Pin { + message_id, + pinned: !pinned, + }) + .await }); } @@ -502,7 +508,7 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.react(&message_id, &emoji).await + network.call(React { message_id, emoji }).await }); } @@ -534,9 +540,9 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let result = match target { ReportTarget::Message(message_id) => { - network.report_message(&message_id, &reason).await + network.call(ReportMessage { message_id, reason }).await } - ReportTarget::User(user_id) => network.report_user(&user_id, &reason).await, + ReportTarget::User(user_id) => network.call(ReportUser { user_id, reason }).await, }; match result { Ok(()) => { diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 75bb582..4cbb198 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -1,5 +1,6 @@ use std::collections::HashSet; +use common::call::{ClosePoll, Vote}; use common::model::{Message, Poll, Rank, User}; use gpui_kit::{ Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, @@ -318,7 +319,12 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.vote(&message_id, positions).await + network + .call(Vote { + message_id, + positions, + }) + .await }); } @@ -330,10 +336,8 @@ impl Yumush { ) { let network = self.network.clone(); - spawn_done( - window, - cx, - async move { network.close_poll(&message_id).await }, - ); + spawn_done(window, cx, async move { + network.call(ClosePoll { message_id }).await + }); } } diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index 7bc70a2..44967b0 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -1,6 +1,7 @@ use std::{collections::HashMap, sync::Arc}; use common::{ + call::{BanMember, DeleteUser, Kick, SetRank, UpdatePresence}, model::{Presence, Rank, User}, permission, }; @@ -642,10 +643,25 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - let reason = reason.as_deref(); let result = match removal { - Removal::Kick => network.kick(&community_id, &user_id, reason).await, - Removal::Ban => network.ban(&community_id, &user_id, reason).await, + Removal::Kick => { + network + .call(Kick { + community_id, + user_id, + reason, + }) + .await + } + Removal::Ban => { + network + .call(BanMember { + community_id, + user_id, + reason, + }) + .await + } }; match result { Ok(()) => { @@ -676,7 +692,13 @@ impl Yumush { let user_id = user_id.to_string(); spawn_done(window, cx, async move { - network.set_rank(&community_id, &user_id, rank).await + network + .call(SetRank { + community_id, + user_id, + rank, + }) + .await }); } @@ -695,7 +717,7 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.update_presence(presence).await + network.call(UpdatePresence { presence }).await }); } @@ -715,7 +737,12 @@ impl Yumush { let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.delete_user(&user_id).await { + match network + .call(DeleteUser { + user_id: user_id.clone(), + }) + .await + { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush.chat.remove_member(&user_id); diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 81117fc..66fbd2a 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -1,7 +1,10 @@ use std::future::Future; use crate::net::Fail; -use common::model::User; +use common::{ + call::{DeleteUser, RemoveAvatar, UpdateAvatar, UpdateStatus, UpdateUser}, + model::User, +}; use gpui_kit::{ AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, @@ -162,7 +165,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.update_user(&username).await; + let result = network.call(UpdateUser { username }).await; apply_user(&this, cx, result); }) .detach(); @@ -173,7 +176,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.update_status(&status).await; + let result = network.call(UpdateStatus { status }).await; apply_user(&this, cx, result); }) .detach(); @@ -188,7 +191,7 @@ impl Yumush { return; }; let result = match prepared { - Ok(bytes) => network.update_avatar(bytes).await, + Ok(bytes) => network.call(UpdateAvatar { image: bytes }).await, Err(error) => Err(error), }; apply_user(&this, cx, result); @@ -200,7 +203,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = network.remove_avatar().await; + let result = network.call(RemoveAvatar).await; apply_user(&this, cx, result); }) .detach(); @@ -225,7 +228,7 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.delete_user(&user_id).await { + match network.call(DeleteUser { user_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.end_session(window, cx); diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index 22119fd..4aea6b2 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -1,6 +1,11 @@ use std::{fmt::Display, future::Future}; use common::{ + call::{ + AcceptFriend, AcceptInvitation, AddFriend, DeclineInvitation, FindUser, Invite, + ListFriends, ListInvitations, ListMembers, ListPresences, OpenDirect, OpenNotes, + RemoveFriend, + }, model::{Community, CommunityKind, Rank, User}, validate::validate_username, }; @@ -122,9 +127,9 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let (friends, invitations, presences) = match ( - network.friends().await, - network.invitations().await, - network.read_presences().await, + network.call(ListFriends).await, + network.call(ListInvitations).await, + network.call(ListPresences).await, ) { (Ok(friends), Ok(invitations), Ok(presences)) => (friends, invitations, presences), (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => { @@ -154,7 +159,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let found = network.find_user(&username).await.ok(); + let found = network + .call(FindUser { + username: username.clone(), + }) + .await + .ok(); let _ = this.update(cx, |yumush, cx| { if search_text(&yumush.chat.search_input, cx) != username { return; @@ -183,17 +193,15 @@ impl Yumush { } let network = self.network.clone(); - spawn_community(window, cx, async move { network.open_notes().await }); + spawn_community(window, cx, async move { network.call(OpenNotes).await }); } pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - spawn_community( - window, - cx, - async move { network.open_direct(&user_id).await }, - ); + spawn_community(window, cx, async move { + network.call(OpenDirect { user_id }).await + }); } pub(super) fn friend_action( @@ -214,11 +222,9 @@ impl Yumush { pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - spawn_done( - window, - cx, - async move { network.add_friend(&user_id).await }, - ); + spawn_done(window, cx, async move { + network.call(AddFriend { user_id }).await + }); } pub(super) fn accept_friend( @@ -229,11 +235,9 @@ impl Yumush { ) { let network = self.network.clone(); - spawn_done( - window, - cx, - async move { network.accept_friend(&user_id).await }, - ); + spawn_done(window, cx, async move { + network.call(AcceptFriend { user_id }).await + }); } pub(super) fn remove_friend( @@ -244,11 +248,9 @@ impl Yumush { ) { let network = self.network.clone(); - spawn_done( - window, - cx, - async move { network.remove_friend(&user_id).await }, - ); + spawn_done(window, cx, async move { + network.call(RemoveFriend { user_id }).await + }); } pub(super) fn accept_invitation( @@ -260,7 +262,7 @@ impl Yumush { let network = self.network.clone(); spawn_community(window, cx, async move { - network.accept_invitation(&community_id).await + network.call(AcceptInvitation { community_id }).await }); } @@ -273,7 +275,7 @@ impl Yumush { let network = self.network.clone(); spawn_done(window, cx, async move { - network.decline_invitation(&community_id).await + network.call(DeclineInvitation { community_id }).await }); } @@ -338,9 +340,19 @@ impl Yumush { let input = input.clone(); cx.spawn_in(window, async move |this, cx| { - let lookup = match network.find_user(&username).await { + let lookup = match network + .call(FindUser { + username: username.clone(), + }) + .await + { Ok(user) => { - let members = network.members(&community_id).await.unwrap_or_default(); + let members = network + .call(ListMembers { + community_id: community_id.clone(), + }) + .await + .unwrap_or_default(); if members.iter().any(|member| member.user.id == user.id) { InviteLookup::Member(user) } else { @@ -371,7 +383,13 @@ impl Yumush { let user_id = user.id.clone(); cx.spawn_in(window, async move |this, cx| { - match network.invite(&community_id, &user_id).await { + match network + .call(Invite { + community_id, + user_id, + }) + .await + { Ok(()) => { let _ = this.update_in(cx, |_, window, cx| window.close_dialog(cx)); } diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 0bf5318..832d7bd 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -4,6 +4,7 @@ use std::{ time::{Duration, Instant}, }; +use common::call::CreateMessage; use common::constant::VOICE_SAMPLE_RATE; use gpui_kit::{ App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled, @@ -283,7 +284,12 @@ impl Yumush { }; ok_or_notify( network - .create_message(&community_id, "", vec![attachment.id], None) + .call(CreateMessage { + community_id, + body: String::new(), + attachments: vec![attachment.id], + reply_to: None, + }) .await, &this, cx, diff --git a/crates/client/src/net/fail.rs b/crates/client/src/net/fail.rs index 6d1031b..973f454 100644 --- a/crates/client/src/net/fail.rs +++ b/crates/client/src/net/fail.rs @@ -7,7 +7,6 @@ const CRYPTO_ERRORS: std::ops::Range = 0x100..0x200; pub enum LinkError { Unreachable, Tls, - Timeout, Outdated, Reset, Closed(Close), @@ -16,7 +15,7 @@ pub enum LinkError { impl std::fmt::Display for LinkError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Unreachable | Self::Timeout => write!(f, "Server unreachable"), + Self::Unreachable => write!(f, "Server unreachable"), Self::Tls => write!(f, "Certificate error"), Self::Outdated => write!(f, "Client is outdated"), Self::Reset => write!(f, "Connection lost"), @@ -38,7 +37,7 @@ impl LinkError { impl From for LinkError { fn from(error: quinn::ConnectionError) -> Self { match error { - quinn::ConnectionError::TimedOut => Self::Timeout, + quinn::ConnectionError::TimedOut => Self::Unreachable, quinn::ConnectionError::ConnectionClosed(close) => { Self::by_code(u64::from(close.error_code)) } @@ -116,19 +115,12 @@ impl From for Fail { } } -impl From for Fail { - fn from(_: quinn::ConnectError) -> Self { - Self::Link(LinkError::Unreachable) - } -} - impl From for Fail { fn from(error: FrameError) -> Self { match error { FrameError::Connection(error) => error.into(), FrameError::Write(error) => error.into(), - FrameError::Read(quinn::ReadExactError::ReadError(error)) => error.into(), - FrameError::Read(quinn::ReadExactError::FinishedEarly(_)) => Self::Protocol, + FrameError::Read(error) => error.into(), FrameError::Closed(error) => error.into(), FrameError::TooLarge { .. } | FrameError::Decode(_) => Self::Protocol, } diff --git a/crates/client/src/net/fetch.rs b/crates/client/src/net/fetch.rs index 01dc4ab..b4b0612 100644 --- a/crates/client/src/net/fetch.rs +++ b/crates/client/src/net/fetch.rs @@ -1,4 +1,7 @@ -use std::{collections::HashMap, sync::Mutex}; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; use common::open::Blob; use tokio::sync::{Semaphore, SemaphorePermit, oneshot}; @@ -7,7 +10,7 @@ use super::{Fail, link}; const PARALLEL_FETCHES: usize = 6; -type Waiter = oneshot::Sender>, Fail>>; +type Waiter = oneshot::Sender>, Fail>>; pub(super) struct Fetches { permits: Semaphore, @@ -49,7 +52,7 @@ impl Fetches { let _permit = self.permit().await; link::download(connection, &blob).await } - .map(std::sync::Arc::new); + .map(Arc::new); let senders = self .waiting .lock() diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index cd789f1..e988528 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -4,26 +4,26 @@ use common::{ call::Call, constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::Error, - frame::{self, DOWN_MAX, Sending, UP_MAX}, + frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, model::{Attachment, User}, open::{Blob, Open, Upload}, session::{Hello, Welcome}, - transport::{Close, alpn, transport}, + transport::{ALPN, Close, transport}, validate::{validate_attachment_name, validate_attachment_size}, }; -use quinn::Endpoint; +use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls}; #[cfg(debug_assertions)] -use quinn::{ - crypto::rustls::QuicClientConfig, - rustls::{ - self, DigitallySignedStruct, SignatureScheme, - client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, - pki_types::{CertificateDer, ServerName, UnixTime}, - }, +use quinn::rustls::{ + DigitallySignedStruct, SignatureScheme, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, UnixTime}, }; #[cfg(debug_assertions)] use rustls_platform_verifier as _; -use tokio::sync::{mpsc, oneshot}; +use tokio::{ + io::AsyncReadExt, + sync::{mpsc, oneshot}, +}; use tracing::{info, warn}; use crate::ClientConfig; @@ -95,14 +95,15 @@ impl Endpoints { } } -fn backoff(attempt: u32) -> Duration { - let base = (BACKOFF_BASE_MILLIS << attempt.min(10)).min(BACKOFF_CAP_MILLIS); +async fn backoff(attempt: &mut u32) { + let base = (BACKOFF_BASE_MILLIS << (*attempt).min(10)).min(BACKOFF_CAP_MILLIS); let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |elapsed| elapsed.subsec_nanos() as u64); let jitter = base * (80 + nanos % 41) / 100; - Duration::from_millis(jitter) + tokio::time::sleep(Duration::from_millis(jitter)).await; + *attempt += 1; } async fn connect( @@ -206,91 +207,61 @@ impl ServerCertVerifier for AcceptAnyCertificate { } } -#[cfg(debug_assertions)] -fn accept_any_client_config() -> Result { +fn config() -> Result { let provider = Arc::new(rustls::crypto::ring::default_provider()); - let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone()) + #[cfg(debug_assertions)] + let verifier = Arc::new(AcceptAnyCertificate { + provider: provider.clone(), + }); + #[cfg(not(debug_assertions))] + let verifier = + Arc::new(rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?); + + let mut tls = rustls::ClientConfig::builder_with_provider(provider) .with_protocol_versions(&[&rustls::version::TLS13]) .map_err(tls_error)? .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider })) + .with_custom_certificate_verifier(verifier) .with_no_client_auth(); - tls.alpn_protocols = vec![alpn()]; + tls.alpn_protocols = vec![ALPN.to_vec()]; let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?; + let mut client_config = quinn::ClientConfig::new(Arc::new(crypto)); + client_config.transport_config(Arc::new(transport())); - Ok(quinn::ClientConfig::new(Arc::new(crypto))) -} - -#[cfg(not(debug_assertions))] -fn platform_client_config() -> Result { - let provider = Arc::new(quinn::rustls::crypto::ring::default_provider()); - let verifier = rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?; - let mut tls = quinn::rustls::ClientConfig::builder_with_provider(provider) - .with_protocol_versions(&[&quinn::rustls::version::TLS13]) - .map_err(tls_error)? - .dangerous() - .with_custom_certificate_verifier(Arc::new(verifier)) - .with_no_client_auth(); - tls.alpn_protocols = vec![alpn()]; - - let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(tls_error)?; - - Ok(quinn::ClientConfig::new(Arc::new(crypto))) + Ok(client_config) } -fn config() -> Result { - #[cfg(debug_assertions)] - let mut client_config = accept_any_client_config()?; - - #[cfg(not(debug_assertions))] - let mut client_config = platform_client_config()?; +async fn exchange( + connection: &quinn::Connection, + request: &impl Encode, +) -> Result<(R, quinn::RecvStream), Fail> { + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + frame::write(&mut send_stream, request, UP_MAX).await?; + send_stream.finish()?; - client_config.transport_config(Arc::new(transport())); + let reply = frame::read::>(&mut receive_stream, DOWN_MAX).await??; - Ok(client_config) + Ok((reply, receive_stream)) } pub(super) async fn call( connection: &quinn::Connection, call: C, ) -> Result { - let (send_stream, mut receive_stream) = connection.open_bi().await?; - let mut send_stream = Sending::new(send_stream); - frame::write(&mut send_stream, &Open::Call(call.into_request()), UP_MAX).await?; - send_stream.finish()?; - - Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) + Ok(exchange(connection, &Open::Call(call.into_request())) + .await? + .0) } async fn hello(connection: &quinn::Connection, token: Option) -> Result { - let (send_stream, mut receive_stream) = connection.open_bi().await?; - let mut send_stream = Sending::new(send_stream); let hello = Hello { token, device: device_name(), }; - frame::write(&mut send_stream, &hello, UP_MAX).await?; - send_stream.finish()?; - Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) -} - -pub(super) async fn send_body( - send_stream: &mut quinn::SendStream, - file: &mut tokio::fs::File, -) -> Result<(), Fail> { - use tokio::io::AsyncReadExt; - - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = file.read(&mut buffer).await?; - if read == 0 { - return Ok(()); - } - - send_stream.write_all(&buffer[..read]).await?; - } + Ok(exchange(connection, &hello).await?.0) } pub(super) async fn upload( @@ -321,7 +292,16 @@ pub(super) async fn upload( frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?; let write = async move { - send_body(send_stream.get(), &mut file).await?; + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; + loop { + let read = file.read(&mut buffer).await?; + if read == 0 { + break; + } + + send_stream.get().write_all(&buffer[..read]).await?; + } + Ok(send_stream.finish()?) }; let read = frame::read::>(&mut receive_stream, DOWN_MAX); @@ -334,31 +314,15 @@ pub(super) async fn upload( } } -async fn open_fetch( - connection: &quinn::Connection, - blob: &Blob, -) -> Result<(quinn::RecvStream, u64), Fail> { - let (send_stream, mut receive_stream) = connection.open_bi().await?; - let mut send_stream = Sending::new(send_stream); - frame::write(&mut send_stream, &Open::Fetch(blob.clone()), UP_MAX).await?; - send_stream.finish()?; - - let length = frame::read::>(&mut receive_stream, DOWN_MAX).await??; - - Ok((receive_stream, length)) -} - pub(super) async fn backup_download( connection: &quinn::Connection, name: &str, path: &Path, ) -> Result<(), Fail> { - let (mut receive_stream, length) = - open_fetch(connection, &Blob::Backup(name.to_string())).await?; + let (length, mut receive_stream) = + exchange::(connection, &Open::Fetch(Blob::Backup(name.to_string()))).await?; - let mut part = path.as_os_str().to_owned(); - part.push(".part"); - let part = std::path::PathBuf::from(part); + let part = path.with_added_extension("part"); let copied = async { let mut file = tokio::fs::File::create(&part).await?; @@ -379,7 +343,8 @@ pub(super) async fn backup_download( } pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Result, Fail> { - let (mut receive_stream, length) = open_fetch(connection, blob).await?; + let (length, mut receive_stream) = + exchange::(connection, &Open::Fetch(blob.clone())).await?; if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES { return Err(Fail::Protocol); @@ -433,8 +398,7 @@ async fn actor( return; } - tokio::time::sleep(backoff(attempt)).await; - attempt += 1; + backoff(&mut attempt).await; } }; }; @@ -464,16 +428,16 @@ async fn actor( } Err(error) => { warn!("hello failed: {error}"); - if let Some(reason) = connection.close_reason() { - let event = LinkError::from(reason); - if event == LinkError::Closed(Close::Banned) { - let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; - while command_receiver.recv().await.is_some() {} - return; - } + if connection.close_reason().map(LinkError::from) + == Some(LinkError::Closed(Close::Banned)) + { + let _ = event_sender + .send(NetworkEvent::Disconnected(LinkError::Closed(Close::Banned))) + .await; + while command_receiver.recv().await.is_some() {} + return; } - tokio::time::sleep(backoff(attempt)).await; - attempt += 1; + backoff(&mut attempt).await; continue 'session; } }; @@ -548,8 +512,7 @@ async fn actor( return; } - tokio::time::sleep(backoff(attempt)).await; - attempt += 1; + backoff(&mut attempt).await; break; } } diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs index 13ab0dc..793851c 100644 --- a/crates/client/src/net/media.rs +++ b/crates/client/src/net/media.rs @@ -49,6 +49,7 @@ struct Want { deafened: bool, } +#[derive(Default)] struct Inner { epoch: u64, connection: Option, @@ -70,6 +71,12 @@ impl Inner { self.sharing.clear(); } + fn end_voice(&mut self) { + self.drop_calls(); + self.want_voice = None; + self.watching.clear(); + } + fn install_voice(&mut self, mut voice: Voice, want: Want) { voice.apply(&want.settings); voice.set_muted(want.muted); @@ -78,6 +85,16 @@ impl Inner { self.voice = Some(voice); self.want_voice = Some(want); } + + fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> { + self.watching + .iter() + .map(|((user_id, kind), watching)| { + let request = watch_request(user_id.clone(), *kind, watching.wanted()); + ((user_id.clone(), *kind), request) + }) + .collect() + } } pub(super) struct Media { @@ -89,16 +106,7 @@ impl Media { pub(super) fn new(handle: Handle) -> Arc { let media = Arc::new(Media { handle: handle.clone(), - inner: Mutex::new(Inner { - epoch: 0, - connection: None, - want_voice: None, - voice: None, - joining: 0, - mic_test: None, - sharing: HashMap::new(), - watching: HashMap::new(), - }), + inner: Mutex::default(), }); handle.spawn(tick_loop(media.clone())); @@ -159,9 +167,7 @@ impl Media { pub(super) fn reset(&self) { let mut inner = self.lock(); inner.connection = None; - inner.drop_calls(); - inner.want_voice = None; - inner.watching.clear(); + inner.end_voice(); } async fn rejoin( @@ -259,9 +265,7 @@ impl Media { } } Down::VoiceEnded => { - inner.drop_calls(); - inner.want_voice = None; - inner.watching.clear(); + inner.end_voice(); return true; } } @@ -288,7 +292,7 @@ impl Media { } async fn join_voice( - &self, + self: Arc, community_id: String, settings: VoiceSettings, ) -> Result, Fail> { @@ -322,19 +326,17 @@ impl Media { Ok(participants) } - async fn leave_voice(&self) -> Result<(), Fail> { + async fn leave_voice(self: Arc) -> Result<(), Fail> { let connection = { let mut inner = self.lock(); - inner.drop_calls(); - inner.want_voice = None; - inner.watching.clear(); + inner.end_voice(); inner.connection.clone().ok_or(Fail::Offline)? }; call(&connection, LeaveVoice).await } - async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> { + async fn start_share(self: Arc, kind: Kind, settings: ShareSettings) -> Result<(), Fail> { let (connection, epoch) = self.current_wait().await?; let top = match kind { Kind::Screen => settings.top, @@ -366,11 +368,12 @@ impl Media { result } - async fn update_share(&self, settings: ShareSettings) -> Result<(), Fail> { + async fn update_share(self: Arc, settings: ShareSettings) -> Result<(), Fail> { + let kind = Kind::Screen; let (connection, _) = self.current_wait().await?; let source = { let mut inner = self.lock(); - let Some(sharing) = inner.sharing.get_mut(&Kind::Screen) else { + let Some(sharing) = inner.sharing.get_mut(&kind) else { return Ok(()); }; sharing @@ -383,17 +386,10 @@ impl Media { .map_err(Fail::Io)? }; - call( - &connection, - StartShare { - kind: Kind::Screen, - source, - }, - ) - .await + call(&connection, StartShare { kind, source }).await } - async fn stop_share(&self, kind: Kind) -> Result<(), Fail> { + async fn stop_share(self: Arc, kind: Kind) -> Result<(), Fail> { self.lock().sharing.remove(&kind); let (connection, _) = self.current_wait().await?; @@ -401,20 +397,12 @@ impl Media { } } -impl Inner { - fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> { - self.watching - .iter() - .map(|((user_id, kind), watching)| { - let request = WatchShare { - user_id: user_id.clone(), - kind: *kind, - quality: watching.wanted(), - decode: capabilities().decode.clone(), - }; - ((user_id.clone(), *kind), request) - }) - .collect() +fn watch_request(user_id: String, kind: Kind, quality: Quality) -> WatchShare { + WatchShare { + user_id, + kind, + quality, + decode: capabilities().decode.clone(), } } @@ -442,52 +430,31 @@ async fn tick_loop(media: Arc) { let mut ticker = tokio::time::interval(TICK); loop { ticker.tick().await; - let (connection, requests) = { - let mut inner = media.lock(); - (inner.connection.clone(), watch_ticks(&mut inner.watching)) - }; - let Some(connection) = connection else { - continue; - }; - for request in requests { - match request { - Ping::Watch(request) => tokio::spawn(send_quietly(connection.clone(), request)), - Ping::Keyframe(request) => tokio::spawn(send_quietly(connection.clone(), request)), - }; + let mut inner = media.lock(); + let connection = inner.connection.clone(); + for ((user_id, kind), watching) in inner.watching.iter_mut() { + for tick in watching.tick() { + let Some(connection) = connection.clone() else { + continue; + }; + match tick { + Tick::Quality(quality) => tokio::spawn(send_quietly( + connection, + watch_request(user_id.clone(), *kind, quality), + )), + Tick::Keyframe => tokio::spawn(send_quietly( + connection, + RequestKeyframe { + user_id: user_id.clone(), + kind: *kind, + }, + )), + }; + } } } } -enum Ping { - Watch(WatchShare), - Keyframe(RequestKeyframe), -} - -fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec { - watching - .iter_mut() - .flat_map(|((user_id, kind), watching)| { - let (user_id, kind) = (user_id.clone(), *kind); - watching - .tick() - .into_iter() - .map(|tick| match tick { - Tick::Quality(quality) => Ping::Watch(WatchShare { - user_id: user_id.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }), - Tick::Keyframe => Ping::Keyframe(RequestKeyframe { - user_id: user_id.clone(), - kind, - }), - }) - .collect::>() - }) - .collect() -} - impl NetworkHandle { fn media(&self) -> &Arc { &self.shared.media @@ -498,21 +465,17 @@ impl NetworkHandle { community_id: &str, settings: &VoiceSettings, ) -> Result, Fail> { - let media = self.media().clone(); - let community_id = community_id.to_string(); - let settings = settings.clone(); - self.media() - .run(async move { media.join_voice(community_id, settings).await }) + .run( + self.media() + .clone() + .join_voice(community_id.to_string(), settings.clone()), + ) .await } pub async fn leave_voice(&self) -> Result<(), Fail> { - let media = self.media().clone(); - - self.media() - .run(async move { media.leave_voice().await }) - .await + self.media().run(self.media().clone().leave_voice()).await } pub fn set_voice_settings(&self, settings: &VoiceSettings) { @@ -618,20 +581,14 @@ impl NetworkHandle { } async fn start(&self, kind: Kind, settings: &ShareSettings) -> Result<(), Fail> { - let media = self.media().clone(); - let settings = settings.clone(); - self.media() - .run(async move { media.start_share(kind, settings).await }) + .run(self.media().clone().start_share(kind, settings.clone())) .await } pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> { - let media = self.media().clone(); - let settings = settings.clone(); - self.media() - .run(async move { media.update_share(settings).await }) + .run(self.media().clone().update_share(settings.clone())) .await } @@ -644,10 +601,8 @@ impl NetworkHandle { } async fn stop(&self, kind: Kind) -> Result<(), Fail> { - let media = self.media().clone(); - self.media() - .run(async move { media.stop_share(kind).await }) + .run(self.media().clone().stop_share(kind)) .await } @@ -697,16 +652,7 @@ impl NetworkHandle { } inner.watching.insert(key.clone(), watching); } - let result = call( - &connection, - WatchShare { - user_id: key.0.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }, - ) - .await; + let result = call(&connection, watch_request(key.0.clone(), kind, quality)).await; if result.is_err() { media.lock().watching.remove(&key); } diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index bb722ea..f2f7c6e 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -1,38 +1,10 @@ use std::{path::PathBuf, sync::Arc}; use common::{ - call::{ - AcceptFriend, AcceptInvitation, AddFriend, BanMember, BanUser, Call, ClearProfile, - ClosePoll, CreateBackup, CreateCommunity, CreateInviteCode, CreateMessage, CreatePoll, - CreateUser, DeclineCall, DeclineInvitation, DeleteAttachment, DeleteBackup, - DeleteCommunity, DeleteInviteCode, DeleteMessage, DeleteUser, FindUser, ForwardMessages, - GetAvatar, GetCommunity, GetDailyStats, GetOverview, GetSettings, GetStorageUsage, GetUser, - HandleReport, Invite, Kick, KickFromVoice, LeaveCommunity, ListAdminLogs, - ListAllCommunities, ListAttachments, ListBackups, ListBans, ListCommunities, ListFriends, - ListInvitations, ListInviteCodes, ListLogs, ListMembers, ListMessages, ListPins, - ListPresences, ListReports, ListServerBans, ListSessions, ListUnreads, ListUsers, - ListVoiceParticipants, ListVoiceRooms, Login, Logout, MarkRead, OpenDirect, OpenNotes, Pin, - PurgeUser, React, Register, RemoveAvatar, RemoveFriend, RemoveServerBan, RenameUser, - ReportMessage, ReportUser, ResetPassword, RevokeSession, RevokeSessions, SearchCommunity, - SearchMessages, ServerMute, Session, SetCommunityVoice, SetGhost, SetRank, SetRole, - SuspendUser, TimeoutUser, TransferOwnership, Typing, Unban, UpdateAvatar, UpdateCommunity, - UpdateCommunityAvatar, UpdateMessage, UpdatePresence, UpdateServerSettings, UpdateStatus, - UpdateUser, Vote, WatchCommunity, - }, - constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, + call::{Call, GetStorageUsage, Login, Logout, Register, Session}, event::Event, - model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community, - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, - Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, - ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, - }, + model::{Attachment, CommunityUsage, Usage, User}, open::Blob, - validate::{ - validate_avatar_size, validate_community_name, validate_forward, validate_new_message, - validate_password, validate_poll, validate_reason, validate_server_settings, - validate_status, validate_username, - }, }; use tokio::sync::{mpsc, oneshot}; @@ -128,7 +100,9 @@ impl NetworkHandle { response.await.map_err(|_| Fail::Offline)? } - async fn call(&self, call: C) -> Result { + pub async fn call(&self, call: C) -> Result { + call.validate()?; + self.ask(|reply| { Command::Call(Box::new(move |connection| { link::answer(reply, async move { link::call(&connection, call).await }); @@ -147,31 +121,6 @@ impl NetworkHandle { Ok((session.user, session.token)) } - pub async fn sessions(&self, user_id: &str) -> Result, Fail> { - self.call(ListSessions { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> { - self.call(RevokeSession { - user_id: user_id.to_string(), - session_id: session_id.to_string(), - }) - .await - } - - pub async fn rename_user(&self, user_id: &str, username: &str) -> Result { - validate_username(username)?; - - self.call(RenameUser { - user_id: user_id.to_string(), - username: username.to_string(), - }) - .await - } - pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { let user = self .switch(Some(token.to_string())) @@ -191,9 +140,6 @@ impl NetworkHandle { password: &str, invite: Option<&str>, ) -> Result<(User, String), Fail> { - validate_username(username)?; - validate_password(password)?; - let session = self .call(Register { username: username.to_string(), @@ -206,8 +152,6 @@ impl NetworkHandle { } pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { - validate_password(password)?; - let session = self .call(Login { username: username.to_string(), @@ -224,596 +168,12 @@ impl NetworkHandle { result } - pub async fn update_user(&self, username: &str) -> Result { - validate_username(username)?; - - self.call(UpdateUser { - username: username.to_string(), - }) - .await - } - - pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> { - self.call(DeleteUser { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn users(&self) -> Result, Fail> { - self.call(ListUsers).await - } - - pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> { - self.call(SuspendUser { - user_id: user_id.to_string(), - suspended, - }) - .await - } - - pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> { - self.call(TimeoutUser { - user_id: user_id.to_string(), - minutes, - }) - .await - } - - pub async fn ban_user( - &self, - user_id: &str, - reason: Option<&str>, - scope: BanScope, - ) -> Result<(), Fail> { - validate_reason(reason)?; - - self.call(BanUser { - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - scope, - }) - .await - } - - pub async fn server_bans(&self) -> Result, Fail> { - self.call(ListServerBans).await - } - - pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> { - self.call(RemoveServerBan { id: id.to_string() }).await - } - - pub async fn create_invite_code( - &self, - uses: u32, - hours: Option, - ) -> Result { - self.call(CreateInviteCode { uses, hours }).await - } - - pub async fn invite_codes(&self) -> Result, Fail> { - self.call(ListInviteCodes).await - } - - pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> { - self.call(DeleteInviteCode { - code: code.to_string(), - }) - .await - } - - pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> { - self.call(RevokeSessions { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> { - validate_password(password)?; - - self.call(ResetPassword { - user_id: user_id.to_string(), - password: password.to_string(), - }) - .await - } - - pub async fn clear_profile(&self, user_id: &str) -> Result { - self.call(ClearProfile { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn set_role(&self, user_id: &str, role: Role) -> Result { - self.call(SetRole { - user_id: user_id.to_string(), - role, - }) - .await - } - - pub async fn admin_logs( - &self, - actor_id: Option, - target_id: Option, - action: Option, - after_ms: Option, - before_ms: Option, - ) -> Result, Fail> { - self.call(ListAdminLogs { - actor_id, - target_id, - action, - after_ms, - before_ms, - }) - .await - } - - pub async fn daily_stats(&self, days: u32) -> Result, Fail> { - self.call(GetDailyStats { days }).await - } - - pub async fn server_settings(&self) -> Result { - self.call(GetSettings).await - } - - pub async fn update_server_settings( - &self, - settings: ServerSettings, - ) -> Result { - validate_server_settings(&settings)?; - - self.call(UpdateServerSettings { settings }).await - } - - pub async fn create_user(&self, username: &str, password: &str) -> Result { - validate_username(username)?; - validate_password(password)?; - - self.call(CreateUser { - username: username.to_string(), - password: password.to_string(), - }) - .await - } - - pub async fn overview(&self) -> Result { - self.call(GetOverview).await - } - - pub async fn all_communities(&self) -> Result, Fail> { - self.call(ListAllCommunities).await - } - - pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.call(TransferOwnership { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn read_user(&self, user_id: &str) -> Result { - self.call(GetUser { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn create_community(&self, name: &str) -> Result { - validate_community_name(name)?; - - self.call(CreateCommunity { - name: name.to_string(), - }) - .await - } - - pub async fn update_community( - &self, - community_id: &str, - name: &str, - ) -> Result { - validate_community_name(name)?; - - self.call(UpdateCommunity { - community_id: community_id.to_string(), - name: name.to_string(), - }) - .await - } - - pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> { - self.call(DeleteCommunity { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> { - self.call(LeaveCommunity { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn communities(&self) -> Result, Fail> { - self.call(ListCommunities).await - } - - pub async fn members(&self, community_id: &str) -> Result, Fail> { - self.call(ListMembers { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn kick( - &self, - community_id: &str, - user_id: &str, - reason: Option<&str>, - ) -> Result<(), Fail> { - validate_reason(reason)?; - self.call(Kick { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await - } - - pub async fn ban( - &self, - community_id: &str, - user_id: &str, - reason: Option<&str>, - ) -> Result<(), Fail> { - validate_reason(reason)?; - self.call(BanMember { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await - } - - pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.call(Unban { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn bans(&self, community_id: &str) -> Result, Fail> { - self.call(ListBans { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn logs(&self, community_id: &str) -> Result, Fail> { - self.call(ListLogs { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn set_rank( - &self, - community_id: &str, - user_id: &str, - rank: Rank, - ) -> Result<(), Fail> { - self.call(SetRank { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - rank, - }) - .await - } - - pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> { - self.call(DeleteMessage { - message_id: message_id.to_string(), - }) - .await - } - - pub async fn create_message( - &self, - community_id: &str, - body: &str, - attachments: Vec, - reply_to: Option, - ) -> Result { - validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; - - self.call(CreateMessage { - community_id: community_id.to_string(), - body: body.to_string(), - attachments, - reply_to, - }) - .await - } - - pub async fn update_message(&self, message_id: &str, body: &str) -> Result { - validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; - - self.call(UpdateMessage { - message_id: message_id.to_string(), - body: body.to_string(), - }) - .await - } - - pub async fn forward_messages( - &self, - message_ids: Vec, - community_id: &str, - snippet: bool, - ) -> Result, Fail> { - validate_forward(message_ids.len())?; - - self.call(ForwardMessages { - message_ids, - community_id: community_id.to_string(), - snippet, - }) - .await - } - - pub async fn find_user(&self, username: &str) -> Result { - self.call(FindUser { - username: username.to_string(), - }) - .await - } - - pub async fn open_notes(&self) -> Result { - self.call(OpenNotes).await - } - - pub async fn open_direct(&self, user_id: &str) -> Result { - self.call(OpenDirect { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn friends(&self) -> Result { - self.call(ListFriends).await - } - - pub async fn read_presences(&self) -> Result, Fail> { - self.call(ListPresences).await - } - - pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> { - self.call(UpdatePresence { presence }).await - } - - pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> { - self.call(AddFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> { - self.call(AcceptFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> { - self.call(RemoveFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.call(Invite { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn invitations(&self) -> Result, Fail> { - self.call(ListInvitations).await - } - - pub async fn accept_invitation(&self, community_id: &str) -> Result { - self.call(AcceptInvitation { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> { - self.call(DeclineInvitation { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> { - self.call(DeclineCall { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> { - self.call(React { - message_id: message_id.to_string(), - emoji: emoji.to_string(), - }) - .await - } - - pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> { - self.call(Pin { - message_id: message_id.to_string(), - pinned, - }) - .await - } - - pub async fn pins(&self, community_id: &str) -> Result, Fail> { - self.call(ListPins { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn create_poll( - &self, - community_id: &str, - question: &str, - options: Vec, - multiple: bool, - ) -> Result { - validate_poll(question, &options)?; - - self.call(CreatePoll { - community_id: community_id.to_string(), - question: question.to_string(), - options, - multiple, - }) - .await - } - - pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Fail> { - self.call(Vote { - message_id: message_id.to_string(), - positions, - }) - .await - } - - pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> { - self.call(ClosePoll { - message_id: message_id.to_string(), - }) - .await - } - - pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> { - validate_reason(Some(reason))?; - - self.call(ReportMessage { - message_id: message_id.to_string(), - reason: reason.to_string(), - }) - .await - } - - pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> { - validate_reason(Some(reason))?; - - self.call(ReportUser { - user_id: user_id.to_string(), - reason: reason.to_string(), - }) - .await - } - - pub async fn reports(&self, status: Option) -> Result, Fail> { - self.call(ListReports { status }).await - } - - pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> { - self.call(HandleReport { - report_id: report_id.to_string(), - status, - }) - .await - } - - pub async fn search_messages( - &self, - text: Option, - user_id: Option, - community_id: Option, - after_ms: Option, - before_ms: Option, - ) -> Result, Fail> { - self.call(SearchMessages { - text, - user_id, - community_id, - after_ms, - before_ms, - }) - .await - } - - pub async fn search_community( - &self, - community_id: String, - text: String, - ) -> Result, Fail> { - self.call(SearchCommunity { community_id, text }).await - } - pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { let usage = self.call(GetStorageUsage).await?; Ok((usage.users, usage.communities)) } - pub async fn create_backup(&self) -> Result { - self.call(CreateBackup).await - } - - pub async fn backups(&self) -> Result, Fail> { - self.call(ListBackups).await - } - - pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> { - self.call(DeleteBackup { - name: name.to_string(), - }) - .await - } - - pub async fn attachments( - &self, - user_id: Option, - community_id: Option, - ) -> Result, Fail> { - self.call(ListAttachments { - user_id, - community_id, - }) - .await - } - - pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> { - self.call(DeleteAttachment { - attachment_id: attachment_id.to_string(), - }) - .await - } - - pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> { - self.call(PurgeUser { - user_id: user_id.to_string(), - }) - .await - } - pub async fn upload_attachment( &self, community_id: &str, @@ -851,133 +211,4 @@ impl NetworkHandle { }) .await } - - pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> { - self.call(WatchCommunity { - community_id: community_id.map(str::to_string), - }) - .await - } - - pub async fn read_messages( - &self, - community_id: &str, - before: Option<&str>, - ) -> Result, Fail> { - self.call(ListMessages { - community_id: community_id.to_string(), - before: before.map(str::to_string), - }) - .await - } - - pub async fn unreads(&self) -> Result, Fail> { - self.call(ListUnreads).await - } - - pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> { - self.call(MarkRead { - community_id: community_id.to_string(), - message_id: message_id.to_string(), - }) - .await - } - - pub async fn update_status(&self, status: &str) -> Result { - validate_status(status)?; - - self.call(UpdateStatus { - status: status.to_string(), - }) - .await - } - - pub async fn update_avatar(&self, bytes: Vec) -> Result { - validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; - - self.call(UpdateAvatar { image: bytes }).await - } - - pub async fn update_community_avatar( - &self, - community_id: &str, - image: Option>, - ) -> Result { - if let Some(bytes) = &image { - validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; - } - - self.call(UpdateCommunityAvatar { - community_id: community_id.to_string(), - image, - }) - .await - } - - pub async fn remove_avatar(&self) -> Result { - self.call(RemoveAvatar).await - } - - pub async fn read_avatar(&self, avatar_id: &str) -> Result, Fail> { - self.call(GetAvatar { - avatar_id: avatar_id.to_string(), - }) - .await - } - - pub async fn typing(&self, community_id: &str) -> Result<(), Fail> { - self.call(Typing { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn read_community(&self, community_id: &str) -> Result { - self.call(GetCommunity { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn voice_participants(&self, community_id: &str) -> Result, Fail> { - self.call(ListVoiceParticipants { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn voice_rooms(&self) -> Result, Fail> { - self.call(ListVoiceRooms).await - } - - pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> { - self.call(SetGhost { enabled }).await - } - - pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> { - self.call(KickFromVoice { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> { - self.call(ServerMute { - user_id: user_id.to_string(), - muted, - }) - .await - } - - pub async fn set_community_voice( - &self, - community_id: &str, - enabled: bool, - ) -> Result { - self.call(SetCommunityVoice { - community_id: community_id.to_string(), - enabled, - }) - .await - } } diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index c7e084e..91c5c00 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -7,7 +7,7 @@ use common::{ constant::{ MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, }, - datagram::{Packet, RELAY_PREFIX}, + datagram::{Packet, RELAY_PREFIX, VOICE_HEADER}, }; use ec_opus::{Application, Bandwidth, Decoder, Encoder}; use uuid::Uuid; @@ -293,7 +293,7 @@ impl Engine { pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { let user_id = Uuid::from_bytes(*from).to_string(); let now = Instant::now(); - self.received_bytes += RELAY_PREFIX + 5 + payload.len(); + self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); let speaker = self .speakers diff --git a/crates/common/src/call.rs b/crates/common/src/call.rs index 6c5cb31..5cecf97 100644 --- a/crates/common/src/call.rs +++ b/crates/common/src/call.rs @@ -1,6 +1,8 @@ use bitcode::{Decode, DecodeOwned, Encode}; use crate::{ + constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, + error::Error, model::{ Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, @@ -8,6 +10,11 @@ use crate::{ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, share::{Codec, Kind, Quality, Share, Source}, + validate::{ + validate_avatar_size, validate_community_name, validate_forward, validate_new_message, + validate_password, validate_poll, validate_reaction, validate_reason, + validate_server_settings, validate_status, validate_username, + }, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -22,10 +29,14 @@ pub trait Call: Encode + DecodeOwned + Send + 'static { const GATE: Gate; fn into_request(self) -> Request; + + fn validate(&self) -> Result<(), Error> { + Ok(()) + } } macro_rules! calls { - ($($name:ident: $gate:ident -> $reply:ty;)*) => { + ($($name:ident: $gate:ident -> $reply:ty $(, |$c:ident| $check:expr)?;)*) => { #[derive(Debug, Clone, Encode, Decode)] pub enum Request { $($name($name),)* @@ -39,6 +50,13 @@ macro_rules! calls { fn into_request(self) -> Request { Request::$name(self) } + + $( + fn validate(&self) -> Result<(), Error> { + let $c = self; + $check + } + )? } )* }; @@ -600,37 +618,37 @@ pub struct StorageUsage { calls! { GetSettings: Guest -> ServerSettings; GetUser: User -> User; - UpdateUser: User -> User; - UpdateStatus: User -> User; + UpdateUser: User -> User, |c| validate_username(&c.username); + UpdateStatus: User -> User, |c| validate_status(&c.status); UpdatePresence: User -> (); ListPresences: User -> Vec<(String, Presence)>; - UpdateAvatar: User -> User; + UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64); RemoveAvatar: User -> User; GetAvatar: User -> Vec; ListSessions: User -> Vec; RevokeSession: User -> (); - CreateCommunity: User -> Community; + CreateCommunity: User -> Community, |c| validate_community_name(&c.name); GetCommunity: User -> Community; - UpdateCommunity: User -> Community; - UpdateCommunityAvatar: User -> Community; + UpdateCommunity: User -> Community, |c| validate_community_name(&c.name); + UpdateCommunityAvatar: User -> Community, |c| c.image.as_deref().map_or(Ok(()), |image| validate_avatar_size(image, MAXIMUM_AVATAR_BYTES as u64)); DeleteCommunity: User -> (); LeaveCommunity: User -> (); ListCommunities: User -> Vec; ListMembers: User -> Vec; - Kick: User -> (); - BanMember: User -> (); + Kick: User -> (), |c| validate_reason(c.reason.as_deref()); + BanMember: User -> (), |c| validate_reason(c.reason.as_deref()); Unban: User -> (); ListBans: User -> Vec; SetRank: User -> (); ListLogs: User -> Vec; - CreateMessage: User -> Message; - ForwardMessages: User -> Vec; - UpdateMessage: User -> Message; + CreateMessage: User -> Message, |c| validate_new_message(&c.body, c.attachments.len(), MAXIMUM_MESSAGE_LENGTH); + ForwardMessages: User -> Vec, |c| validate_forward(c.message_ids.len()); + UpdateMessage: User -> Message, |c| validate_new_message(&c.body, 0, MAXIMUM_MESSAGE_LENGTH); DeleteMessage: User -> (); - CreatePoll: User -> Message; + CreatePoll: User -> Message, |c| validate_poll(&c.question, &c.options); Vote: User -> (); ClosePoll: User -> (); - React: User -> (); + React: User -> (), |c| validate_reaction(&c.emoji); Pin: User -> (); ListPins: User -> Vec; ListMessages: User -> Vec; @@ -648,8 +666,8 @@ calls! { ListInvitations: User -> Vec; AcceptInvitation: User -> Community; DeclineInvitation: User -> (); - ReportMessage: User -> (); - ReportUser: User -> (); + ReportMessage: User -> (), |c| validate_reason(Some(&c.reason)); + ReportUser: User -> (), |c| validate_reason(Some(&c.reason)); ListReports: Builder -> Vec; HandleReport: User -> (); JoinVoice: User -> Vec; @@ -665,8 +683,8 @@ calls! { ListVoiceRooms: Builder -> Vec; KickFromVoice: User -> (); ServerMute: User -> (); - Register: Guest -> Session; - Login: Guest -> Session; + Register: Guest -> Session, |c| validate_username(&c.username).and(validate_password(&c.password)); + Login: Guest -> Session, |c| validate_password(&c.password); Logout: User -> (); DeleteUser: User -> (); WatchCommunity: User -> (); @@ -676,15 +694,15 @@ calls! { GetOverview: Builder -> Overview; SuspendUser: User -> (); RevokeSessions: User -> (); - ResetPassword: User -> (); + ResetPassword: User -> (), |c| validate_password(&c.password); ClearProfile: User -> User; ListAllCommunities: Builder -> Vec; TransferOwnership: User -> (); - UpdateServerSettings: Builder -> ServerSettings; - CreateUser: Builder -> User; - RenameUser: User -> User; + UpdateServerSettings: Builder -> ServerSettings, |c| validate_server_settings(&c.settings); + CreateUser: Builder -> User, |c| validate_username(&c.username).and(validate_password(&c.password)); + RenameUser: User -> User, |c| validate_username(&c.username); TimeoutUser: User -> (); - BanUser: User -> (); + BanUser: User -> (), |c| validate_reason(c.reason.as_deref()); ListServerBans: Builder -> Vec; RemoveServerBan: Builder -> (); CreateInviteCode: User -> InviteCode; diff --git a/crates/common/src/datagram.rs b/crates/common/src/datagram.rs index c77b48f..4171cfd 100644 --- a/crates/common/src/datagram.rs +++ b/crates/common/src/datagram.rs @@ -12,9 +12,9 @@ use crate::{ }; pub const RELAY_PREFIX: usize = 16; -pub const MAX_DATAGRAM: usize = 1200 - 48; +const MAX_DATAGRAM: usize = 1200 - 48; -const VOICE_HEADER: usize = 5; +pub const VOICE_HEADER: usize = 5; const SHARE_AUDIO_HEADER: usize = 9; const VIDEO_HEADER: usize = 17; const KEYFRAME_FLAG: u8 = 1; @@ -186,10 +186,7 @@ impl<'a> Packet<'a> { } pub fn relayed(from: &[u8; RELAY_PREFIX], uplink: &[u8]) -> Bytes { - let mut bytes = Vec::with_capacity(RELAY_PREFIX + uplink.len()); - bytes.extend_from_slice(from); - bytes.extend_from_slice(uplink); - Bytes::from(bytes) + Bytes::from([from.as_slice(), uplink].concat()) } pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> { @@ -258,15 +255,9 @@ pub fn send(connection: &Connection, bytes: Bytes) { } pub fn warn_if_small(connection: &Connection) { - if connection - .max_datagram_size() - .is_none_or(|size| size < MAX_DATAGRAM) - { - warn!( - max = ?connection.max_datagram_size(), - needed = MAX_DATAGRAM, - "datagram size limit below media packets" - ); + let max = connection.max_datagram_size(); + if max.is_none_or(|size| size < MAX_DATAGRAM) { + warn!(?max, needed = MAX_DATAGRAM, "datagram size limit below media packets"); } } diff --git a/crates/common/src/frame.rs b/crates/common/src/frame.rs index fa2be81..b829198 100644 --- a/crates/common/src/frame.rs +++ b/crates/common/src/frame.rs @@ -1,4 +1,4 @@ -use bitcode::{DecodeOwned, Encode}; +pub use bitcode::{DecodeOwned, Encode}; use quinn::{RecvStream, SendStream}; use crate::constant::MAXIMUM_AVATAR_BYTES; @@ -50,24 +50,23 @@ impl Drop for Sending { } } -pub fn encode(value: &T) -> Vec { +pub fn encode(value: &T, max: u32) -> Result, FrameError> { let payload = bitcode::encode(value); - let mut framed = Vec::with_capacity(4 + payload.len()); - framed.extend_from_slice(&(payload.len() as u32).to_le_bytes()); - framed.extend_from_slice(&payload); - framed -} - -pub async fn write(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> { - let framed = encode(value); - let length = framed.len() as u32 - 4; + let length = payload.len() as u32; if length > max { return Err(FrameError::TooLarge { actual: length, maximum: max, }); } - stream.get().write_all(&framed).await?; + let mut framed = Vec::with_capacity(4 + payload.len()); + framed.extend_from_slice(&length.to_le_bytes()); + framed.extend_from_slice(&payload); + Ok(framed) +} + +pub async fn write(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> { + stream.get().write_all(&encode(value, max)?).await?; Ok(()) } diff --git a/crates/common/src/transport.rs b/crates/common/src/transport.rs index b0d5067..352271b 100644 --- a/crates/common/src/transport.rs +++ b/crates/common/src/transport.rs @@ -2,17 +2,13 @@ use std::time::Duration; use quinn::{TransportConfig, VarInt}; -pub const PROTOCOL: u32 = 2; +pub const ALPN: &[u8] = b"yumush/2"; const IDLE_TIMEOUT: Duration = Duration::from_secs(10); const KEEP_ALIVE: Duration = Duration::from_secs(2); const BIDI_STREAMS: u32 = 256; const DATAGRAM_RECEIVE_BYTES: usize = 1 << 20; -pub fn alpn() -> Vec { - format!("yumush/{PROTOCOL}").into_bytes() -} - pub fn transport() -> TransportConfig { let mut config = TransportConfig::default(); config.keep_alive_interval(Some(KEEP_ALIVE)); @@ -46,9 +42,7 @@ impl Close { ]; pub fn of(code: VarInt) -> Option { - Self::ALL - .into_iter() - .find(|close| u64::from(code) == u64::from(*close as u32)) + Self::ALL.into_iter().find(|close| close.code() == code) } pub fn reason(self) -> &'static str { diff --git a/crates/server/src/call/admin.rs b/crates/server/src/call/admin.rs index f165a5b..7a12e61 100644 --- a/crates/server/src/call/admin.rs +++ b/crates/server/src/call/admin.rs @@ -20,20 +20,22 @@ use common::{ permission, time::{self, MINUTE_MILLIS}, transport::Close, - validate::{validate_reason, validate_server_settings}, }; use crate::{ - admin_log, attachment, authentication, backup, + admin_log, attachment, + authentication::{self, Revoke}, + backup, + call::user::user_updated, call::{Cx, Handle, Me}, community, error::ServerError, invite, log, message, overview, publish::{Broadcast, To}, request::{ - allowed, call_ended, ensure, ensure_editable, is_outsider, leave_user_voice, limit_logins, - managed, message_event, record_ghost_voice, shares_ended, user_updated, voice_closed, - voice_joined, voice_silenced, voice_unmuted, + allowed, call_ended, ensure, ensure_editable, is_outsider, leave_room_voice, + leave_user_voice, limit_logins, managed, message_event, record_ghost_voice, shares_ended, + voice_closed, voice_joined, voice_muted, }, server_ban, server_settings, stats, user, user_community, }; @@ -76,7 +78,6 @@ impl Handle for UpdateServerSettings { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; let settings = self.settings; - validate_server_settings(&settings)?; server_settings::update(&settings, &cx.db).await?; admin_log::record( Some(&me.id), @@ -114,7 +115,7 @@ impl Handle for RenameUser { &cx.db, ) .await?; - cx.out.extend(user_updated(&user)); + user_updated(&user, cx); Ok(user) } @@ -181,12 +182,8 @@ impl Handle for SuspendUser { }; admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?; if self.suspended { - authentication::revoke( - &cx.sh.services.hub, - authentication::Revoke::User(&self.user_id), - &cx.db, - ) - .await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db) + .await?; } Ok(()) @@ -197,12 +194,7 @@ impl Handle for RevokeSessions { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; managed(&me, &self.user_id, &cx.db).await?; - authentication::revoke( - &cx.sh.services.hub, - authentication::Revoke::User(&self.user_id), - &cx.db, - ) - .await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; admin_log::record( Some(&me.id), Some(&self.user_id), @@ -221,12 +213,7 @@ impl Handle for ResetPassword { let me = me.user()?; managed(&me, &self.user_id, &cx.db).await?; authentication::reset_password(&self.user_id, &self.password, &cx.db).await?; - authentication::revoke( - &cx.sh.services.hub, - authentication::Revoke::User(&self.user_id), - &cx.db, - ) - .await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; admin_log::record( Some(&me.id), Some(&self.user_id), @@ -254,7 +241,7 @@ impl Handle for ClearProfile { &cx.db, ) .await?; - cx.out.extend(user_updated(&user)); + user_updated(&user, cx); Ok(user) } @@ -274,10 +261,12 @@ impl Handle for SetRole { &cx.db, ) .await?; - cx.out.extend(user_updated(&user)); + user_updated(&user, cx); if permission::is_builder(role) { - let broadcasts = voice_unmuted(&cx.sh.services.rooms, &user_id, &cx.db).await?; - cx.out.extend(broadcasts); + if let Some(community_id) = cx.sh.services.rooms.set_muted(&user_id, false) { + cx.out + .push(voice_muted(Some(community_id), &user_id, false, &cx.db).await?); + } } else { user::set_ghost(&user_id, false, &cx.db).await?; cx.sh.services.hub.kick_user(&user_id, Close::Revoked); @@ -466,12 +455,7 @@ impl Handle for TimeoutUser { let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); user::set_timeout(&user_id, until, &cx.db).await?; if until.is_some() { - authentication::revoke( - &cx.sh.services.hub, - authentication::Revoke::User(&user_id), - &cx.db, - ) - .await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(&user_id), &cx.db).await?; } admin_log::record( Some(&me.id), @@ -495,7 +479,6 @@ impl Handle for BanUser { scope, } = self; let target = managed(&me, &user_id, &cx.db).await?; - validate_reason(reason.as_deref())?; let tx = cx.db.transaction().await?; user::set_suspended(&user_id, true, &tx).await?; authentication::revoke_sessions(&user_id, &tx).await?; @@ -756,8 +739,13 @@ impl Handle for SetCommunityVoice { } tx.commit().await?; if !enabled { - let broadcasts = voice_silenced(&cx.sh.services.rooms, &community_id, &cx.db).await?; - cx.out.extend(broadcasts); + let rooms = &cx.sh.services.rooms; + for user_id in rooms.room_users(&community_id) { + if !permission::is_builder(user::read(&user_id, &cx.db).await?.role) { + cx.out + .extend(leave_room_voice(rooms, &community_id, &user_id, &cx.db).await?); + } + } } cx.emit( To::Community(community_id), diff --git a/crates/server/src/call/community.rs b/crates/server/src/call/community.rs index 40c4fea..1b067bd 100644 --- a/crates/server/src/call/community.rs +++ b/crates/server/src/call/community.rs @@ -8,7 +8,7 @@ use common::{ event::Event, model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User}, permission, - validate::{validate_avatar_size, validate_reason}, + validate::validate_avatar_size, }; use crate::{ @@ -24,21 +24,14 @@ use crate::{ server_settings, user, user_community, }; -struct Removal { +async fn remove_member( + me: &User, community_id: String, user_id: String, reason: Option, sanction: Sanction, -} - -async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let Removal { - community_id, - user_id, - reason, - sanction, - } = removal; - validate_reason(reason.as_deref())?; + cx: &mut Cx<'_>, +) -> Result<(), ServerError> { ensure_editable(&community_id, &cx.db).await?; let target = user::read(&user_id, &cx.db).await?; ensure(permission::can_moderate( @@ -61,9 +54,8 @@ async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<( }; log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; tx.commit().await?; - let broadcasts = - leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?; - cx.out.extend(broadcasts); + cx.out + .extend(leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?); cx.emit( To::User(user_id.clone()), Event::Removed { @@ -199,8 +191,8 @@ impl Handle for DeleteCommunity { .await?; } tx.commit().await?; - let broadcasts = voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?; - cx.out.extend(broadcasts); + cx.out + .extend(voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?); cx.emit( To::Users(member_ids), Event::CommunityDeleted { @@ -269,28 +261,30 @@ impl Handle for ListMembers { impl Handle for Kick { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let removal = Removal { - community_id: self.community_id, - user_id: self.user_id, - reason: self.reason, - sanction: Sanction::Kick, - }; - - remove_member(&me, removal, cx).await + remove_member( + &me, + self.community_id, + self.user_id, + self.reason, + Sanction::Kick, + cx, + ) + .await } } impl Handle for BanMember { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let removal = Removal { - community_id: self.community_id, - user_id: self.user_id, - reason: self.reason, - sanction: Sanction::Ban, - }; - - remove_member(&me, removal, cx).await + remove_member( + &me, + self.community_id, + self.user_id, + self.reason, + Sanction::Ban, + cx, + ) + .await } } diff --git a/crates/server/src/call/message.rs b/crates/server/src/call/message.rs index 2d4199b..90a943b 100644 --- a/crates/server/src/call/message.rs +++ b/crates/server/src/call/message.rs @@ -7,9 +7,7 @@ use common::{ event::Event, model::{AdminAction, LogAction, Message, ServerSettings, Unread, User}, permission, - validate::{ - validate_forward, validate_new_message, validate_poll, validate_reaction, validate_vote, - }, + validate::{validate_new_message, validate_vote}, }; use crate::{ @@ -19,7 +17,7 @@ use crate::{ error::ServerError, log, message, publish::To, - request::{actor_rank, allowed, ensure, is_outsider}, + request::{actor_rank, allowed, ensure, is_outsider, message_event}, server_settings, stats, user, user_community, }; @@ -35,13 +33,6 @@ fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<( .allow(&me.id, settings.messages_per_minute)?) } -fn emit_message(message: &Message, event: fn(Message) -> Event, cx: &mut Cx<'_>) { - cx.emit( - To::Community(message.community_id.clone()), - event(message.clone()), - ); -} - impl Handle for CreateMessage { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; @@ -65,7 +56,7 @@ impl Handle for CreateMessage { .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - emit_message(&created, Event::MessageCreated, cx); + cx.out.push(message_event(&created, Event::MessageCreated)); Ok(created) } @@ -75,7 +66,6 @@ impl Handle for ForwardMessages { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?; - validate_forward(self.message_ids.len())?; ensure(permission::can_post( actor_rank(&me, &self.community_id, &cx.db).await?, ))?; @@ -104,7 +94,7 @@ impl Handle for ForwardMessages { .await?; tx.commit().await?; for message in &created { - emit_message(message, Event::MessageCreated, cx); + cx.out.push(message_event(message, Event::MessageCreated)); } Ok(created) @@ -123,7 +113,7 @@ impl Handle for UpdateMessage { server_settings::read(&cx.db).await?.max_message_length as usize, )?; let updated = message::update(&self.message_id, &self.body, &cx.db).await?; - emit_message(&updated, Event::MessageUpdated, cx); + cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(updated) } @@ -178,7 +168,6 @@ impl Handle for CreatePoll { let me = me.user()?; let settings = server_settings::read(&cx.db).await?; limit_messages(&me, &settings, cx)?; - validate_poll(&self.question, &self.options)?; allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; let tx = cx.db.transaction().await?; let created = message::create_poll( @@ -192,7 +181,7 @@ impl Handle for CreatePoll { .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - emit_message(&created, Event::MessageCreated, cx); + cx.out.push(message_event(&created, Event::MessageCreated)); Ok(created) } @@ -208,7 +197,7 @@ impl Handle for Vote { let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; validate_vote(poll, &self.positions)?; let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?; - emit_message(&updated, Event::MessageUpdated, cx); + cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) } @@ -223,7 +212,7 @@ impl Handle for ClosePoll { existing.user_id == me.id, ))?; let updated = message::close_poll(&self.message_id, &cx.db).await?; - emit_message(&updated, Event::MessageUpdated, cx); + cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) } @@ -232,13 +221,12 @@ impl Handle for ClosePoll { impl Handle for React { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - validate_reaction(&self.emoji)?; let existing = message::read(&self.message_id, &cx.db).await?; ensure(permission::can_read( actor_rank(&me, &existing.community_id, &cx.db).await?, ))?; let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?; - emit_message(&updated, Event::MessageUpdated, cx); + cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) } @@ -254,7 +242,7 @@ impl Handle for Pin { direct, ))?; let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?; - emit_message(&updated, Event::MessageUpdated, cx); + cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) } diff --git a/crates/server/src/call/mod.rs b/crates/server/src/call/mod.rs index 5b1e31a..943bf75 100644 --- a/crates/server/src/call/mod.rs +++ b/crates/server/src/call/mod.rs @@ -13,6 +13,7 @@ use common::{ event::Event, frame::{self, DOWN_MAX}, model::User, + permission, }; use turso::Connection; @@ -72,12 +73,18 @@ async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { match gate { Gate::Guest => Ok(Me::Guest), Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)), - Gate::Builder => Ok(Me::User(request::builder(cx.client, &cx.db).await?)), + Gate::Builder => { + let user = request::authenticated(cx.client, &cx.db).await?; + request::ensure(permission::is_builder(user.role))?; + + Ok(Me::User(user)) + } } } async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { let reply = async { + call.validate()?; let me = gate(C::GATE, cx).await?; call.handle(me, cx).await } @@ -85,12 +92,9 @@ async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { publish(cx.sh, std::mem::take(&mut cx.out)).await; let reply = reply.map_err(Error::from); - let framed = frame::encode(&reply); - if framed.len() - 4 > DOWN_MAX as usize { - return frame::encode(&Err::(Error::Server)); - } - - framed + frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| { + frame::encode(&Err::(Error::Server), DOWN_MAX).expect("small") + }) } pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { diff --git a/crates/server/src/call/social.rs b/crates/server/src/call/social.rs index 4420309..7bbdfea 100644 --- a/crates/server/src/call/social.rs +++ b/crates/server/src/call/social.rs @@ -11,7 +11,6 @@ use common::{ User, }, permission, - validate::validate_reason, }; use crate::{ @@ -197,7 +196,6 @@ impl Handle for ReportMessage { let message = message::read(&self.message_id, &cx.db).await?; let actor = actor_rank(&me, &message.community_id, &cx.db).await?; ensure(permission::can_read(actor) && me.id != message.user_id)?; - validate_reason(Some(&self.reason))?; ensure_with( !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?, Error::Taken, @@ -223,7 +221,6 @@ impl Handle for ReportUser { let me = me.user()?; user::read(&self.user_id, &cx.db).await?; ensure(me.id != self.user_id)?; - validate_reason(Some(&self.reason))?; ensure_with( !report::is_open(&me.id, &self.user_id, None, &cx.db).await?, Error::Taken, diff --git a/crates/server/src/call/user.rs b/crates/server/src/call/user.rs index e8be929..fcd725d 100644 --- a/crates/server/src/call/user.rs +++ b/crates/server/src/call/user.rs @@ -17,7 +17,7 @@ use crate::{ server_settings, user, }; -fn user_updated(user: &User, cx: &mut Cx<'_>) { +pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) { cx.emit( To::Related(user.id.clone()), Event::UserUpdated(user.clone()), @@ -60,8 +60,8 @@ impl Handle for UpdatePresence { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; user::update_presence(&me.id, self.presence, &cx.db).await?; - let broadcasts = presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?; - cx.out.extend(broadcasts); + cx.out + .extend(presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?); Ok(()) } diff --git a/crates/server/src/call/voice.rs b/crates/server/src/call/voice.rs index 712dc40..0b4b1f6 100644 --- a/crates/server/src/call/voice.rs +++ b/crates/server/src/call/voice.rs @@ -17,10 +17,10 @@ use crate::{ community, error::ServerError, message, - publish::{Broadcast, To}, + publish::To, request::{ allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event, - share_ended, voice_joined, voice_muted, voice_rooms, + share_ended, voice_joined, voice_muted, }, user, }; @@ -65,8 +65,7 @@ impl Handle for LeaveVoice { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { me.user()?; if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { - let broadcasts = departed(departure, &cx.db).await?; - cx.out.extend(broadcasts); + cx.out.extend(departed(departure, &cx.db).await?); } Ok(()) @@ -91,13 +90,11 @@ impl Handle for StartShare { source: self.source.clone(), }, }; - let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)]; - broadcasts.extend( - rooms - .start_share(cx.client.id, self.kind, self.source) - .ok_or(Error::NotFound)?, - ); - cx.out.extend(broadcasts); + let media = rooms + .start_share(cx.client.id, self.kind, self.source) + .ok_or(Error::NotFound)?; + cx.emit(To::Community(community_id), event); + cx.out.extend(media); Ok(()) } @@ -126,7 +123,7 @@ impl Handle for ListShares { impl Handle for WatchShare { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { me.user()?; - let broadcasts = cx + let media = cx .sh .services .rooms @@ -138,7 +135,7 @@ impl Handle for WatchShare { &self.decode, ) .ok_or(Error::NotFound)?; - cx.out.extend(broadcasts); + cx.out.extend(media); Ok(()) } @@ -147,12 +144,12 @@ impl Handle for WatchShare { impl Handle for UnwatchShare { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { me.user()?; - let broadcasts = cx - .sh - .services - .rooms - .unwatch(cx.client.id, &self.user_id, self.kind); - cx.out.extend(broadcasts); + cx.out.extend( + cx.sh + .services + .rooms + .unwatch(cx.client.id, &self.user_id, self.kind), + ); Ok(()) } @@ -202,7 +199,29 @@ impl Handle for ListVoiceParticipants { impl Handle for ListVoiceRooms { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - voice_rooms(&cx.sh.services.rooms, &cx.db).await + let mut rooms = Vec::new(); + for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() { + let community = community::label(&community_id, &cx.db).await?; + let mut users = Vec::new(); + let mut muted = Vec::new(); + for user_id in user_ids { + let user = user::read(&user_id, &cx.db).await?; + if user::voice_muted(&user_id, &cx.db).await? { + muted.push(user_id); + } + users.push(user); + } + rooms.push(VoiceRoom { + community_id, + community, + users, + muted, + ghosts, + }); + } + rooms.sort_by(|a, b| a.community.cmp(&b.community)); + + Ok(rooms) } } diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index bdef365..9e1095a 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -115,7 +115,7 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result, tx: mpsc::Sender, pub closed: AtomicBool, - pub watching: Mutex>, - pub ghost_logged: Mutex>, + watching: Mutex>, + ghost_logged: Mutex>, } impl Client { @@ -73,10 +73,6 @@ impl Client { pub fn watch(&self, community_id: Option<&str>) { *self.watching.lock().unwrap() = community_id.map(str::to_string); } - - fn watches(&self, community_id: &str) -> bool { - self.watching.lock().unwrap().as_deref() == Some(community_id) - } } pub enum Presence { @@ -127,22 +123,14 @@ impl Hub { Self::online_in(&self.0.lock().unwrap(), user_id) } - pub fn user_ids(&self) -> Vec { - let mut user_ids: Vec = self - .0 - .lock() - .unwrap() + pub fn online(&self) -> usize { + let clients = self.0.lock().unwrap(); + let ids: HashSet<&str> = clients .values() - .filter_map(|client| client.user_id().map(str::to_string)) + .filter_map(|client| client.user_id()) .collect(); - user_ids.sort(); - user_ids.dedup(); - user_ids - } - - pub fn online(&self) -> usize { - self.user_ids().len() + ids.len() } pub fn conns_of(&self, user_ids: &[String]) -> Vec { @@ -164,7 +152,7 @@ impl Hub { .lock() .unwrap() .values() - .filter(|client| client.watches(community_id)) + .filter(|client| client.watching.lock().unwrap().as_deref() == Some(community_id)) .map(|client| client.id) .collect() } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 1c8c6f7..3e6794e 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -214,7 +214,12 @@ async fn admit( let conn = database::connect(&shared.db).await?; let user = authentication::resume(&token, &conn).await?; stats::mark_active(&user.id, &conn).await?; - request::record_address(&user, Some(connection), &conn).await?; + user::set_last_ip( + &user.id, + &connection.remote_address().ip().to_string(), + &conn, + ) + .await?; if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await { warn!("device: {error}"); } diff --git a/crates/server/src/publish.rs b/crates/server/src/publish.rs index 4422ac6..fe8d0dc 100644 --- a/crates/server/src/publish.rs +++ b/crates/server/src/publish.rs @@ -54,11 +54,10 @@ pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { } }; let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. })); - let framed = frame::encode(&broadcast.down); - if framed.len() - 4 > DOWN_MAX as usize { - warn!("event too large: {} bytes", framed.len() - 4); + let Ok(framed) = frame::encode(&broadcast.down, DOWN_MAX) else { + warn!("event too large"); continue; - } + }; let bytes = Bytes::from(framed); shared.services.hub.send(&ids, &bytes, droppable); } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 044a334..cf2b636 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,7 +1,7 @@ use common::{ error::Error as CommonError, event::Event, - model::{AdminAction, CallLog, Message, Presence, Rank, User, VoiceRoom}, + model::{AdminAction, CallLog, Message, Presence, Rank, User}, permission, share::Kind, }; @@ -18,39 +18,6 @@ use crate::{ server_settings, user, user_community, }; -pub(crate) async fn voice_rooms( - occupied: &Rooms, - conn: &Connection, -) -> Result, ServerError> { - let mut rooms = Vec::new(); - for (community_id, user_ids, ghosts) in occupied.list() { - let community = community::label(&community_id, conn).await?; - let mut users = Vec::new(); - let mut muted = Vec::new(); - for user_id in user_ids { - let user = user::read(&user_id, conn).await?; - if user::voice_muted(&user_id, conn).await? { - muted.push(user.id.clone()); - } - users.push(user); - } - rooms.push(VoiceRoom { - community_id, - community, - users, - muted, - ghosts, - }); - } - rooms.sort_by(|a, b| a.community.cmp(&b.community)); - - Ok(rooms) -} - -fn ip_of(connection: Option<&quinn::Connection>) -> Option { - connection.map(|connection| connection.remote_address().ip().to_string()) -} - pub(crate) async fn limit_logins( rate_limit: &RateLimit, connection: Option<&quinn::Connection>, @@ -58,26 +25,11 @@ pub(crate) async fn limit_logins( ) -> Result<(), ServerError> { let limit = server_settings::read(conn).await?.logins_per_minute; - Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?) -} + let ip = connection + .map(|connection| connection.remote_address().ip().to_string()) + .unwrap_or_default(); -pub(crate) async fn record_address( - user: &User, - connection: Option<&quinn::Connection>, - conn: &Connection, -) -> Result<(), ServerError> { - if let Some(ip) = ip_of(connection) { - user::set_last_ip(&user.id, &ip, conn).await?; - } - - Ok(()) -} - -pub(crate) fn user_updated(user: &User) -> Vec { - vec![Broadcast::new( - To::Related(user.id.clone()), - Event::UserUpdated(user.clone()), - )] + Ok(rate_limit.allow(&ip, limit)?) } pub(crate) async fn effective_presence( @@ -133,20 +85,6 @@ pub(crate) async fn leave_room_voice( } } -pub(crate) async fn voice_unmuted( - rooms: &Rooms, - user_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let Some(community_id) = rooms.set_muted(user_id, false) else { - return Ok(Vec::new()); - }; - - Ok(vec![ - voice_muted(Some(community_id), user_id, false, conn).await?, - ]) -} - pub(crate) async fn voice_muted( community_id: Option, user_id: &str, @@ -168,22 +106,6 @@ pub(crate) async fn voice_muted( Ok(Broadcast::new(To::Users(user_ids), event)) } -pub(crate) async fn voice_silenced( - rooms: &Rooms, - community_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut broadcasts = Vec::new(); - for user_id in rooms.room_users(community_id) { - if permission::is_builder(user::read(&user_id, conn).await?.role) { - continue; - } - broadcasts.extend(leave_room_voice(rooms, community_id, &user_id, conn).await?); - } - - Ok(broadcasts) -} - pub(crate) async fn voice_closed( rooms: &Rooms, community_id: &str, @@ -271,13 +193,6 @@ pub(crate) async fn authenticated(client: &Client, conn: &Connection) -> Result< user::read(user_id, conn).await } -pub(crate) async fn builder(client: &Client, conn: &Connection) -> Result { - let user = authenticated(client, conn).await?; - ensure(permission::is_builder(user.role))?; - - Ok(user) -} - pub async fn actor_rank( me: &User, community_id: &str, @@ -385,9 +300,7 @@ pub(crate) async fn record_ghost_voice( &AdminAction::GhostVoice { seconds }, conn, ) - .await?; - - Ok(()) + .await } #[cfg(test)] diff --git a/crates/server/src/rooms.rs b/crates/server/src/rooms.rs index ef71ce5..8285f09 100644 --- a/crates/server/src/rooms.rs +++ b/crates/server/src/rooms.rs @@ -153,9 +153,7 @@ fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec { true }); - let mut broadcasts: Vec = layers_changed(sharer.conn, sharer.kind, sharing, before) - .into_iter() - .collect(); + let mut broadcasts = Vec::from_iter(layers_changed(sharer.conn, sharer.kind, sharing, before)); broadcasts.extend(keyframes); broadcasts.extend(stopped); @@ -335,16 +333,14 @@ impl Rooms { let mut transferred = false; let mut joined_at = Instant::now(); if let Some(previous) = inner.seat_conn(user_id) { - let same_room = inner.seat_of.get(&previous).map(String::as_str) == Some(community_id); - let kept_ghost = inner + let kept = inner .rooms .get(community_id) .and_then(|room| room.seats.get(&previous)) - .map(|seat| (seat.ghost, seat.joined_at)); - transferred = same_room && kept_ghost.is_some_and(|(was, _)| was == ghost); - if let (true, Some((_, at))) = (transferred, kept_ghost) { - joined_at = at; - } + .filter(|seat| seat.ghost == ghost) + .map(|seat| seat.joined_at); + transferred = kept.is_some(); + joined_at = kept.unwrap_or(joined_at); departure = inner.take(previous, previous != client.id, transferred); } let room = inner @@ -398,19 +394,19 @@ impl Rooms { pub fn close_room(&self, community_id: &str) -> Vec { let mut inner = self.0.lock().unwrap(); - let Some(room) = inner.rooms.get(community_id) else { - return Vec::new(); - }; - let ids: Vec = room.seats.keys().copied().collect(); - let mut departures: Vec = ids - .into_iter() - .filter_map(|id| inner.take(id, true, false)) - .collect(); - for departure in &mut departures { - departure.call_log = None; - } + let ids: Vec = inner + .rooms + .get(community_id) + .map(|room| room.seats.keys().copied().collect()) + .unwrap_or_default(); - departures + ids.into_iter() + .filter_map(|id| inner.take(id, true, false)) + .map(|departure| Departure { + call_log: None, + ..departure + }) + .collect() } pub fn decline(&self, community_id: &str) { @@ -425,17 +421,15 @@ impl Rooms { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; let (community_id, room) = inner.seat_mut(id)?; - let community_id = community_id.to_string(); room.seats.get_mut(&id)?.muted = muted; - Some(community_id) + Some(community_id.to_string()) } pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; let (community_id, room) = inner.seat_mut(id)?; - let community_id = community_id.to_string(); if room.seats.get(&id)?.ghost == ghost { return None; } @@ -446,22 +440,20 @@ impl Rooms { let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs()); seat.ghost = ghost; seat.joined_at = Instant::now(); - let shares: Vec = if ghost { - std::mem::take(&mut seat.shares).into_keys().collect() + let (shares, media) = if ghost { + ( + std::mem::take(&mut seat.shares).into_keys().collect(), + room.drop_viewer(user_id), + ) } else { - Vec::new() - }; - let media = if ghost { - room.drop_viewer(user_id) - } else { - Vec::new() + (Vec::new(), Vec::new()) }; let call_log = (ghost && !room.occupied()) .then(|| room.call_log()) .flatten(); Some(Departure { - community_id, + community_id: community_id.to_string(), user_id: user_id.to_string(), ghost_seconds, call_log, @@ -542,37 +534,28 @@ impl Rooms { pub fn start_share(&self, id: ConnId, kind: Kind, source: Source) -> Option> { let mut inner = self.0.lock().unwrap(); let (community_id, room) = inner.seat_mut(id)?; - let community_id = community_id.to_string(); let seat = room.seats.get_mut(&id)?; - let user_id = seat.user_id.clone(); let sharer = Sharer { conn: id, - user_id: &user_id, - community_id: &community_id, + user_id: &seat.user_id, + community_id, kind, }; - if let Some(sharing) = seat.shares.get_mut(&kind) { - sharing.source = source; - return Some(reroute(&sharer, sharing)); - } - seat.shares.insert( - kind, - Sharing { - source, - viewers: Vec::new(), - }, - ); + let sharing = seat.shares.entry(kind).or_insert_with(|| Sharing { + source: source.clone(), + viewers: Vec::new(), + }); + sharing.source = source; - Some(Vec::new()) + Some(reroute(&sharer, sharing)) } pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); let (community_id, room) = inner.seat_mut(id)?; - let community_id = community_id.to_string(); room.seats.get_mut(&id)?.shares.remove(&kind)?; - Some(community_id) + Some(community_id.to_string()) } pub fn watch( @@ -605,9 +588,7 @@ impl Rooms { decode: decode.to_vec(), forward, }); - let mut broadcasts: Vec = layers_changed(sharer_conn, kind, sharing, before) - .into_iter() - .collect(); + let mut broadcasts = Vec::from_iter(layers_changed(sharer_conn, kind, sharing, before)); broadcasts.push(Broadcast::media( sharer_conn, Media::Keyframe { kind, layer }, @@ -616,24 +597,14 @@ impl Rooms { Some(broadcasts) } - pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Vec { + pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); - let Some(sharer_conn) = inner.seat_conn(sharer_id) else { - return Vec::new(); - }; - let Some((_, room)) = inner.seat_mut(id) else { - return Vec::new(); - }; - let Some(viewer_id) = room.seats.get(&id).map(|seat| seat.user_id.clone()) else { - return Vec::new(); - }; + let sharer_conn = inner.seat_conn(sharer_id)?; + let (_, room) = inner.seat_mut(id)?; + let viewer_id = room.seats.get(&id)?.user_id.clone(); + let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; - room.seats - .get_mut(&sharer_conn) - .and_then(|seat| seat.shares.get_mut(&kind)) - .and_then(|sharing| remove_viewer(sharer_conn, kind, sharing, &viewer_id)) - .into_iter() - .collect() + remove_viewer(sharer_conn, kind, sharing, &viewer_id) } pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option { @@ -658,9 +629,6 @@ impl Rooms { } pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec { - if from.me.is_none() { - return Vec::new(); - } let mut inner = self.0.lock().unwrap(); let Some((_, room)) = inner.seat_mut(from.id) else { return Vec::new(); @@ -671,17 +639,19 @@ impl Rooms { match Packet::decode(packet) { Some(Packet::Voice { seq, .. }) => relay_voice(room, from.id, seq, packet), Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet), - _ => Vec::new(), + _ => {} } + + Vec::new() } } -fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) -> Vec { +fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) { let Some(sender) = room.seats.get(&id) else { - return Vec::new(); + return; }; if sender.muted { - return Vec::new(); + return; } let mut echo = Vec::new(); Packet::Voice { seq, opus: &[] }.encode(&mut echo); @@ -692,23 +662,19 @@ fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) -> Vec Vec { +fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { let Some(seat) = room.seats.get(&id) else { - return Vec::new(); + return; }; let Some(sharing) = seat.shares.get(&Kind::Screen) else { - return Vec::new(); + return; }; let bytes = relayed(&seat.uuid, packet); for viewer in &sharing.viewers { datagram::send(&viewer.connection, bytes.clone()); } - - Vec::new() } fn relay_video( @@ -736,8 +702,5 @@ fn relay_video( } } - before - .and_then(|before| layers_changed(id, kind, sharing, before)) - .into_iter() - .collect() + Vec::from_iter(before.and_then(|before| layers_changed(id, kind, sharing, before))) }