forge
Explore
Log in

Don't you dare go Hollow

One transport, one framing and a split error model

Browse files at this commit

e2d1bd5c083a732086a0070e23d86d362a42fad8Ahmet Kaan GümüşParent: d46d713
  • refactor
    • one transport, one framing and a split error model
Show full message
♻️ refactor: one transport, one framing and a split error model

Split the client network module into net/{link,events,datagram,voice,share}.
Both sides share one QUIC transport config, an ALPN protocol version and
typed close codes; the client resolves hosts per family with backoff.
Every stream uses one length prefixed bitcode frame with a reset on drop
send guard, and uploads, downloads and backups go through Open{Call,
Upload, Fetch}. Wire errors are separate from server internal and client
link errors, and the GUI matches enums instead of strings.

67 changed files +3430 -2981

crates/client/Cargo.tomlmodified+3 -1
@@ -9,7 +9,7 @@ pixel.workspace = true
99 spectrum.workspace = true
1010 reed-solomon-simd = "3.1.0"
1111 tokio.workspace = true
12-quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
12+quinn = { workspace = true, features = ["rustls-ring"] }
1313
1414 gpui-kit = { version = "0.11.0", features = ["syntect"] }
1515 ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" }
@@ -31,6 +31,8 @@ jiff = "1.0.2"
3131 dirs = "7.0.0"
3232 image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] }
3333 rtrb = "0.4.1"
34+gethostname = "1.1.0"
35+rustls-platform-verifier = "0.7.1"
3436
3537 [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies]
3638 nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] }
crates/client/src/avatar.rsmodified+11 -8
@@ -1,12 +1,13 @@
1+use crate::net::Fail;
12 use common::{
23 constant::AVATAR_SIZE,
3- error::{Error, Field, InvalidInput},
4+ error::{Error, Field, Problem},
45 };
56 use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
67
78 const QUALITIES: [u8; 3] = [85, 60, 40];
89
9-pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {
10+pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Fail> {
1011 let image = image::load_from_memory(bytes).map_err(image_error)?;
1112 let square = center_square(image)
1213 .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3)
@@ -22,11 +23,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {
2223
2324 Err(Error::Invalid {
2425 field: Field::Avatar,
25- input: InvalidInput::TooLarge {
26- maximum,
26+ problem: Problem::Length {
27+ min: 0,
28+ max: maximum,
2729 actual: encoded.len() as u64,
2830 },
29- })
31+ }
32+ .into())
3033 }
3134
3235 fn center_square(image: DynamicImage) -> DynamicImage {
@@ -37,7 +40,7 @@ fn center_square(image: DynamicImage) -> DynamicImage {
3740 image.crop_imm(x, y, side, side)
3841 }
3942
40-fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> {
43+fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Fail> {
4144 let mut bytes = Vec::new();
4245 JpegEncoder::new_with_quality(&mut bytes, quality)
4346 .encode_image(image)
@@ -46,8 +49,8 @@ fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> {
4649 Ok(bytes)
4750 }
4851
49-fn image_error(error: image::ImageError) -> Error {
50- Error::Decode(error.to_string())
52+fn image_error(error: image::ImageError) -> Fail {
53+ Fail::Io(error.to_string())
5154 }
5255
5356 const HUE_BINS: usize = 24;
crates/client/src/gui.rsmodified+4 -18
@@ -37,7 +37,7 @@ use tokio::sync::mpsc;
3737 use crate::{
3838 accounts::{self, Accounts},
3939 mutes,
40- network::{NetworkEvent, NetworkHandle},
40+ net::{Fail, LinkError, NetworkEvent, NetworkHandle},
4141 settings::{Look, Scale, Settings, ThemeChoice},
4242 };
4343
@@ -540,32 +540,18 @@ impl Connection {
540540 matches!(self, Self::Connected)
541541 }
542542
543- fn lost(&mut self, error: &Error) {
543+ fn lost(&mut self, error: &LinkError) {
544544 let attempts = match self {
545545 Self::Lost { attempts, .. } => *attempts + 1,
546546 _ => 1,
547547 };
548548 *self = Self::Lost {
549- error: reason(error),
549+ error: error.to_string(),
550550 attempts,
551551 };
552552 }
553553 }
554554
555-fn reason(error: &Error) -> String {
556- let text = error.to_string();
557- let lower = text.to_lowercase();
558- if lower.contains("timed out") || lower.contains("unreachable") {
559- "Server unreachable".into()
560- } else if lower.contains("certificate") || lower.contains("tls") {
561- "Certificate error".into()
562- } else if lower.contains("refused") {
563- "Connection refused".into()
564- } else {
565- text
566- }
567-}
568-
569555 fn connection_notice(connection: &Connection, palette: Palette) -> Option<Div> {
570556 let (label, color) = match connection {
571557 Connection::Connecting => ("Connecting…".to_string(), palette.muted),
@@ -755,7 +741,7 @@ impl Yumush {
755741 let result = network.resume(&account.token).await;
756742 let _ = this.update_in(cx, |yumush, window, cx| match result {
757743 Ok((user, token)) => yumush.enter_session(user, token, window, cx),
758- Err(error @ (Error::NotFound | Error::Unauthenticated)) => {
744+ Err(error @ Fail::Server(Error::NotFound | Error::Unauthenticated)) => {
759745 yumush.accounts.forget(&account.user_id);
760746 window.push_notification(Notification::error(error.to_string()), cx);
761747 cx.notify();
crates/client/src/gui/builder.rsmodified+1 -1
@@ -32,7 +32,7 @@ use super::{
3232 Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header,
3333 text, widget::search_text,
3434 };
35-use crate::network::NetworkHandle;
35+use crate::net::NetworkHandle;
3636
3737 pub(super) fn save_directory() -> PathBuf {
3838 dirs::download_dir().unwrap_or_else(std::env::temp_dir)
crates/client/src/gui/builder/overview.rsmodified+3 -2
@@ -1,4 +1,5 @@
1-use common::{error::Error, model::DayStat, time::DAY_MILLIS};
1+use crate::net::Fail;
2+use common::{model::DayStat, time::DAY_MILLIS};
23 use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px};
34 use jiff::Timestamp;
45
@@ -107,7 +108,7 @@ impl Yumush {
107108 window,
108109 cx,
109110 |network| async move {
110- Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?))
111+ Ok::<_, Fail>((network.overview().await?, network.daily_stats(30).await?))
111112 },
112113 |yumush, (overview, stats), cx| {
113114 yumush.chat.builder_overview = Some(overview);
crates/client/src/gui/builder/reports.rsmodified+3 -6
@@ -1,9 +1,6 @@
11 use std::future::Future;
22
3-use common::{
4- error::Error,
5- model::{BanScope, Report, ReportStatus},
6-};
3+use common::model::{BanScope, Report, ReportStatus};
74 use gpui_kit::{
85 AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window,
96 div, px,
@@ -20,7 +17,7 @@ use crate::{
2017 settings_page::{segment, segment_track},
2118 text,
2219 },
23- network::NetworkHandle,
20+ net::{Fail, NetworkHandle},
2421 };
2522
2623 const REPORT_FILTERS: [Option<ReportStatus>; 4] = [
@@ -91,7 +88,7 @@ impl Yumush {
9188 cx: &mut Context<Self>,
9289 action: impl FnOnce(NetworkHandle) -> Fut + 'static,
9390 ) where
94- Fut: Future<Output = Result<(), Error>> + 'static,
91+ Fut: Future<Output = Result<(), Fail>> + 'static,
9592 {
9693 let network = self.network.clone();
9794
crates/client/src/gui/builder/users.rsmodified+2 -3
@@ -1,7 +1,6 @@
11 use std::future::Future;
22
33 use common::{
4- error::Error,
54 model::{Account, BanScope, Role, SessionInfo, User},
65 permission,
76 time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms},
@@ -26,7 +25,7 @@ use crate::{
2625 text,
2726 widget::{field, search_text},
2827 },
29- network::NetworkHandle,
28+ net::{Fail, NetworkHandle},
3029 };
3130
3231 const MINUTES_PER_HOUR: u64 = HOUR_MILLIS / MINUTE_MILLIS;
@@ -143,7 +142,7 @@ impl Yumush {
143142 cx: &mut Context<Self>,
144143 action: impl FnOnce(NetworkHandle) -> Fut + 'static,
145144 ) where
146- Fut: Future<Output = Result<(), Error>> + 'static,
145+ Fut: Future<Output = Result<(), Fail>> + 'static,
147146 {
148147 let network = self.network.clone();
149148
crates/client/src/gui/builder/voice.rsmodified+3 -6
@@ -1,9 +1,6 @@
11 use std::future::Future;
22
3-use common::{
4- error::Error,
5- model::{User, VoiceRoom},
6-};
3+use common::model::{User, VoiceRoom};
74 use gpui_kit::{
85 AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,
96 div, px,
@@ -12,7 +9,7 @@ use gpui_kit::{
129 use super::ui::{card, card_header, icon_button, list_card, pill, rows_body};
1310 use crate::{
1411 gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text},
15- network::NetworkHandle,
12+ net::{Fail, NetworkHandle},
1613 };
1714
1815 impl Yumush {
@@ -34,7 +31,7 @@ impl Yumush {
3431 cx: &mut Context<Self>,
3532 action: impl FnOnce(NetworkHandle) -> Fut + 'static,
3633 ) where
37- Fut: Future<Output = Result<(), Error>> + 'static,
34+ Fut: Future<Output = Result<(), Fail>> + 'static,
3835 {
3936 let network = self.network.clone();
4037
crates/client/src/gui/chat.rsmodified+1 -1
@@ -28,7 +28,7 @@ use crate::gui::{
2828 voice_note::{self, VoiceNote},
2929 widget::{icon_button, ok_or_notify, search_text, spawn_done},
3030 };
31-use crate::network::Levels;
31+use crate::net::Levels;
3232 use crate::settings::VOLUME;
3333 use crate::share::session::ShareSample;
3434 use crate::voice::VoiceSample;
crates/client/src/gui/community_settings.rsmodified+10 -3
@@ -1,7 +1,7 @@
11 use std::{collections::HashMap, sync::Arc};
22
3+use crate::net::Fail;
34 use common::{
4- error::Error,
55 model::{Ban, Community, LogAction, LogEntry, User},
66 permission,
77 validate::validate_community_name,
@@ -56,7 +56,7 @@ const LOG_SORTS: [(LogSort, &str); 2] = [(LogSort::Newest, "Newest"), (LogSort::
5656 fn apply_community(
5757 this: &WeakEntity<Yumush>,
5858 cx: &mut AsyncWindowContext,
59- result: Result<Community, Error>,
59+ result: Result<Community, Fail>,
6060 ) {
6161 match result {
6262 Ok(community) => {
@@ -225,7 +225,14 @@ impl Yumush {
225225 let Some(community_id) = self.chat.selected_community_id.clone() else {
226226 return;
227227 };
228- let name = self.chat.community_name_input.read(cx).text().to_string().trim().to_string();
228+ let name = self
229+ .chat
230+ .community_name_input
231+ .read(cx)
232+ .text()
233+ .to_string()
234+ .trim()
235+ .to_string();
229236
230237 if let Err(error) = validate_community_name(&name) {
231238 window.push_notification(Notification::error(error.to_string()), cx);
crates/client/src/gui/composer.rsmodified+5 -16
@@ -2,6 +2,7 @@ use super::text;
22 use super::widget::{compact_field, icon_button, panel, spawn_done};
33 use std::time::{Duration, Instant};
44
5+use crate::net::Fail;
56 use common::{
67 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS},
78 error::Error,
@@ -275,19 +276,12 @@ impl Yumush {
275276 .await
276277 {
277278 Ok(_) => {}
278- Err(Error::RateLimited {
279+ Err(Fail::Server(Error::RateLimited {
279280 retry_after_seconds,
280- }) => {
281+ })) => {
281282 let _ = this.update_in(cx, |yumush, window, cx| {
282- yumush.slow_down(
283- retry_after_seconds,
284- &restore,
285- &community_id,
286- body,
287- pending,
288- window,
289- cx,
290- )
283+ yumush.restore_message(&restore, &community_id, body, pending, window, cx);
284+ yumush.slow_down(retry_after_seconds, window, cx)
291285 });
292286 }
293287 Err(error) => {
@@ -330,14 +324,9 @@ impl Yumush {
330324 fn slow_down(
331325 &mut self,
332326 seconds: u64,
333- input: &Entity<InputState>,
334- community_id: &str,
335- body: String,
336- pending: Vec<Attachment>,
337327 window: &mut Window,
338328 cx: &mut Context<Self>,
339329 ) {
340- self.restore_message(input, community_id, body, pending, window, cx);
341330 self.chat.slowed_until = Some(now_ms() + seconds * 1000);
342331
343332 cx.spawn_in(window, async move |this, cx| {
crates/client/src/gui/media_view.rsmodified+5 -5
@@ -29,7 +29,7 @@ use super::{
2929 use crate::{
3030 embed::{self, Embed, EmbedKind},
3131 media::{Player, voice_note as note},
32- network::NetworkHandle,
32+ net::{Fail, NetworkHandle},
3333 };
3434
3535 const FRAME_TICK: Duration = Duration::from_millis(16);
@@ -152,7 +152,7 @@ pub(super) async fn upload_file(
152152 path: PathBuf,
153153 maximum: Option<u64>,
154154 cx: &mut AsyncWindowContext,
155-) -> Result<Attachment, common::error::Error> {
155+) -> Result<Attachment, Fail> {
156156 let _ = this.update(cx, |yumush, cx| {
157157 yumush.chat.media.uploading += 1;
158158 cx.notify();
@@ -322,11 +322,11 @@ impl Yumush {
322322 &self,
323323 attachment: &Attachment,
324324 cx: &mut Context<Self>,
325- ) -> Task<Result<PathBuf, common::error::Error>> {
325+ ) -> Task<Result<PathBuf, Fail>> {
326326 let network = self.network.clone();
327327 let attachment = attachment.clone();
328328 cx.spawn(async move |_, cx| {
329- let path = cache_path(&attachment).ok_or(common::error::Error::Server)?;
329+ let path = cache_path(&attachment).ok_or(Fail::Protocol)?;
330330 if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) {
331331 return Ok(path);
332332 }
@@ -337,7 +337,7 @@ impl Yumush {
337337 async move { std::fs::write(&path, bytes) }
338338 })
339339 .await
340- .map_err(|_| common::error::Error::Server)?;
340+ .map_err(|_| Fail::Protocol)?;
341341 Ok(path)
342342 })
343343 }
crates/client/src/gui/settings_page.rsmodified+4 -3
@@ -1,6 +1,7 @@
11 use std::future::Future;
22
3-use common::{error::Error, model::User};
3+use crate::net::Fail;
4+use common::model::User;
45 use gpui_kit::{
56 AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla,
67 InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful,
@@ -255,7 +256,7 @@ impl Yumush {
255256 }
256257 }
257258
258-fn apply_user(this: &WeakEntity<Yumush>, cx: &mut AsyncWindowContext, result: Result<User, Error>) {
259+fn apply_user(this: &WeakEntity<Yumush>, cx: &mut AsyncWindowContext, result: Result<User, Fail>) {
259260 match result {
260261 Ok(user) => {
261262 let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
@@ -267,7 +268,7 @@ fn apply_user(this: &WeakEntity<Yumush>, cx: &mut AsyncWindowContext, result: Re
267268 pub(super) fn picked_avatar(
268269 cx: &App,
269270 maximum: u64,
270-) -> impl Future<Output = Option<Result<Vec<u8>, Error>>> + 'static {
271+) -> impl Future<Output = Option<Result<Vec<u8>, Fail>>> + 'static {
271272 let picked = cx.prompt_for_paths(PathPromptOptions {
272273 files: true,
273274 directories: false,
crates/client/src/gui/voice_note.rsmodified+5 -1
@@ -153,7 +153,11 @@ pub fn recording_row(
153153 .text_size(text(13.))
154154 .text_color(palette.text)
155155 .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.)))
156- .child(time_text(started.elapsed().min(Duration::from_secs(MAX_SECONDS as u64))))
156+ .child(time_text(
157+ started
158+ .elapsed()
159+ .min(Duration::from_secs(MAX_SECONDS as u64)),
160+ ))
157161 .child(bars(levels, 1., palette, |_, _, _| {})),
158162 )
159163 .child(
crates/client/src/gui/wave.rsmodified+1 -1
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
22
33 use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px};
44
5-use crate::network::Levels;
5+use crate::net::Levels;
66
77 const DECAY: f32 = 0.82;
88 const GONE: f32 = 0.02;
crates/client/src/lib.rsmodified+1 -1
@@ -9,7 +9,7 @@ pub mod embed;
99 pub mod gui;
1010 pub mod media;
1111 pub mod mutes;
12-pub mod network;
12+pub mod net;
1313 pub mod settings;
1414 pub mod share;
1515 pub mod tray;
crates/client/src/main.rsmodified+2 -2
@@ -3,7 +3,7 @@
33 use client::{
44 ClientConfig, NAME,
55 gui::{self, Yumush},
6- network, settings,
6+ net, settings,
77 tray::{self, TrayAction, TrayState},
88 };
99 use gpui_kit::{
@@ -25,7 +25,7 @@ fn main() {
2525 .init();
2626
2727 let settings = settings::load();
28- let (network_handle, network_event_receiver) = network::start(ClientConfig::default());
28+ let (network_handle, network_event_receiver) = net::start(ClientConfig::default());
2929 let (mut tray_receiver, tray_handle) = tray::start();
3030
3131 application()
crates/client/src/net/datagram.rsadded+34 -0
@@ -0,0 +1,34 @@
1+use common::{
2+ datagram::{Datagram, decode_relay},
3+ share::Kind,
4+};
5+
6+use super::*;
7+
8+pub(super) async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) {
9+ let loss: u64 = std::env::var("YUMUSH_TEST_LOSS")
10+ .ok()
11+ .and_then(|value| value.parse().ok())
12+ .unwrap_or(0);
13+ let mut received: u64 = 0;
14+ while let Ok(datagram) = connection.read_datagram().await {
15+ if let Some(voice) = shared.voice.lock().unwrap().as_ref() {
16+ voice.receive(&datagram);
17+ }
18+ if let Some((user_id, packet)) = decode_relay(&datagram) {
19+ if let Datagram::Video(_) = packet {
20+ received += 1;
21+ if received * 37 % 100 < loss {
22+ continue;
23+ }
24+ }
25+ let kind = match &packet {
26+ Datagram::Video(fragment) => fragment.kind,
27+ _ => Kind::Screen,
28+ };
29+ if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) {
30+ watching.receive(packet);
31+ }
32+ }
33+ }
34+}
crates/client/src/net/events.rsadded+28 -0
@@ -0,0 +1,28 @@
1+use common::{
2+ event::Event,
3+ frame::{self, DOWN_MAX},
4+};
5+use tokio::sync::mpsc;
6+
7+use super::*;
8+
9+pub(super) async fn event_receive_loop(
10+ connection: quinn::Connection,
11+ event_sender: mpsc::Sender<NetworkEvent>,
12+ share: SharedShare,
13+) {
14+ let Ok(mut receive_stream) = connection.accept_uni().await else {
15+ return;
16+ };
17+
18+ while let Ok(event) = frame::read::<Event>(&mut receive_stream, DOWN_MAX).await {
19+ share.lock().unwrap().event(&event);
20+ if event_sender
21+ .send(NetworkEvent::Pushed(Box::new(event)))
22+ .await
23+ .is_err()
24+ {
25+ return;
26+ }
27+ }
28+}
crates/client/src/net/fail.rsadded+151 -0
@@ -0,0 +1,151 @@
1+use common::{error::Error, frame::FrameError, transport::Close};
2+
3+const NO_APPLICATION_PROTOCOL: u64 = 0x100 + 120;
4+const CRYPTO_ERRORS: std::ops::Range<u64> = 0x100..0x200;
5+
6+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7+pub enum LinkError {
8+ Unreachable,
9+ Tls,
10+ Timeout,
11+ Outdated,
12+ Reset,
13+ Closed(Close),
14+}
15+
16+impl std::fmt::Display for LinkError {
17+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18+ match self {
19+ Self::Unreachable | Self::Timeout => write!(f, "Server unreachable"),
20+ Self::Tls => write!(f, "Certificate error"),
21+ Self::Outdated => write!(f, "Client is outdated"),
22+ Self::Reset => write!(f, "Connection lost"),
23+ Self::Closed(close) => write!(f, "{}", close.reason()),
24+ }
25+ }
26+}
27+
28+impl LinkError {
29+ fn by_code(code: u64) -> Self {
30+ match code {
31+ NO_APPLICATION_PROTOCOL => Self::Outdated,
32+ code if CRYPTO_ERRORS.contains(&code) => Self::Tls,
33+ _ => Self::Reset,
34+ }
35+ }
36+}
37+
38+impl From<quinn::ConnectionError> for LinkError {
39+ fn from(error: quinn::ConnectionError) -> Self {
40+ match error {
41+ quinn::ConnectionError::TimedOut => Self::Timeout,
42+ quinn::ConnectionError::ConnectionClosed(close) => {
43+ Self::by_code(u64::from(close.error_code))
44+ }
45+ quinn::ConnectionError::TransportError(error) => Self::by_code(u64::from(error.code)),
46+ quinn::ConnectionError::ApplicationClosed(close) => {
47+ Close::of(close.error_code).map_or(Self::Reset, Self::Closed)
48+ }
49+ quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal),
50+ quinn::ConnectionError::VersionMismatch => Self::Outdated,
51+ quinn::ConnectionError::Reset | quinn::ConnectionError::CidsExhausted => Self::Reset,
52+ }
53+ }
54+}
55+
56+#[derive(Debug, Clone)]
57+pub enum Fail {
58+ Server(Error),
59+ Offline,
60+ Link(LinkError),
61+ Protocol,
62+ Io(String),
63+}
64+
65+impl std::fmt::Display for Fail {
66+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67+ match self {
68+ Self::Server(error) => write!(f, "{error}"),
69+ Self::Offline => write!(f, "Offline"),
70+ Self::Link(error) => write!(f, "{error}"),
71+ Self::Protocol => write!(f, "Protocol error"),
72+ Self::Io(message) => write!(f, "{message}"),
73+ }
74+ }
75+}
76+
77+impl From<Error> for Fail {
78+ fn from(error: Error) -> Self {
79+ Self::Server(error)
80+ }
81+}
82+
83+impl From<LinkError> for Fail {
84+ fn from(error: LinkError) -> Self {
85+ Self::Link(error)
86+ }
87+}
88+
89+impl From<quinn::ConnectionError> for Fail {
90+ fn from(error: quinn::ConnectionError) -> Self {
91+ Self::Link(error.into())
92+ }
93+}
94+
95+impl From<quinn::WriteError> for Fail {
96+ fn from(error: quinn::WriteError) -> Self {
97+ match error {
98+ quinn::WriteError::ConnectionLost(error) => error.into(),
99+ _ => Self::Link(LinkError::Reset),
100+ }
101+ }
102+}
103+
104+impl From<quinn::ReadError> for Fail {
105+ fn from(error: quinn::ReadError) -> Self {
106+ match error {
107+ quinn::ReadError::ConnectionLost(error) => error.into(),
108+ _ => Self::Link(LinkError::Reset),
109+ }
110+ }
111+}
112+
113+impl From<quinn::ClosedStream> for Fail {
114+ fn from(_: quinn::ClosedStream) -> Self {
115+ Self::Link(LinkError::Reset)
116+ }
117+}
118+
119+impl From<quinn::ConnectError> for Fail {
120+ fn from(_: quinn::ConnectError) -> Self {
121+ Self::Link(LinkError::Unreachable)
122+ }
123+}
124+
125+impl From<FrameError> for Fail {
126+ fn from(error: FrameError) -> Self {
127+ match error {
128+ FrameError::Connection(error) => error.into(),
129+ FrameError::Write(error) => error.into(),
130+ FrameError::Read(quinn::ReadExactError::ReadError(error)) => error.into(),
131+ FrameError::Read(quinn::ReadExactError::FinishedEarly(_)) => Self::Protocol,
132+ FrameError::Closed(error) => error.into(),
133+ FrameError::TooLarge { .. } | FrameError::Decode(_) => Self::Protocol,
134+ }
135+ }
136+}
137+
138+impl From<std::io::Error> for Fail {
139+ fn from(error: std::io::Error) -> Self {
140+ Self::Io(error.to_string())
141+ }
142+}
143+
144+impl From<quinn::ReadExactError> for Fail {
145+ fn from(error: quinn::ReadExactError) -> Self {
146+ match error {
147+ quinn::ReadExactError::ReadError(error) => error.into(),
148+ quinn::ReadExactError::FinishedEarly(_) => Self::Protocol,
149+ }
150+ }
151+}
crates/client/src/net/fetch.rsadded+68 -0
@@ -0,0 +1,68 @@
1+use std::{collections::HashMap, sync::Mutex};
2+
3+use common::open::Blob;
4+use tokio::sync::{Semaphore, SemaphorePermit, oneshot};
5+
6+use super::{Fail, link};
7+
8+const PARALLEL_FETCHES: usize = 6;
9+
10+type Waiter = oneshot::Sender<Result<std::sync::Arc<Vec<u8>>, Fail>>;
11+
12+pub(super) struct Fetches {
13+ permits: Semaphore,
14+ waiting: Mutex<HashMap<Blob, Vec<Waiter>>>,
15+}
16+
17+impl Default for Fetches {
18+ fn default() -> Self {
19+ Self {
20+ permits: Semaphore::new(PARALLEL_FETCHES),
21+ waiting: Mutex::default(),
22+ }
23+ }
24+}
25+
26+impl Fetches {
27+ pub(super) async fn permit(&self) -> SemaphorePermit<'_> {
28+ self.permits
29+ .acquire()
30+ .await
31+ .expect("semaphore never closes")
32+ }
33+
34+ pub(super) async fn memory(
35+ &self,
36+ connection: &quinn::Connection,
37+ blob: Blob,
38+ ) -> Result<Vec<u8>, Fail> {
39+ let (sender, receiver) = oneshot::channel();
40+ let leader = {
41+ let mut waiting = self.waiting.lock().unwrap();
42+ let senders = waiting.entry(blob.clone()).or_default();
43+ senders.push(sender);
44+ senders.len() == 1
45+ };
46+
47+ if leader {
48+ let result = {
49+ let _permit = self.permit().await;
50+ link::download(connection, &blob).await
51+ }
52+ .map(std::sync::Arc::new);
53+ let senders = self
54+ .waiting
55+ .lock()
56+ .unwrap()
57+ .remove(&blob)
58+ .unwrap_or_default();
59+ for sender in senders {
60+ let _ = sender.send(result.clone());
61+ }
62+ }
63+
64+ let bytes = receiver.await.map_err(|_| Fail::Offline)??;
65+
66+ Ok((*bytes).clone())
67+ }
68+}
crates/client/src/net/link.rsadded+603 -0
@@ -0,0 +1,603 @@
1+use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};
2+
3+use common::{
4+ constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},
5+ error::Error,
6+ frame::{self, DOWN_MAX, Sending, UP_MAX},
7+ model::Attachment,
8+ open::{Blob, Open, Upload},
9+ request::Request,
10+ response::Response,
11+ transport::{Close, alpn, transport},
12+ validate::{validate_attachment_name, validate_attachment_size},
13+};
14+use quinn::Endpoint;
15+#[cfg(debug_assertions)]
16+use quinn::{
17+ crypto::rustls::QuicClientConfig,
18+ rustls::{
19+ self, DigitallySignedStruct, SignatureScheme,
20+ client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
21+ pki_types::{CertificateDer, ServerName, UnixTime},
22+ },
23+};
24+#[cfg(debug_assertions)]
25+use rustls_platform_verifier as _;
26+use tokio::sync::{mpsc, oneshot};
27+use tracing::{info, warn};
28+
29+use crate::{
30+ ClientConfig,
31+ voice::{self},
32+};
33+
34+use super::{
35+ datagram::datagram_receive_loop,
36+ events::event_receive_loop,
37+ share::{start_share, update_share},
38+ *,
39+};
40+
41+const CHANNEL_SIZE: usize = 32;
42+const BACKOFF_BASE_MILLIS: u64 = 250;
43+const BACKOFF_CAP_MILLIS: u64 = 8_000;
44+
45+const SHARE_TICK: Duration = Duration::from_secs(1);
46+
47+pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {
48+ let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);
49+ let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);
50+ let shared = Shared::default();
51+
52+ std::thread::Builder::new()
53+ .name("network".to_string())
54+ .spawn({
55+ let shared = shared.clone();
56+ move || {
57+ tokio::runtime::Builder::new_current_thread()
58+ .enable_all()
59+ .build()
60+ .expect("network runtime")
61+ .block_on(actor(client_config, command_receiver, event_sender, shared));
62+ }
63+ })
64+ .expect("network thread");
65+
66+ (
67+ NetworkHandle {
68+ command_sender,
69+ shared,
70+ },
71+ event_receiver,
72+ )
73+}
74+
75+#[derive(Default)]
76+struct Endpoints {
77+ v6: Option<Endpoint>,
78+ v4: Option<Endpoint>,
79+}
80+
81+impl Endpoints {
82+ fn get(&mut self, address: SocketAddr) -> Result<Endpoint, LinkError> {
83+ let (slot, bind) = match address {
84+ SocketAddr::V6(_) => (&mut self.v6, "[::]:0"),
85+ SocketAddr::V4(_) => (&mut self.v4, "0.0.0.0:0"),
86+ };
87+ if let Some(endpoint) = slot {
88+ return Ok(endpoint.clone());
89+ }
90+
91+ let bind: SocketAddr = bind.parse().map_err(|_| LinkError::Unreachable)?;
92+ let mut endpoint = Endpoint::client(bind).map_err(|_| LinkError::Unreachable)?;
93+ endpoint.set_default_client_config(config()?);
94+ *slot = Some(endpoint.clone());
95+
96+ Ok(endpoint)
97+ }
98+
99+ fn forget(&mut self, address: SocketAddr) {
100+ match address {
101+ SocketAddr::V6(_) => self.v6 = None,
102+ SocketAddr::V4(_) => self.v4 = None,
103+ }
104+ }
105+}
106+
107+fn backoff(attempt: u32) -> Duration {
108+ let base = (BACKOFF_BASE_MILLIS << attempt.min(10)).min(BACKOFF_CAP_MILLIS);
109+ let nanos = std::time::SystemTime::now()
110+ .duration_since(std::time::UNIX_EPOCH)
111+ .map_or(0, |elapsed| elapsed.subsec_nanos() as u64);
112+ let jitter = base * (80 + nanos % 41) / 100;
113+
114+ Duration::from_millis(jitter)
115+}
116+
117+async fn connect(
118+ client_config: &ClientConfig,
119+ endpoints: &mut Endpoints,
120+) -> Result<quinn::Connection, LinkError> {
121+ let mut addresses: Vec<SocketAddr> =
122+ tokio::net::lookup_host(client_config.server_address.as_str())
123+ .await
124+ .map_err(|_| LinkError::Unreachable)?
125+ .collect();
126+ addresses.sort_by_key(|address| address.is_ipv4());
127+
128+ let mut last = LinkError::Unreachable;
129+ for address in addresses {
130+ let endpoint = match endpoints.get(address) {
131+ Ok(endpoint) => endpoint,
132+ Err(error) => {
133+ last = error;
134+ continue;
135+ }
136+ };
137+ let connecting = match endpoint.connect(address, &client_config.server_name) {
138+ Ok(connecting) => connecting,
139+ Err(_) => {
140+ endpoints.forget(address);
141+ last = LinkError::Unreachable;
142+ continue;
143+ }
144+ };
145+ match connecting.await {
146+ Ok(connection) => return Ok(connection),
147+ Err(error) => {
148+ endpoints.forget(address);
149+ last = error.into();
150+ if last == LinkError::Outdated {
151+ return Err(last);
152+ }
153+ }
154+ }
155+ }
156+
157+ Err(last)
158+}
159+
160+fn tls_error(_: impl std::fmt::Display) -> LinkError {
161+ LinkError::Tls
162+}
163+
164+#[cfg(debug_assertions)]
165+#[derive(Debug)]
166+struct AcceptAnyCertificate {
167+ provider: Arc<rustls::crypto::CryptoProvider>,
168+}
169+
170+#[cfg(debug_assertions)]
171+impl ServerCertVerifier for AcceptAnyCertificate {
172+ fn verify_server_cert(
173+ &self,
174+ _end_entity: &CertificateDer<'_>,
175+ _intermediates: &[CertificateDer<'_>],
176+ _server_name: &ServerName<'_>,
177+ _ocsp_response: &[u8],
178+ _now: UnixTime,
179+ ) -> Result<ServerCertVerified, rustls::Error> {
180+ Ok(ServerCertVerified::assertion())
181+ }
182+
183+ fn verify_tls12_signature(
184+ &self,
185+ message: &[u8],
186+ cert: &CertificateDer<'_>,
187+ dss: &DigitallySignedStruct,
188+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
189+ rustls::crypto::verify_tls12_signature(
190+ message,
191+ cert,
192+ dss,
193+ &self.provider.signature_verification_algorithms,
194+ )
195+ }
196+
197+ fn verify_tls13_signature(
198+ &self,
199+ message: &[u8],
200+ cert: &CertificateDer<'_>,
201+ dss: &DigitallySignedStruct,
202+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
203+ rustls::crypto::verify_tls13_signature(
204+ message,
205+ cert,
206+ dss,
207+ &self.provider.signature_verification_algorithms,
208+ )
209+ }
210+
211+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
212+ self.provider
213+ .signature_verification_algorithms
214+ .supported_schemes()
215+ }
216+}
217+
218+#[cfg(debug_assertions)]
219+fn accept_any_client_config() -> Result<quinn::ClientConfig, LinkError> {
220+ let provider = Arc::new(rustls::crypto::ring::default_provider());
221+ let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone())
222+ .with_protocol_versions(&[&rustls::version::TLS13])
223+ .map_err(tls_error)?
224+ .dangerous()
225+ .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider }))
226+ .with_no_client_auth();
227+ tls.alpn_protocols = vec![alpn()];
228+
229+ let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?;
230+
231+ Ok(quinn::ClientConfig::new(Arc::new(crypto)))
232+}
233+
234+#[cfg(not(debug_assertions))]
235+fn platform_client_config() -> Result<quinn::ClientConfig, LinkError> {
236+ let provider = Arc::new(quinn::rustls::crypto::ring::default_provider());
237+ let verifier = rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?;
238+ let mut tls = quinn::rustls::ClientConfig::builder_with_provider(provider)
239+ .with_protocol_versions(&[&quinn::rustls::version::TLS13])
240+ .map_err(tls_error)?
241+ .dangerous()
242+ .with_custom_certificate_verifier(Arc::new(verifier))
243+ .with_no_client_auth();
244+ tls.alpn_protocols = vec![alpn()];
245+
246+ let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(tls_error)?;
247+
248+ Ok(quinn::ClientConfig::new(Arc::new(crypto)))
249+}
250+
251+fn config() -> Result<quinn::ClientConfig, LinkError> {
252+ #[cfg(debug_assertions)]
253+ let mut client_config = accept_any_client_config()?;
254+
255+ #[cfg(not(debug_assertions))]
256+ let mut client_config = platform_client_config()?;
257+
258+ client_config.transport_config(Arc::new(transport()));
259+
260+ Ok(client_config)
261+}
262+
263+pub(super) async fn send(
264+ connection: &quinn::Connection,
265+ request: &Request,
266+) -> Result<Response, Fail> {
267+ let (send_stream, mut receive_stream) = connection.open_bi().await?;
268+ let mut send_stream = Sending::new(send_stream);
269+ frame::write(&mut send_stream, &Open::Call(request.clone()), UP_MAX).await?;
270+ send_stream.finish()?;
271+
272+ Ok(frame::read::<Result<Response, Error>>(&mut receive_stream, DOWN_MAX).await??)
273+}
274+
275+pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> {
276+ match send(connection, &request).await? {
277+ Response::Done => Ok(()),
278+ _ => Err(Fail::Protocol),
279+ }
280+}
281+
282+pub(super) async fn send_body(
283+ send_stream: &mut quinn::SendStream,
284+ file: &mut tokio::fs::File,
285+) -> Result<(), Fail> {
286+ use tokio::io::AsyncReadExt;
287+
288+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
289+ loop {
290+ let read = file.read(&mut buffer).await?;
291+ if read == 0 {
292+ return Ok(());
293+ }
294+
295+ send_stream.write_all(&buffer[..read]).await?;
296+ }
297+}
298+
299+pub(super) async fn upload(
300+ connection: &quinn::Connection,
301+ community_id: &str,
302+ path: &Path,
303+ maximum: Option<u64>,
304+) -> Result<Attachment, Fail> {
305+ let name = path
306+ .file_name()
307+ .map(|name| name.to_string_lossy().into_owned())
308+ .unwrap_or_default();
309+ validate_attachment_name(&name)?;
310+
311+ let mut file = tokio::fs::File::open(path).await?;
312+ let size = file.metadata().await?.len();
313+ if let Some(maximum) = maximum {
314+ validate_attachment_size(size, maximum)?;
315+ }
316+
317+ let (send_stream, mut receive_stream) = connection.open_bi().await?;
318+ let mut send_stream = Sending::new(send_stream);
319+ let header = Upload {
320+ community_id: community_id.to_string(),
321+ name,
322+ size,
323+ };
324+ frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?;
325+
326+ let write = async move {
327+ send_body(send_stream.get(), &mut file).await?;
328+ Ok(send_stream.finish()?)
329+ };
330+ let read = frame::read::<Result<Attachment, Error>>(&mut receive_stream, DOWN_MAX);
331+ let (sent, reply) = tokio::join!(write, read);
332+
333+ match (sent, reply) {
334+ (_, Ok(reply)) => Ok(reply?),
335+ (Err(error), _) => Err(error),
336+ (_, Err(error)) => Err(error.into()),
337+ }
338+}
339+
340+async fn open_fetch(
341+ connection: &quinn::Connection,
342+ blob: &Blob,
343+) -> Result<(quinn::RecvStream, u64), Fail> {
344+ let (send_stream, mut receive_stream) = connection.open_bi().await?;
345+ let mut send_stream = Sending::new(send_stream);
346+ frame::write(&mut send_stream, &Open::Fetch(blob.clone()), UP_MAX).await?;
347+ send_stream.finish()?;
348+
349+ let length = frame::read::<Result<u64, Error>>(&mut receive_stream, DOWN_MAX).await??;
350+
351+ Ok((receive_stream, length))
352+}
353+
354+pub(super) async fn backup_download(
355+ connection: &quinn::Connection,
356+ name: &str,
357+ path: &Path,
358+) -> Result<(), Fail> {
359+ let (mut receive_stream, length) =
360+ open_fetch(connection, &Blob::Backup(name.to_string())).await?;
361+
362+ let mut part = path.as_os_str().to_owned();
363+ part.push(".part");
364+ let part = std::path::PathBuf::from(part);
365+
366+ let copied = async {
367+ let mut file = tokio::fs::File::create(&part).await?;
368+ let copied = tokio::io::copy(&mut receive_stream, &mut file).await?;
369+ if copied != length {
370+ return Err(Fail::Protocol);
371+ }
372+ file.sync_all().await?;
373+ tokio::fs::rename(&part, path).await?;
374+ Ok(())
375+ }
376+ .await;
377+ if copied.is_err() {
378+ let _ = tokio::fs::remove_file(&part).await;
379+ }
380+
381+ copied
382+}
383+
384+pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Result<Vec<u8>, Fail> {
385+ let (mut receive_stream, length) = open_fetch(connection, blob).await?;
386+
387+ if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
388+ return Err(Fail::Protocol);
389+ }
390+
391+ let mut bytes = vec![0u8; length as usize];
392+ receive_stream.read_exact(&mut bytes).await?;
393+
394+ Ok(bytes)
395+}
396+
397+pub(super) fn answer<T: Send + 'static>(
398+ reply: oneshot::Sender<Result<T, Fail>>,
399+ work: impl Future<Output = Result<T, Fail>> + Send + 'static,
400+) {
401+ tokio::spawn(async move {
402+ let _ = reply.send(work.await);
403+ });
404+}
405+
406+async fn actor(
407+ client_config: ClientConfig,
408+ mut command_receiver: mpsc::Receiver<Command>,
409+ event_sender: mpsc::Sender<NetworkEvent>,
410+ shared: Shared,
411+) {
412+ let mut token: Option<String> = None;
413+ let mut endpoints = Endpoints::default();
414+ let mut attempt = 0u32;
415+ 'session: loop {
416+ let connection = loop {
417+ match connect(&client_config, &mut endpoints).await {
418+ Ok(connection) => break connection,
419+ Err(LinkError::Outdated) => {
420+ warn!("server speaks another protocol version");
421+ let _ = event_sender
422+ .send(NetworkEvent::Disconnected(LinkError::Outdated))
423+ .await;
424+ while command_receiver.recv().await.is_some() {}
425+ return;
426+ }
427+ Err(error) => {
428+ warn!("connect failed: {error}");
429+
430+ if event_sender
431+ .send(NetworkEvent::Disconnected(error))
432+ .await
433+ .is_err()
434+ {
435+ return;
436+ }
437+
438+ tokio::time::sleep(backoff(attempt)).await;
439+ attempt += 1;
440+ }
441+ };
442+ };
443+
444+ if let Some(stored) = token.clone() {
445+ let request = Request::Resume { token: stored };
446+ match send(&connection, &request).await {
447+ Ok(Response::Session { token: resumed, .. }) => {
448+ token = Some(resumed);
449+ }
450+ Err(error) => {
451+ warn!("session resume failed: {error}");
452+ if let Some(reason) = connection.close_reason() {
453+ let event = LinkError::from(reason);
454+ if event == LinkError::Closed(Close::Banned) {
455+ let _ = event_sender.send(NetworkEvent::Disconnected(event)).await;
456+ while command_receiver.recv().await.is_some() {}
457+ return;
458+ }
459+ }
460+ tokio::time::sleep(backoff(attempt)).await;
461+ attempt += 1;
462+ continue 'session;
463+ }
464+ Ok(_) => {
465+ warn!("session resume rejected");
466+ token = None;
467+
468+ if event_sender.send(NetworkEvent::SessionLost).await.is_err() {
469+ return;
470+ }
471+ }
472+ }
473+ }
474+
475+ attempt = 0;
476+ info!("connected");
477+ if event_sender.send(NetworkEvent::Connected).await.is_err() {
478+ return;
479+ }
480+
481+ tokio::spawn(event_receive_loop(
482+ connection.clone(),
483+ event_sender.clone(),
484+ shared.share.clone(),
485+ ));
486+ tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone()));
487+ let mut ticker = tokio::time::interval(SHARE_TICK);
488+
489+ loop {
490+ tokio::select! {
491+ command = command_receiver.recv() => match command {
492+ Some(Command::Request { request, reply }) => match &request {
493+ Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => {
494+ hang_up(&shared);
495+
496+ let response = send(&connection, &request).await;
497+ if let Ok(Response::Session { token: session_token, .. }) = &response {
498+ token = Some(session_token.clone());
499+ }
500+ let _ = reply.send(response);
501+ }
502+ Request::Logout | Request::Detach => {
503+ token = None;
504+ hang_up(&shared);
505+
506+ let connection = connection.clone();
507+ answer(reply, async move { send(&connection, &request).await });
508+ }
509+ Request::JoinVoice { .. } => {
510+ let shared = shared.clone();
511+ let settings = shared.voice_settings.lock().unwrap().clone();
512+ let connection = connection.clone();
513+
514+ answer(reply, async move {
515+ let response = send(&connection, &request).await;
516+ if let Ok(Response::Voice(_)) = &response {
517+ shared.mic_test.lock().unwrap().take();
518+ *shared.voice.lock().unwrap() =
519+ Some(voice::start(Some(connection), &settings));
520+ }
521+ response
522+ });
523+ }
524+ Request::LeaveVoice => {
525+ hang_up(&shared);
526+
527+ let connection = connection.clone();
528+ answer(reply, async move { send(&connection, &request).await });
529+ }
530+ _ => {
531+ let connection = connection.clone();
532+ answer(reply, async move { send(&connection, &request).await });
533+ }
534+ },
535+ Some(Command::StartShare { kind, settings, reply }) => {
536+ let connection = connection.clone();
537+ let share = shared.share.clone();
538+
539+ answer(reply, async move { start_share(&connection, &share, kind, &settings).await });
540+ }
541+ Some(Command::UpdateShare { settings, reply }) => {
542+ let connection = connection.clone();
543+ let share = shared.share.clone();
544+
545+ answer(reply, async move { update_share(&connection, &share, &settings).await });
546+ }
547+ Some(Command::Upload { community_id, path, maximum, reply }) => {
548+ let connection = connection.clone();
549+
550+ answer(reply, async move { upload(&connection, &community_id, &path, maximum).await });
551+ }
552+ Some(Command::Download { blob, reply }) => {
553+ let connection = connection.clone();
554+ let fetches = shared.fetches.clone();
555+
556+ answer(reply, async move { fetches.memory(&connection, blob).await });
557+ }
558+ Some(Command::BackupDownload { name, path, reply }) => {
559+ let connection = connection.clone();
560+ let fetches = shared.fetches.clone();
561+
562+ answer(reply, async move {
563+ let _permit = fetches.permit().await;
564+ backup_download(&connection, &name, &path).await
565+ });
566+ }
567+ None => break 'session,
568+ },
569+
570+ _ = ticker.tick() => {
571+ let requests = shared.share.lock().unwrap().ticks();
572+ for request in requests {
573+ let connection = connection.clone();
574+ tokio::spawn(async move {
575+ let _ = send(&connection, &request).await;
576+ });
577+ }
578+ }
579+
580+ error = connection.closed() => {
581+ warn!("disconnected: {error}");
582+ hang_up(&shared);
583+
584+ let event = LinkError::from(error);
585+ let banned = event == LinkError::Closed(Close::Banned);
586+
587+ if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() {
588+ return;
589+ }
590+
591+ if banned {
592+ while command_receiver.recv().await.is_some() {}
593+ return;
594+ }
595+
596+ tokio::time::sleep(backoff(attempt)).await;
597+ attempt += 1;
598+ break;
599+ }
600+ }
601+ }
602+ }
603+}
crates/client/src/net/mod.rsadded+1160 -0
@@ -0,0 +1,1160 @@
1+use std::{
2+ path::PathBuf,
3+ sync::{Arc, Mutex},
4+};
5+
6+use common::{
7+ constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
8+ event::Event,
9+ model::{
10+ Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
11+ CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
12+ Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
13+ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
14+ },
15+ open::Blob,
16+ request::Request,
17+ response::Response,
18+ share::Kind,
19+ validate::{
20+ validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
21+ validate_password, validate_poll, validate_reason, validate_server_settings,
22+ validate_status, validate_username,
23+ },
24+};
25+use tokio::sync::{mpsc, oneshot};
26+
27+use crate::{
28+ settings::{ShareSettings, VoiceSettings},
29+ voice::Voice,
30+};
31+
32+macro_rules! expect {
33+ ($response:expr, $variant:path) => {
34+ match $response {
35+ $variant(value) => Ok(value),
36+ _ => Err(Fail::Protocol),
37+ }
38+ };
39+}
40+
41+mod datagram;
42+mod events;
43+mod fail;
44+mod fetch;
45+mod link;
46+mod share;
47+mod voice;
48+
49+pub use fail::{Fail, LinkError};
50+pub use link::start;
51+use share::Share;
52+
53+fn device_name() -> String {
54+ let host = gethostname::gethostname()
55+ .to_string_lossy()
56+ .trim()
57+ .to_string();
58+ let host = if host.is_empty() {
59+ "unknown".to_string()
60+ } else {
61+ host
62+ };
63+
64+ format!("{host} {}", std::env::consts::OS)
65+}
66+
67+type SharedVoice = Arc<Mutex<Option<Voice>>>;
68+type SharedSettings = Arc<Mutex<VoiceSettings>>;
69+type SharedShare = Arc<Mutex<Share>>;
70+type SharedShareSettings = Arc<Mutex<ShareSettings>>;
71+
72+#[derive(Clone, Default)]
73+struct Shared {
74+ voice: SharedVoice,
75+ mic_test: SharedVoice,
76+ voice_settings: SharedSettings,
77+ share: SharedShare,
78+ share_settings: SharedShareSettings,
79+ fetches: Arc<fetch::Fetches>,
80+}
81+
82+fn hang_up(shared: &Shared) {
83+ shared.voice.lock().unwrap().take();
84+ *shared.share.lock().unwrap() = Share::default();
85+}
86+
87+#[derive(Default)]
88+pub struct Levels {
89+ pub voice: Vec<(String, Vec<f32>)>,
90+ pub watching: Vec<(String, Vec<f32>)>,
91+ pub sharing: Option<Vec<f32>>,
92+}
93+
94+#[derive(Debug)]
95+pub enum NetworkEvent {
96+ Connected,
97+ Disconnected(LinkError),
98+ SessionLost,
99+ Pushed(Box<Event>),
100+}
101+
102+#[derive(Debug)]
103+enum Command {
104+ Request {
105+ request: Request,
106+ reply: oneshot::Sender<Result<Response, Fail>>,
107+ },
108+ Upload {
109+ community_id: String,
110+ path: PathBuf,
111+ maximum: Option<u64>,
112+ reply: oneshot::Sender<Result<Attachment, Fail>>,
113+ },
114+ Download {
115+ blob: Blob,
116+ reply: oneshot::Sender<Result<Vec<u8>, Fail>>,
117+ },
118+ BackupDownload {
119+ name: String,
120+ path: PathBuf,
121+ reply: oneshot::Sender<Result<(), Fail>>,
122+ },
123+ StartShare {
124+ kind: Kind,
125+ settings: ShareSettings,
126+ reply: oneshot::Sender<Result<(), Fail>>,
127+ },
128+ UpdateShare {
129+ settings: ShareSettings,
130+ reply: oneshot::Sender<Result<(), Fail>>,
131+ },
132+}
133+
134+#[derive(Clone)]
135+pub struct NetworkHandle {
136+ command_sender: mpsc::Sender<Command>,
137+ shared: Shared,
138+}
139+
140+impl NetworkHandle {
141+ async fn ask<T>(
142+ &self,
143+ build: impl FnOnce(oneshot::Sender<Result<T, Fail>>) -> Command,
144+ ) -> Result<T, Fail> {
145+ let (reply, response) = oneshot::channel();
146+
147+ self.command_sender
148+ .send(build(reply))
149+ .await
150+ .map_err(|_| Fail::Offline)?;
151+
152+ response.await.map_err(|_| Fail::Offline)?
153+ }
154+
155+ fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> {
156+ self.shared.voice.lock().unwrap().as_ref().map(f)
157+ }
158+
159+ async fn request(&self, request: Request) -> Result<Response, Fail> {
160+ self.ask(|reply| Command::Request { request, reply }).await
161+ }
162+
163+ async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> {
164+ let session = match self.request(request).await? {
165+ Response::Session { user, token } => (user, token),
166+ _ => return Err(Fail::Protocol),
167+ };
168+ let _ = self
169+ .done(Request::SetDevice {
170+ name: device_name(),
171+ })
172+ .await;
173+
174+ Ok(session)
175+ }
176+
177+ pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {
178+ expect!(
179+ self.request(Request::Sessions {
180+ user_id: user_id.to_string(),
181+ })
182+ .await?,
183+ Response::Sessions
184+ )
185+ }
186+
187+ pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> {
188+ self.done(Request::RevokeSession {
189+ user_id: user_id.to_string(),
190+ session_id: session_id.to_string(),
191+ })
192+ .await
193+ }
194+
195+ pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Fail> {
196+ validate_username(username)?;
197+
198+ expect!(
199+ self.request(Request::RenameUser {
200+ user_id: user_id.to_string(),
201+ username: username.to_string(),
202+ })
203+ .await?,
204+ Response::User
205+ )
206+ }
207+
208+ pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {
209+ self.sign_in(Request::Resume {
210+ token: token.to_string(),
211+ })
212+ .await
213+ }
214+
215+ pub async fn detach(&self) -> Result<(), Fail> {
216+ self.done(Request::Detach).await
217+ }
218+
219+ pub async fn register(
220+ &self,
221+ username: &str,
222+ password: &str,
223+ invite: Option<&str>,
224+ ) -> Result<(User, String), Fail> {
225+ validate_username(username)?;
226+ validate_password(password)?;
227+
228+ self.sign_in(Request::Register {
229+ username: username.to_string(),
230+ password: password.to_string(),
231+ invite: invite.map(str::to_string),
232+ })
233+ .await
234+ }
235+
236+ pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {
237+ validate_password(password)?;
238+
239+ self.sign_in(Request::Login {
240+ username: username.to_string(),
241+ password: password.to_string(),
242+ })
243+ .await
244+ }
245+
246+ pub async fn logout(&self) -> Result<(), Fail> {
247+ self.done(Request::Logout).await
248+ }
249+
250+ pub async fn update_user(&self, username: &str) -> Result<User, Fail> {
251+ validate_username(username)?;
252+
253+ expect!(
254+ self.request(Request::UpdateUser {
255+ username: username.to_string(),
256+ })
257+ .await?,
258+ Response::User
259+ )
260+ }
261+
262+ pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {
263+ expect!(
264+ self.request(Request::DeleteUser {
265+ user_id: user_id.to_string(),
266+ })
267+ .await?,
268+ Response::User
269+ )
270+ .map(|_| ())
271+ }
272+
273+ pub async fn users(&self) -> Result<Vec<Account>, Fail> {
274+ expect!(self.request(Request::Users).await?, Response::Users)
275+ }
276+
277+ pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {
278+ self.done(Request::SuspendUser {
279+ user_id: user_id.to_string(),
280+ suspended,
281+ })
282+ .await
283+ }
284+
285+ pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {
286+ self.done(Request::TimeoutUser {
287+ user_id: user_id.to_string(),
288+ minutes,
289+ })
290+ .await
291+ }
292+
293+ pub async fn ban_user(
294+ &self,
295+ user_id: &str,
296+ reason: Option<&str>,
297+ scope: BanScope,
298+ ) -> Result<(), Fail> {
299+ validate_reason(reason)?;
300+
301+ self.done(Request::BanUser {
302+ user_id: user_id.to_string(),
303+ reason: reason.map(str::to_string),
304+ scope,
305+ })
306+ .await
307+ }
308+
309+ pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {
310+ expect!(
311+ self.request(Request::ServerBans).await?,
312+ Response::ServerBans
313+ )
314+ }
315+
316+ pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {
317+ self.done(Request::RemoveServerBan { id: id.to_string() })
318+ .await
319+ }
320+
321+ pub async fn create_invite_code(
322+ &self,
323+ uses: u32,
324+ hours: Option<u32>,
325+ ) -> Result<InviteCode, Fail> {
326+ expect!(
327+ self.request(Request::CreateInviteCode { uses, hours })
328+ .await?,
329+ Response::InviteCode
330+ )
331+ }
332+
333+ pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {
334+ expect!(
335+ self.request(Request::InviteCodes).await?,
336+ Response::InviteCodes
337+ )
338+ }
339+
340+ pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {
341+ self.done(Request::DeleteInviteCode {
342+ code: code.to_string(),
343+ })
344+ .await
345+ }
346+
347+ pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {
348+ self.done(Request::RevokeSessions {
349+ user_id: user_id.to_string(),
350+ })
351+ .await
352+ }
353+
354+ pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {
355+ validate_password(password)?;
356+
357+ self.done(Request::ResetPassword {
358+ user_id: user_id.to_string(),
359+ password: password.to_string(),
360+ })
361+ .await
362+ }
363+
364+ pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {
365+ expect!(
366+ self.request(Request::ClearProfile {
367+ user_id: user_id.to_string(),
368+ })
369+ .await?,
370+ Response::User
371+ )
372+ }
373+
374+ pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {
375+ expect!(
376+ self.request(Request::SetRole {
377+ user_id: user_id.to_string(),
378+ role,
379+ })
380+ .await?,
381+ Response::User
382+ )
383+ }
384+
385+ pub async fn admin_logs(
386+ &self,
387+ actor_id: Option<String>,
388+ target_id: Option<String>,
389+ action: Option<String>,
390+ after_ms: Option<u64>,
391+ before_ms: Option<u64>,
392+ ) -> Result<Vec<AdminLogEntry>, Fail> {
393+ let request = Request::AdminLogs {
394+ actor_id,
395+ target_id,
396+ action,
397+ after_ms,
398+ before_ms,
399+ };
400+ expect!(self.request(request).await?, Response::AdminLogs)
401+ }
402+
403+ pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {
404+ expect!(
405+ self.request(Request::DailyStats { days }).await?,
406+ Response::DailyStats
407+ )
408+ }
409+
410+ pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {
411+ expect!(
412+ self.request(Request::ServerSettings).await?,
413+ Response::ServerSettings
414+ )
415+ }
416+
417+ pub async fn update_server_settings(
418+ &self,
419+ settings: ServerSettings,
420+ ) -> Result<ServerSettings, Fail> {
421+ validate_server_settings(&settings)?;
422+
423+ expect!(
424+ self.request(Request::UpdateServerSettings { settings })
425+ .await?,
426+ Response::ServerSettings
427+ )
428+ }
429+
430+ pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Fail> {
431+ validate_username(username)?;
432+ validate_password(password)?;
433+
434+ expect!(
435+ self.request(Request::CreateUser {
436+ username: username.to_string(),
437+ password: password.to_string(),
438+ })
439+ .await?,
440+ Response::User
441+ )
442+ }
443+
444+ pub async fn overview(&self) -> Result<Overview, Fail> {
445+ expect!(self.request(Request::Overview).await?, Response::Overview)
446+ }
447+
448+ pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {
449+ expect!(
450+ self.request(Request::AllCommunities).await?,
451+ Response::AllCommunities
452+ )
453+ }
454+
455+ pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
456+ self.done(Request::TransferOwnership {
457+ community_id: community_id.to_string(),
458+ user_id: user_id.to_string(),
459+ })
460+ .await
461+ }
462+
463+ pub async fn read_user(&self, user_id: &str) -> Result<User, Fail> {
464+ expect!(
465+ self.request(Request::ReadUser {
466+ user_id: user_id.to_string(),
467+ })
468+ .await?,
469+ Response::User
470+ )
471+ }
472+
473+ pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {
474+ validate_community_name(name)?;
475+
476+ expect!(
477+ self.request(Request::CreateCommunity {
478+ name: name.to_string(),
479+ })
480+ .await?,
481+ Response::Community
482+ )
483+ }
484+
485+ pub async fn update_community(
486+ &self,
487+ community_id: &str,
488+ name: &str,
489+ ) -> Result<Community, Fail> {
490+ validate_community_name(name)?;
491+
492+ expect!(
493+ self.request(Request::UpdateCommunity {
494+ community_id: community_id.to_string(),
495+ name: name.to_string(),
496+ })
497+ .await?,
498+ Response::Community
499+ )
500+ }
501+
502+ pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {
503+ expect!(
504+ self.request(Request::DeleteCommunity {
505+ community_id: community_id.to_string(),
506+ })
507+ .await?,
508+ Response::Community
509+ )
510+ .map(|_| ())
511+ }
512+
513+ pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {
514+ self.done(Request::LeaveCommunity {
515+ community_id: community_id.to_string(),
516+ })
517+ .await
518+ }
519+
520+ pub async fn communities(&self) -> Result<Vec<Community>, Fail> {
521+ expect!(
522+ self.request(Request::Communities).await?,
523+ Response::Communities
524+ )
525+ }
526+
527+ pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {
528+ expect!(
529+ self.request(Request::Members {
530+ community_id: community_id.to_string(),
531+ })
532+ .await?,
533+ Response::Members
534+ )
535+ }
536+
537+ pub async fn kick(
538+ &self,
539+ community_id: &str,
540+ user_id: &str,
541+ reason: Option<&str>,
542+ ) -> Result<(), Fail> {
543+ validate_reason(reason)?;
544+ self.done(Request::Kick {
545+ community_id: community_id.to_string(),
546+ user_id: user_id.to_string(),
547+ reason: reason.map(str::to_string),
548+ })
549+ .await
550+ }
551+
552+ pub async fn ban(
553+ &self,
554+ community_id: &str,
555+ user_id: &str,
556+ reason: Option<&str>,
557+ ) -> Result<(), Fail> {
558+ validate_reason(reason)?;
559+ self.done(Request::Ban {
560+ community_id: community_id.to_string(),
561+ user_id: user_id.to_string(),
562+ reason: reason.map(str::to_string),
563+ })
564+ .await
565+ }
566+
567+ pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
568+ self.done(Request::Unban {
569+ community_id: community_id.to_string(),
570+ user_id: user_id.to_string(),
571+ })
572+ .await
573+ }
574+
575+ pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {
576+ expect!(
577+ self.request(Request::Bans {
578+ community_id: community_id.to_string(),
579+ })
580+ .await?,
581+ Response::Bans
582+ )
583+ }
584+
585+ pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {
586+ expect!(
587+ self.request(Request::Logs {
588+ community_id: community_id.to_string(),
589+ })
590+ .await?,
591+ Response::Logs
592+ )
593+ }
594+
595+ pub async fn set_rank(
596+ &self,
597+ community_id: &str,
598+ user_id: &str,
599+ rank: Rank,
600+ ) -> Result<(), Fail> {
601+ self.done(Request::SetRank {
602+ community_id: community_id.to_string(),
603+ user_id: user_id.to_string(),
604+ rank,
605+ })
606+ .await
607+ }
608+
609+ pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {
610+ expect!(
611+ self.request(Request::DeleteMessage {
612+ message_id: message_id.to_string(),
613+ })
614+ .await?,
615+ Response::Message
616+ )
617+ .map(|_| ())
618+ }
619+
620+ pub async fn create_message(
621+ &self,
622+ community_id: &str,
623+ body: &str,
624+ attachments: Vec<String>,
625+ reply_to: Option<String>,
626+ ) -> Result<Message, Fail> {
627+ validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
628+
629+ expect!(
630+ self.request(Request::CreateMessage {
631+ community_id: community_id.to_string(),
632+ body: body.to_string(),
633+ attachments,
634+ reply_to,
635+ })
636+ .await?,
637+ Response::Message
638+ )
639+ }
640+
641+ pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Fail> {
642+ validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
643+
644+ expect!(
645+ self.request(Request::UpdateMessage {
646+ message_id: message_id.to_string(),
647+ body: body.to_string(),
648+ })
649+ .await?,
650+ Response::Message
651+ )
652+ }
653+
654+ pub async fn forward_messages(
655+ &self,
656+ message_ids: Vec<String>,
657+ community_id: &str,
658+ snippet: bool,
659+ ) -> Result<Vec<Message>, Fail> {
660+ validate_forward(message_ids.len())?;
661+
662+ expect!(
663+ self.request(Request::ForwardMessages {
664+ message_ids,
665+ community_id: community_id.to_string(),
666+ snippet,
667+ })
668+ .await?,
669+ Response::Messages
670+ )
671+ }
672+
673+ pub async fn find_user(&self, username: &str) -> Result<User, Fail> {
674+ expect!(
675+ self.request(Request::FindUser {
676+ username: username.to_string(),
677+ })
678+ .await?,
679+ Response::User
680+ )
681+ }
682+
683+ pub async fn open_notes(&self) -> Result<Community, Fail> {
684+ expect!(self.request(Request::OpenNotes).await?, Response::Community)
685+ }
686+
687+ pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {
688+ expect!(
689+ self.request(Request::OpenDirect {
690+ user_id: user_id.to_string(),
691+ })
692+ .await?,
693+ Response::Community
694+ )
695+ }
696+
697+ pub async fn friends(&self) -> Result<Friends, Fail> {
698+ expect!(self.request(Request::Friends).await?, Response::Friends)
699+ }
700+
701+ pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {
702+ expect!(
703+ self.request(Request::ReadPresences).await?,
704+ Response::Presences
705+ )
706+ }
707+
708+ pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> {
709+ self.done(Request::UpdatePresence { presence }).await
710+ }
711+
712+ pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {
713+ self.done(Request::AddFriend {
714+ user_id: user_id.to_string(),
715+ })
716+ .await
717+ }
718+
719+ pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {
720+ self.done(Request::AcceptFriend {
721+ user_id: user_id.to_string(),
722+ })
723+ .await
724+ }
725+
726+ pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {
727+ self.done(Request::RemoveFriend {
728+ user_id: user_id.to_string(),
729+ })
730+ .await
731+ }
732+
733+ pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
734+ self.done(Request::Invite {
735+ community_id: community_id.to_string(),
736+ user_id: user_id.to_string(),
737+ })
738+ .await
739+ }
740+
741+ pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {
742+ expect!(
743+ self.request(Request::Invitations).await?,
744+ Response::Invitations
745+ )
746+ }
747+
748+ pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {
749+ expect!(
750+ self.request(Request::AcceptInvitation {
751+ community_id: community_id.to_string(),
752+ })
753+ .await?,
754+ Response::Community
755+ )
756+ }
757+
758+ pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {
759+ self.done(Request::DeclineInvitation {
760+ community_id: community_id.to_string(),
761+ })
762+ .await
763+ }
764+
765+ pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {
766+ self.done(Request::DeclineCall {
767+ community_id: community_id.to_string(),
768+ })
769+ .await
770+ }
771+
772+ pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {
773+ self.done(Request::React {
774+ message_id: message_id.to_string(),
775+ emoji: emoji.to_string(),
776+ })
777+ .await
778+ }
779+
780+ pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {
781+ self.done(Request::Pin {
782+ message_id: message_id.to_string(),
783+ pinned,
784+ })
785+ .await
786+ }
787+
788+ pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {
789+ expect!(
790+ self.request(Request::Pins {
791+ community_id: community_id.to_string(),
792+ })
793+ .await?,
794+ Response::Messages
795+ )
796+ }
797+
798+ pub async fn create_poll(
799+ &self,
800+ community_id: &str,
801+ question: &str,
802+ options: Vec<String>,
803+ multiple: bool,
804+ ) -> Result<Message, Fail> {
805+ validate_poll(question, &options)?;
806+
807+ expect!(
808+ self.request(Request::CreatePoll {
809+ community_id: community_id.to_string(),
810+ question: question.to_string(),
811+ options,
812+ multiple,
813+ })
814+ .await?,
815+ Response::Message
816+ )
817+ }
818+
819+ pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {
820+ self.done(Request::Vote {
821+ message_id: message_id.to_string(),
822+ positions,
823+ })
824+ .await
825+ }
826+
827+ pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {
828+ self.done(Request::ClosePoll {
829+ message_id: message_id.to_string(),
830+ })
831+ .await
832+ }
833+
834+ pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {
835+ validate_reason(Some(reason))?;
836+
837+ self.done(Request::ReportMessage {
838+ message_id: message_id.to_string(),
839+ reason: reason.to_string(),
840+ })
841+ .await
842+ }
843+
844+ pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {
845+ validate_reason(Some(reason))?;
846+
847+ self.done(Request::ReportUser {
848+ user_id: user_id.to_string(),
849+ reason: reason.to_string(),
850+ })
851+ .await
852+ }
853+
854+ pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {
855+ expect!(
856+ self.request(Request::Reports { status }).await?,
857+ Response::Reports
858+ )
859+ }
860+
861+ pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {
862+ self.done(Request::HandleReport {
863+ report_id: report_id.to_string(),
864+ status,
865+ })
866+ .await
867+ }
868+
869+ pub async fn search_messages(
870+ &self,
871+ text: Option<String>,
872+ user_id: Option<String>,
873+ community_id: Option<String>,
874+ after_ms: Option<u64>,
875+ before_ms: Option<u64>,
876+ ) -> Result<Vec<MessageHit>, Fail> {
877+ expect!(
878+ self.request(Request::SearchMessages {
879+ text,
880+ user_id,
881+ community_id,
882+ after_ms,
883+ before_ms,
884+ })
885+ .await?,
886+ Response::MessageHits
887+ )
888+ }
889+
890+ pub async fn search_community(
891+ &self,
892+ community_id: String,
893+ text: String,
894+ ) -> Result<Vec<MessageHit>, Fail> {
895+ expect!(
896+ self.request(Request::SearchCommunity { community_id, text })
897+ .await?,
898+ Response::MessageHits
899+ )
900+ }
901+
902+ pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {
903+ match self.request(Request::StorageUsage).await? {
904+ Response::StorageUsage { users, communities } => Ok((users, communities)),
905+ _ => Err(Fail::Protocol),
906+ }
907+ }
908+
909+ pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {
910+ expect!(self.request(Request::CreateBackup).await?, Response::Backup)
911+ }
912+
913+ pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {
914+ expect!(self.request(Request::Backups).await?, Response::Backups)
915+ }
916+
917+ pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {
918+ self.done(Request::DeleteBackup {
919+ name: name.to_string(),
920+ })
921+ .await
922+ }
923+
924+ pub async fn attachments(
925+ &self,
926+ user_id: Option<String>,
927+ community_id: Option<String>,
928+ ) -> Result<Vec<AttachmentInfo>, Fail> {
929+ expect!(
930+ self.request(Request::AllAttachments {
931+ user_id,
932+ community_id,
933+ })
934+ .await?,
935+ Response::AttachmentInfos
936+ )
937+ }
938+
939+ pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {
940+ self.done(Request::DeleteAttachment {
941+ attachment_id: attachment_id.to_string(),
942+ })
943+ .await
944+ }
945+
946+ pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {
947+ self.done(Request::PurgeUser {
948+ user_id: user_id.to_string(),
949+ })
950+ .await
951+ }
952+
953+ async fn done(&self, request: Request) -> Result<(), Fail> {
954+ match self.request(request).await? {
955+ Response::Done => Ok(()),
956+ _ => Err(Fail::Protocol),
957+ }
958+ }
959+
960+ pub async fn upload_attachment(
961+ &self,
962+ community_id: &str,
963+ path: PathBuf,
964+ maximum: Option<u64>,
965+ ) -> Result<Attachment, Fail> {
966+ self.ask(|reply| Command::Upload {
967+ community_id: community_id.to_string(),
968+ path,
969+ maximum,
970+ reply,
971+ })
972+ .await
973+ }
974+
975+ pub async fn download_attachment(
976+ &self,
977+ attachment_id: &str,
978+ thumbnail: bool,
979+ ) -> Result<Vec<u8>, Fail> {
980+ let id = attachment_id.to_string();
981+ let blob = if thumbnail {
982+ Blob::Thumbnail(id)
983+ } else {
984+ Blob::Attachment(id)
985+ };
986+ self.ask(|reply| Command::Download { blob, reply }).await
987+ }
988+
989+ pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Fail> {
990+ self.ask(|reply| Command::BackupDownload {
991+ name: name.to_string(),
992+ path,
993+ reply,
994+ })
995+ .await
996+ }
997+
998+ pub async fn read_messages(
999+ &self,
1000+ community_id: &str,
1001+ before: Option<&str>,
1002+ ) -> Result<Vec<Message>, Fail> {
1003+ expect!(
1004+ self.request(Request::ReadMessages {
1005+ community_id: community_id.to_string(),
1006+ before: before.map(str::to_string),
1007+ })
1008+ .await?,
1009+ Response::Messages
1010+ )
1011+ }
1012+
1013+ pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {
1014+ expect!(self.request(Request::Unreads).await?, Response::Unreads)
1015+ }
1016+
1017+ pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {
1018+ self.done(Request::MarkRead {
1019+ community_id: community_id.to_string(),
1020+ message_id: message_id.to_string(),
1021+ })
1022+ .await
1023+ }
1024+
1025+ pub async fn update_status(&self, status: &str) -> Result<User, Fail> {
1026+ validate_status(status)?;
1027+
1028+ expect!(
1029+ self.request(Request::UpdateStatus {
1030+ status: status.to_string(),
1031+ })
1032+ .await?,
1033+ Response::User
1034+ )
1035+ }
1036+
1037+ pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Fail> {
1038+ validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1039+
1040+ expect!(
1041+ self.request(Request::UpdateAvatar { image: bytes }).await?,
1042+ Response::User
1043+ )
1044+ }
1045+
1046+ pub async fn update_community_avatar(
1047+ &self,
1048+ community_id: &str,
1049+ image: Option<Vec<u8>>,
1050+ ) -> Result<Community, Fail> {
1051+ if let Some(bytes) = &image {
1052+ validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1053+ }
1054+
1055+ expect!(
1056+ self.request(Request::UpdateCommunityAvatar {
1057+ community_id: community_id.to_string(),
1058+ image,
1059+ })
1060+ .await?,
1061+ Response::Community
1062+ )
1063+ }
1064+
1065+ pub async fn remove_avatar(&self) -> Result<User, Fail> {
1066+ expect!(self.request(Request::RemoveAvatar).await?, Response::User)
1067+ }
1068+
1069+ pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Fail> {
1070+ expect!(
1071+ self.request(Request::ReadAvatar {
1072+ avatar_id: avatar_id.to_string(),
1073+ })
1074+ .await?,
1075+ Response::Avatar
1076+ )
1077+ }
1078+
1079+ pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1080+ expect!(
1081+ self.request(Request::JoinVoice {
1082+ community_id: community_id.to_string(),
1083+ })
1084+ .await?,
1085+ Response::Voice
1086+ )
1087+ }
1088+
1089+ pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {
1090+ self.done(Request::Typing {
1091+ community_id: community_id.to_string(),
1092+ })
1093+ .await
1094+ }
1095+
1096+ pub async fn leave_voice(&self) -> Result<(), Fail> {
1097+ self.done(Request::LeaveVoice).await
1098+ }
1099+
1100+ pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {
1101+ expect!(
1102+ self.request(Request::ReadCommunity {
1103+ community_id: community_id.to_string(),
1104+ })
1105+ .await?,
1106+ Response::Community
1107+ )
1108+ }
1109+
1110+ pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1111+ expect!(
1112+ self.request(Request::VoiceParticipants {
1113+ community_id: community_id.to_string(),
1114+ })
1115+ .await?,
1116+ Response::Voice
1117+ )
1118+ }
1119+
1120+ pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {
1121+ expect!(
1122+ self.request(Request::VoiceRooms).await?,
1123+ Response::VoiceRooms
1124+ )
1125+ }
1126+
1127+ pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {
1128+ self.done(Request::SetGhost { enabled }).await
1129+ }
1130+
1131+ pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {
1132+ self.done(Request::KickFromVoice {
1133+ user_id: user_id.to_string(),
1134+ })
1135+ .await
1136+ }
1137+
1138+ pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {
1139+ self.done(Request::ServerMute {
1140+ user_id: user_id.to_string(),
1141+ muted,
1142+ })
1143+ .await
1144+ }
1145+
1146+ pub async fn set_community_voice(
1147+ &self,
1148+ community_id: &str,
1149+ enabled: bool,
1150+ ) -> Result<Community, Fail> {
1151+ expect!(
1152+ self.request(Request::SetCommunityVoice {
1153+ community_id: community_id.to_string(),
1154+ enabled,
1155+ })
1156+ .await?,
1157+ Response::Community
1158+ )
1159+ }
1160+}
crates/client/src/net/share.rsadded+335 -0
@@ -0,0 +1,335 @@
1+use std::collections::HashMap;
2+
3+use common::{
4+ event::Event,
5+ request::Request,
6+ response::Response,
7+ share::{Fps, Kind, Quality, Resolution, Source},
8+};
9+
10+use crate::{
11+ settings::ShareSettings,
12+ share::{
13+ audio::AudioApp,
14+ audio_capture,
15+ encode::capabilities,
16+ session::{ShareSample, Sharing, Tick, WatchQuality, Watching},
17+ },
18+};
19+
20+use super::{link::done, *};
21+
22+#[derive(Default)]
23+pub(super) struct Share {
24+ pub(super) sharing: HashMap<Kind, Sharing>,
25+ pub(super) sources: HashMap<Kind, Source>,
26+ pub(super) watching: HashMap<(String, Kind), Watching>,
27+}
28+
29+impl Share {
30+ pub(super) fn event(&mut self, event: &Event) {
31+ match event {
32+ Event::ShareLayers { kind, layers } => {
33+ if let Some(sharing) = self.sharing.get_mut(kind) {
34+ sharing.set_layers(layers);
35+ }
36+ }
37+ Event::KeyframeWanted { kind, layer } => {
38+ if let Some(sharing) = self.sharing.get(kind) {
39+ sharing.keyframe(*layer);
40+ }
41+ }
42+ Event::ShareStopped { user_id, kind, .. } => {
43+ self.watching.remove(&(user_id.clone(), *kind));
44+ }
45+ _ => {}
46+ }
47+ }
48+
49+ pub(super) fn ticks(&mut self) -> Vec<Request> {
50+ self.watching
51+ .iter_mut()
52+ .flat_map(|((user_id, kind), watching)| {
53+ let (user_id, kind) = (user_id.clone(), *kind);
54+ watching
55+ .tick()
56+ .into_iter()
57+ .map(|tick| match tick {
58+ Tick::Quality(quality) => Request::WatchShare {
59+ user_id: user_id.clone(),
60+ kind,
61+ quality,
62+ decode: capabilities().decode.clone(),
63+ },
64+ Tick::Keyframe => Request::RequestKeyframe {
65+ user_id: user_id.clone(),
66+ kind,
67+ },
68+ })
69+ .collect::<Vec<_>>()
70+ })
71+ .collect()
72+ }
73+}
74+
75+const CAMERA_TOP: Quality = Quality {
76+ resolution: Resolution::P2160,
77+ fps: Fps::F60,
78+};
79+
80+impl NetworkHandle {
81+ pub async fn start_share(&self) -> Result<(), Fail> {
82+ self.start(Kind::Screen).await
83+ }
84+
85+ pub async fn start_camera(&self) -> Result<(), Fail> {
86+ self.start(Kind::Camera).await
87+ }
88+
89+ async fn start(&self, kind: Kind) -> Result<(), Fail> {
90+ let settings = self.shared.share_settings.lock().unwrap().clone();
91+ self.ask(|reply| Command::StartShare {
92+ kind,
93+ settings,
94+ reply,
95+ })
96+ .await
97+ }
98+
99+ pub async fn update_share(&self) -> Result<(), Fail> {
100+ let settings = self.shared.share_settings.lock().unwrap().clone();
101+ self.ask(|reply| Command::UpdateShare { settings, reply })
102+ .await
103+ }
104+
105+ pub async fn stop_share(&self) -> Result<(), Fail> {
106+ self.stop(Kind::Screen).await
107+ }
108+
109+ pub async fn stop_camera(&self) -> Result<(), Fail> {
110+ self.stop(Kind::Camera).await
111+ }
112+
113+ async fn stop(&self, kind: Kind) -> Result<(), Fail> {
114+ let result = self.done(Request::StopShare { kind }).await;
115+ let mut share = self.shared.share.lock().unwrap();
116+ share.sharing.remove(&kind);
117+ share.sources.remove(&kind);
118+ result
119+ }
120+
121+ pub fn sharing(&self) -> bool {
122+ self.shared
123+ .share
124+ .lock()
125+ .unwrap()
126+ .sharing
127+ .contains_key(&Kind::Screen)
128+ }
129+
130+ pub fn camera_on(&self) -> bool {
131+ self.shared
132+ .share
133+ .lock()
134+ .unwrap()
135+ .sharing
136+ .contains_key(&Kind::Camera)
137+ }
138+
139+ pub fn share_source(&self) -> Option<Source> {
140+ self.shared
141+ .share
142+ .lock()
143+ .unwrap()
144+ .sources
145+ .get(&Kind::Screen)
146+ .cloned()
147+ }
148+
149+ pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {
150+ expect!(
151+ self.request(Request::Shares {
152+ community_id: community_id.to_string(),
153+ })
154+ .await?,
155+ Response::Shares
156+ )
157+ }
158+
159+ pub async fn watch_share(
160+ &self,
161+ user_id: &str,
162+ kind: Kind,
163+ watch: WatchQuality,
164+ ) -> Result<(), Fail> {
165+ let volume = self.shared.share_settings.lock().unwrap().volume;
166+ let choice = self.shared.voice_settings.lock().unwrap().choice.clone();
167+ let key = (user_id.to_string(), kind);
168+ let watching = Watching::new(kind, watch, volume, choice);
169+ let quality = watching.wanted();
170+ self.shared
171+ .share
172+ .lock()
173+ .unwrap()
174+ .watching
175+ .insert(key.clone(), watching);
176+
177+ let result = self
178+ .done(Request::WatchShare {
179+ user_id: key.0.clone(),
180+ kind,
181+ quality,
182+ decode: capabilities().decode.clone(),
183+ })
184+ .await;
185+ if result.is_err() {
186+ self.shared.share.lock().unwrap().watching.remove(&key);
187+ }
188+ result
189+ }
190+
191+ pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> {
192+ self.shared
193+ .share
194+ .lock()
195+ .unwrap()
196+ .watching
197+ .remove(&(user_id.to_string(), kind));
198+ self.done(Request::UnwatchShare {
199+ user_id: user_id.to_string(),
200+ kind,
201+ })
202+ .await
203+ }
204+
205+ pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) {
206+ if let Some(watching) = self
207+ .shared
208+ .share
209+ .lock()
210+ .unwrap()
211+ .watching
212+ .get_mut(&(user_id.to_string(), kind))
213+ {
214+ watching.set_quality(quality);
215+ }
216+ }
217+
218+ pub fn share_sample(&self) -> ShareSample {
219+ let mut share = self.shared.share.lock().unwrap();
220+ ShareSample {
221+ sending: share
222+ .sharing
223+ .get(&Kind::Screen)
224+ .map(Sharing::stats)
225+ .unwrap_or_default(),
226+ watching: share
227+ .watching
228+ .iter_mut()
229+ .filter(|((_, kind), _)| *kind == Kind::Screen)
230+ .map(|((user_id, _), watching)| (user_id.clone(), watching.stats()))
231+ .collect(),
232+ }
233+ }
234+
235+ pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> {
236+ self.shared
237+ .share
238+ .lock()
239+ .unwrap()
240+ .watching
241+ .get(&(user_id.to_string(), kind))?
242+ .frame()
243+ }
244+
245+ pub fn set_share_settings(&self, settings: ShareSettings) -> bool {
246+ let changed = self.sharing()
247+ && self
248+ .shared
249+ .share_settings
250+ .lock()
251+ .unwrap()
252+ .encoding_differs(&settings);
253+ *self.shared.share_settings.lock().unwrap() = settings.clone();
254+ for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() {
255+ if *kind == Kind::Screen {
256+ watching.set_volume(settings.volume);
257+ watching.set_quality(settings.watch);
258+ }
259+ }
260+ changed
261+ }
262+
263+ pub fn audio_apps(&self) -> Vec<AudioApp> {
264+ audio_capture::apps()
265+ }
266+}
267+
268+pub(super) async fn start_share(
269+ connection: &quinn::Connection,
270+ share: &SharedShare,
271+ kind: Kind,
272+ settings: &ShareSettings,
273+) -> Result<(), Fail> {
274+ let top = match kind {
275+ Kind::Screen => settings.top,
276+ Kind::Camera => CAMERA_TOP,
277+ };
278+ let (sharing, source) = Sharing::start(
279+ connection.clone(),
280+ kind,
281+ top,
282+ settings.encode(),
283+ settings.audio_mode(),
284+ )
285+ .await
286+ .map_err(Fail::Io)?;
287+ {
288+ let mut share = share.lock().unwrap();
289+ share.sharing.insert(kind, sharing);
290+ share.sources.insert(kind, source.clone());
291+ }
292+
293+ let result = done(connection, Request::StartShare { kind, source }).await;
294+ if result.is_err() {
295+ let mut share = share.lock().unwrap();
296+ share.sharing.remove(&kind);
297+ share.sources.remove(&kind);
298+ }
299+ result
300+}
301+
302+pub(super) async fn update_share(
303+ connection: &quinn::Connection,
304+ share: &SharedShare,
305+ settings: &ShareSettings,
306+) -> Result<(), Fail> {
307+ let source = {
308+ let mut share = share.lock().unwrap();
309+ let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else {
310+ return Ok(());
311+ };
312+ sharing
313+ .update(
314+ connection,
315+ settings.top,
316+ settings.encode(),
317+ settings.audio_mode(),
318+ )
319+ .map_err(Fail::Io)?
320+ };
321+ share
322+ .lock()
323+ .unwrap()
324+ .sources
325+ .insert(Kind::Screen, source.clone());
326+
327+ done(
328+ connection,
329+ Request::StartShare {
330+ kind: Kind::Screen,
331+ source,
332+ },
333+ )
334+ .await
335+}
crates/client/src/net/voice.rsadded+87 -0
@@ -0,0 +1,87 @@
1+use common::share::Kind;
2+
3+use crate::{
4+ settings::VoiceSettings,
5+ share::session::Sharing,
6+ voice::{self, Voice, VoiceSample},
7+};
8+
9+use super::*;
10+
11+impl NetworkHandle {
12+ pub fn set_voice_settings(&self, settings: VoiceSettings) {
13+ *self.shared.voice_settings.lock().unwrap() = settings.clone();
14+
15+ if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() {
16+ voice.apply(&settings);
17+ }
18+ if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() {
19+ voice.apply(&settings);
20+ }
21+ }
22+
23+ pub fn start_mic_test(&self) {
24+ if self.shared.voice.lock().unwrap().is_some() {
25+ return;
26+ }
27+ let settings = self.shared.voice_settings.lock().unwrap().clone();
28+ *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings));
29+ }
30+
31+ pub fn play_chime(&self) {
32+ voice::play_chime(&self.shared.voice_settings.lock().unwrap());
33+ }
34+
35+ pub fn play_notification(&self) {
36+ voice::play_yumush(&self.shared.voice_settings.lock().unwrap());
37+ }
38+
39+ pub fn play_ring(&self) {
40+ voice::play_ring(&self.shared.voice_settings.lock().unwrap());
41+ }
42+
43+ pub fn stop_mic_test(&self) {
44+ self.shared.mic_test.lock().unwrap().take();
45+ }
46+
47+ pub fn voice_level_db(&self) -> Option<f32> {
48+ self.with_voice(Voice::level_db).or_else(|| {
49+ self.shared
50+ .mic_test
51+ .lock()
52+ .unwrap()
53+ .as_ref()
54+ .map(Voice::level_db)
55+ })
56+ }
57+
58+ pub fn voice_sample(&self) -> Option<VoiceSample> {
59+ self.with_voice(Voice::sample)
60+ }
61+
62+ pub fn set_talking(&self, talking: bool) {
63+ self.with_voice(|voice| voice.set_talking(talking));
64+ }
65+
66+ pub fn set_muted(&self, muted: bool) {
67+ self.with_voice(|voice| voice.set_muted(muted));
68+ }
69+
70+ pub fn set_deafened(&self, deafened: bool) {
71+ self.with_voice(|voice| voice.set_deafened(deafened));
72+ }
73+
74+ pub fn levels(&self) -> Levels {
75+ let share = self.shared.share.lock().unwrap();
76+ Levels {
77+ voice: self.with_voice(Voice::levels).unwrap_or_default(),
78+ watching: share
79+ .watching
80+ .iter()
81+ .filter(|((_, kind), _)| *kind == Kind::Screen)
82+ .map(|((user_id, _), watching)| (user_id.clone(), watching.level()))
83+ .collect(),
84+ sharing: share.sharing.get(&Kind::Screen).map(Sharing::level),
85+ }
86+ }
87+}
crates/client/src/network.rsdeleted+0 -2047

Diff too large; view file

@@ -1,2047 +0,0 @@
1-use std::{
2- collections::HashMap,
3- future::Future,
4- path::{Path, PathBuf},
5- sync::{Arc, Mutex},
6- time::Duration,
7-};
8-
9-use common::{
10- constant::{
11- ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_AVATAR_BYTES,
12- MAXIMUM_MESSAGE_LENGTH,
13- },
14- datagram::{Datagram, decode_relay},
15- error::Error,
16- event::Event,
17- model::{
18- Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
19- CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
20- Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
21- ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
22- },
23- network::{
24- RESPONSE_MAX_READ_LENGTH, StreamKind, open_download, receive_decoded, receive_event,
25- send_request, send_stream_kind, send_upload_header,
26- },
27- request::{DownloadRequest, Request, UploadHeader},
28- response::Response,
29- share::{Fps, Kind, Quality, Resolution, Source},
30- validate::{
31- validate_attachment_name, validate_attachment_size, validate_avatar_size,
32- validate_community_name, validate_forward, validate_new_message, validate_password,
33- validate_poll, validate_reason, validate_server_settings, validate_status,
34- validate_username,
35- },
36-};
37-use quinn::Endpoint;
38-#[cfg(debug_assertions)]
39-use quinn::{
40- crypto::rustls::QuicClientConfig,
41- rustls::{
42- self, DigitallySignedStruct, SignatureScheme,
43- client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
44- pki_types::{CertificateDer, ServerName, UnixTime},
45- },
46-};
47-use tokio::sync::{mpsc, oneshot};
48-use tracing::{info, warn};
49-
50-use crate::{
51- ClientConfig,
52- settings::{ShareSettings, VoiceSettings},
53- share::{
54- audio::AudioApp,
55- audio_capture,
56- encode::capabilities,
57- session::{ShareSample, Sharing, Tick, WatchQuality, Watching},
58- },
59- voice::{self, Voice, VoiceSample},
60-};
61-
62-fn device_name() -> String {
63- let host = std::fs::read_to_string("/etc/hostname")
64- .or_else(|_| std::env::var("HOSTNAME"))
65- .or_else(|_| std::env::var("COMPUTERNAME"))
66- .map(|host| host.trim().to_string())
67- .ok()
68- .filter(|host| !host.is_empty())
69- .unwrap_or_else(|| "unknown".to_string());
70-
71- format!("{host} {}", std::env::consts::OS)
72-}
73-
74-const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);
75-const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);
76-
77-const CHANNEL_SIZE: usize = 32;
78-const RECONNECT_DELAY: Duration = Duration::from_secs(1);
79-
80-const SHARE_TICK: Duration = Duration::from_secs(1);
81-
82-type SharedVoice = Arc<Mutex<Option<Voice>>>;
83-type SharedSettings = Arc<Mutex<VoiceSettings>>;
84-type SharedShare = Arc<Mutex<Share>>;
85-type SharedShareSettings = Arc<Mutex<ShareSettings>>;
86-
87-#[derive(Clone, Default)]
88-struct Shared {
89- voice: SharedVoice,
90- mic_test: SharedVoice,
91- voice_settings: SharedSettings,
92- share: SharedShare,
93- share_settings: SharedShareSettings,
94-}
95-
96-fn hang_up(shared: &Shared) {
97- shared.voice.lock().unwrap().take();
98- *shared.share.lock().unwrap() = Share::default();
99-}
100-
101-#[derive(Default)]
102-pub struct Levels {
103- pub voice: Vec<(String, Vec<f32>)>,
104- pub watching: Vec<(String, Vec<f32>)>,
105- pub sharing: Option<Vec<f32>>,
106-}
107-
108-#[derive(Default)]
109-struct Share {
110- sharing: HashMap<Kind, Sharing>,
111- sources: HashMap<Kind, Source>,
112- watching: HashMap<(String, Kind), Watching>,
113-}
114-
115-impl Share {
116- fn event(&mut self, event: &Event) {
117- match event {
118- Event::ShareLayers { kind, layers } => {
119- if let Some(sharing) = self.sharing.get_mut(kind) {
120- sharing.set_layers(layers);
121- }
122- }
123- Event::KeyframeWanted { kind, layer } => {
124- if let Some(sharing) = self.sharing.get(kind) {
125- sharing.keyframe(*layer);
126- }
127- }
128- Event::ShareStopped { user_id, kind, .. } => {
129- self.watching.remove(&(user_id.clone(), *kind));
130- }
131- _ => {}
132- }
133- }
134-
135- fn ticks(&mut self) -> Vec<Request> {
136- self.watching
137- .iter_mut()
138- .flat_map(|((user_id, kind), watching)| {
139- let (user_id, kind) = (user_id.clone(), *kind);
140- watching
141- .tick()
142- .into_iter()
143- .map(|tick| match tick {
144- Tick::Quality(quality) => Request::WatchShare {
145- user_id: user_id.clone(),
146- kind,
147- quality,
148- decode: capabilities().decode.clone(),
149- },
150- Tick::Keyframe => Request::RequestKeyframe {
151- user_id: user_id.clone(),
152- kind,
153- },
154- })
155- .collect::<Vec<_>>()
156- })
157- .collect()
158- }
159-}
160-
161-const CAMERA_TOP: Quality = Quality {
162- resolution: Resolution::P2160,
163- fps: Fps::F60,
164-};
165-
166-#[derive(Debug)]
167-pub enum NetworkEvent {
168- Connected,
169- Disconnected(Error),
170- SessionLost,
171- Pushed(Box<Event>),
172-}
173-
174-#[derive(Debug)]
175-enum Command {
176- Request {
177- request: Request,
178- reply: oneshot::Sender<Result<Response, Error>>,
179- },
180- Upload {
181- community_id: String,
182- path: PathBuf,
183- maximum: Option<u64>,
184- reply: oneshot::Sender<Result<Attachment, Error>>,
185- },
186- Download {
187- attachment_id: String,
188- thumbnail: bool,
189- reply: oneshot::Sender<Result<Vec<u8>, Error>>,
190- },
191- BackupDownload {
192- name: String,
193- path: PathBuf,
194- reply: oneshot::Sender<Result<(), Error>>,
195- },
196- StartShare {
197- kind: Kind,
198- settings: ShareSettings,
199- reply: oneshot::Sender<Result<(), Error>>,
200- },
201- UpdateShare {
202- settings: ShareSettings,
203- reply: oneshot::Sender<Result<(), Error>>,
204- },
205-}
206-
207-#[derive(Clone)]
208-pub struct NetworkHandle {
209- command_sender: mpsc::Sender<Command>,
210- shared: Shared,
211-}
212-
213-macro_rules! expect {
214- ($response:expr, $variant:path) => {
215- match $response {
216- $variant(value) => Ok(value),
217- _ => Err(Error::Server),
218- }
219- };
220-}
221-
222-impl NetworkHandle {
223- async fn ask<T>(
224- &self,
225- build: impl FnOnce(oneshot::Sender<Result<T, Error>>) -> Command,
226- ) -> Result<T, Error> {
227- let (reply, response) = oneshot::channel();
228-
229- self.command_sender
230- .send(build(reply))
231- .await
232- .map_err(|_| Error::ChannelClosed)?;
233-
234- response.await.map_err(|_| Error::ChannelClosed)?
235- }
236-
237- fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> {
238- self.shared.voice.lock().unwrap().as_ref().map(f)
239- }
240-
241- async fn request(&self, request: Request) -> Result<Response, Error> {
242- match self
243- .ask(|reply| Command::Request { request, reply })
244- .await?
245- {
246- Response::Error(error) => Err(error),
247- response => Ok(response),
248- }
249- }
250-
251- async fn sign_in(&self, request: Request) -> Result<(User, String), Error> {
252- let session = match self.request(request).await? {
253- Response::Session { user, token } => (user, token),
254- _ => return Err(Error::Server),
255- };
256- let _ = self
257- .done(Request::SetDevice {
258- name: device_name(),
259- })
260- .await;
261-
262- Ok(session)
263- }
264-
265- pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Error> {
266- expect!(
267- self.request(Request::Sessions {
268- user_id: user_id.to_string(),
269- })
270- .await?,
271- Response::Sessions
272- )
273- }
274-
275- pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Error> {
276- self.done(Request::RevokeSession {
277- user_id: user_id.to_string(),
278- session_id: session_id.to_string(),
279- })
280- .await
281- }
282-
283- pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Error> {
284- validate_username(username)?;
285-
286- expect!(
287- self.request(Request::RenameUser {
288- user_id: user_id.to_string(),
289- username: username.to_string(),
290- })
291- .await?,
292- Response::User
293- )
294- }
295-
296- pub async fn resume(&self, token: &str) -> Result<(User, String), Error> {
297- self.sign_in(Request::Resume {
298- token: token.to_string(),
299- })
300- .await
301- }
302-
303- pub async fn detach(&self) -> Result<(), Error> {
304- self.done(Request::Detach).await
305- }
306-
307- pub async fn register(
308- &self,
309- username: &str,
310- password: &str,
311- invite: Option<&str>,
312- ) -> Result<(User, String), Error> {
313- validate_username(username)?;
314- validate_password(password)?;
315-
316- self.sign_in(Request::Register {
317- username: username.to_string(),
318- password: password.to_string(),
319- invite: invite.map(str::to_string),
320- })
321- .await
322- }
323-
324- pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> {
325- validate_password(password)?;
326-
327- self.sign_in(Request::Login {
328- username: username.to_string(),
329- password: password.to_string(),
330- })
331- .await
332- }
333-
334- pub async fn logout(&self) -> Result<(), Error> {
335- self.done(Request::Logout).await
336- }
337-
338- pub async fn update_user(&self, username: &str) -> Result<User, Error> {
339- validate_username(username)?;
340-
341- expect!(
342- self.request(Request::UpdateUser {
343- username: username.to_string(),
344- })
345- .await?,
346- Response::User
347- )
348- }
349-
350- pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> {
351- expect!(
352- self.request(Request::DeleteUser {
353- user_id: user_id.to_string(),
354- })
355- .await?,
356- Response::User
357- )
358- .map(|_| ())
359- }
360-
361- pub async fn users(&self) -> Result<Vec<Account>, Error> {
362- expect!(self.request(Request::Users).await?, Response::Users)
363- }
364-
365- pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Error> {
366- self.done(Request::SuspendUser {
367- user_id: user_id.to_string(),
368- suspended,
369- })
370- .await
371- }
372-
373- pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Error> {
374- self.done(Request::TimeoutUser {
375- user_id: user_id.to_string(),
376- minutes,
377- })
378- .await
379- }
380-
381- pub async fn ban_user(
382- &self,
383- user_id: &str,
384- reason: Option<&str>,
385- scope: BanScope,
386- ) -> Result<(), Error> {
387- validate_reason(reason)?;
388-
389- self.done(Request::BanUser {
390- user_id: user_id.to_string(),
391- reason: reason.map(str::to_string),
392- scope,
393- })
394- .await
395- }
396-
397- pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Error> {
398- expect!(
399- self.request(Request::ServerBans).await?,
400- Response::ServerBans
401- )
402- }
403-
404- pub async fn remove_server_ban(&self, id: &str) -> Result<(), Error> {
405- self.done(Request::RemoveServerBan { id: id.to_string() })
406- .await
407- }
408-
409- pub async fn create_invite_code(
410- &self,
411- uses: u32,
412- hours: Option<u32>,
413- ) -> Result<InviteCode, Error> {
414- expect!(
415- self.request(Request::CreateInviteCode { uses, hours })
416- .await?,
417- Response::InviteCode
418- )
419- }
420-
421- pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Error> {
422- expect!(
423- self.request(Request::InviteCodes).await?,
424- Response::InviteCodes
425- )
426- }
427-
428- pub async fn delete_invite_code(&self, code: &str) -> Result<(), Error> {
429- self.done(Request::DeleteInviteCode {
430- code: code.to_string(),
431- })
432- .await
433- }
434-
435- pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Error> {
436- self.done(Request::RevokeSessions {
437- user_id: user_id.to_string(),
438- })
439- .await
440- }
441-
442- pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Error> {
443- validate_password(password)?;
444-
445- self.done(Request::ResetPassword {
446- user_id: user_id.to_string(),
447- password: password.to_string(),
448- })
449- .await
450- }
451-
452- pub async fn clear_profile(&self, user_id: &str) -> Result<User, Error> {
453- expect!(
454- self.request(Request::ClearProfile {
455- user_id: user_id.to_string(),
456- })
457- .await?,
458- Response::User
459- )
460- }
461-
462- pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Error> {
463- expect!(
464- self.request(Request::SetRole {
465- user_id: user_id.to_string(),
466- role,
467- })
468- .await?,
469- Response::User
470- )
471- }
472-
473- pub async fn admin_logs(
474- &self,
475- actor_id: Option<String>,
476- target_id: Option<String>,
477- action: Option<String>,
478- after_ms: Option<u64>,
479- before_ms: Option<u64>,
480- ) -> Result<Vec<AdminLogEntry>, Error> {
481- let request = Request::AdminLogs {
482- actor_id,
483- target_id,
484- action,
485- after_ms,
486- before_ms,
487- };
488- expect!(self.request(request).await?, Response::AdminLogs)
489- }
490-
491- pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Error> {
492- expect!(
493- self.request(Request::DailyStats { days }).await?,
494- Response::DailyStats
495- )
496- }
497-
498- pub async fn server_settings(&self) -> Result<ServerSettings, Error> {
499- expect!(
500- self.request(Request::ServerSettings).await?,
501- Response::ServerSettings
502- )
503- }
504-
505- pub async fn update_server_settings(
506- &self,
507- settings: ServerSettings,
508- ) -> Result<ServerSettings, Error> {
509- validate_server_settings(&settings)?;
510-
511- expect!(
512- self.request(Request::UpdateServerSettings { settings })
513- .await?,
514- Response::ServerSettings
515- )
516- }
517-
518- pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Error> {
519- validate_username(username)?;
520- validate_password(password)?;
521-
522- expect!(
523- self.request(Request::CreateUser {
524- username: username.to_string(),
525- password: password.to_string(),
526- })
527- .await?,
528- Response::User
529- )
530- }
531-
532- pub async fn overview(&self) -> Result<Overview, Error> {
533- expect!(self.request(Request::Overview).await?, Response::Overview)
534- }
535-
536- pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Error> {
537- expect!(
538- self.request(Request::AllCommunities).await?,
539- Response::AllCommunities
540- )
541- }
542-
543- pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
544- self.done(Request::TransferOwnership {
545- community_id: community_id.to_string(),
546- user_id: user_id.to_string(),
547- })
548- .await
549- }
550-
551- pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
552- expect!(
553- self.request(Request::ReadUser {
554- user_id: user_id.to_string(),
555- })
556- .await?,
557- Response::User
558- )
559- }
560-
561- pub async fn create_community(&self, name: &str) -> Result<Community, Error> {
562- validate_community_name(name)?;
563-
564- expect!(
565- self.request(Request::CreateCommunity {
566- name: name.to_string(),
567- })
568- .await?,
569- Response::Community
570- )
571- }
572-
573- pub async fn update_community(
574- &self,
575- community_id: &str,
576- name: &str,
577- ) -> Result<Community, Error> {
578- validate_community_name(name)?;
579-
580- expect!(
581- self.request(Request::UpdateCommunity {
582- community_id: community_id.to_string(),
583- name: name.to_string(),
584- })
585- .await?,
586- Response::Community
587- )
588- }
589-
590- pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> {
591- expect!(
592- self.request(Request::DeleteCommunity {
593- community_id: community_id.to_string(),
594- })
595- .await?,
596- Response::Community
597- )
598- .map(|_| ())
599- }
600-
601- pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> {
602- self.done(Request::LeaveCommunity {
603- community_id: community_id.to_string(),
604- })
605- .await
606- }
607-
608- pub async fn communities(&self) -> Result<Vec<Community>, Error> {
609- expect!(
610- self.request(Request::Communities).await?,
611- Response::Communities
612- )
613- }
614-
615- pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Error> {
616- expect!(
617- self.request(Request::Members {
618- community_id: community_id.to_string(),
619- })
620- .await?,
621- Response::Members
622- )
623- }
624-
625- pub async fn kick(
626- &self,
627- community_id: &str,
628- user_id: &str,
629- reason: Option<&str>,
630- ) -> Result<(), Error> {
631- validate_reason(reason)?;
632- self.done(Request::Kick {
633- community_id: community_id.to_string(),
634- user_id: user_id.to_string(),
635- reason: reason.map(str::to_string),
636- })
637- .await
638- }
639-
640- pub async fn ban(
641- &self,
642- community_id: &str,
643- user_id: &str,
644- reason: Option<&str>,
645- ) -> Result<(), Error> {
646- validate_reason(reason)?;
647- self.done(Request::Ban {
648- community_id: community_id.to_string(),
649- user_id: user_id.to_string(),
650- reason: reason.map(str::to_string),
651- })
652- .await
653- }
654-
655- pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
656- self.done(Request::Unban {
657- community_id: community_id.to_string(),
658- user_id: user_id.to_string(),
659- })
660- .await
661- }
662-
663- pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> {
664- expect!(
665- self.request(Request::Bans {
666- community_id: community_id.to_string(),
667- })
668- .await?,
669- Response::Bans
670- )
671- }
672-
673- pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Error> {
674- expect!(
675- self.request(Request::Logs {
676- community_id: community_id.to_string(),
677- })
678- .await?,
679- Response::Logs
680- )
681- }
682-
683- pub async fn set_rank(
684- &self,
685- community_id: &str,
686- user_id: &str,
687- rank: Rank,
688- ) -> Result<(), Error> {
689- self.done(Request::SetRank {
690- community_id: community_id.to_string(),
691- user_id: user_id.to_string(),
692- rank,
693- })
694- .await
695- }
696-
697- pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> {
698- expect!(
699- self.request(Request::DeleteMessage {
700- message_id: message_id.to_string(),
701- })
702- .await?,
703- Response::Message
704- )
705- .map(|_| ())
706- }
707-
708- pub async fn create_message(
709- &self,
710- community_id: &str,
711- body: &str,
712- attachments: Vec<String>,
713- reply_to: Option<String>,
714- ) -> Result<Message, Error> {
715- validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
716-
717- expect!(
718- self.request(Request::CreateMessage {
719- community_id: community_id.to_string(),
720- body: body.to_string(),
721- attachments,
722- reply_to,
723- })
724- .await?,
725- Response::Message
726- )
727- }
728-
729- pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Error> {
730- validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
731-
732- expect!(
733- self.request(Request::UpdateMessage {
734- message_id: message_id.to_string(),
735- body: body.to_string(),
736- })
737- .await?,
738- Response::Message
739- )
740- }
741-
742- pub async fn forward_messages(
743- &self,
744- message_ids: Vec<String>,
745- community_id: &str,
746- snippet: bool,
747- ) -> Result<Vec<Message>, Error> {
748- validate_forward(message_ids.len())?;
749-
750- expect!(
751- self.request(Request::ForwardMessages {
752- message_ids,
753- community_id: community_id.to_string(),
754- snippet,
755- })
756- .await?,
757- Response::Messages
758- )
759- }
760-
761- pub async fn find_user(&self, username: &str) -> Result<User, Error> {
762- expect!(
763- self.request(Request::FindUser {
764- username: username.to_string(),
765- })
766- .await?,
767- Response::User
768- )
769- }
770-
771- pub async fn open_notes(&self) -> Result<Community, Error> {
772- expect!(self.request(Request::OpenNotes).await?, Response::Community)
773- }
774-
775- pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> {
776- expect!(
777- self.request(Request::OpenDirect {
778- user_id: user_id.to_string(),
779- })
780- .await?,
781- Response::Community
782- )
783- }
784-
785- pub async fn friends(&self) -> Result<Friends, Error> {
786- expect!(self.request(Request::Friends).await?, Response::Friends)
787- }
788-
789- pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Error> {
790- expect!(
791- self.request(Request::ReadPresences).await?,
792- Response::Presences
793- )
794- }
795-
796- pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> {
797- self.done(Request::UpdatePresence { presence }).await
798- }
799-
800- pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> {
801- self.done(Request::AddFriend {
802- user_id: user_id.to_string(),
803- })
804- .await
805- }
806-
807- pub async fn accept_friend(&self, user_id: &str) -> Result<(), Error> {
808- self.done(Request::AcceptFriend {
809- user_id: user_id.to_string(),
810- })
811- .await
812- }
813-
814- pub async fn remove_friend(&self, user_id: &str) -> Result<(), Error> {
815- self.done(Request::RemoveFriend {
816- user_id: user_id.to_string(),
817- })
818- .await
819- }
820-
821- pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
822- self.done(Request::Invite {
823- community_id: community_id.to_string(),
824- user_id: user_id.to_string(),
825- })
826- .await
827- }
828-
829- pub async fn invitations(&self) -> Result<Vec<Invitation>, Error> {
830- expect!(
831- self.request(Request::Invitations).await?,
832- Response::Invitations
833- )
834- }
835-
836- pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Error> {
837- expect!(
838- self.request(Request::AcceptInvitation {
839- community_id: community_id.to_string(),
840- })
841- .await?,
842- Response::Community
843- )
844- }
845-
846- pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> {
847- self.done(Request::DeclineInvitation {
848- community_id: community_id.to_string(),
849- })
850- .await
851- }
852-
853- pub async fn decline_call(&self, community_id: &str) -> Result<(), Error> {
854- self.done(Request::DeclineCall {
855- community_id: community_id.to_string(),
856- })
857- .await
858- }
859-
860- pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Error> {
861- self.done(Request::React {
862- message_id: message_id.to_string(),
863- emoji: emoji.to_string(),
864- })
865- .await
866- }
867-
868- pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Error> {
869- self.done(Request::Pin {
870- message_id: message_id.to_string(),
871- pinned,
872- })
873- .await
874- }
875-
876- pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Error> {
877- expect!(
878- self.request(Request::Pins {
879- community_id: community_id.to_string(),
880- })
881- .await?,
882- Response::Messages
883- )
884- }
885-
886- pub async fn create_poll(
887- &self,
888- community_id: &str,
889- question: &str,
890- options: Vec<String>,
891- multiple: bool,
892- ) -> Result<Message, Error> {
893- validate_poll(question, &options)?;
894-
895- expect!(
896- self.request(Request::CreatePoll {
897- community_id: community_id.to_string(),
898- question: question.to_string(),
899- options,
900- multiple,
901- })
902- .await?,
903- Response::Message
904- )
905- }
906-
907- pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Error> {
908- self.done(Request::Vote {
909- message_id: message_id.to_string(),
910- positions,
911- })
912- .await
913- }
914-
915- pub async fn close_poll(&self, message_id: &str) -> Result<(), Error> {
916- self.done(Request::ClosePoll {
917- message_id: message_id.to_string(),
918- })
919- .await
920- }
921-
922- pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Error> {
923- validate_reason(Some(reason))?;
924-
925- self.done(Request::ReportMessage {
926- message_id: message_id.to_string(),
927- reason: reason.to_string(),
928- })
929- .await
930- }
931-
932- pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Error> {
933- validate_reason(Some(reason))?;
934-
935- self.done(Request::ReportUser {
936- user_id: user_id.to_string(),
937- reason: reason.to_string(),
938- })
939- .await
940- }
941-
942- pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Error> {
943- expect!(
944- self.request(Request::Reports { status }).await?,
945- Response::Reports
946- )
947- }
948-
949- pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Error> {
950- self.done(Request::HandleReport {
951- report_id: report_id.to_string(),
952- status,
953- })
954- .await
955- }
956-
957- pub async fn search_messages(
958- &self,
959- text: Option<String>,
960- user_id: Option<String>,
961- community_id: Option<String>,
962- after_ms: Option<u64>,
963- before_ms: Option<u64>,
964- ) -> Result<Vec<MessageHit>, Error> {
965- expect!(
966- self.request(Request::SearchMessages {
967- text,
968- user_id,
969- community_id,
970- after_ms,
971- before_ms,
972- })
973- .await?,
974- Response::MessageHits
975- )
976- }
977-
978- pub async fn search_community(
979- &self,
980- community_id: String,
981- text: String,
982- ) -> Result<Vec<MessageHit>, Error> {
983- expect!(
984- self.request(Request::SearchCommunity { community_id, text })
985- .await?,
986- Response::MessageHits
987- )
988- }
989-
990- pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> {
991- match self.request(Request::StorageUsage).await? {
992- Response::StorageUsage { users, communities } => Ok((users, communities)),
993- _ => Err(Error::Server),
994- }
995- }
996-
997- pub async fn create_backup(&self) -> Result<BackupInfo, Error> {
998- expect!(self.request(Request::CreateBackup).await?, Response::Backup)
999- }
1000-
1001- pub async fn backups(&self) -> Result<Vec<BackupInfo>, Error> {
1002- expect!(self.request(Request::Backups).await?, Response::Backups)
1003- }
1004-
1005- pub async fn delete_backup(&self, name: &str) -> Result<(), Error> {
1006- self.done(Request::DeleteBackup {
1007- name: name.to_string(),
1008- })
1009- .await
1010- }
1011-
1012- pub async fn attachments(
1013- &self,
1014- user_id: Option<String>,
1015- community_id: Option<String>,
1016- ) -> Result<Vec<AttachmentInfo>, Error> {
1017- expect!(
1018- self.request(Request::AllAttachments {
1019- user_id,
1020- community_id,
1021- })
1022- .await?,
1023- Response::AttachmentInfos
1024- )
1025- }
1026-
1027- pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Error> {
1028- self.done(Request::DeleteAttachment {
1029- attachment_id: attachment_id.to_string(),
1030- })
1031- .await
1032- }
1033-
1034- pub async fn purge_user(&self, user_id: &str) -> Result<(), Error> {
1035- self.done(Request::PurgeUser {
1036- user_id: user_id.to_string(),
1037- })
1038- .await
1039- }
1040-
1041- async fn done(&self, request: Request) -> Result<(), Error> {
1042- match self.request(request).await? {
1043- Response::Done => Ok(()),
1044- _ => Err(Error::Server),
1045- }
1046- }
1047-
1048- pub async fn upload_attachment(
1049- &self,
1050- community_id: &str,
1051- path: PathBuf,
1052- maximum: Option<u64>,
1053- ) -> Result<Attachment, Error> {
1054- self.ask(|reply| Command::Upload {
1055- community_id: community_id.to_string(),
1056- path,
1057- maximum,
1058- reply,
1059- })
1060- .await
1061- }
1062-
1063- pub async fn download_attachment(
1064- &self,
1065- attachment_id: &str,
1066- thumbnail: bool,
1067- ) -> Result<Vec<u8>, Error> {
1068- self.ask(|reply| Command::Download {
1069- attachment_id: attachment_id.to_string(),
1070- thumbnail,
1071- reply,
1072- })
1073- .await
1074- }
1075-
1076- pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> {
1077- self.ask(|reply| Command::BackupDownload {
1078- name: name.to_string(),
1079- path,
1080- reply,
1081- })
1082- .await
1083- }
1084-
1085- pub async fn read_messages(
1086- &self,
1087- community_id: &str,
1088- before: Option<&str>,
1089- ) -> Result<Vec<Message>, Error> {
1090- expect!(
1091- self.request(Request::ReadMessages {
1092- community_id: community_id.to_string(),
1093- before: before.map(str::to_string),
1094- })
1095- .await?,
1096- Response::Messages
1097- )
1098- }
1099-
1100- pub async fn unreads(&self) -> Result<Vec<Unread>, Error> {
1101- expect!(self.request(Request::Unreads).await?, Response::Unreads)
1102- }
1103-
1104- pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> {
1105- self.done(Request::MarkRead {
1106- community_id: community_id.to_string(),
1107- message_id: message_id.to_string(),
1108- })
1109- .await
1110- }
1111-
1112- pub async fn update_status(&self, status: &str) -> Result<User, Error> {
1113- validate_status(status)?;
1114-
1115- expect!(
1116- self.request(Request::UpdateStatus {
1117- status: status.to_string(),
1118- })
1119- .await?,
1120- Response::User
1121- )
1122- }
1123-
1124- pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Error> {
1125- validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1126-
1127- expect!(
1128- self.request(Request::UpdateAvatar { image: bytes }).await?,
1129- Response::User
1130- )
1131- }
1132-
1133- pub async fn update_community_avatar(
1134- &self,
1135- community_id: &str,
1136- image: Option<Vec<u8>>,
1137- ) -> Result<Community, Error> {
1138- if let Some(bytes) = &image {
1139- validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1140- }
1141-
1142- expect!(
1143- self.request(Request::UpdateCommunityAvatar {
1144- community_id: community_id.to_string(),
1145- image,
1146- })
1147- .await?,
1148- Response::Community
1149- )
1150- }
1151-
1152- pub async fn remove_avatar(&self) -> Result<User, Error> {
1153- expect!(self.request(Request::RemoveAvatar).await?, Response::User)
1154- }
1155-
1156- pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Error> {
1157- expect!(
1158- self.request(Request::ReadAvatar {
1159- avatar_id: avatar_id.to_string(),
1160- })
1161- .await?,
1162- Response::Avatar
1163- )
1164- }
1165-
1166- pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Error> {
1167- expect!(
1168- self.request(Request::JoinVoice {
1169- community_id: community_id.to_string(),
1170- })
1171- .await?,
1172- Response::Voice
1173- )
1174- }
1175-
1176- pub async fn typing(&self, community_id: &str) -> Result<(), Error> {
1177- self.done(Request::Typing {
1178- community_id: community_id.to_string(),
1179- })
1180- .await
1181- }
1182-
1183- pub async fn leave_voice(&self) -> Result<(), Error> {
1184- self.done(Request::LeaveVoice).await
1185- }
1186-
1187- pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {
1188- expect!(
1189- self.request(Request::ReadCommunity {
1190- community_id: community_id.to_string(),
1191- })
1192- .await?,
1193- Response::Community
1194- )
1195- }
1196-
1197- pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> {
1198- expect!(
1199- self.request(Request::VoiceParticipants {
1200- community_id: community_id.to_string(),
1201- })
1202- .await?,
1203- Response::Voice
1204- )
1205- }
1206-
1207- pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Error> {
1208- expect!(
1209- self.request(Request::VoiceRooms).await?,
1210- Response::VoiceRooms
1211- )
1212- }
1213-
1214- pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> {
1215- self.done(Request::SetGhost { enabled }).await
1216- }
1217-
1218- pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Error> {
1219- self.done(Request::KickFromVoice {
1220- user_id: user_id.to_string(),
1221- })
1222- .await
1223- }
1224-
1225- pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Error> {
1226- self.done(Request::ServerMute {
1227- user_id: user_id.to_string(),
1228- muted,
1229- })
1230- .await
1231- }
1232-
1233- pub async fn set_community_voice(
1234- &self,
1235- community_id: &str,
1236- enabled: bool,
1237- ) -> Result<Community, Error> {
1238- expect!(
1239- self.request(Request::SetCommunityVoice {
1240- community_id: community_id.to_string(),
1241- enabled,
1242- })
1243- .await?,
1244- Response::Community
1245- )
1246- }
1247-
1248- pub fn set_voice_settings(&self, settings: VoiceSettings) {
1249- *self.shared.voice_settings.lock().unwrap() = settings.clone();
1250-
1251- if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() {
1252- voice.apply(&settings);
1253- }
1254- if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() {
1255- voice.apply(&settings);
1256- }
1257- }
1258-
1259- pub fn start_mic_test(&self) {
1260- if self.shared.voice.lock().unwrap().is_some() {
1261- return;
1262- }
1263- let settings = self.shared.voice_settings.lock().unwrap().clone();
1264- *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings));
1265- }
1266-
1267- pub fn play_chime(&self) {
1268- voice::play_chime(&self.shared.voice_settings.lock().unwrap());
1269- }
1270-
1271- pub fn play_notification(&self) {
1272- voice::play_yumush(&self.shared.voice_settings.lock().unwrap());
1273- }
1274-
1275- pub fn play_ring(&self) {
1276- voice::play_ring(&self.shared.voice_settings.lock().unwrap());
1277- }
1278-
1279- pub fn stop_mic_test(&self) {
1280- self.shared.mic_test.lock().unwrap().take();
1281- }
1282-
1283- pub fn voice_level_db(&self) -> Option<f32> {
1284- self.with_voice(Voice::level_db).or_else(|| {
1285- self.shared
1286- .mic_test
1287- .lock()
1288- .unwrap()
1289- .as_ref()
1290- .map(Voice::level_db)
1291- })
1292- }
1293-
1294- pub fn voice_sample(&self) -> Option<VoiceSample> {
1295- self.with_voice(Voice::sample)
1296- }
1297-
1298- pub fn set_talking(&self, talking: bool) {
1299- self.with_voice(|voice| voice.set_talking(talking));
1300- }
1301-
1302- pub fn set_muted(&self, muted: bool) {
1303- self.with_voice(|voice| voice.set_muted(muted));
1304- }
1305-
1306- pub fn set_deafened(&self, deafened: bool) {
1307- self.with_voice(|voice| voice.set_deafened(deafened));
1308- }
1309-
1310- pub fn levels(&self) -> Levels {
1311- let share = self.shared.share.lock().unwrap();
1312- Levels {
1313- voice: self.with_voice(Voice::levels).unwrap_or_default(),
1314- watching: share
1315- .watching
1316- .iter()
1317- .filter(|((_, kind), _)| *kind == Kind::Screen)
1318- .map(|((user_id, _), watching)| (user_id.clone(), watching.level()))
1319- .collect(),
1320- sharing: share.sharing.get(&Kind::Screen).map(Sharing::level),
1321- }
1322- }
1323-
1324- pub async fn start_share(&self) -> Result<(), Error> {
1325- self.start(Kind::Screen).await
1326- }
1327-
1328- pub async fn start_camera(&self) -> Result<(), Error> {
1329- self.start(Kind::Camera).await
1330- }
1331-
1332- async fn start(&self, kind: Kind) -> Result<(), Error> {
1333- let settings = self.shared.share_settings.lock().unwrap().clone();
1334- self.ask(|reply| Command::StartShare {
1335- kind,
1336- settings,
1337- reply,
1338- })
1339- .await
1340- }
1341-
1342- pub async fn update_share(&self) -> Result<(), Error> {
1343- let settings = self.shared.share_settings.lock().unwrap().clone();
1344- self.ask(|reply| Command::UpdateShare { settings, reply })
1345- .await
1346- }
1347-
1348- pub async fn stop_share(&self) -> Result<(), Error> {
1349- self.stop(Kind::Screen).await
1350- }
1351-
1352- pub async fn stop_camera(&self) -> Result<(), Error> {
1353- self.stop(Kind::Camera).await
1354- }
1355-
1356- async fn stop(&self, kind: Kind) -> Result<(), Error> {
1357- let result = self.done(Request::StopShare { kind }).await;
1358- let mut share = self.shared.share.lock().unwrap();
1359- share.sharing.remove(&kind);
1360- share.sources.remove(&kind);
1361- result
1362- }
1363-
1364- pub fn sharing(&self) -> bool {
1365- self.shared
1366- .share
1367- .lock()
1368- .unwrap()
1369- .sharing
1370- .contains_key(&Kind::Screen)
1371- }
1372-
1373- pub fn camera_on(&self) -> bool {
1374- self.shared
1375- .share
1376- .lock()
1377- .unwrap()
1378- .sharing
1379- .contains_key(&Kind::Camera)
1380- }
1381-
1382- pub fn share_source(&self) -> Option<Source> {
1383- self.shared
1384- .share
1385- .lock()
1386- .unwrap()
1387- .sources
1388- .get(&Kind::Screen)
1389- .cloned()
1390- }
1391-
1392- pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Error> {
1393- expect!(
1394- self.request(Request::Shares {
1395- community_id: community_id.to_string(),
1396- })
1397- .await?,
1398- Response::Shares
1399- )
1400- }
1401-
1402- pub async fn watch_share(
1403- &self,
1404- user_id: &str,
1405- kind: Kind,
1406- watch: WatchQuality,
1407- ) -> Result<(), Error> {
1408- let volume = self.shared.share_settings.lock().unwrap().volume;
1409- let choice = self.shared.voice_settings.lock().unwrap().choice.clone();
1410- let key = (user_id.to_string(), kind);
1411- let watching = Watching::new(kind, watch, volume, choice);
1412- let quality = watching.wanted();
1413- self.shared
1414- .share
1415- .lock()
1416- .unwrap()
1417- .watching
1418- .insert(key.clone(), watching);
1419-
1420- let result = self
1421- .done(Request::WatchShare {
1422- user_id: key.0.clone(),
1423- kind,
1424- quality,
1425- decode: capabilities().decode.clone(),
1426- })
1427- .await;
1428- if result.is_err() {
1429- self.shared.share.lock().unwrap().watching.remove(&key);
1430- }
1431- result
1432- }
1433-
1434- pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Error> {
1435- self.shared
1436- .share
1437- .lock()
1438- .unwrap()
1439- .watching
1440- .remove(&(user_id.to_string(), kind));
1441- self.done(Request::UnwatchShare {
1442- user_id: user_id.to_string(),
1443- kind,
1444- })
1445- .await
1446- }
1447-
1448- pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) {
1449- if let Some(watching) = self
1450- .shared
1451- .share
1452- .lock()
1453- .unwrap()
1454- .watching
1455- .get_mut(&(user_id.to_string(), kind))
1456- {
1457- watching.set_quality(quality);
1458- }
1459- }
1460-
1461- pub fn share_sample(&self) -> ShareSample {
1462- let mut share = self.shared.share.lock().unwrap();
1463- ShareSample {
1464- sending: share
1465- .sharing
1466- .get(&Kind::Screen)
1467- .map(Sharing::stats)
1468- .unwrap_or_default(),
1469- watching: share
1470- .watching
1471- .iter_mut()
1472- .filter(|((_, kind), _)| *kind == Kind::Screen)
1473- .map(|((user_id, _), watching)| (user_id.clone(), watching.stats()))
1474- .collect(),
1475- }
1476- }
1477-
1478- pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> {
1479- self.shared
1480- .share
1481- .lock()
1482- .unwrap()
1483- .watching
1484- .get(&(user_id.to_string(), kind))?
1485- .frame()
1486- }
1487-
1488- pub fn set_share_settings(&self, settings: ShareSettings) -> bool {
1489- let changed = self.sharing()
1490- && self
1491- .shared
1492- .share_settings
1493- .lock()
1494- .unwrap()
1495- .encoding_differs(&settings);
1496- *self.shared.share_settings.lock().unwrap() = settings.clone();
1497- for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() {
1498- if *kind == Kind::Screen {
1499- watching.set_volume(settings.volume);
1500- watching.set_quality(settings.watch);
1501- }
1502- }
1503- changed
1504- }
1505-
1506- pub fn audio_apps(&self) -> Vec<AudioApp> {
1507- audio_capture::apps()
1508- }
1509-}
1510-
1511-pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {
1512- let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);
1513- let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);
1514- let shared = Shared::default();
1515-
1516- std::thread::Builder::new()
1517- .name("network".to_string())
1518- .spawn({
1519- let shared = shared.clone();
1520- move || {
1521- tokio::runtime::Builder::new_current_thread()
1522- .enable_all()
1523- .build()
1524- .expect("network runtime")
1525- .block_on(actor(client_config, command_receiver, event_sender, shared));
1526- }
1527- })
1528- .expect("network thread");
1529-
1530- (
1531- NetworkHandle {
1532- command_sender,
1533- shared,
1534- },
1535- event_receiver,
1536- )
1537-}
1538-
1539-async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> {
1540- let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?;
1541- endpoint.set_default_client_config(config()?);
1542-
1543- let connection = endpoint
1544- .connect(
1545- client_config.server_address.parse()?,
1546- &client_config.server_name,
1547- )?
1548- .await?;
1549-
1550- Ok(connection)
1551-}
1552-
1553-fn network_error(error: impl std::fmt::Display) -> Error {
1554- Error::Network(error.to_string())
1555-}
1556-
1557-#[cfg(debug_assertions)]
1558-#[derive(Debug)]
1559-struct AcceptAnyCertificate {
1560- provider: Arc<rustls::crypto::CryptoProvider>,
1561-}
1562-
1563-#[cfg(debug_assertions)]
1564-impl ServerCertVerifier for AcceptAnyCertificate {
1565- fn verify_server_cert(
1566- &self,
1567- _end_entity: &CertificateDer<'_>,
1568- _intermediates: &[CertificateDer<'_>],
1569- _server_name: &ServerName<'_>,
1570- _ocsp_response: &[u8],
1571- _now: UnixTime,
1572- ) -> Result<ServerCertVerified, rustls::Error> {
1573- Ok(ServerCertVerified::assertion())
1574- }
1575-
1576- fn verify_tls12_signature(
1577- &self,
1578- message: &[u8],
1579- cert: &CertificateDer<'_>,
1580- dss: &DigitallySignedStruct,
1581- ) -> Result<HandshakeSignatureValid, rustls::Error> {
1582- rustls::crypto::verify_tls12_signature(
1583- message,
1584- cert,
1585- dss,
1586- &self.provider.signature_verification_algorithms,
1587- )
1588- }
1589-
1590- fn verify_tls13_signature(
1591- &self,
1592- message: &[u8],
1593- cert: &CertificateDer<'_>,
1594- dss: &DigitallySignedStruct,
1595- ) -> Result<HandshakeSignatureValid, rustls::Error> {
1596- rustls::crypto::verify_tls13_signature(
1597- message,
1598- cert,
1599- dss,
1600- &self.provider.signature_verification_algorithms,
1601- )
1602- }
1603-
1604- fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1605- self.provider
1606- .signature_verification_algorithms
1607- .supported_schemes()
1608- }
1609-}
1610-
1611-#[cfg(debug_assertions)]
1612-fn accept_any_client_config() -> Result<quinn::ClientConfig, Error> {
1613- let provider = Arc::new(rustls::crypto::ring::default_provider());
1614- let tls = rustls::ClientConfig::builder_with_provider(provider.clone())
1615- .with_protocol_versions(&[&rustls::version::TLS13])
1616- .map_err(network_error)?
1617- .dangerous()
1618- .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider }))
1619- .with_no_client_auth();
1620-
1621- let crypto = QuicClientConfig::try_from(tls).map_err(network_error)?;
1622-
1623- Ok(quinn::ClientConfig::new(Arc::new(crypto)))
1624-}
1625-
1626-fn config() -> Result<quinn::ClientConfig, Error> {
1627- #[cfg(debug_assertions)]
1628- let mut client_config = accept_any_client_config()?;
1629-
1630- #[cfg(not(debug_assertions))]
1631- let mut client_config =
1632- quinn::ClientConfig::try_with_platform_verifier().map_err(network_error)?;
1633-
1634- let mut transport_config = quinn::TransportConfig::default();
1635- transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));
1636- transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap()));
1637-
1638- client_config.transport_config(Arc::new(transport_config));
1639-
1640- Ok(client_config)
1641-}
1642-
1643-async fn send(connection: &quinn::Connection, request: &Request) -> Result<Response, Error> {
1644- let (send_stream, receive_stream) = connection.open_bi().await?;
1645- send_request(request, send_stream, receive_stream).await
1646-}
1647-
1648-async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Error> {
1649- match send(connection, &request).await? {
1650- Response::Done => Ok(()),
1651- Response::Error(error) => Err(error),
1652- _ => Err(Error::Server),
1653- }
1654-}
1655-
1656-async fn send_body(
1657- send_stream: &mut quinn::SendStream,
1658- file: &mut tokio::fs::File,
1659-) -> Result<(), Error> {
1660- use tokio::io::AsyncReadExt;
1661-
1662- let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
1663- loop {
1664- let read = file.read(&mut buffer).await?;
1665- if read == 0 {
1666- return Ok(());
1667- }
1668-
1669- send_stream.write_all(&buffer[..read]).await?;
1670- }
1671-}
1672-
1673-async fn upload(
1674- connection: &quinn::Connection,
1675- community_id: &str,
1676- path: &Path,
1677- maximum: Option<u64>,
1678-) -> Result<Attachment, Error> {
1679- let name = path
1680- .file_name()
1681- .map(|name| name.to_string_lossy().into_owned())
1682- .unwrap_or_default();
1683- validate_attachment_name(&name)?;
1684-
1685- let mut file = tokio::fs::File::open(path).await?;
1686- let size = file.metadata().await?.len();
1687- if let Some(maximum) = maximum {
1688- validate_attachment_size(size, maximum)?;
1689- }
1690-
1691- let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
1692- send_stream_kind(StreamKind::Upload, &mut send_stream).await?;
1693- let header = UploadHeader {
1694- community_id: community_id.to_string(),
1695- name,
1696- size,
1697- };
1698- send_upload_header(&header, &mut send_stream).await?;
1699-
1700- let sent = match send_body(&mut send_stream, &mut file).await {
1701- Ok(()) => send_stream.finish().map_err(Error::from),
1702- Err(error) => Err(error),
1703- };
1704- let response = receive_decoded::<Response>(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await;
1705-
1706- match (sent, response) {
1707- (_, Ok(Response::Attachment(attachment))) => Ok(attachment),
1708- (_, Ok(Response::Error(error))) => Err(error),
1709- (Err(error), _) | (_, Err(error)) => Err(error),
1710- (Ok(()), Ok(_)) => Err(Error::Server),
1711- }
1712-}
1713-
1714-async fn backup_download(
1715- connection: &quinn::Connection,
1716- name: &str,
1717- path: &Path,
1718-) -> Result<(), Error> {
1719- let request = Request::DownloadBackup {
1720- name: name.to_string(),
1721- };
1722- let (mut receive_stream, length) =
1723- open_download(connection, StreamKind::Backup, &request).await?;
1724-
1725- let mut file = tokio::fs::File::create(path).await?;
1726- let copied = tokio::io::copy(&mut receive_stream, &mut file).await?;
1727- if copied != length {
1728- return Err(Error::Network(format!(
1729- "backup truncated ({copied} < {length})"
1730- )));
1731- }
1732-
1733- Ok(())
1734-}
1735-
1736-async fn download(
1737- connection: &quinn::Connection,
1738- attachment_id: &str,
1739- thumbnail: bool,
1740-) -> Result<Vec<u8>, Error> {
1741- let request = DownloadRequest {
1742- attachment_id: attachment_id.to_string(),
1743- thumbnail,
1744- };
1745- let (mut receive_stream, length) =
1746- open_download(connection, StreamKind::Download, &request).await?;
1747-
1748- if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES {
1749- return Err(Error::ReadBoundExceed {
1750- actual: length as usize,
1751- maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize,
1752- });
1753- }
1754-
1755- let mut bytes = vec![0u8; length as usize];
1756- receive_stream.read_exact(&mut bytes).await?;
1757-
1758- Ok(bytes)
1759-}
1760-
1761-fn answer<T: Send + 'static>(
1762- reply: oneshot::Sender<Result<T, Error>>,
1763- work: impl Future<Output = Result<T, Error>> + Send + 'static,
1764-) {
1765- tokio::spawn(async move {
1766- let _ = reply.send(work.await);
1767- });
1768-}
1769-
1770-async fn actor(
1771- client_config: ClientConfig,
1772- mut command_receiver: mpsc::Receiver<Command>,
1773- event_sender: mpsc::Sender<NetworkEvent>,
1774- shared: Shared,
1775-) {
1776- let mut token: Option<String> = None;
1777- 'session: loop {
1778- let connection = loop {
1779- match connect(&client_config).await {
1780- Ok(connection) => break connection,
1781- Err(error) => {
1782- warn!("connect failed: {error}");
1783-
1784- if event_sender
1785- .send(NetworkEvent::Disconnected(error))
1786- .await
1787- .is_err()
1788- {
1789- return;
1790- }
1791-
1792- tokio::time::sleep(RECONNECT_DELAY).await;
1793- }
1794- };
1795- };
1796-
1797- if let Some(stored) = token.clone() {
1798- let request = Request::Resume { token: stored };
1799- match send(&connection, &request).await {
1800- Ok(Response::Session { token: resumed, .. }) => token = Some(resumed),
1801- Err(error) => {
1802- warn!("session resume failed: {error}");
1803- tokio::time::sleep(RECONNECT_DELAY).await;
1804- continue 'session;
1805- }
1806- Ok(_) => {
1807- warn!("session resume rejected");
1808- token = None;
1809-
1810- if event_sender.send(NetworkEvent::SessionLost).await.is_err() {
1811- return;
1812- }
1813- }
1814- }
1815- }
1816-
1817- info!("connected");
1818- if event_sender.send(NetworkEvent::Connected).await.is_err() {
1819- return;
1820- }
1821-
1822- tokio::spawn(event_receive_loop(
1823- connection.clone(),
1824- event_sender.clone(),
1825- shared.share.clone(),
1826- ));
1827- tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone()));
1828- let mut ticker = tokio::time::interval(SHARE_TICK);
1829-
1830- loop {
1831- tokio::select! {
1832- command = command_receiver.recv() => match command {
1833- Some(Command::Request { request, reply }) => match &request {
1834- Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => {
1835- hang_up(&shared);
1836-
1837- let response = send(&connection, &request).await;
1838- if let Ok(Response::Session { token: session_token, .. }) = &response {
1839- token = Some(session_token.clone());
1840- }
1841- let _ = reply.send(response);
1842- }
1843- Request::Logout | Request::Detach => {
1844- token = None;
1845- hang_up(&shared);
1846-
1847- let connection = connection.clone();
1848- answer(reply, async move { send(&connection, &request).await });
1849- }
1850- Request::JoinVoice { .. } => {
1851- let shared = shared.clone();
1852- let settings = shared.voice_settings.lock().unwrap().clone();
1853- let connection = connection.clone();
1854-
1855- answer(reply, async move {
1856- let response = send(&connection, &request).await;
1857- if let Ok(Response::Voice(_)) = &response {
1858- shared.mic_test.lock().unwrap().take();
1859- *shared.voice.lock().unwrap() =
1860- Some(voice::start(Some(connection), &settings));
1861- }
1862- response
1863- });
1864- }
1865- Request::LeaveVoice => {
1866- hang_up(&shared);
1867-
1868- let connection = connection.clone();
1869- answer(reply, async move { send(&connection, &request).await });
1870- }
1871- _ => {
1872- let connection = connection.clone();
1873- answer(reply, async move { send(&connection, &request).await });
1874- }
1875- },
1876- Some(Command::StartShare { kind, settings, reply }) => {
1877- let connection = connection.clone();
1878- let share = shared.share.clone();
1879-
1880- answer(reply, async move { start_share(&connection, &share, kind, &settings).await });
1881- }
1882- Some(Command::UpdateShare { settings, reply }) => {
1883- let connection = connection.clone();
1884- let share = shared.share.clone();
1885-
1886- answer(reply, async move { update_share(&connection, &share, &settings).await });
1887- }
1888- Some(Command::Upload { community_id, path, maximum, reply }) => {
1889- let connection = connection.clone();
1890-
1891- answer(reply, async move { upload(&connection, &community_id, &path, maximum).await });
1892- }
1893- Some(Command::Download { attachment_id, thumbnail, reply }) => {
1894- let connection = connection.clone();
1895-
1896- answer(reply, async move { download(&connection, &attachment_id, thumbnail).await });
1897- }
1898- Some(Command::BackupDownload { name, path, reply }) => {
1899- let connection = connection.clone();
1900-
1901- answer(reply, async move { backup_download(&connection, &name, &path).await });
1902- }
1903- None => break 'session,
1904- },
1905-
1906- _ = ticker.tick() => {
1907- let requests = shared.share.lock().unwrap().ticks();
1908- for request in requests {
1909- let connection = connection.clone();
1910- tokio::spawn(async move {
1911- let _ = send(&connection, &request).await;
1912- });
1913- }
1914- }
1915-
1916- error = connection.closed() => {
1917- warn!("disconnected: {error}");
1918- hang_up(&shared);
1919-
1920- if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() {
1921- return;
1922- }
1923-
1924- break;
1925- }
1926- }
1927- }
1928- }
1929-}
1930-
1931-async fn start_share(
1932- connection: &quinn::Connection,
1933- share: &SharedShare,
1934- kind: Kind,
1935- settings: &ShareSettings,
1936-) -> Result<(), Error> {
1937- let top = match kind {
1938- Kind::Screen => settings.top,
1939- Kind::Camera => CAMERA_TOP,
1940- };
1941- let (sharing, source) = Sharing::start(
1942- connection.clone(),
1943- kind,
1944- top,
1945- settings.encode(),
1946- settings.audio_mode(),
1947- )
1948- .await
1949- .map_err(Error::Device)?;
1950- {
1951- let mut share = share.lock().unwrap();
1952- share.sharing.insert(kind, sharing);
1953- share.sources.insert(kind, source.clone());
1954- }
1955-
1956- let result = done(connection, Request::StartShare { kind, source }).await;
1957- if result.is_err() {
1958- let mut share = share.lock().unwrap();
1959- share.sharing.remove(&kind);
1960- share.sources.remove(&kind);
1961- }
1962- result
1963-}
1964-
1965-async fn update_share(
1966- connection: &quinn::Connection,
1967- share: &SharedShare,
1968- settings: &ShareSettings,
1969-) -> Result<(), Error> {
1970- let source = {
1971- let mut share = share.lock().unwrap();
1972- let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else {
1973- return Ok(());
1974- };
1975- sharing
1976- .update(
1977- connection,
1978- settings.top,
1979- settings.encode(),
1980- settings.audio_mode(),
1981- )
1982- .map_err(Error::Device)?
1983- };
1984- share
1985- .lock()
1986- .unwrap()
1987- .sources
1988- .insert(Kind::Screen, source.clone());
1989-
1990- done(
1991- connection,
1992- Request::StartShare {
1993- kind: Kind::Screen,
1994- source,
1995- },
1996- )
1997- .await
1998-}
1999-
2000-async fn event_receive_loop(
crates/client/src/share/encode.rsmodified+13 -8
@@ -64,8 +64,8 @@ struct Settings {
6464 }
6565
6666 enum Backend {
67- Hardware(hardware::Encoder),
68- H264(ec_h264::Encoder),
67+ Hardware(Box<hardware::Encoder>),
68+ H264(Box<ec_h264::Encoder>),
6969 }
7070
7171 impl Backend {
@@ -75,10 +75,12 @@ impl Backend {
7575 } else {
7676 None
7777 };
78- hardware.map(Self::Hardware).or_else(|| {
79- tracing::warn!(codec = ?settings.codec, "share encode falls back to software");
80- Self::software(settings)
81- })
78+ hardware
79+ .map(|encoder| Self::Hardware(Box::new(encoder)))
80+ .or_else(|| {
81+ tracing::warn!(codec = ?settings.codec, "share encode falls back to software");
82+ Self::software(settings)
83+ })
8284 }
8385
8486 fn software(settings: &Settings) -> Option<Self> {
@@ -90,7 +92,7 @@ impl Backend {
9092 config.bitrate = settings.bitrate;
9193 config.gop_size = settings.gop;
9294 config.threads = 4;
93- report(ec_h264::Encoder::new(config)).map(Self::H264)
95+ report(ec_h264::Encoder::new(config)).map(|encoder| Self::H264(Box::new(encoder)))
9496 }
9597 Codec::H265 | Codec::Av1 | Codec::Vp8 | Codec::Vp9 => None,
9698 }
@@ -165,7 +167,10 @@ mod hardware {
165167 timestamp: i64::from(frame.timestamp_ms),
166168 force_keyframe: force,
167169 };
168- let coded = if frame.width % 2 == 0 && frame.height % 2 == 0 && frame.stride % 4 == 0 {
170+ let coded = if frame.width.is_multiple_of(2)
171+ && frame.height.is_multiple_of(2)
172+ && frame.stride.is_multiple_of(4)
173+ {
169174 let rgb = ec_hw::RgbFrame {
170175 data: &frame.bgra,
171176 width: frame.width,
crates/client/src/share/reassembly.rsmodified+6 -0
@@ -92,6 +92,12 @@ pub struct Reassembler {
9292 lost_frames: u32,
9393 }
9494
95+impl Default for Reassembler {
96+ fn default() -> Self {
97+ Self::new()
98+ }
99+}
100+
95101 impl Reassembler {
96102 pub fn new() -> Reassembler {
97103 Reassembler {
crates/common/src/config.rsmodified+11 -5
@@ -1,11 +1,17 @@
11 use std::collections::HashMap;
22
3-use crate::error::Error;
3+#[derive(Debug, thiserror::Error)]
4+pub enum ConfigError {
5+ #[error("invalid line: {0}")]
6+ InvalidLine(String),
7+ #[error("missing key: {0}")]
8+ MissingKey(String),
9+}
410
511 pub struct Config(HashMap<String, String>);
612
713 impl Config {
8- pub fn parse(content: &str) -> Result<Self, Error> {
14+ pub fn parse(content: &str) -> Result<Self, ConfigError> {
915 let mut fields = HashMap::new();
1016
1117 for line in content.lines().map(str::trim) {
@@ -15,7 +21,7 @@ impl Config {
1521
1622 let (key, value) = line
1723 .split_once('=')
18- .ok_or_else(|| Error::Config(format!("invalid line: {line}")))?;
24+ .ok_or_else(|| ConfigError::InvalidLine(line.to_string()))?;
1925
2026 fields.insert(
2127 key.trim().to_string(),
@@ -26,10 +32,10 @@ impl Config {
2632 Ok(Self(fields))
2733 }
2834
29- pub fn get(&self, key: &str) -> Result<String, Error> {
35+ pub fn get(&self, key: &str) -> Result<String, ConfigError> {
3036 self.0
3137 .get(key)
3238 .cloned()
33- .ok_or_else(|| Error::Config(format!("missing key: {key}")))
39+ .ok_or_else(|| ConfigError::MissingKey(key.to_string()))
3440 }
3541 }
crates/common/src/error.rsmodified+51 -93
@@ -2,42 +2,14 @@ use std::fmt::Display;
22
33 use bitcode::{Decode, Encode};
44
5-#[macro_export]
6-macro_rules! error_from {
7- ($target:ty { $($source:ty => $variant:path as $middle:ty),+ $(,)? }) => {
8- $(
9- impl From<$source> for $target {
10- fn from(value: $source) -> Self {
11- $variant(<$middle>::from(value))
12- }
13- }
14- )+
15- };
16-}
17-
18-macro_rules! from_display {
19- ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => {
20- $(
21- impl From<$source> for $target {
22- fn from(value: $source) -> Self {
23- $variant(value.to_string())
24- }
25- }
26- )+
27- };
28-}
29-
305 #[derive(Debug, Clone, Encode, Decode)]
31-pub enum InvalidInput {
32- TooShort { minimum: usize, actual: usize },
33- TooLong { maximum: usize, actual: usize },
34- TooLarge { maximum: u64, actual: u64 },
6+pub enum Problem {
7+ Length { min: u64, max: u64, actual: u64 },
358 Empty,
9+ Characters,
3610 MultiLine,
37- ForbiddenCharacter,
3811 NotJpeg,
3912 Dimensions { expected: u32 },
40- TooSmall { minimum: u64, actual: u64 },
4113 }
4214
4315 pub fn size_text(size: u64) -> String {
@@ -48,38 +20,40 @@ pub fn size_text(size: u64) -> String {
4820 }
4921 }
5022
51-impl Display for InvalidInput {
52- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53- match self {
54- InvalidInput::TooShort { minimum, actual } => {
55- write!(f, "too short ({actual} < {minimum})")
56- }
57- InvalidInput::TooLong { maximum, actual } => {
58- write!(f, "too long ({actual} > {maximum})")
59- }
60- InvalidInput::TooLarge { maximum, actual } => {
61- write!(
62- f,
63- "too large: {} (max {})",
23+impl Problem {
24+ pub fn describe(&self, field: &Field) -> String {
25+ match (self, field.is_size()) {
26+ (Problem::Length { min, actual, .. }, true) if actual < min => {
27+ format!(
28+ "too small: {} (min {})",
6429 size_text(*actual),
65- size_text(*maximum)
30+ size_text(*min)
6631 )
6732 }
68- InvalidInput::Empty => write!(f, "empty"),
69- InvalidInput::MultiLine => write!(f, "contains line break"),
70- InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"),
71- InvalidInput::NotJpeg => write!(f, "not JPEG"),
72- InvalidInput::Dimensions { expected } => {
73- write!(f, "must be {expected}x{expected} px")
74- }
75- InvalidInput::TooSmall { minimum, actual } => {
76- write!(
77- f,
78- "too small: {} (min {})",
33+ (Problem::Length { max, actual, .. }, true) => {
34+ format!(
35+ "too large: {} (max {})",
7936 size_text(*actual),
80- size_text(*minimum)
37+ size_text(*max)
8138 )
8239 }
40+ _ => self.to_string(),
41+ }
42+ }
43+}
44+
45+impl Display for Problem {
46+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47+ match self {
48+ Problem::Length { min, actual, .. } if actual < min => {
49+ write!(f, "too short ({actual} < {min})")
50+ }
51+ Problem::Length { max, actual, .. } => write!(f, "too long ({actual} > {max})"),
52+ Problem::Empty => write!(f, "empty"),
53+ Problem::Characters => write!(f, "contains forbidden character"),
54+ Problem::MultiLine => write!(f, "contains line break"),
55+ Problem::NotJpeg => write!(f, "not JPEG"),
56+ Problem::Dimensions { expected } => write!(f, "must be {expected}x{expected} px"),
8357 }
8458 }
8559 }
@@ -101,6 +75,17 @@ pub enum Field {
10175 BackupName,
10276 Quota,
10377 Announcement,
78+ Poll,
79+ Reaction,
80+}
81+
82+impl Field {
83+ fn is_size(&self) -> bool {
84+ matches!(
85+ self,
86+ Field::Attachment | Field::Avatar | Field::AttachmentLimit | Field::Quota
87+ )
88+ }
10489 }
10590
10691 impl Display for Field {
@@ -121,6 +106,8 @@ impl Display for Field {
121106 Field::BackupName => "backup name:",
122107 Field::Quota => "quota:",
123108 Field::Announcement => "announcement:",
109+ Field::Poll => "poll:",
110+ Field::Reaction => "reaction:",
124111 };
125112 write!(f, "{label}")
126113 }
@@ -138,34 +125,16 @@ pub enum Error {
138125 Taken,
139126 #[error("wrong credentials")]
140127 WrongCredentials,
141- #[error("server error")]
142- Server,
143- #[error("channel closed")]
144- ChannelClosed,
145- #[error("config: {0}")]
146- Config(String),
147- #[error("network: {0}")]
148- Network(String),
149- #[error("decode: {0}")]
150- Decode(String),
151- #[error("read bound exceeded ({actual} > {maximum})")]
152- ReadBoundExceed { actual: usize, maximum: usize },
153- #[error("{field} {input}")]
154- Invalid { field: Field, input: InvalidInput },
155- #[error("upload: {0}")]
156- Upload(String),
157- #[error("certificate: {0}")]
158- Certificate(String),
159128 #[error("already a member")]
160129 AlreadyMember,
161130 #[error("already invited")]
162131 AlreadyInvited,
163132 #[error("suspended")]
164- Suspended,
165- #[error("registration closed")]
166- RegistrationClosed,
133+ Suspended { until_ms: Option<u64> },
167134 #[error("banned")]
168135 Banned,
136+ #[error("registration closed")]
137+ RegistrationClosed,
169138 #[error("maintenance")]
170139 Maintenance,
171140 #[error("storage quota exceeded")]
@@ -174,19 +143,8 @@ pub enum Error {
174143 LimitReached,
175144 #[error("too many requests, retry in {retry_after_seconds}s")]
176145 RateLimited { retry_after_seconds: u64 },
177- #[error("{0}")]
178- Device(String),
146+ #[error("{field} {}", .problem.describe(.field))]
147+ Invalid { field: Field, problem: Problem },
148+ #[error("server error")]
149+ Server,
179150 }
180-
181-from_display! { Error {
182- std::net::AddrParseError => Error::Network,
183- std::io::Error => Error::Network,
184- quinn::ConnectionError => Error::Network,
185- quinn::ConnectError => Error::Network,
186- quinn::ReadError => Error::Network,
187- quinn::ReadToEndError => Error::Network,
188- quinn::ReadExactError => Error::Network,
189- quinn::WriteError => Error::Network,
190- quinn::ClosedStream => Error::Network,
191- bitcode::Error => Error::Decode,
192-} }
crates/common/src/frame.rsadded+89 -0
@@ -0,0 +1,89 @@
1+use bitcode::{DecodeOwned, Encode};
2+use quinn::{RecvStream, SendStream};
3+
4+use crate::constant::MAXIMUM_AVATAR_BYTES;
5+
6+#[derive(Debug, thiserror::Error)]
7+pub enum FrameError {
8+ #[error(transparent)]
9+ Connection(#[from] quinn::ConnectionError),
10+ #[error(transparent)]
11+ Write(#[from] quinn::WriteError),
12+ #[error(transparent)]
13+ Read(#[from] quinn::ReadExactError),
14+ #[error(transparent)]
15+ Closed(#[from] quinn::ClosedStream),
16+ #[error("frame too large ({actual} > {maximum})")]
17+ TooLarge { actual: u32, maximum: u32 },
18+ #[error("frame decode: {0}")]
19+ Decode(#[from] bitcode::Error),
20+}
21+
22+pub const UP_MAX: u32 = 64 << 10;
23+pub const DOWN_MAX: u32 = 16 << 20;
24+
25+const _: () = assert!(MAXIMUM_AVATAR_BYTES as u32 + 4096 <= UP_MAX);
26+
27+pub struct Sending(Option<SendStream>);
28+
29+impl Sending {
30+ pub fn new(stream: SendStream) -> Self {
31+ Self(Some(stream))
32+ }
33+
34+ pub fn get(&mut self) -> &mut SendStream {
35+ self.0.as_mut().expect("stream is present until finish")
36+ }
37+
38+ pub fn finish(mut self) -> Result<(), FrameError> {
39+ let mut stream = self.0.take().expect("stream is present until finish");
40+ stream.finish()?;
41+ Ok(())
42+ }
43+}
44+
45+impl Drop for Sending {
46+ fn drop(&mut self) {
47+ if let Some(stream) = &mut self.0 {
48+ let _ = stream.reset(quinn::VarInt::from_u32(0));
49+ }
50+ }
51+}
52+
53+pub fn encode<T: Encode>(value: &T) -> Vec<u8> {
54+ let payload = bitcode::encode(value);
55+ let mut framed = Vec::with_capacity(4 + payload.len());
56+ framed.extend_from_slice(&(payload.len() as u32).to_le_bytes());
57+ framed.extend_from_slice(&payload);
58+ framed
59+}
60+
61+pub async fn write<T: Encode>(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> {
62+ let framed = encode(value);
63+ let length = framed.len() as u32 - 4;
64+ if length > max {
65+ return Err(FrameError::TooLarge {
66+ actual: length,
67+ maximum: max,
68+ });
69+ }
70+ stream.get().write_all(&framed).await?;
71+ Ok(())
72+}
73+
74+pub async fn read<T: DecodeOwned>(stream: &mut RecvStream, max: u32) -> Result<T, FrameError> {
75+ let mut length_bytes = [0u8; 4];
76+ stream.read_exact(&mut length_bytes).await?;
77+
78+ let length = u32::from_le_bytes(length_bytes);
79+ if length > max {
80+ return Err(FrameError::TooLarge {
81+ actual: length,
82+ maximum: max,
83+ });
84+ }
85+
86+ let mut payload = vec![0u8; length as usize];
87+ stream.read_exact(&mut payload).await?;
88+ Ok(bitcode::decode(&payload)?)
89+}
crates/common/src/lib.rsmodified+3 -1
@@ -3,11 +3,13 @@ pub mod constant;
33 pub mod datagram;
44 pub mod error;
55 pub mod event;
6+pub mod frame;
67 pub mod model;
7-pub mod network;
8+pub mod open;
89 pub mod permission;
910 pub mod request;
1011 pub mod response;
1112 pub mod share;
1213 pub mod time;
14+pub mod transport;
1315 pub mod validate;
crates/common/src/network.rsdeleted+0 -193
@@ -1,193 +0,0 @@
1-use bitcode::{DecodeOwned, Encode};
2-use quinn::{RecvStream, SendStream};
3-
4-use crate::{
5- error::Error,
6- event::Event,
7- request::{Request, UploadHeader},
8- response::Response,
9-};
10-
11-pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024;
12-pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024;
13-pub const REQUEST_MAX_READ_LENGTH: usize = 64 * 1024;
14-pub const EVENT_MAX_ENCODED_LENGTH: usize = 16 * 1024 * 1024;
15-pub const RESPONSE_MAX_READ_LENGTH: usize = 16 * 1024 * 1024;
16-
17-#[repr(u8)]
18-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19-pub enum StreamKind {
20- Request = 0,
21- Upload = 1,
22- Download = 2,
23- Backup = 3,
24-}
25-
26-impl StreamKind {
27- pub fn parse(byte: u8) -> Option<Self> {
28- match byte {
29- 0 => Some(StreamKind::Request),
30- 1 => Some(StreamKind::Upload),
31- 2 => Some(StreamKind::Download),
32- 3 => Some(StreamKind::Backup),
33- _ => None,
34- }
35- }
36-}
37-
38-#[repr(u8)]
39-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40-enum DownloadStatus {
41- Ok = 0,
42- Error = 1,
43-}
44-
45-impl DownloadStatus {
46- fn parse(byte: u8) -> Option<Self> {
47- match byte {
48- 0 => Some(DownloadStatus::Ok),
49- 1 => Some(DownloadStatus::Error),
50- _ => None,
51- }
52- }
53-}
54-
55-pub async fn send_stream_kind(kind: StreamKind, send_stream: &mut SendStream) -> Result<(), Error> {
56- send_stream.write_all(&[kind as u8]).await?;
57- Ok(())
58-}
59-
60-pub async fn receive_stream_kind(receive_stream: &mut RecvStream) -> Result<StreamKind, Error> {
61- let mut byte = [0u8; 1];
62- receive_stream.read_exact(&mut byte).await?;
63-
64- StreamKind::parse(byte[0]).ok_or_else(|| Error::Decode(format!("stream kind {}", byte[0])))
65-}
66-
67-pub async fn send_download_reply(
68- reply: Result<u64, Error>,
69- send_stream: &mut SendStream,
70-) -> Result<(), Error> {
71- match reply {
72- Ok(length) => {
73- send_stream.write_all(&[DownloadStatus::Ok as u8]).await?;
74- send_stream.write_all(&length.to_le_bytes()).await?;
75- }
76- Err(error) => {
77- send_stream
78- .write_all(&[DownloadStatus::Error as u8])
79- .await?;
80- send_encoded(&error, send_stream).await?;
81- }
82- }
83-
84- Ok(())
85-}
86-
87-async fn receive_download_status(receive_stream: &mut RecvStream) -> Result<DownloadStatus, Error> {
88- let mut byte = [0u8; 1];
89- receive_stream.read_exact(&mut byte).await?;
90-
91- DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))
92-}
93-
94-pub async fn open_download<T: Encode>(
95- connection: &quinn::Connection,
96- kind: StreamKind,
97- request: &T,
98-) -> Result<(RecvStream, u64), Error> {
99- let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
100- send_stream_kind(kind, &mut send_stream).await?;
101- send_encoded(request, &mut send_stream).await?;
102- send_stream.finish()?;
103-
104- match receive_download_status(&mut receive_stream).await? {
105- DownloadStatus::Error => {
106- Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
107- }
108- DownloadStatus::Ok => {
109- let mut length_bytes = [0u8; 8];
110- receive_stream.read_exact(&mut length_bytes).await?;
111- Ok((receive_stream, u64::from_le_bytes(length_bytes)))
112- }
113- }
114-}
115-
116-async fn send_framed<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
117- let payload = bitcode::encode(value);
118- send_stream
119- .write_all(&(payload.len() as u32).to_le_bytes())
120- .await?;
121- send_stream.write_all(&payload).await?;
122- Ok(())
123-}
124-
125-async fn receive_framed<T: DecodeOwned>(
126- receive_stream: &mut RecvStream,
127- maximum: usize,
128-) -> Result<T, Error> {
129- let mut length_bytes = [0u8; 4];
130- receive_stream.read_exact(&mut length_bytes).await?;
131-
132- let length = u32::from_le_bytes(length_bytes) as usize;
133- if length > maximum {
134- return Err(Error::ReadBoundExceed {
135- actual: length,
136- maximum,
137- });
138- }
139-
140- let mut payload = vec![0u8; length];
141- receive_stream.read_exact(&mut payload).await?;
142- Ok(bitcode::decode(&payload)?)
143-}
144-
145-pub async fn send_upload_header(
146- header: &UploadHeader,
147- send_stream: &mut SendStream,
148-) -> Result<(), Error> {
149- send_framed(header, send_stream).await
150-}
151-
152-pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result<UploadHeader, Error> {
153- receive_framed(receive_stream, UPLOAD_HEADER_MAX_LENGTH).await
154-}
155-
156-pub async fn send_encoded<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
157- send_stream.write_all(&bitcode::encode(value)).await?;
158- Ok(())
159-}
160-
161-pub async fn receive_decoded<T: DecodeOwned>(
162- receive_stream: &mut RecvStream,
163- limit: usize,
164-) -> Result<T, Error> {
165- let bytes = receive_stream.read_to_end(limit).await?;
166- Ok(bitcode::decode(&bytes)?)
167-}
168-
169-pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> {
170- send_encoded(response, &mut send_stream).await?;
171- send_stream.finish()?;
172- Ok(())
173-}
174-
175-pub async fn send_request(
176- request: &Request,
177- mut send_stream: SendStream,
178- mut receive_stream: RecvStream,
179-) -> Result<Response, Error> {
180- send_stream_kind(StreamKind::Request, &mut send_stream).await?;
181- send_encoded(request, &mut send_stream).await?;
182- send_stream.finish()?;
183-
184- receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await
185-}
186-
187-pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> {
188- send_framed(event, send_stream).await
189-}
190-
191-pub async fn receive_event(receive_stream: &mut RecvStream) -> Result<Event, Error> {
192- receive_framed(receive_stream, EVENT_MAX_ENCODED_LENGTH).await
193-}
crates/common/src/open.rsadded+24 -0
@@ -0,0 +1,24 @@
1+use bitcode::{Decode, Encode};
2+
3+use crate::request::Request;
4+
5+#[derive(Debug, Clone, Encode, Decode)]
6+pub enum Open {
7+ Call(Request),
8+ Upload(Upload),
9+ Fetch(Blob),
10+}
11+
12+#[derive(Debug, Clone, Encode, Decode)]
13+pub struct Upload {
14+ pub community_id: String,
15+ pub name: String,
16+ pub size: u64,
17+}
18+
19+#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
20+pub enum Blob {
21+ Attachment(String),
22+ Thumbnail(String),
23+ Backup(String),
24+}
crates/common/src/request.rsmodified+0 -16
@@ -5,19 +5,6 @@ use crate::{
55 share::{Codec, Kind, Quality, Source},
66 };
77
8-#[derive(Debug, Clone, Encode, Decode)]
9-pub struct UploadHeader {
10- pub community_id: String,
11- pub name: String,
12- pub size: u64,
13-}
14-
15-#[derive(Debug, Clone, Encode, Decode)]
16-pub struct DownloadRequest {
17- pub attachment_id: String,
18- pub thumbnail: bool,
19-}
20-
218 #[derive(Debug, Clone, Encode, Decode)]
229 pub enum Request {
2310 Register {
@@ -357,7 +344,4 @@ pub enum Request {
357344 DeleteBackup {
358345 name: String,
359346 },
360- DownloadBackup {
361- name: String,
362- },
363347 }
crates/common/src/response.rsmodified+0 -2
@@ -1,7 +1,6 @@
11 use bitcode::{Decode, Encode};
22
33 use crate::{
4- error::Error,
54 model::{
65 Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community,
76 CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
@@ -32,7 +31,6 @@ pub enum Response {
3231 Friends(Friends),
3332 Invitations(Vec<Invitation>),
3433 Done,
35- Error(Error),
3634 Logs(Vec<LogEntry>),
3735 Users(Vec<Account>),
3836 AdminLogs(Vec<AdminLogEntry>),
crates/common/src/transport.rsadded+69 -0
@@ -0,0 +1,69 @@
1+use std::time::Duration;
2+
3+use quinn::{TransportConfig, VarInt};
4+
5+pub const PROTOCOL: u32 = 1;
6+
7+const IDLE_TIMEOUT: Duration = Duration::from_secs(10);
8+const KEEP_ALIVE: Duration = Duration::from_secs(2);
9+const BIDI_STREAMS: u32 = 256;
10+const DATAGRAM_RECEIVE_BYTES: usize = 1 << 20;
11+
12+pub fn alpn() -> Vec<u8> {
13+ format!("yumush/{PROTOCOL}").into_bytes()
14+}
15+
16+pub fn transport() -> TransportConfig {
17+ let mut config = TransportConfig::default();
18+ config.keep_alive_interval(Some(KEEP_ALIVE));
19+ config.max_idle_timeout(Some(IDLE_TIMEOUT.try_into().expect("idle timeout")));
20+ config.max_concurrent_bidi_streams(VarInt::from_u32(BIDI_STREAMS));
21+ config.datagram_receive_buffer_size(Some(DATAGRAM_RECEIVE_BYTES));
22+ config
23+}
24+
25+#[repr(u32)]
26+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27+pub enum Close {
28+ Normal = 0,
29+ SignedOut = 1,
30+ Revoked = 2,
31+ Banned = 3,
32+ Maintenance = 4,
33+ Slow = 5,
34+ Protocol = 6,
35+}
36+
37+impl Close {
38+ pub const ALL: [Self; 7] = [
39+ Self::Normal,
40+ Self::SignedOut,
41+ Self::Revoked,
42+ Self::Banned,
43+ Self::Maintenance,
44+ Self::Slow,
45+ Self::Protocol,
46+ ];
47+
48+ pub fn of(code: VarInt) -> Option<Self> {
49+ Self::ALL
50+ .into_iter()
51+ .find(|close| u64::from(code) == u64::from(*close as u32))
52+ }
53+
54+ pub fn reason(self) -> &'static str {
55+ match self {
56+ Self::Normal => "closed",
57+ Self::SignedOut => "signed out",
58+ Self::Revoked => "session revoked",
59+ Self::Banned => "banned",
60+ Self::Maintenance => "maintenance",
61+ Self::Slow => "slow",
62+ Self::Protocol => "protocol error",
63+ }
64+ }
65+
66+ pub fn code(self) -> VarInt {
67+ VarInt::from_u32(self as u32)
68+ }
69+}
crates/common/src/validate.rsmodified+48 -49
@@ -11,34 +11,36 @@ use crate::{
1111 MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS,
1212 MINIMUM_USERNAME_LENGTH, REACTIONS,
1313 },
14- error::{Error, Field, InvalidInput},
14+ error::{Error, Field, Problem},
1515 model::{Poll, ServerSettings},
1616 };
1717
18-fn invalid(field: Field) -> impl Fn(InvalidInput) -> Error {
19- move |input| Error::Invalid { field, input }
18+fn invalid(field: Field) -> impl Fn(Problem) -> Error {
19+ move |problem| Error::Invalid { field, problem }
2020 }
2121
22-fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
23- if actual < minimum {
24- return Err(InvalidInput::TooShort { minimum, actual });
25- }
26-
27- if actual > maximum {
28- return Err(InvalidInput::TooLong { maximum, actual });
22+fn check_range(actual: u64, min: u64, max: u64) -> Result<(), Problem> {
23+ if actual < min || actual > max {
24+ return Err(Problem::Length { min, max, actual });
2925 }
3026
3127 Ok(())
3228 }
3329
34-fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
30+fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), Problem> {
31+ check_range(actual as u64, minimum as u64, maximum as u64)
32+}
33+
34+fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), Problem> {
3535 check_length(text.chars().count(), minimum, maximum)
3636 }
3737
38-fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
39- let allowed = name.bytes().all(|byte| byte.is_ascii_graphic() || byte == b' ');
38+fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), Problem> {
39+ let allowed = name
40+ .bytes()
41+ .all(|byte| byte.is_ascii_graphic() || byte == b' ');
4042 if !allowed || name != name.trim() {
41- return Err(InvalidInput::ForbiddenCharacter);
43+ return Err(Problem::Characters);
4244 }
4345
4446 check_length(name.len(), minimum, maximum)
@@ -50,13 +52,21 @@ pub fn validate_username(username: &str) -> Result<(), Error> {
5052 }
5153
5254 pub fn validate_password(password: &str) -> Result<(), Error> {
53- check_length(password.len(), MINIMUM_PASSWORD_LENGTH, MAXIMUM_PASSWORD_LENGTH)
54- .map_err(invalid(Field::Password))
55+ check_length(
56+ password.len(),
57+ MINIMUM_PASSWORD_LENGTH,
58+ MAXIMUM_PASSWORD_LENGTH,
59+ )
60+ .map_err(invalid(Field::Password))
5561 }
5662
5763 pub fn validate_community_name(name: &str) -> Result<(), Error> {
58- check_name(name, MINIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_COMMUNITY_NAME_LENGTH)
59- .map_err(invalid(Field::Community))
64+ check_name(
65+ name,
66+ MINIMUM_COMMUNITY_NAME_LENGTH,
67+ MAXIMUM_COMMUNITY_NAME_LENGTH,
68+ )
69+ .map_err(invalid(Field::Community))
6070 }
6171
6272 pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> {
@@ -69,11 +79,11 @@ pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> R
6979 }
7080
7181 pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {
72- check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Message))?;
82+ check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Poll))?;
7383 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)
74- .map_err(invalid(Field::Message))?;
84+ .map_err(invalid(Field::Poll))?;
7585 for option in options {
76- check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Message))?;
86+ check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Poll))?;
7787 }
7888
7989 Ok(())
@@ -97,16 +107,14 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> {
97107 return Ok(());
98108 }
99109
100- Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter))
110+ Err(invalid(Field::Reaction)(Problem::Characters))
101111 }
102112
103113 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
104114 check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(invalid(Field::AttachmentName))?;
105115
106116 if name.contains(['/', '\\']) || name.chars().any(char::is_control) {
107- return Err(invalid(Field::AttachmentName)(
108- InvalidInput::ForbiddenCharacter,
109- ));
117+ return Err(invalid(Field::AttachmentName)(Problem::Characters));
110118 }
111119
112120 Ok(())
@@ -119,17 +127,16 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> {
119127 character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
120128 })
121129 {
122- return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter));
130+ return Err(invalid(Field::BackupName)(Problem::Characters));
123131 }
124132
125133 Ok(())
126134 }
127135
128-fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {
136+fn check_size(actual: u64, maximum: u64) -> Result<(), Problem> {
129137 match actual {
130- 0 => Err(InvalidInput::Empty),
131- actual if actual > maximum => Err(InvalidInput::TooLarge { maximum, actual }),
132- _ => Ok(()),
138+ 0 => Err(Problem::Empty),
139+ actual => check_range(actual, 0, maximum),
133140 }
134141 }
135142
@@ -138,27 +145,19 @@ pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> {
138145 }
139146
140147 pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> {
141- match limit {
142- limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => {
143- Err(invalid(Field::AttachmentLimit)(InvalidInput::TooSmall {
144- minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES,
145- actual: limit,
146- }))
147- }
148- limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => {
149- Err(invalid(Field::AttachmentLimit)(InvalidInput::TooLarge {
150- maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES,
151- actual: limit,
152- }))
153- }
154- _ => Ok(()),
155- }
148+ check_range(
149+ limit,
150+ MINIMUM_ATTACHMENT_LIMIT_BYTES,
151+ MAXIMUM_ATTACHMENT_LIMIT_BYTES,
152+ )
153+ .map_err(invalid(Field::AttachmentLimit))
156154 }
157155
158156 fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
159157 if quota != 0 && quota < minimum {
160- return Err(invalid(Field::Quota)(InvalidInput::TooSmall {
161- minimum,
158+ return Err(invalid(Field::Quota)(Problem::Length {
159+ min: minimum,
160+ max: u64::MAX,
162161 actual: quota,
163162 }));
164163 }
@@ -166,9 +165,9 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> {
166165 Ok(())
167166 }
168167
169-fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
168+fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), Problem> {
170169 if text.contains(['\n', '\r']) {
171- return Err(InvalidInput::MultiLine);
170+ return Err(Problem::MultiLine);
172171 }
173172
174173 check_text(text, minimum, maximum)
crates/pixel/src/lib.rsmodified+13 -10
@@ -30,6 +30,7 @@ pub struct I420 {
3030 pub height: u32,
3131 }
3232
33+#[allow(clippy::too_many_arguments)]
3334 pub fn yuv_to_bgra(
3435 y: &[u8],
3536 y_stride: usize,
@@ -166,6 +167,18 @@ fn scale(source: &Bgra, width: u32, height: u32) -> Option<Vec<u8>> {
166167 Some(target.into_vec())
167168 }
168169
170+pub fn jpeg_to_bgra(data: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
171+ let options = zune_core::options::DecoderOptions::default()
172+ .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::BGRA);
173+ let mut decoder = zune_jpeg::JpegDecoder::new_with_options(
174+ zune_core::bytestream::ZCursor::new(data),
175+ options,
176+ );
177+ let bgra = decoder.decode().ok()?;
178+ let (width, height) = decoder.dimensions()?;
179+ Some((width as u32, height as u32, bgra))
180+}
181+
169182 #[cfg(test)]
170183 mod tests {
171184 use super::*;
@@ -185,13 +198,3 @@ mod tests {
185198 );
186199 }
187200 }
188-
189-pub fn jpeg_to_bgra(data: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
190- let options = zune_core::options::DecoderOptions::default()
191- .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::BGRA);
192- let mut decoder =
193- zune_jpeg::JpegDecoder::new_with_options(zune_core::bytestream::ZCursor::new(data), options);
194- let bgra = decoder.decode().ok()?;
195- let (width, height) = decoder.dimensions()?;
196- Some((width as u32, height as u32, bgra))
197-}
crates/server/src/admin_log.rsmodified+3 -3
@@ -5,7 +5,7 @@ use common::{
55 };
66 use turso::Connection;
77
8-use crate::{database::new_id, error::Error, user};
8+use crate::{database::new_id, error::ServerError, user};
99
1010 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {
1111 Some(match AdminActionKind::parse(text)? {
@@ -63,7 +63,7 @@ pub async fn record(
6363 community: Option<&str>,
6464 action: &AdminAction,
6565 conn: &Connection,
66-) -> Result<(), Error> {
66+) -> Result<(), ServerError> {
6767 let id = new_id();
6868 let detail = action_detail(action);
6969 conn.execute(
@@ -89,7 +89,7 @@ pub async fn list(
8989 after_ms: Option<u64>,
9090 before_ms: Option<u64>,
9191 conn: &Connection,
92-) -> Result<Vec<AdminLogEntry>, Error> {
92+) -> Result<Vec<AdminLogEntry>, ServerError> {
9393 let (after, before) = time::range_bounds(after_ms, before_ms);
9494 let mut rows = conn
9595 .query(
crates/server/src/attachment.rsmodified+82 -84
@@ -10,22 +10,18 @@ use common::{
1010 ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE,
1111 THUMBNAIL_SIZE,
1212 },
13- error::Error as CommonError,
13+ error::{Error as CommonError, Field, Problem},
14+ frame::{self, DOWN_MAX, Sending},
1415 model::{
1516 Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User,
1617 },
17- network::{
18- DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded, receive_upload_header,
19- send_download_reply, send_response,
20- },
18+ open::{Blob, Upload},
2119 permission,
22- request::{DownloadRequest, UploadHeader},
23- response::Response,
2420 time::{self, HOUR_MILLIS},
2521 validate::{validate_attachment_name, validate_attachment_size},
2622 };
2723 use image::{ImageFormat, ImageReader, Limits};
28-use quinn::{RecvStream, SendStream, VarInt};
24+use quinn::{RecvStream, VarInt};
2925 use tokio::{
3026 fs::File,
3127 io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
@@ -34,9 +30,9 @@ use tracing::error;
3430 use turso::{Connection, Row};
3531
3632 use crate::{
37- community,
33+ backup, community,
3834 database::{self, DB, new_id},
39- error::Error,
35+ error::ServerError,
4036 request::{actor_rank, ensure},
4137 server_settings, user,
4238 };
@@ -56,7 +52,7 @@ pub struct Stored {
5652 pub message_id: Option<String>,
5753 }
5854
59-fn from_row(row: &Row) -> Result<Attachment, Error> {
55+fn from_row(row: &Row) -> Result<Attachment, ServerError> {
6056 let size: i64 = row.get(2)?;
6157 let kind: String = row.get(3)?;
6258 let width: Option<i64> = row.get(4)?;
@@ -76,7 +72,7 @@ pub async fn of_message(
7672 message_id: &str,
7773 snippet_position: Option<i64>,
7874 conn: &Connection,
79-) -> Result<Vec<Attachment>, Error> {
75+) -> Result<Vec<Attachment>, ServerError> {
8076 let mut rows = conn
8177 .query(
8278 "SELECT id, name, size, kind, width, height FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id",
@@ -98,7 +94,7 @@ pub async fn bind(
9894 community_id: &str,
9995 attachment_ids: &[String],
10096 conn: &Connection,
101-) -> Result<(), Error> {
97+) -> Result<(), ServerError> {
10298 if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE {
10399 return Err(CommonError::NotFound.into());
104100 }
@@ -128,7 +124,7 @@ fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> {
128124 std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop))
129125 }
130126
131-async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> {
127+async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), ServerError> {
132128 tokio::task::spawn_blocking(move || link_or_copy(&source, &target))
133129 .await
134130 .map_err(|_| CommonError::Server)?
@@ -137,7 +133,7 @@ async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> {
137133 Ok(())
138134 }
139135
140-async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), Error> {
136+async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), ServerError> {
141137 if tokio::fs::try_exists(&source)
142138 .await
143139 .map_err(|_| CommonError::Server)?
@@ -156,7 +152,7 @@ pub async fn copy(
156152 snippet_position: Option<i64>,
157153 directory: &Path,
158154 conn: &Connection,
159-) -> Result<(), Error> {
155+) -> Result<(), ServerError> {
160156 let id = new_id();
161157 conn.execute(
162158 "INSERT INTO attachment (id, uploader_id, community_id, message_id, name, size, kind, width, height, snippet_position) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
@@ -183,7 +179,10 @@ pub async fn copy(
183179 .await
184180 }
185181
186-pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
182+pub async fn ids_of_message(
183+ message_id: &str,
184+ conn: &Connection,
185+) -> Result<Vec<String>, ServerError> {
187186 database::ids(
188187 conn,
189188 "SELECT id FROM attachment WHERE message_id = ?1",
@@ -192,7 +191,7 @@ pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<S
192191 .await
193192 }
194193
195-pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), Error> {
194+pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), ServerError> {
196195 conn.execute("DELETE FROM attachment WHERE id = ?1", (attachment_id,))
197196 .await?;
198197
@@ -203,7 +202,7 @@ pub async fn all(
203202 user_id: Option<&str>,
204203 community_id: Option<&str>,
205204 conn: &Connection,
206-) -> Result<Vec<AttachmentInfo>, Error> {
205+) -> Result<Vec<AttachmentInfo>, ServerError> {
207206 let mut rows = conn
208207 .query(
209208 &format!("SELECT a.id, a.name, a.size, a.kind, a.width, a.height, a.community_id, {} FROM attachment a LEFT JOIN user u ON u.id = a.uploader_id WHERE (?1 IS NULL OR a.uploader_id = ?1) AND (?2 IS NULL OR a.community_id = ?2) ORDER BY a.size DESC LIMIT ?3", user::user_columns("u")),
@@ -230,7 +229,7 @@ pub async fn all(
230229 Ok(infos)
231230 }
232231
233-async fn totals(column: &str, conn: &Connection) -> Result<Vec<(String, u64, u64)>, Error> {
232+async fn totals(column: &str, conn: &Connection) -> Result<Vec<(String, u64, u64)>, ServerError> {
234233 let mut rows = conn
235234 .query(
236235 &format!(
@@ -250,7 +249,7 @@ async fn totals(column: &str, conn: &Connection) -> Result<Vec<(String, u64, u64
250249 Ok(totals)
251250 }
252251
253-pub async fn usage(conn: &Connection) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> {
252+pub async fn usage(conn: &Connection) -> Result<(Vec<Usage>, Vec<CommunityUsage>), ServerError> {
254253 let mut users = Vec::new();
255254 for (user_id, bytes, count) in totals("uploader_id", conn).await? {
256255 users.push(Usage {
@@ -279,7 +278,7 @@ async fn over_quota(
279278 limit: u64,
280279 size: u64,
281280 conn: &Connection,
282-) -> Result<bool, Error> {
281+) -> Result<bool, ServerError> {
283282 if limit == 0 {
284283 return Ok(false);
285284 }
@@ -294,7 +293,7 @@ async fn ensure_quota(
294293 size: u64,
295294 settings: &ServerSettings,
296295 conn: &Connection,
297-) -> Result<(), Error> {
296+) -> Result<(), ServerError> {
298297 if over_quota(
299298 "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1",
300299 user_id,
@@ -321,7 +320,7 @@ async fn ensure_quota(
321320 Ok(())
322321 }
323322
324-pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
323+pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> {
325324 database::ids(
326325 conn,
327326 "SELECT id FROM attachment WHERE uploader_id = ?1",
@@ -330,7 +329,7 @@ pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>,
330329 .await
331330 }
332331
333-pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Error> {
332+pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), ServerError> {
334333 conn.execute("DELETE FROM attachment WHERE uploader_id = ?1", (user_id,))
335334 .await?;
336335
@@ -344,7 +343,7 @@ pub fn remove_files(attachment_ids: &[String], directory: &Path) {
344343 }
345344 }
346345
347-pub async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, Error> {
346+pub async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, ServerError> {
348347 let mut rows = conn
349348 .query(
350349 "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1",
@@ -423,8 +422,15 @@ async fn receive_body<R: AsyncRead + Unpin>(
423422 reader: &mut R,
424423 part: &Path,
425424 size: u64,
426-) -> Result<Vec<u8>, Error> {
427- let mismatch = || CommonError::Upload("size mismatch".to_string());
425+) -> Result<Vec<u8>, ServerError> {
426+ let mismatch = |actual: u64| CommonError::Invalid {
427+ field: Field::Attachment,
428+ problem: Problem::Length {
429+ min: size,
430+ max: size,
431+ actual,
432+ },
433+ };
428434 let mut file = File::create(part).await?;
429435
430436 let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize];
@@ -441,13 +447,13 @@ async fn receive_body<R: AsyncRead + Unpin>(
441447
442448 received += read as u64;
443449 if received > size {
444- return Err(mismatch().into());
450+ return Err(mismatch(received).into());
445451 }
446452 file.write_all(&buffer[..read]).await?;
447453 }
448454
449455 if received != size {
450- return Err(mismatch().into());
456+ return Err(mismatch(received).into());
451457 }
452458 file.flush().await?;
453459
@@ -456,11 +462,11 @@ async fn receive_body<R: AsyncRead + Unpin>(
456462
457463 pub async fn store<R: AsyncRead + Unpin>(
458464 user: &User,
459- header: &UploadHeader,
465+ header: &Upload,
460466 reader: &mut R,
461467 db: &DB,
462468 directory: &Path,
463-) -> Result<Attachment, Error> {
469+) -> Result<Attachment, ServerError> {
464470 let conn = database::connect(db).await?;
465471 let rank = actor_rank(user, &header.community_id, &conn).await?;
466472 ensure(permission::can_post(rank))?;
@@ -525,44 +531,44 @@ pub async fn store<R: AsyncRead + Unpin>(
525531
526532 pub async fn upload(
527533 user: Option<&User>,
534+ header: Upload,
528535 mut receive_stream: RecvStream,
529- send_stream: SendStream,
536+ mut send_stream: Sending,
530537 db: &DB,
531538 directory: &Path,
532-) -> Result<(), Error> {
533- let header = receive_upload_header(&mut receive_stream).await?;
539+) -> Result<(), ServerError> {
534540 let stored = match user {
535541 Some(user) => store(user, &header, &mut receive_stream, db, directory).await,
536542 None => Err(CommonError::Unauthenticated.into()),
537543 };
544+ let rejected = stored.is_err();
545+ let reply = stored.map_err(CommonError::from);
538546
539- let response = match stored {
540- Ok(attachment) => Response::Attachment(attachment),
541- Err(error) => {
542- let _ = receive_stream.stop(VarInt::from_u32(0));
543- Response::Error(error.into())
544- }
545- };
546- send_response(&response, send_stream).await?;
547+ frame::write(&mut send_stream, &reply, DOWN_MAX).await?;
548+ send_stream.finish()?;
549+ if rejected {
550+ let _ = receive_stream.stop(VarInt::from_u32(0));
551+ }
547552
548553 Ok(())
549554 }
550555
551-async fn locate(
556+pub async fn locate(
552557 user: Option<&User>,
553- request: &DownloadRequest,
558+ attachment_id: &str,
559+ thumbnail: bool,
554560 db: &DB,
555561 directory: &Path,
556-) -> Result<(PathBuf, u64), Error> {
562+) -> Result<(PathBuf, u64), ServerError> {
557563 let user = user.ok_or(CommonError::Unauthenticated)?;
558564 let conn = database::connect(db).await?;
559- let stored = read(&request.attachment_id, &conn).await?;
565+ let stored = read(attachment_id, &conn).await?;
560566
561567 let rank = actor_rank(user, &stored.community_id, &conn).await?;
562568 ensure(permission::can_read(rank))?;
563569 ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?;
564570
565- let path = if request.thumbnail {
571+ let path = if thumbnail {
566572 thumb_path(directory, &stored.attachment.id)
567573 } else {
568574 directory.join(&stored.attachment.id)
@@ -575,46 +581,36 @@ async fn locate(
575581 Ok((path, length))
576582 }
577583
578-pub async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> {
579- let mut file = File::open(path).await?;
580- let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
581- loop {
582- let read = file.read(&mut buffer).await?;
583- if read == 0 {
584- return Ok(());
585- }
586-
587- send_stream.write_all(&buffer[..read]).await?;
588- }
589-}
590-
591-pub async fn download(
584+pub async fn fetch(
592585 user: Option<&User>,
593- mut receive_stream: RecvStream,
594- mut send_stream: SendStream,
586+ blob: Blob,
587+ mut send_stream: Sending,
595588 db: &DB,
596589 directory: &Path,
597-) -> Result<(), Error> {
598- let request: DownloadRequest =
599- receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;
600-
601- let located = locate(user, &request, db, directory)
602- .await
603- .map_err(CommonError::from);
604- send_file(located, &mut send_stream).await
605-}
606-
607-pub async fn send_file(
608- located: Result<(PathBuf, u64), CommonError>,
609- send_stream: &mut SendStream,
610-) -> Result<(), Error> {
590+ backups: &Path,
591+) -> Result<(), ServerError> {
592+ let located = match &blob {
593+ Blob::Attachment(id) => locate(user, id, false, db, directory).await,
594+ Blob::Thumbnail(id) => locate(user, id, true, db, directory).await,
595+ Blob::Backup(name) => backup::locate(user, name, db, backups).await,
596+ };
597+ let located = located.map_err(CommonError::from);
611598 let reply = located
612599 .as_ref()
613600 .map(|(_, length)| *length)
614601 .map_err(Clone::clone);
615- send_download_reply(reply, send_stream).await?;
602+ frame::write(&mut send_stream, &reply, DOWN_MAX).await?;
603+
616604 if let Ok((path, _)) = located {
617- stream_file(&path, send_stream).await?;
605+ let mut file = File::open(path).await?;
606+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
607+ loop {
608+ let read = file.read(&mut buffer).await?;
609+ if read == 0 {
610+ break;
611+ }
612+ send_stream.get().write_all(&buffer[..read]).await?;
613+ }
618614 }
619615 send_stream.finish()?;
620616
@@ -631,7 +627,7 @@ pub async fn collect(db: DB, directory: PathBuf) {
631627 }
632628 }
633629
634-async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {
630+async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> {
635631 let conn = database::connect(db).await?;
636632 let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS);
637633 let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms);
@@ -676,7 +672,8 @@ mod tests {
676672
677673 use common::{
678674 model::{AttachmentKind, Rank},
679- request::{Request, UploadHeader},
675+ open::Upload,
676+ request::Request,
680677 };
681678 use image::{ImageFormat, RgbImage};
682679
@@ -704,7 +701,7 @@ mod tests {
704701 .unwrap();
705702 let png = png.into_inner();
706703 let directory = test::directory();
707- let header = UploadHeader {
704+ let header = Upload {
708705 community_id: community.id.clone(),
709706 name: "pixel.png".to_string(),
710707 size: png.len() as u64,
@@ -717,7 +714,7 @@ mod tests {
717714 user: user.clone(),
718715 token: "token".to_string(),
719716 });
720- handle(
717+ let (reply, _) = handle(
721718 Request::CreateMessage {
722719 community_id: community.id.clone(),
723720 body: String::new(),
@@ -732,6 +729,7 @@ mod tests {
732729 &test::directory(),
733730 )
734731 .await;
732+ reply.unwrap();
735733
736734 let messages = message::read_page(&community.id, None, &conn)
737735 .await
crates/server/src/authentication.rsmodified+29 -24
@@ -7,34 +7,35 @@ use common::{
77 };
88 use turso::Connection;
99
10-use crate::{database::new_id, error::Error, invite, server_ban, server_settings, user};
10+use crate::{database::new_id, error::ServerError, invite, server_ban, server_settings, user};
1111
1212 const SALT_LENGTH: usize = 16;
1313 const TOKEN_LENGTH: usize = 32;
1414
15-pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N], Error> {
15+pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N], ServerError> {
1616 let mut bytes = [0u8; N];
17- getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?;
17+ getrandom::fill(&mut bytes)
18+ .map_err(|error| ServerError::Internal(format!("random: {error}")))?;
1819
1920 Ok(bytes)
2021 }
2122
22-fn hash(password: &str) -> Result<String, Error> {
23+fn hash(password: &str) -> Result<String, ServerError> {
2324 let salt = random_bytes::<SALT_LENGTH>()?;
2425 let hash = Argon2::default()
2526 .hash_password_with_salt(password.as_bytes(), &salt)
26- .map_err(|error| Error::Hash(error.to_string()))?;
27+ .map_err(|error| ServerError::Internal(error.to_string()))?;
2728
2829 Ok(hash.to_string())
2930 }
3031
31-fn verify(password: &str, password_hash: &str) -> Result<(), Error> {
32+fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> {
3233 Argon2::default()
3334 .verify_password(password.as_bytes(), password_hash)
34- .map_err(|_| Error::from(CommonError::WrongCredentials))
35+ .map_err(|_| ServerError::from(CommonError::WrongCredentials))
3536 }
3637
37-async fn open_session(user_id: &str, conn: &Connection) -> Result<String, Error> {
38+async fn open_session(user_id: &str, conn: &Connection) -> Result<String, ServerError> {
3839 let token: String = random_bytes::<TOKEN_LENGTH>()?
3940 .iter()
4041 .map(|byte| format!("{byte:02x}"))
@@ -50,7 +51,7 @@ async fn open_session(user_id: &str, conn: &Connection) -> Result<String, Error>
5051 Ok(token)
5152 }
5253
53-pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), Error> {
54+pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), ServerError> {
5455 if user::is_ghost(user_id, conn).await? {
5556 return Ok(());
5657 }
@@ -69,7 +70,7 @@ pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), E
6970 Ok(())
7071 }
7172
72-pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), Error> {
73+pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), ServerError> {
7374 validate_device(name)?;
7475 conn.execute(
7576 "UPDATE session SET device = ?2 WHERE token = ?1",
@@ -80,7 +81,7 @@ pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<()
8081 Ok(())
8182 }
8283
83-pub async fn sessions(user_id: &str, conn: &Connection) -> Result<Vec<SessionInfo>, Error> {
84+pub async fn sessions(user_id: &str, conn: &Connection) -> Result<Vec<SessionInfo>, ServerError> {
8485 let mut rows = conn
8586 .query(
8687 "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC",
@@ -104,7 +105,7 @@ pub async fn revoke_session(
104105 user_id: &str,
105106 session_id: &str,
106107 conn: &Connection,
107-) -> Result<String, Error> {
108+) -> Result<String, ServerError> {
108109 let mut rows = conn
109110 .query(
110111 "DELETE FROM session WHERE id = ?1 AND user_id = ?2 RETURNING token",
@@ -120,7 +121,7 @@ pub async fn create_account(
120121 username: &str,
121122 password: &str,
122123 conn: &Connection,
123-) -> Result<User, Error> {
124+) -> Result<User, ServerError> {
124125 validate_username(username)?;
125126 validate_password(password)?;
126127
@@ -136,7 +137,7 @@ pub async fn register(
136137 password: &str,
137138 invite_code: Option<&str>,
138139 conn: &mut Connection,
139-) -> Result<(User, String), Error> {
140+) -> Result<(User, String), ServerError> {
140141 let tx = conn.transaction().await?;
141142 if server_ban::username_banned(username, &tx).await? {
142143 return Err(CommonError::Banned.into());
@@ -156,7 +157,7 @@ pub async fn login(
156157 username: &str,
157158 password: &str,
158159 conn: &Connection,
159-) -> Result<(User, String), Error> {
160+) -> Result<(User, String), ServerError> {
160161 let (user, password_hash) = user::credentials(username, conn)
161162 .await?
162163 .ok_or(CommonError::WrongCredentials)?;
@@ -167,12 +168,12 @@ pub async fn login(
167168 Ok((user, token))
168169 }
169170
170-async fn admit(user: &User, conn: &Connection) -> Result<(), Error> {
171+async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> {
171172 if server_ban::username_banned(&user.username, conn).await? {
172173 return Err(CommonError::Banned.into());
173174 }
174- if user::suspended(&user.id, conn).await? {
175- return Err(CommonError::Suspended.into());
175+ if let Some(until_ms) = user::suspended(&user.id, conn).await? {
176+ return Err(CommonError::Suspended { until_ms }.into());
176177 }
177178 if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance {
178179 return Err(CommonError::Maintenance.into());
@@ -181,7 +182,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> {
181182 Ok(())
182183 }
183184
184-pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {
185+pub async fn resume(token: &str, conn: &Connection) -> Result<User, ServerError> {
185186 let user = user::by_session_token(token, conn).await?;
186187 admit(&user, conn).await?;
187188 seen(&user.id, token, conn).await?;
@@ -189,21 +190,25 @@ pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {
189190 Ok(user)
190191 }
191192
192-pub async fn logout(token: &str, conn: &Connection) -> Result<(), Error> {
193+pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> {
193194 conn.execute("DELETE FROM session WHERE token = ?1", (token,))
194195 .await?;
195196
196197 Ok(())
197198 }
198199
199-pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), Error> {
200+pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> {
200201 conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,))
201202 .await?;
202203
203204 Ok(())
204205 }
205206
206-pub async fn reset_password(user_id: &str, password: &str, conn: &Connection) -> Result<(), Error> {
207+pub async fn reset_password(
208+ user_id: &str,
209+ password: &str,
210+ conn: &Connection,
211+) -> Result<(), ServerError> {
207212 validate_password(password)?;
208213 user::set_password_hash(user_id, &hash(password)?, conn).await?;
209214 revoke_sessions(user_id, conn).await
@@ -213,7 +218,7 @@ pub async fn reset_password(user_id: &str, password: &str, conn: &Connection) ->
213218 mod tests {
214219 use common::error::Error as CommonError;
215220
216- use crate::{authentication, database, error::Error, test};
221+ use crate::{authentication, database, error::ServerError, test};
217222
218223 #[tokio::test]
219224 async fn register_and_login() {
@@ -232,7 +237,7 @@ mod tests {
232237 assert_eq!(registered_user, logged_in_user);
233238 assert!(matches!(
234239 wrong_password,
235- Err(Error::Common(CommonError::WrongCredentials))
240+ Err(ServerError::Wire(CommonError::WrongCredentials))
236241 ));
237242 }
238243 }
crates/server/src/backup.rsmodified+15 -36
@@ -3,19 +3,15 @@ use std::path::{Path, PathBuf};
33 use common::{
44 error::Error as CommonError,
55 model::{AdminAction, BackupInfo, User},
6- network::{DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded},
7- permission,
8- request::Request,
9- time,
6+ permission, time,
107 validate::validate_backup_name,
118 };
12-use quinn::{RecvStream, SendStream};
139 use turso::Connection;
1410
1511 use crate::{
16- admin_log, attachment,
12+ admin_log,
1713 database::{self, DB},
18- error::Error,
14+ error::ServerError,
1915 request::ensure,
2016 user,
2117 };
@@ -30,7 +26,7 @@ fn created_secs(name: &str) -> Option<u64> {
3026 .ok()
3127 }
3228
33-fn info(directory: &Path, name: &str) -> Result<BackupInfo, Error> {
29+fn info(directory: &Path, name: &str) -> Result<BackupInfo, ServerError> {
3430 let created_secs = created_secs(name).ok_or(CommonError::NotFound)?;
3531 let size_bytes = std::fs::metadata(directory.join(name))?.len();
3632
@@ -41,14 +37,14 @@ fn info(directory: &Path, name: &str) -> Result<BackupInfo, Error> {
4137 })
4238 }
4339
44-fn path_of(directory: &Path, name: &str) -> Result<PathBuf, Error> {
40+fn path_of(directory: &Path, name: &str) -> Result<PathBuf, ServerError> {
4541 validate_backup_name(name)?;
4642 created_secs(name).ok_or(CommonError::NotFound)?;
4743
4844 Ok(directory.join(name))
4945 }
5046
51-pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, Error> {
47+pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, ServerError> {
5248 let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000);
5349 let path = directory.join(&name);
5450 let statement = format!(
@@ -60,7 +56,7 @@ pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, E
6056 info(directory, &name)
6157 }
6258
63-pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> {
59+pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, ServerError> {
6460 let mut backups = Vec::new();
6561 for entry in std::fs::read_dir(directory)? {
6662 let name = entry?.file_name().to_string_lossy().into_owned();
@@ -73,27 +69,24 @@ pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> {
7369 Ok(backups)
7470 }
7571
76-pub fn delete(name: &str, directory: &Path) -> Result<(), Error> {
72+pub fn delete(name: &str, directory: &Path) -> Result<(), ServerError> {
7773 std::fs::remove_file(path_of(directory, name)?)?;
7874
7975 Ok(())
8076 }
8177
82-async fn locate(
78+pub async fn locate(
8379 user: Option<&User>,
84- request: Request,
80+ name: &str,
8581 db: &DB,
8682 directory: &Path,
87-) -> Result<(PathBuf, u64), Error> {
83+) -> Result<(PathBuf, u64), ServerError> {
8884 let user = user.ok_or(CommonError::Unauthenticated)?;
89- let Request::DownloadBackup { name } = request else {
90- return Err(CommonError::Forbidden.into());
91- };
9285 let conn = database::connect(db).await?;
9386 let me = user::read(&user.id, &conn).await?;
9487 ensure(permission::is_builder(me.role))?;
9588
96- let path = path_of(directory, &name)?;
89+ let path = path_of(directory, name)?;
9790 let length = tokio::fs::metadata(&path)
9891 .await
9992 .map_err(|_| CommonError::NotFound)?
@@ -102,26 +95,12 @@ async fn locate(
10295 Some(&me.id),
10396 None,
10497 None,
105- &AdminAction::BackupDownloaded { name },
98+ &AdminAction::BackupDownloaded {
99+ name: name.to_string(),
100+ },
106101 &conn,
107102 )
108103 .await?;
109104
110105 Ok((path, length))
111106 }
112-
113-pub async fn download(
114- user: Option<&User>,
115- mut receive_stream: RecvStream,
116- mut send_stream: SendStream,
117- db: &DB,
118- directory: &Path,
119-) -> Result<(), Error> {
120- let request: Request =
121- receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;
122-
123- let located = locate(user, request, db, directory)
124- .await
125- .map_err(CommonError::from);
126- attachment::send_file(located, &mut send_stream).await
127-}
crates/server/src/certificate.rsmodified+11 -7
@@ -13,7 +13,7 @@ use rustls::{
1313 };
1414 use tracing::{error, info, warn};
1515
16-use crate::error::Error;
16+use crate::error::ServerError;
1717
1818 const RELOAD_INTERVAL: Duration = Duration::from_secs(600);
1919 const SUBJECT_ALT_NAME: &str = "localhost";
@@ -34,11 +34,11 @@ impl ResolvesServerCert for Reloader {
3434 }
3535 }
3636
37-fn certificate_error(error: impl std::fmt::Display) -> Error {
38- Error::Common(common::error::Error::Certificate(error.to_string()))
37+fn certificate_error(error: impl std::fmt::Display) -> ServerError {
38+ ServerError::Internal(format!("certificate: {error}"))
3939 }
4040
41-fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> {
41+fn generate(certificate_path: &str, key_path: &str) -> Result<(), ServerError> {
4242 let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()])
4343 .map_err(certificate_error)?;
4444
@@ -56,7 +56,7 @@ fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> {
5656 Ok(())
5757 }
5858
59-fn certified_key(certificate_path: &str, key_path: &str) -> Result<CertifiedKey, Error> {
59+fn certified_key(certificate_path: &str, key_path: &str) -> Result<CertifiedKey, ServerError> {
6060 let chain = CertificateDer::pem_file_iter(certificate_path)
6161 .map_err(certificate_error)?
6262 .collect::<Result<Vec<_>, _>>()
@@ -101,7 +101,7 @@ async fn watch(reloader: Arc<Reloader>, certificate_path: String, key_path: Stri
101101 }
102102 }
103103
104-pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, Error> {
104+pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, ServerError> {
105105 if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() {
106106 generate(certificate_path, key_path)?;
107107 warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}");
@@ -115,6 +115,7 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi
115115 .with_no_client_auth()
116116 .with_cert_resolver(reloader.clone());
117117 tls.max_early_data_size = u32::MAX;
118+ tls.alpn_protocols = vec![common::transport::alpn()];
118119
119120 let crypto =
120121 quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
@@ -125,5 +126,8 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi
125126 key_path.to_string(),
126127 ));
127128
128- Ok(quinn::ServerConfig::with_crypto(Arc::new(crypto)))
129+ let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(crypto));
130+ server_config.transport_config(Arc::new(common::transport::transport()));
131+
132+ Ok(server_config)
129133 }
crates/server/src/community.rsmodified+24 -21
@@ -6,7 +6,7 @@ use common::{
66 };
77 use turso::{Connection, Row};
88
9-use crate::{database::new_id, error::Error, user};
9+use crate::{database::new_id, error::ServerError, user};
1010
1111 string_enum! {
1212 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -19,7 +19,7 @@ string_enum! {
1919
2020 type Raw = (String, String, Kind, Option<String>, bool);
2121
22-fn raw_of(row: &Row) -> Result<Raw, Error> {
22+fn raw_of(row: &Row) -> Result<Raw, ServerError> {
2323 let text: String = row.get(2)?;
2424 let kind = Kind::parse(&text).ok_or(CommonError::Server)?;
2525
@@ -32,7 +32,7 @@ fn raw_of(row: &Row) -> Result<Raw, Error> {
3232 ))
3333 }
3434
35-async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result<User, Error> {
35+async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result<User, ServerError> {
3636 let mut rows = conn
3737 .query(
3838 &format!("SELECT {} FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1", user::user_columns("user")),
@@ -48,7 +48,7 @@ async fn outsider_name(
4848 community_id: &str,
4949 viewer_id: &str,
5050 conn: &Connection,
51-) -> Result<Option<String>, Error> {
51+) -> Result<Option<String>, ServerError> {
5252 let mut rows = conn
5353 .query(
5454 "SELECT a.username, b.username FROM direct JOIN user a ON a.id = direct.user_a JOIN user b ON b.id = direct.user_b WHERE direct.community_id = ?1 AND direct.user_a != ?2 AND direct.user_b != ?2",
@@ -64,7 +64,7 @@ async fn outsider_name(
6464 Ok(Some(format!("{first} & {second}")))
6565 }
6666
67-async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, Error> {
67+async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, ServerError> {
6868 let (id, mut name, kind, avatar_id, voice_enabled) = raw;
6969 let kind = match kind {
7070 Kind::Group => CommunityKind::Group,
@@ -88,7 +88,7 @@ async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community
8888 })
8989 }
9090
91-pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> {
91+pub async fn create(name: &str, conn: &Connection) -> Result<Community, ServerError> {
9292 validate_community_name(name)?;
9393
9494 let id = new_id();
@@ -107,7 +107,7 @@ pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> {
107107 })
108108 }
109109
110-pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result<String, Error> {
110+pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result<String, ServerError> {
111111 let id = new_id();
112112 conn.execute(
113113 "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)",
@@ -122,7 +122,7 @@ pub async fn read(
122122 community_id: &str,
123123 viewer_id: &str,
124124 conn: &Connection,
125-) -> Result<Community, Error> {
125+) -> Result<Community, ServerError> {
126126 let raw = {
127127 let mut rows = conn
128128 .query(
@@ -138,7 +138,10 @@ pub async fn read(
138138 build(raw, viewer_id, conn).await
139139 }
140140
141-pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Community>, Error> {
141+pub async fn communities_of(
142+ user_id: &str,
143+ conn: &Connection,
144+) -> Result<Vec<Community>, ServerError> {
142145 let raws = {
143146 let mut rows = conn
144147 .query(
@@ -163,7 +166,7 @@ pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Comm
163166 Ok(communities)
164167 }
165168
166-pub async fn groups(conn: &Connection) -> Result<Vec<Community>, Error> {
169+pub async fn groups(conn: &Connection) -> Result<Vec<Community>, ServerError> {
167170 let mut rows = conn
168171 .query(
169172 "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE",
@@ -191,7 +194,7 @@ pub async fn update(
191194 name: &str,
192195 viewer_id: &str,
193196 conn: &Connection,
194-) -> Result<Community, Error> {
197+) -> Result<Community, ServerError> {
195198 validate_community_name(name)?;
196199
197200 conn.execute(
@@ -208,7 +211,7 @@ pub async fn set_avatar(
208211 image: Option<&[u8]>,
209212 viewer_id: &str,
210213 conn: &mut Connection,
211-) -> Result<Community, Error> {
214+) -> Result<Community, ServerError> {
212215 if let Some(bytes) = image {
213216 user::check_avatar(bytes)?;
214217 }
@@ -242,7 +245,7 @@ pub async fn delete(
242245 community_id: &str,
243246 viewer_id: &str,
244247 conn: &Connection,
245-) -> Result<Community, Error> {
248+) -> Result<Community, ServerError> {
246249 let deleted = read(community_id, viewer_id, conn).await?;
247250 conn.execute("DELETE FROM community WHERE id = ?1", (community_id,))
248251 .await?;
@@ -250,7 +253,7 @@ pub async fn delete(
250253 Ok(deleted)
251254 }
252255
253-pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error> {
256+pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, ServerError> {
254257 let mut rows = conn
255258 .query("SELECT kind FROM community WHERE id = ?1", (community_id,))
256259 .await?;
@@ -260,11 +263,11 @@ pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error>
260263 Ok(Kind::parse(&text).ok_or(CommonError::Server)?)
261264 }
262265
263-pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, Error> {
266+pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, ServerError> {
264267 Ok(kind(community_id, conn).await? == Kind::Direct)
265268 }
266269
267-pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, Error> {
270+pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, ServerError> {
268271 Ok(kind(community_id, conn).await? != Kind::Group)
269272 }
270273
@@ -272,7 +275,7 @@ pub async fn set_voice_enabled(
272275 community_id: &str,
273276 enabled: bool,
274277 conn: &Connection,
275-) -> Result<(), Error> {
278+) -> Result<(), ServerError> {
276279 conn.execute(
277280 "UPDATE community SET voice_enabled = ?2 WHERE id = ?1",
278281 (community_id, i64::from(enabled)),
@@ -282,7 +285,7 @@ pub async fn set_voice_enabled(
282285 Ok(())
283286 }
284287
285-pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool, Error> {
288+pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool, ServerError> {
286289 let mut rows = conn
287290 .query(
288291 "SELECT voice_enabled FROM community WHERE id = ?1",
@@ -294,7 +297,7 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool
294297 user::bool_at(&row, 0)
295298 }
296299
297-pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> {
300+pub async fn label(community_id: &str, conn: &Connection) -> Result<String, ServerError> {
298301 let prefix = match kind(community_id, conn).await? {
299302 Kind::Group => {
300303 let mut rows = conn
@@ -325,7 +328,7 @@ pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Erro
325328 mod tests {
326329 use common::error::Error as CommonError;
327330
328- use crate::{community, database, error::Error, test, user};
331+ use crate::{community, database, error::ServerError, test, user};
329332
330333 #[tokio::test]
331334 async fn create() {
@@ -382,7 +385,7 @@ mod tests {
382385
383386 assert!(matches!(
384387 updated_community,
385- Err(Error::Common(CommonError::NotFound))
388+ Err(ServerError::Wire(CommonError::NotFound))
386389 ));
387390 }
388391
crates/server/src/database.rsmodified+9 -9
@@ -3,7 +3,7 @@ use std::time::Duration;
33 use common::error::Error as CommonError;
44 use turso::Connection;
55
6-use crate::error::Error;
6+use crate::error::ServerError;
77
88 pub type DB = turso::Database;
99
@@ -292,14 +292,14 @@ const MIGRATIONS: &[&str] = &[
292292 "ALTER TABLE snippet_message ADD COLUMN poll BLOB;",
293293 ];
294294
295-pub async fn open(path: &str) -> Result<DB, Error> {
295+pub async fn open(path: &str) -> Result<DB, ServerError> {
296296 let db = turso::Builder::new_local(path).build().await?;
297297 migrate(&db).await?;
298298
299299 Ok(db)
300300 }
301301
302-pub async fn connect(db: &DB) -> Result<Connection, Error> {
302+pub async fn connect(db: &DB) -> Result<Connection, ServerError> {
303303 let conn = db.connect()?;
304304 conn.busy_timeout(BUSY_TIMEOUT)?;
305305 conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
@@ -311,7 +311,7 @@ pub async fn scalar_i64(
311311 conn: &Connection,
312312 sql: &str,
313313 params: impl turso::IntoParams,
314-) -> Result<i64, Error> {
314+) -> Result<i64, ServerError> {
315315 let mut rows = conn.query(sql, params).await?;
316316 let row = rows
317317 .next()
@@ -325,7 +325,7 @@ pub async fn exists(
325325 conn: &Connection,
326326 sql: &str,
327327 params: impl turso::IntoParams,
328-) -> Result<bool, Error> {
328+) -> Result<bool, ServerError> {
329329 Ok(scalar_i64(conn, sql, params).await? != 0)
330330 }
331331
@@ -333,7 +333,7 @@ pub async fn ids(
333333 conn: &Connection,
334334 sql: &str,
335335 params: impl turso::IntoParams,
336-) -> Result<Vec<String>, Error> {
336+) -> Result<Vec<String>, ServerError> {
337337 let mut rows = conn.query(sql, params).await?;
338338
339339 let mut ids = Vec::new();
@@ -344,7 +344,7 @@ pub async fn ids(
344344 Ok(ids)
345345 }
346346
347-pub fn expect_one(affected: u64) -> Result<(), Error> {
347+pub fn expect_one(affected: u64) -> Result<(), ServerError> {
348348 if affected != 1 {
349349 return Err(CommonError::NotFound.into());
350350 }
@@ -352,7 +352,7 @@ pub fn expect_one(affected: u64) -> Result<(), Error> {
352352 Ok(())
353353 }
354354
355-async fn migrate(db: &DB) -> Result<(), Error> {
355+async fn migrate(db: &DB) -> Result<(), ServerError> {
356356 let mut conn = connect(db).await?;
357357 let applied = user_version(&conn).await?;
358358
@@ -366,7 +366,7 @@ async fn migrate(db: &DB) -> Result<(), Error> {
366366 Ok(())
367367 }
368368
369-async fn user_version(conn: &Connection) -> Result<usize, Error> {
369+async fn user_version(conn: &Connection) -> Result<usize, ServerError> {
370370 Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize)
371371 }
372372
crates/server/src/datagram.rsadded+19 -0
@@ -0,0 +1,19 @@
1+use std::sync::{Arc, Mutex};
2+
3+use quinn::Connection;
4+
5+use crate::network::{Shared, State, publish};
6+
7+pub(crate) async fn relay_datagrams(
8+ connection: Connection,
9+ state: Arc<Mutex<State>>,
10+ shared: Shared,
11+) {
12+ while let Ok(bytes) = connection.read_datagram().await {
13+ if matches!(*state.lock().unwrap(), State::Authenticated { .. }) {
14+ shared.services.voice.relay(connection.stable_id(), &bytes);
15+ let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes);
16+ publish(&shared, broadcasts).await;
17+ }
18+ }
19+}
crates/server/src/direct.rsmodified+7 -3
@@ -1,9 +1,13 @@
11 use common::model::{Community, Rank};
22 use turso::Connection;
33
4-use crate::{community, error::Error, request::ensure, user, user_community};
4+use crate::{community, error::ServerError, request::ensure, user, user_community};
55
6-async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result<Option<String>, Error> {
6+async fn find(
7+ user_a: &str,
8+ user_b: &str,
9+ conn: &Connection,
10+) -> Result<Option<String>, ServerError> {
711 let mut rows = conn
812 .query(
913 "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2",
@@ -19,7 +23,7 @@ pub enum Opening {
1923 Existing(Community),
2024 }
2125
22-pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result<Opening, Error> {
26+pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result<Opening, ServerError> {
2327 ensure(me != other)?;
2428 user::read(other, conn).await?;
2529
crates/server/src/error.rsmodified+34 -22
@@ -1,22 +1,19 @@
1-use common::error_from;
21 use tracing::error;
32
43 #[derive(Debug, thiserror::Error)]
5-pub enum Error {
4+pub enum ServerError {
65 #[error(transparent)]
7- Common(#[from] common::error::Error),
8- #[error(transparent)]
9- Database(#[from] turso::Error),
10- #[error("password hash: {0}")]
11- Hash(String),
6+ Wire(#[from] common::error::Error),
7+ #[error("{0}")]
8+ Internal(String),
129 }
1310
14-impl From<Error> for common::error::Error {
15- fn from(value: Error) -> Self {
11+impl From<ServerError> for common::error::Error {
12+ fn from(value: ServerError) -> Self {
1613 match value {
17- Error::Common(error) => error,
18- error => {
19- error!("{error}");
14+ ServerError::Wire(error) => error,
15+ ServerError::Internal(message) => {
16+ error!("{message}");
2017
2118 common::error::Error::Server
2219 }
@@ -24,13 +21,28 @@ impl From<Error> for common::error::Error {
2421 }
2522 }
2623
27-error_from! { Error {
28- std::net::AddrParseError => Error::Common as common::error::Error,
29- std::io::Error => Error::Common as common::error::Error,
30- quinn::ConnectionError => Error::Common as common::error::Error,
31- quinn::ReadError => Error::Common as common::error::Error,
32- quinn::ReadExactError => Error::Common as common::error::Error,
33- quinn::WriteError => Error::Common as common::error::Error,
34- quinn::ClosedStream => Error::Common as common::error::Error,
35- bitcode::Error => Error::Common as common::error::Error,
36-} }
24+macro_rules! internal_from {
25+ ($($source:ty),+ $(,)?) => {
26+ $(
27+ impl From<$source> for ServerError {
28+ fn from(value: $source) -> Self {
29+ ServerError::Internal(value.to_string())
30+ }
31+ }
32+ )+
33+ };
34+}
35+
36+internal_from! {
37+ std::net::AddrParseError,
38+ std::io::Error,
39+ turso::Error,
40+ quinn::ConnectionError,
41+ quinn::ReadError,
42+ quinn::ReadExactError,
43+ quinn::WriteError,
44+ quinn::ClosedStream,
45+ bitcode::Error,
46+ common::config::ConfigError,
47+ common::frame::FrameError,
48+}
crates/server/src/friend.rsmodified+10 -10
@@ -4,9 +4,9 @@ use common::{
44 };
55 use turso::Connection;
66
7-use crate::{database, error::Error, request::ensure_with, user};
7+use crate::{database, error::ServerError, request::ensure_with, user};
88
9-async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result<Vec<User>, Error> {
9+async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result<Vec<User>, ServerError> {
1010 let mut rows = conn.query(sql, (user_id,)).await?;
1111
1212 let mut users = Vec::new();
@@ -22,11 +22,11 @@ async fn pair_exists(
2222 first: &str,
2323 second: &str,
2424 conn: &Connection,
25-) -> Result<bool, Error> {
25+) -> Result<bool, ServerError> {
2626 database::exists(conn, sql, (first, second)).await
2727 }
2828
29-async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Error> {
29+async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, ServerError> {
3030 pair_exists(
3131 "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2",
3232 me,
@@ -36,7 +36,7 @@ async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Err
3636 .await
3737 }
3838
39-async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, Error> {
39+async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, ServerError> {
4040 pair_exists(
4141 "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2",
4242 from,
@@ -46,7 +46,7 @@ async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, E
4646 .await
4747 }
4848
49-async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> {
49+async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), ServerError> {
5050 conn.execute(
5151 "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2",
5252 (other, me),
@@ -66,7 +66,7 @@ async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error>
6666 Ok(())
6767 }
6868
69-pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, Error> {
69+pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, ServerError> {
7070 Ok(Friends {
7171 friends: users(
7272 &format!("SELECT {} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id", user::user_columns("user")),
@@ -89,7 +89,7 @@ pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, Error> {
8989 })
9090 }
9191
92-pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
92+pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> {
9393 ensure_with(me != other, CommonError::Forbidden)?;
9494 user::read(other, conn).await?;
9595
@@ -112,7 +112,7 @@ pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Err
112112 Ok(())
113113 }
114114
115-pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
115+pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> {
116116 let tx = conn.transaction().await?;
117117 if !is_requested(other, me, &tx).await? {
118118 return Err(CommonError::NotFound.into());
@@ -123,7 +123,7 @@ pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(),
123123 Ok(())
124124 }
125125
126-pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
126+pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> {
127127 let tx = conn.transaction().await?;
128128 tx.execute(
129129 "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)",
crates/server/src/invitation.rsmodified+9 -5
@@ -1,9 +1,9 @@
11 use common::{error::Error as CommonError, model::Invitation};
22 use turso::Connection;
33
4-use crate::{community, database, error::Error, user};
4+use crate::{community, database, error::ServerError, user};
55
6-pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Error> {
6+pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, ServerError> {
77 let pairs = {
88 let mut rows = conn
99 .query(
@@ -31,7 +31,11 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Err
3131 Ok(invitations)
3232 }
3333
34-pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> {
34+pub async fn exists(
35+ community_id: &str,
36+ user_id: &str,
37+ conn: &Connection,
38+) -> Result<bool, ServerError> {
3539 database::exists(
3640 conn,
3741 "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)",
@@ -45,7 +49,7 @@ pub async fn insert(
4549 user_id: &str,
4650 inviter_id: &str,
4751 conn: &Connection,
48-) -> Result<(), Error> {
52+) -> Result<(), ServerError> {
4953 conn.execute(
5054 "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)",
5155 (community_id, user_id, inviter_id),
@@ -55,7 +59,7 @@ pub async fn insert(
5559 Ok(())
5660 }
5761
58-pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> {
62+pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), ServerError> {
5963 let mut rows = conn
6064 .query(
6165 "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id",
crates/server/src/invite.rsmodified+6 -6
@@ -5,12 +5,12 @@ use common::{
55 };
66 use turso::Connection;
77
8-use crate::{authentication, error::Error};
8+use crate::{authentication, error::ServerError};
99
1010 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1111 const CODE_LENGTH: usize = 8;
1212
13-fn generate() -> Result<String, Error> {
13+fn generate() -> Result<String, ServerError> {
1414 let bytes = authentication::random_bytes::<CODE_LENGTH>()?;
1515
1616 Ok(bytes
@@ -24,7 +24,7 @@ pub async fn create(
2424 hours: Option<u32>,
2525 created_by: &User,
2626 conn: &Connection,
27-) -> Result<InviteCode, Error> {
27+) -> Result<InviteCode, ServerError> {
2828 let code = generate()?;
2929 let expires_at = hours.map(|hours| time::now_ms() + u64::from(hours) * HOUR_MILLIS);
3030 conn.execute(
@@ -45,7 +45,7 @@ pub async fn create(
4545 })
4646 }
4747
48-pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> {
48+pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, ServerError> {
4949 let mut rows = conn
5050 .query("SELECT code, uses_left, expires_at FROM invite_code", ())
5151 .await?;
@@ -64,7 +64,7 @@ pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> {
6464 Ok(codes)
6565 }
6666
67-pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> {
67+pub async fn delete(code: &str, conn: &Connection) -> Result<(), ServerError> {
6868 let mut rows = conn
6969 .query(
7070 "DELETE FROM invite_code WHERE code = ?1 RETURNING code",
@@ -76,7 +76,7 @@ pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> {
7676 Ok(())
7777 }
7878
79-pub async fn consume(code: &str, conn: &Connection) -> Result<(), Error> {
79+pub async fn consume(code: &str, conn: &Connection) -> Result<(), ServerError> {
8080 let mut rows = conn
8181 .query(
8282 "UPDATE invite_code SET uses_left = uses_left - 1 WHERE code = ?1 AND uses_left > 0 AND (expires_at IS NULL OR expires_at > ?2) RETURNING code",
crates/server/src/lib.rsmodified+6 -5
@@ -5,6 +5,7 @@ pub mod backup;
55 pub mod certificate;
66 pub mod community;
77 pub mod database;
8+pub mod datagram;
89 pub mod direct;
910 pub mod error;
1011 pub mod friend;
@@ -34,7 +35,7 @@ use std::path::{Path, PathBuf};
3435
3536 use common::{config::Config, error::Error as CommonError, model::Role};
3637
37-use crate::error::Error;
38+use crate::error::ServerError;
3839
3940 const SERVER_CONFIG_FILE_PATH: &str = concat!(
4041 env!("CARGO_MANIFEST_DIR"),
@@ -54,7 +55,7 @@ pub struct ServerConfig {
5455 pub key_path: String,
5556 }
5657
57-fn load_config() -> Result<ServerConfig, Error> {
58+fn load_config() -> Result<ServerConfig, ServerError> {
5859 let content = std::fs::read_to_string(config_path())?;
5960 let config = Config::parse(&content)?;
6061
@@ -66,7 +67,7 @@ fn load_config() -> Result<ServerConfig, Error> {
6667 })
6768 }
6869
69-fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> {
70+fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, ServerError> {
7071 let directory = Path::new(database_path)
7172 .parent()
7273 .unwrap_or_else(|| Path::new(""))
@@ -76,7 +77,7 @@ fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error>
7677 Ok(directory)
7778 }
7879
79-pub async fn showtime() -> Result<(), Error> {
80+pub async fn showtime() -> Result<(), ServerError> {
8081 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
8182
8283 let config = load_config()?;
@@ -98,7 +99,7 @@ pub async fn showtime() -> Result<(), Error> {
9899 .await
99100 }
100101
101-pub async fn set_role(username: &str, role: Role) -> Result<(), Error> {
102+pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> {
102103 let config = load_config()?;
103104 let database = database::open(&config.database_path).await?;
104105 let conn = database::connect(&database).await?;
crates/server/src/log.rsmodified+3 -3
@@ -4,7 +4,7 @@ use common::{
44 };
55 use turso::Connection;
66
7-use crate::{database::new_id, error::Error, user};
7+use crate::{database::new_id, error::ServerError, user};
88
99 common::string_enum! {
1010 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -67,7 +67,7 @@ pub async fn record(
6767 target_id: Option<&str>,
6868 action: &LogAction,
6969 conn: &Connection,
70-) -> Result<(), Error> {
70+) -> Result<(), ServerError> {
7171 let id = new_id();
7272 let (action, detail) = parts(action);
7373 conn.execute(
@@ -79,7 +79,7 @@ pub async fn record(
7979 Ok(())
8080 }
8181
82-pub async fn list(community_id: &str, conn: &Connection) -> Result<Vec<LogEntry>, Error> {
82+pub async fn list(community_id: &str, conn: &Connection) -> Result<Vec<LogEntry>, ServerError> {
8383 let mut rows = conn
8484 .query(
8585 &format!("SELECT l.id, l.action, l.detail, {}, {} FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")),
crates/server/src/main.rsmodified+1 -1
@@ -2,7 +2,7 @@ use common::model::Role;
22 use server::{set_role, showtime};
33
44 #[tokio::main]
5-async fn main() -> Result<(), server::error::Error> {
5+async fn main() -> Result<(), server::error::ServerError> {
66 tracing_subscriber::fmt()
77 .with_max_level(tracing::Level::INFO)
88 .init();
crates/server/src/message.rsmodified+41 -32
@@ -2,7 +2,7 @@ use std::{collections::HashMap, path::Path};
22
33 use common::{
44 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
5- error::{Error as CommonError, Field, InvalidInput},
5+ error::{Error as CommonError, Field, Problem},
66 model::{
77 CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage,
88 User,
@@ -11,13 +11,13 @@ use common::{
1111 };
1212 use turso::{Connection, Row};
1313
14-use crate::{attachment, community, database, database::new_id, error::Error, user};
14+use crate::{attachment, community, database, database::new_id, error::ServerError, user};
1515
1616 const SEARCH_LIMIT: usize = 200;
1717
1818 const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to";
1919
20-fn from_row(row: &Row) -> Result<Message, Error> {
20+fn from_row(row: &Row) -> Result<Message, ServerError> {
2121 let edited: i64 = row.get(4)?;
2222 let call_seconds: i64 = row.get(10)?;
2323 let pinned: i64 = row.get(11)?;
@@ -64,7 +64,7 @@ fn placeholders(count: usize) -> String {
6464 async fn reactions_of(
6565 message_ids: &[String],
6666 conn: &Connection,
67-) -> Result<HashMap<String, Vec<Reaction>>, Error> {
67+) -> Result<HashMap<String, Vec<Reaction>>, ServerError> {
6868 let mut reactions: HashMap<String, Vec<Reaction>> = HashMap::new();
6969 if message_ids.is_empty() {
7070 return Ok(reactions);
@@ -103,7 +103,7 @@ async fn reactions_of(
103103 async fn polls_of(
104104 message_ids: &[String],
105105 conn: &Connection,
106-) -> Result<HashMap<String, Poll>, Error> {
106+) -> Result<HashMap<String, Poll>, ServerError> {
107107 let mut polls: HashMap<String, Poll> = HashMap::new();
108108 if message_ids.is_empty() {
109109 return Ok(polls);
@@ -174,7 +174,7 @@ async fn polls_of(
174174 Ok(polls)
175175 }
176176
177-async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, Error> {
177+async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, ServerError> {
178178 let mut rows = conn
179179 .query(
180180 "SELECT origin FROM snippet WHERE message_id = ?1",
@@ -222,7 +222,7 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippe
222222 Ok(Some(Snippet { origin, messages }))
223223 }
224224
225-async fn hydrate(messages: Vec<Message>, conn: &Connection) -> Result<Vec<Message>, Error> {
225+async fn hydrate(messages: Vec<Message>, conn: &Connection) -> Result<Vec<Message>, ServerError> {
226226 let ids: Vec<String> = messages.iter().map(|message| message.id.clone()).collect();
227227 let mut reactions = reactions_of(&ids, conn).await?;
228228 let mut polls = polls_of(&ids, conn).await?;
@@ -245,7 +245,7 @@ async fn insert(
245245 body: &str,
246246 reply_to: Option<&str>,
247247 conn: &Connection,
248-) -> Result<String, Error> {
248+) -> Result<String, ServerError> {
249249 let message_id = new_id();
250250 conn.execute(
251251 "INSERT INTO message (id, user_id, community_id, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5)",
@@ -260,7 +260,7 @@ pub async fn ensure_in_community(
260260 message_id: &str,
261261 community_id: &str,
262262 conn: &Connection,
263-) -> Result<(), Error> {
263+) -> Result<(), ServerError> {
264264 let mut rows = conn
265265 .query(
266266 "SELECT id FROM message WHERE id = ?1 AND community_id = ?2",
@@ -279,7 +279,7 @@ pub async fn create_call_log(
279279 user_id: &str,
280280 call: CallLog,
281281 conn: &Connection,
282-) -> Result<Message, Error> {
282+) -> Result<Message, ServerError> {
283283 let message_id = new_id();
284284 conn.execute(
285285 "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)",
@@ -303,7 +303,7 @@ pub async fn create(
303303 attachments: &[String],
304304 reply_to: Option<&str>,
305305 conn: &Connection,
306-) -> Result<Message, Error> {
306+) -> Result<Message, ServerError> {
307307 if let Some(reply_to) = reply_to {
308308 ensure_in_community(reply_to, community_id, conn).await?;
309309 }
@@ -314,7 +314,7 @@ pub async fn create(
314314 read(&message_id, conn).await
315315 }
316316
317-pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, Error> {
317+pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, ServerError> {
318318 let mut rows = conn
319319 .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,))
320320 .await?;
@@ -332,7 +332,7 @@ pub async fn read_page(
332332 community_id: &str,
333333 before: Option<&str>,
334334 conn: &Connection,
335-) -> Result<Vec<Message>, Error> {
335+) -> Result<Vec<Message>, ServerError> {
336336 let mut rows = conn
337337 .query(
338338 &format!(
@@ -359,7 +359,7 @@ pub async fn create_poll(
359359 options: &[String],
360360 multiple: bool,
361361 conn: &Connection,
362-) -> Result<Message, Error> {
362+) -> Result<Message, ServerError> {
363363 let message_id = insert(user_id, community_id, "", None, conn).await?;
364364 conn.execute(
365365 "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)",
@@ -382,7 +382,7 @@ pub async fn vote(
382382 user_id: &str,
383383 positions: &[u32],
384384 conn: &Connection,
385-) -> Result<Message, Error> {
385+) -> Result<Message, ServerError> {
386386 conn.execute(
387387 "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2",
388388 (message_id, user_id),
@@ -399,7 +399,7 @@ pub async fn vote(
399399 read(message_id, conn).await
400400 }
401401
402-pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message, Error> {
402+pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message, ServerError> {
403403 let updated = conn
404404 .execute(
405405 "UPDATE poll SET closed = 1 WHERE message_id = ?1",
@@ -416,7 +416,7 @@ pub async fn react(
416416 user_id: &str,
417417 emoji: &str,
418418 conn: &Connection,
419-) -> Result<Message, Error> {
419+) -> Result<Message, ServerError> {
420420 let removed = conn
421421 .execute(
422422 "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3",
@@ -434,7 +434,11 @@ pub async fn react(
434434 read(message_id, conn).await
435435 }
436436
437-pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result<Message, Error> {
437+pub async fn pin(
438+ message_id: &str,
439+ pinned: bool,
440+ conn: &Connection,
441+) -> Result<Message, ServerError> {
438442 conn.execute(
439443 "UPDATE message SET pinned = ?2 WHERE id = ?1",
440444 (message_id, pinned as i64),
@@ -444,7 +448,7 @@ pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result<Me
444448 read(message_id, conn).await
445449 }
446450
447-pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message>, Error> {
451+pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message>, ServerError> {
448452 let mut rows = conn
449453 .query(
450454 &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"),
@@ -461,7 +465,11 @@ pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message
461465 hydrate(messages, conn).await
462466 }
463467
464-pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {
468+pub async fn update(
469+ message_id: &str,
470+ body: &str,
471+ conn: &Connection,
472+) -> Result<Message, ServerError> {
465473 let updated = conn
466474 .execute(
467475 "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",
@@ -473,7 +481,7 @@ pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<M
473481 read(message_id, conn).await
474482 }
475483
476-pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Error> {
484+pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, ServerError> {
477485 let message = read(message_id, conn).await?;
478486 conn.execute("DELETE FROM message WHERE id = ?1", (message_id,))
479487 .await?;
@@ -481,7 +489,7 @@ pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Erro
481489 Ok(message)
482490 }
483491
484-pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
492+pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> {
485493 database::ids(
486494 conn,
487495 "SELECT id FROM message WHERE user_id = ?1",
@@ -497,7 +505,7 @@ pub async fn search(
497505 after_ms: Option<u64>,
498506 before_ms: Option<u64>,
499507 conn: &Connection,
500-) -> Result<Vec<MessageHit>, Error> {
508+) -> Result<Vec<MessageHit>, ServerError> {
501509 let (after, before) = time::range_bounds(after_ms, before_ms);
502510 let mut rows = conn
503511 .query(
@@ -534,7 +542,7 @@ pub async fn search(
534542 Ok(hits)
535543 }
536544
537-async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, Error> {
545+async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, ServerError> {
538546 let Some(first) = sources.first() else {
539547 return Ok(None);
540548 };
@@ -558,7 +566,7 @@ async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>
558566 })
559567 }
560568
561-async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Error> {
569+async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, ServerError> {
562570 let author: User = user::read(&source.user_id, conn).await?;
563571
564572 Ok(SnippetMessage {
@@ -580,7 +588,7 @@ async fn write_snippet(
580588 entries: &[SnippetMessage],
581589 directory: &Path,
582590 conn: &Connection,
583-) -> Result<(), Error> {
591+) -> Result<(), ServerError> {
584592 conn.execute(
585593 "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)",
586594 (message_id, origin),
@@ -634,7 +642,7 @@ pub async fn forward(
634642 mode: ForwardMode,
635643 directory: &Path,
636644 conn: &Connection,
637-) -> Result<Vec<Message>, Error> {
645+) -> Result<Vec<Message>, ServerError> {
638646 if mode == ForwardMode::Copy {
639647 let mut created = Vec::new();
640648 for source in sources {
@@ -679,9 +687,10 @@ pub async fn forward(
679687 if entries.len() > MAXIMUM_FORWARD_MESSAGES {
680688 return Err(CommonError::Invalid {
681689 field: Field::Forward,
682- input: InvalidInput::TooLong {
683- maximum: MAXIMUM_FORWARD_MESSAGES,
684- actual: entries.len(),
690+ problem: Problem::Length {
691+ min: 1,
692+ max: MAXIMUM_FORWARD_MESSAGES as u64,
693+ actual: entries.len() as u64,
685694 },
686695 }
687696 .into());
@@ -707,7 +716,7 @@ pub async fn forward(
707716 mod tests {
708717 use common::error::Error as CommonError;
709718
710- use crate::{community, database, error::Error, message, test, user};
719+ use crate::{community, database, error::ServerError, message, test, user};
711720
712721 #[tokio::test]
713722 async fn create() {
@@ -802,7 +811,7 @@ mod tests {
802811
803812 assert!(matches!(
804813 updated_message,
805- Err(Error::Common(CommonError::NotFound))
814+ Err(ServerError::Wire(CommonError::NotFound))
806815 ));
807816 }
808817
crates/server/src/network.rsmodified+52 -62
@@ -6,21 +6,21 @@ use std::{
66
77 use common::{
88 event::Event as Push,
9+ frame::{self, DOWN_MAX, Sending, UP_MAX},
910 model::User,
10- network::{
11- REQUEST_MAX_READ_LENGTH, StreamKind, receive_decoded, receive_stream_kind, send_event,
12- send_response,
13- },
11+ open::Open,
1412 request::Request,
13+ transport::Close,
1514 };
1615 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
1716 use tokio::{sync::mpsc, task::JoinHandle};
1817 use tracing::{info, warn};
1918
2019 use crate::{
21- attachment, authentication, backup,
20+ attachment, authentication,
2221 database::{self, DB},
23- error::Error,
22+ datagram,
23+ error::ServerError,
2424 rate_limit::RateLimit,
2525 request::{self, Broadcast},
2626 server_ban,
@@ -139,7 +139,7 @@ impl Presence {
139139 self.user_ids().len()
140140 }
141141
142- fn close_where(&self, matches: impl Fn(&Signed) -> bool, reason: &[u8]) {
142+ fn close_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) {
143143 let connections: Vec<Connection> = self
144144 .0
145145 .lock()
@@ -149,20 +149,20 @@ impl Presence {
149149 .map(|signed| signed.connection.clone())
150150 .collect();
151151 for connection in connections {
152- connection.close(0u32.into(), reason);
152+ connection.close(close.code(), close.reason().as_bytes());
153153 }
154154 }
155155
156- pub fn disconnect(&self, user_id: &str) {
157- self.close_where(|signed| signed.user_id == user_id, b"signed out");
156+ pub fn disconnect(&self, user_id: &str, close: Close) {
157+ self.close_where(|signed| signed.user_id == user_id, close);
158158 }
159159
160- pub fn disconnect_except(&self, keep: &[String], reason: &[u8]) {
161- self.close_where(|signed| !keep.contains(&signed.user_id), reason);
160+ pub fn disconnect_except(&self, keep: &[String], close: Close) {
161+ self.close_where(|signed| !keep.contains(&signed.user_id), close);
162162 }
163163
164164 pub fn disconnect_token(&self, token: &str) {
165- self.close_where(|signed| signed.token == token, b"session revoked");
165+ self.close_where(|signed| signed.token == token, Close::Revoked);
166166 }
167167 }
168168
@@ -194,10 +194,10 @@ struct Session {
194194 }
195195
196196 #[derive(Clone)]
197-struct Shared {
197+pub(crate) struct Shared {
198198 event_sender: mpsc::Sender<Event>,
199199 db: DB,
200- services: Services,
200+ pub(crate) services: Services,
201201 directory: PathBuf,
202202 backups: PathBuf,
203203 }
@@ -208,7 +208,7 @@ pub async fn serve(
208208 db: DB,
209209 directory: PathBuf,
210210 backups: PathBuf,
211-) -> Result<(), Error> {
211+) -> Result<(), ServerError> {
212212 let endpoint = Endpoint::server(server_config, server_address.parse()?)?;
213213 info!("listening on {server_address}");
214214
@@ -236,11 +236,14 @@ async fn handle_connection(incoming: Incoming, shared: Shared) {
236236 }
237237 }
238238
239-async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Error> {
239+async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> {
240240 let ip = incoming.remote_address().ip().to_string();
241241 let conn = database::connect(&shared.db).await?;
242242 if server_ban::ip_banned(&ip, &conn).await? {
243- incoming.refuse();
243+ incoming
244+ .accept()?
245+ .await?
246+ .close(Close::Banned.code(), Close::Banned.reason().as_bytes());
244247 return Ok(());
245248 }
246249 let connection = incoming.await?;
@@ -256,7 +259,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
256259
257260 let state = Arc::new(Mutex::new(State::Anonymous));
258261
259- tokio::spawn(relay_datagrams(
262+ tokio::spawn(datagram::relay_datagrams(
260263 connection.clone(),
261264 Arc::clone(&state),
262265 shared.clone(),
@@ -297,31 +300,21 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
297300 Ok(())
298301 }
299302
300-async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, shared: Shared) {
301- while let Ok(bytes) = connection.read_datagram().await {
302- if matches!(*state.lock().unwrap(), State::Authenticated { .. }) {
303- shared.services.voice.relay(connection.stable_id(), &bytes);
304- let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes);
305- publish(&shared, broadcasts).await;
306- }
307- }
308-}
309-
310303 async fn route(
311304 connection: Connection,
312305 state: Arc<Mutex<State>>,
313306 (send_stream, mut receive_stream): (SendStream, RecvStream),
314307 shared: Shared,
315-) -> Result<(), Error> {
316- let kind = receive_stream_kind(&mut receive_stream).await?;
308+) -> Result<(), ServerError> {
309+ let send_stream = Sending::new(send_stream);
310+ let open: Open = frame::read(&mut receive_stream, UP_MAX).await?;
317311 let user = signed_user(&state);
318- match kind {
319- StreamKind::Request => {
320- answer(connection, state, (send_stream, receive_stream), shared).await
321- }
322- StreamKind::Upload => {
312+ match open {
313+ Open::Call(request) => answer(connection, state, request, send_stream, shared).await,
314+ Open::Upload(upload) => {
323315 attachment::upload(
324316 user.as_ref(),
317+ upload,
325318 receive_stream,
326319 send_stream,
327320 &shared.db,
@@ -329,22 +322,13 @@ async fn route(
329322 )
330323 .await
331324 }
332- StreamKind::Download => {
333- attachment::download(
325+ Open::Fetch(blob) => {
326+ attachment::fetch(
334327 user.as_ref(),
335- receive_stream,
328+ blob,
336329 send_stream,
337330 &shared.db,
338331 &shared.directory,
339- )
340- .await
341- }
342- StreamKind::Backup => {
343- backup::download(
344- user.as_ref(),
345- receive_stream,
346- send_stream,
347- &shared.db,
348332 &shared.backups,
349333 )
350334 .await
@@ -355,11 +339,10 @@ async fn route(
355339 async fn answer(
356340 connection: Connection,
357341 state: Arc<Mutex<State>>,
358- (send_stream, mut receive_stream): (SendStream, RecvStream),
342+ request: Request,
343+ mut send_stream: Sending,
359344 shared: Shared,
360-) -> Result<(), Error> {
361- let request: Request = receive_decoded(&mut receive_stream, REQUEST_MAX_READ_LENGTH).await?;
362-
345+) -> Result<(), ServerError> {
363346 let before = signed_in(&state);
364347 let (response, broadcasts) = request::handle(
365348 request,
@@ -377,7 +360,10 @@ async fn answer(
377360 let connection_id = connection.stable_id();
378361 shared.services.visits.forget(connection_id);
379362 match &after {
380- Some((user_id, token)) => shared.services.presence.sign_in(&connection, user_id, token),
363+ Some((user_id, token)) => shared
364+ .services
365+ .presence
366+ .sign_in(&connection, user_id, token),
381367 None => shared.services.presence.sign_out(connection_id),
382368 }
383369 let before_id = before.map(|(user_id, _)| user_id);
@@ -392,21 +378,22 @@ async fn answer(
392378 if let Some(user_id) = &before_id {
393379 broadcast_presence(&shared, user_id).await;
394380 }
395- if after_id != before_id {
396- if let Some(user_id) = &after_id {
397- broadcast_presence(&shared, user_id).await;
398- }
381+ if after_id != before_id
382+ && let Some(user_id) = &after_id
383+ {
384+ broadcast_presence(&shared, user_id).await;
399385 }
400386 }
401387
402388 publish(&shared, broadcasts).await;
403389
404- send_response(&response, send_stream).await?;
390+ frame::write(&mut send_stream, &response, DOWN_MAX).await?;
391+ send_stream.finish()?;
405392
406393 Ok(())
407394 }
408395
409-async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) {
396+pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) {
410397 for broadcast in broadcasts {
411398 let _ = shared
412399 .event_sender
@@ -440,9 +427,10 @@ fn signed_in(state: &Mutex<State>) -> Option<(String, String)> {
440427 }
441428 }
442429
443-async fn write_session(mut event_receiver: mpsc::Receiver<Arc<Push>>, mut send_stream: SendStream) {
430+async fn write_session(mut event_receiver: mpsc::Receiver<Arc<Push>>, send_stream: SendStream) {
431+ let mut send_stream = Sending::new(send_stream);
444432 while let Some(event) = event_receiver.recv().await {
445- if let Err(error) = send_event(&event, &mut send_stream).await {
433+ if let Err(error) = frame::write(&mut send_stream, &*event, DOWN_MAX).await {
446434 warn!("session write: {error}");
447435 break;
448436 }
@@ -505,7 +493,9 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) {
505493 Err(error) => {
506494 warn!("session dropped {user_id}: {error}");
507495 session.writer.abort();
508- session.connection.close(0u32.into(), b"slow");
496+ session
497+ .connection
498+ .close(Close::Slow.code(), Close::Slow.reason().as_bytes());
509499 false
510500 }
511501 }
crates/server/src/notes.rsmodified+3 -3
@@ -1,9 +1,9 @@
11 use common::model::{Community, Rank};
22 use turso::Connection;
33
4-use crate::{community, error::Error, user_community};
4+use crate::{community, error::ServerError, user_community};
55
6-async fn find(user_id: &str, conn: &Connection) -> Result<Option<String>, Error> {
6+async fn find(user_id: &str, conn: &Connection) -> Result<Option<String>, ServerError> {
77 let mut rows = conn
88 .query(
99 "SELECT community_id FROM notes WHERE user_id = ?1",
@@ -14,7 +14,7 @@ async fn find(user_id: &str, conn: &Connection) -> Result<Option<String>, Error>
1414 Ok(rows.next().await?.map(|row| row.get(0)).transpose()?)
1515 }
1616
17-pub async fn open(me: &str, conn: &mut Connection) -> Result<Community, Error> {
17+pub async fn open(me: &str, conn: &mut Connection) -> Result<Community, ServerError> {
1818 let tx = conn.transaction().await?;
1919 let community_id = match find(me, &tx).await? {
2020 Some(community_id) => community_id,
crates/server/src/overview.rsmodified+3 -3
@@ -1,13 +1,13 @@
11 use common::model::{Overview, Role};
22 use turso::Connection;
33
4-use crate::{community::Kind, error::Error, network::Presence, voice::Voice};
4+use crate::{community::Kind, error::ServerError, network::Presence, voice::Voice};
55
66 pub async fn read(
77 presence: &Presence,
88 voice: &Voice,
99 conn: &Connection,
10-) -> Result<Overview, Error> {
10+) -> Result<Overview, ServerError> {
1111 let mut rows = conn
1212 .query(
1313 "SELECT
@@ -24,7 +24,7 @@ pub async fn read(
2424 .next()
2525 .await?
2626 .ok_or(turso::Error::QueryReturnedNoRows)?;
27- let count = |index: usize| -> Result<u64, Error> {
27+ let count = |index: usize| -> Result<u64, ServerError> {
2828 let value: i64 = row.get(index)?;
2929 Ok(value as u64)
3030 };
crates/server/src/report.rsmodified+8 -5
@@ -7,7 +7,7 @@ use turso::Connection;
77
88 use crate::{
99 database::{self, new_id},
10- error::Error,
10+ error::ServerError,
1111 user,
1212 };
1313
@@ -16,7 +16,7 @@ pub async fn is_open(
1616 target_id: &str,
1717 message_id: Option<&str>,
1818 conn: &Connection,
19-) -> Result<bool, Error> {
19+) -> Result<bool, ServerError> {
2020 database::exists(
2121 conn,
2222 "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)",
@@ -33,7 +33,7 @@ pub async fn insert(
3333 body: Option<&str>,
3434 reason: &str,
3535 conn: &Connection,
36-) -> Result<(), Error> {
36+) -> Result<(), ServerError> {
3737 conn.execute(
3838 "INSERT INTO report (id, reporter_id, target_id, message_id, community_id, body, reason) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
3939 (new_id(), reporter_id, target_id, message_id, community_id, body, reason),
@@ -43,7 +43,10 @@ pub async fn insert(
4343 Ok(())
4444 }
4545
46-pub async fn list(status: Option<ReportStatus>, conn: &Connection) -> Result<Vec<Report>, Error> {
46+pub async fn list(
47+ status: Option<ReportStatus>,
48+ conn: &Connection,
49+) -> Result<Vec<Report>, ServerError> {
4750 let mut rows = conn
4851 .query(
4952 &format!("SELECT r.id, {}, {}, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, {} FROM report r LEFT JOIN user rp ON rp.id = r.reporter_id LEFT JOIN user t ON t.id = r.target_id LEFT JOIN community c ON c.id = r.community_id LEFT JOIN user h ON h.id = r.handled_by WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("rp"), user::user_columns("t"), user::user_columns("h")),
@@ -76,7 +79,7 @@ pub async fn handle(
7679 status: ReportStatus,
7780 handled_by: &str,
7881 conn: &Connection,
79-) -> Result<Option<String>, Error> {
82+) -> Result<Option<String>, ServerError> {
8083 let mut rows = conn
8184 .query(
8285 "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id",
crates/server/src/request.rsmodified+71 -55
@@ -16,6 +16,7 @@ use common::{
1616 response::Response,
1717 share::{Kind, Share},
1818 time::{self, MINUTE_MILLIS},
19+ transport::Close,
1920 validate::{
2021 validate_avatar_size, validate_forward, validate_new_message, validate_poll,
2122 validate_reaction, validate_reason, validate_server_settings, validate_vote,
@@ -27,7 +28,7 @@ use crate::{
2728 admin_log, attachment, authentication, backup, community,
2829 database::{self, DB},
2930 direct,
30- error::Error,
31+ error::ServerError,
3132 friend, invitation, invite, log, message,
3233 network::{self, Services, State},
3334 notes, overview,
@@ -53,10 +54,10 @@ pub async fn handle(
5354 connection: Option<&quinn::Connection>,
5455 directory: &Path,
5556 backups: &Path,
56-) -> Outcome {
57+) -> (Result<Response, CommonError>, Vec<Broadcast>) {
5758 match dispatch(request, state, db, services, connection, directory, backups).await {
58- Ok(outcome) => outcome,
59- Err(error) => (Response::Error(error.into()), Vec::new()),
59+ Ok((response, broadcasts)) => (Ok(response), broadcasts),
60+ Err(error) => (Err(error.into()), Vec::new()),
6061 }
6162 }
6263
@@ -68,7 +69,7 @@ async fn dispatch(
6869 connection: Option<&quinn::Connection>,
6970 directory: &Path,
7071 backups: &Path,
71-) -> Result<Outcome, Error> {
72+) -> Result<Outcome, ServerError> {
7273 let Services {
7374 voice,
7475 share,
@@ -146,7 +147,7 @@ async fn dispatch(
146147 .await?;
147148 if settings.maintenance {
148149 let builders = user::builder_ids(&conn).await?;
149- presence.disconnect_except(&builders, b"maintenance");
150+ presence.disconnect_except(&builders, Close::Maintenance);
150151 }
151152 let broadcasts = if settings.announcement == previous.announcement {
152153 Vec::new()
@@ -275,7 +276,7 @@ async fn dispatch(
275276 admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?;
276277 if suspended {
277278 authentication::revoke_sessions(&user_id, &conn).await?;
278- presence.disconnect(&user_id);
279+ presence.disconnect(&user_id, Close::Revoked);
279280 }
280281 (Response::Done, Vec::new())
281282 }
@@ -283,7 +284,7 @@ async fn dispatch(
283284 let me = authenticated(state, &conn).await?;
284285 managed(&me, &user_id, &conn).await?;
285286 authentication::revoke_sessions(&user_id, &conn).await?;
286- presence.disconnect(&user_id);
287+ presence.disconnect(&user_id, Close::Revoked);
287288 admin_log::record(
288289 Some(&me.id),
289290 Some(&user_id),
@@ -298,7 +299,7 @@ async fn dispatch(
298299 let me = authenticated(state, &conn).await?;
299300 managed(&me, &user_id, &conn).await?;
300301 authentication::reset_password(&user_id, &password, &conn).await?;
301- presence.disconnect(&user_id);
302+ presence.disconnect(&user_id, Close::Revoked);
302303 admin_log::record(
303304 Some(&me.id),
304305 Some(&user_id),
@@ -342,7 +343,7 @@ async fn dispatch(
342343 broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?);
343344 } else {
344345 user::set_ghost(&user_id, false, &conn).await?;
345- presence.disconnect(&user_id);
346+ presence.disconnect(&user_id, Close::Revoked);
346347 }
347348 (Response::User(user), broadcasts)
348349 }
@@ -435,7 +436,7 @@ async fn dispatch(
435436 if me.id == user_id {
436437 set_state(state, State::Anonymous);
437438 } else {
438- presence.disconnect(&user_id);
439+ presence.disconnect(&user_id, Close::Revoked);
439440 }
440441 (Response::User(deleted), broadcasts)
441442 }
@@ -1291,7 +1292,7 @@ async fn dispatch(
12911292 user::set_timeout(&user_id, until, &conn).await?;
12921293 if until.is_some() {
12931294 authentication::revoke_sessions(&user_id, &conn).await?;
1294- presence.disconnect(&user_id);
1295+ presence.disconnect(&user_id, Close::Revoked);
12951296 }
12961297 admin_log::record(
12971298 Some(&me.id),
@@ -1337,7 +1338,7 @@ async fn dispatch(
13371338 )
13381339 .await?;
13391340 tx.commit().await?;
1340- presence.disconnect(&user_id);
1341+ presence.disconnect(&user_id, Close::Banned);
13411342 (Response::Done, Vec::new())
13421343 }
13431344 Request::ServerBans => {
@@ -1549,9 +1550,6 @@ async fn dispatch(
15491550 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
15501551 (Response::Done, Vec::new())
15511552 }
1552- Request::DownloadBackup { .. } => {
1553- return Err(CommonError::Server.into());
1554- }
15551553 Request::VoiceRooms => {
15561554 builder(state, &conn).await?;
15571555 (
@@ -1687,7 +1685,7 @@ async fn dispatch(
16871685 Ok(outcome)
16881686 }
16891687
1690-async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>, Error> {
1688+async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>, ServerError> {
16911689 let mut rooms = Vec::new();
16921690 for (community_id, user_ids, ghosts) in voice.rooms() {
16931691 let community = community::label(&community_id, conn).await?;
@@ -1713,7 +1711,7 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>,
17131711 Ok(rooms)
17141712 }
17151713
1716-async fn report_created(conn: &Connection) -> Result<Broadcast, Error> {
1714+async fn report_created(conn: &Connection) -> Result<Broadcast, ServerError> {
17171715 Ok(Broadcast {
17181716 event: Event::ReportCreated,
17191717 user_ids: user::builder_ids(conn).await?,
@@ -1728,7 +1726,7 @@ async fn limit_logins(
17281726 rate_limit: &RateLimit,
17291727 connection: Option<&quinn::Connection>,
17301728 conn: &Connection,
1731-) -> Result<(), Error> {
1729+) -> Result<(), ServerError> {
17321730 let limit = server_settings::read(conn).await?.logins_per_minute;
17331731
17341732 Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)
@@ -1738,7 +1736,7 @@ fn limit_messages(
17381736 me: &User,
17391737 rate_limit: &RateLimit,
17401738 settings: &ServerSettings,
1741-) -> Result<(), Error> {
1739+) -> Result<(), ServerError> {
17421740 if permission::is_builder(me.role) {
17431741 return Ok(());
17441742 }
@@ -1750,7 +1748,7 @@ async fn record_address(
17501748 user: &User,
17511749 connection: Option<&quinn::Connection>,
17521750 conn: &Connection,
1753-) -> Result<(), Error> {
1751+) -> Result<(), ServerError> {
17541752 if let Some(ip) = ip_of(connection) {
17551753 user::set_last_ip(&user.id, &ip, conn).await?;
17561754 }
@@ -1771,7 +1769,7 @@ async fn remove_member(
17711769 voice: &Voice,
17721770 share: &Shares,
17731771 conn: &mut Connection,
1774-) -> Result<Outcome, Error> {
1772+) -> Result<Outcome, ServerError> {
17751773 let Removal {
17761774 community_id,
17771775 user_id,
@@ -1821,7 +1819,7 @@ async fn remove_member(
18211819 Ok((Response::Done, broadcasts))
18221820 }
18231821
1824-async fn related_user_ids(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
1822+async fn related_user_ids(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> {
18251823 let mut user_ids = BTreeSet::from([user_id.to_string()]);
18261824 for community in community::communities_of(user_id, conn).await? {
18271825 for member in user_community::members(&community.id, conn).await? {
@@ -1835,7 +1833,7 @@ async fn related_user_ids(user_id: &str, conn: &Connection) -> Result<Vec<String
18351833 Ok(user_ids.into_iter().collect())
18361834 }
18371835
1838-async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
1836+async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, ServerError> {
18391837 Ok(vec![Broadcast {
18401838 event: Event::UserUpdated(user.clone()),
18411839 user_ids: related_user_ids(&user.id, conn).await?,
@@ -1846,7 +1844,7 @@ async fn effective_presence(
18461844 presence: &network::Presence,
18471845 user_id: &str,
18481846 conn: &Connection,
1849-) -> Result<Presence, Error> {
1847+) -> Result<Presence, ServerError> {
18501848 if !presence.is_online(user_id) {
18511849 return Ok(Presence::Offline);
18521850 }
@@ -1858,7 +1856,7 @@ pub async fn presence_changed(
18581856 presence: &network::Presence,
18591857 user_id: &str,
18601858 conn: &Connection,
1861-) -> Result<Vec<Broadcast>, Error> {
1859+) -> Result<Vec<Broadcast>, ServerError> {
18621860 let presence = effective_presence(presence, user_id, conn).await?;
18631861
18641862 Ok(vec![Broadcast {
@@ -1870,7 +1868,10 @@ pub async fn presence_changed(
18701868 }])
18711869 }
18721870
1873-async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result<Vec<Broadcast>, Error> {
1871+async fn friends_updated(
1872+ user_ids: &[&str],
1873+ conn: &Connection,
1874+) -> Result<Vec<Broadcast>, ServerError> {
18741875 let mut broadcasts = Vec::new();
18751876 for user_id in user_ids {
18761877 broadcasts.push(Broadcast {
@@ -1882,7 +1883,7 @@ async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result<Vec<Bro
18821883 Ok(broadcasts)
18831884 }
18841885
1885-async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, Error> {
1886+async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, ServerError> {
18861887 Ok(Broadcast {
18871888 event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?),
18881889 user_ids: vec![user_id.to_string()],
@@ -1894,7 +1895,7 @@ async fn leave_user_voice(
18941895 share: &Shares,
18951896 user_id: &str,
18961897 conn: &Connection,
1897-) -> Result<Vec<Broadcast>, Error> {
1898+) -> Result<Vec<Broadcast>, ServerError> {
18981899 match voice.leave(user_id) {
18991900 Some(left) => voice_left(share, left, conn).await,
19001901 None => Ok(Vec::new()),
@@ -1906,7 +1907,7 @@ pub async fn leave_connection_voice(
19061907 share: &Shares,
19071908 connection: Option<&quinn::Connection>,
19081909 conn: &Connection,
1909-) -> Result<Vec<Broadcast>, Error> {
1910+) -> Result<Vec<Broadcast>, ServerError> {
19101911 match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) {
19111912 Some(left) => voice_left(share, left, conn).await,
19121913 None => Ok(Vec::new()),
@@ -1919,7 +1920,7 @@ async fn leave_room_voice(
19191920 community_id: &str,
19201921 user_id: &str,
19211922 conn: &Connection,
1922-) -> Result<Vec<Broadcast>, Error> {
1923+) -> Result<Vec<Broadcast>, ServerError> {
19231924 match voice.leave_room(community_id, user_id) {
19241925 Some(left) => voice_left(share, left, conn).await,
19251926 None => Ok(Vec::new()),
@@ -1930,7 +1931,7 @@ async fn voice_unmuted(
19301931 voice: &Voice,
19311932 user_id: &str,
19321933 conn: &Connection,
1933-) -> Result<Vec<Broadcast>, Error> {
1934+) -> Result<Vec<Broadcast>, ServerError> {
19341935 let Some(community_id) = voice.set_muted(user_id, false) else {
19351936 return Ok(Vec::new());
19361937 };
@@ -1958,7 +1959,7 @@ async fn voice_silenced(
19581959 share: &Shares,
19591960 community_id: &str,
19601961 conn: &Connection,
1961-) -> Result<Vec<Broadcast>, Error> {
1962+) -> Result<Vec<Broadcast>, ServerError> {
19621963 let mut broadcasts = Vec::new();
19631964 for user_id in voice.room_users(community_id) {
19641965 if permission::is_builder(user::read(&user_id, conn).await?.role) {
@@ -1977,7 +1978,7 @@ async fn voice_closed(
19771978 share: &Shares,
19781979 community_id: &str,
19791980 conn: &Connection,
1980-) -> Result<Vec<Broadcast>, Error> {
1981+) -> Result<Vec<Broadcast>, ServerError> {
19811982 let mut broadcasts = Vec::new();
19821983 for left in voice.remove_room(community_id) {
19831984 broadcasts.extend(voice_left(share, left, conn).await?);
@@ -2000,7 +2001,7 @@ async fn call_ended(
20002001 call: Option<CallEnd>,
20012002 members: &[Member],
20022003 conn: &Connection,
2003-) -> Result<Vec<Broadcast>, Error> {
2004+) -> Result<Vec<Broadcast>, ServerError> {
20042005 let Some(call) = call else {
20052006 return Ok(Vec::new());
20062007 };
@@ -2019,7 +2020,7 @@ async fn voice_left(
20192020 share: &Shares,
20202021 left: Left,
20212022 conn: &Connection,
2022-) -> Result<Vec<Broadcast>, Error> {
2023+) -> Result<Vec<Broadcast>, ServerError> {
20232024 let mut broadcasts = share_left(share, &left.user_id, conn).await?;
20242025 let Some(seconds) = left.ghost_seconds else {
20252026 let members = user_community::members(&left.community_id, conn).await?;
@@ -2044,7 +2045,7 @@ async fn share_ended(
20442045 user_id: &str,
20452046 kind: Kind,
20462047 conn: &Connection,
2047-) -> Result<Broadcast, Error> {
2048+) -> Result<Broadcast, ServerError> {
20482049 let members = user_community::members(community_id, conn).await?;
20492050 let event = Event::ShareStopped {
20502051 community_id: community_id.to_string(),
@@ -2060,7 +2061,7 @@ async fn share_stopped(
20602061 user_id: &str,
20612062 kind: Kind,
20622063 conn: &Connection,
2063-) -> Result<Vec<Broadcast>, Error> {
2064+) -> Result<Vec<Broadcast>, ServerError> {
20642065 let Some(community_id) = share.stop(user_id, kind) else {
20652066 return Ok(Vec::new());
20662067 };
@@ -2072,7 +2073,7 @@ async fn share_left(
20722073 share: &Shares,
20732074 user_id: &str,
20742075 conn: &Connection,
2075-) -> Result<Vec<Broadcast>, Error> {
2076+) -> Result<Vec<Broadcast>, ServerError> {
20762077 let mut broadcasts = Vec::new();
20772078 for (community_id, kind) in share.stop_all(user_id) {
20782079 broadcasts.push(share_ended(&community_id, user_id, kind, conn).await?);
@@ -2090,7 +2091,7 @@ async fn enter(
20902091 share: &Shares,
20912092 connection: Option<&quinn::Connection>,
20922093 conn: &Connection,
2093-) -> Result<Outcome, Error> {
2094+) -> Result<Outcome, ServerError> {
20942095 stats::mark_active(&user.id, conn).await?;
20952096 record_address(&user, connection, conn).await?;
20962097 let broadcasts = leave_connection_voice(voice, share, connection, conn).await?;
@@ -2114,14 +2115,14 @@ fn set_state(state: &Mutex<State>, new_state: State) {
21142115 *state.lock().unwrap() = new_state;
21152116 }
21162117
2117-fn session(state: &Mutex<State>) -> Result<(User, String), Error> {
2118+fn session(state: &Mutex<State>) -> Result<(User, String), ServerError> {
21182119 match state.lock().unwrap().clone() {
21192120 State::Anonymous => Err(CommonError::Unauthenticated.into()),
21202121 State::Authenticated { user, token } => Ok((user, token)),
21212122 }
21222123 }
21232124
2124-fn session_token(state: &Mutex<State>) -> Result<String, Error> {
2125+fn session_token(state: &Mutex<State>) -> Result<String, ServerError> {
21252126 Ok(session(state)?.1)
21262127 }
21272128
@@ -2131,7 +2132,7 @@ fn cache_user(state: &Mutex<State>, user: User) {
21312132 }
21322133 }
21332134
2134-async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> {
2135+async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, ServerError> {
21352136 let (cached, _) = session(state)?;
21362137 let user = user::read(&cached.id, conn).await?;
21372138 cache_user(state, user.clone());
@@ -2139,7 +2140,7 @@ async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User,
21392140 Ok(user)
21402141 }
21412142
2142-async fn builder(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> {
2143+async fn builder(state: &Mutex<State>, conn: &Connection) -> Result<User, ServerError> {
21432144 let user = authenticated(state, conn).await?;
21442145 ensure(permission::is_builder(user.role))?;
21452146
@@ -2150,13 +2151,13 @@ pub async fn actor_rank(
21502151 me: &User,
21512152 community_id: &str,
21522153 conn: &Connection,
2153-) -> Result<Option<Rank>, Error> {
2154+) -> Result<Option<Rank>, ServerError> {
21542155 let rank = user_community::rank(&me.id, community_id, conn).await?;
21552156
21562157 Ok(permission::effective_rank(me.role, rank))
21572158 }
21582159
2159-async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, Error> {
2160+async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, ServerError> {
21602161 let target = user::read(user_id, conn).await?;
21612162 ensure(permission::can_manage_user(
21622163 me.role,
@@ -2167,11 +2168,11 @@ async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, Er
21672168 Ok(target)
21682169 }
21692170
2170-pub fn ensure(allowed: bool) -> Result<(), Error> {
2171+pub fn ensure(allowed: bool) -> Result<(), ServerError> {
21712172 ensure_with(allowed, CommonError::Forbidden)
21722173 }
21732174
2174-pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), Error> {
2175+pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> {
21752176 if !allowed {
21762177 return Err(error.into());
21772178 }
@@ -2184,17 +2185,21 @@ async fn allowed(
21842185 community_id: &str,
21852186 conn: &Connection,
21862187 check: fn(Option<Rank>) -> bool,
2187-) -> Result<(), Error> {
2188+) -> Result<(), ServerError> {
21882189 ensure(check(actor_rank(me, community_id, conn).await?))
21892190 }
21902191
2191-async fn is_outsider(user_id: &str, community_id: &str, conn: &Connection) -> Result<bool, Error> {
2192+async fn is_outsider(
2193+ user_id: &str,
2194+ community_id: &str,
2195+ conn: &Connection,
2196+) -> Result<bool, ServerError> {
21922197 Ok(user_community::rank(user_id, community_id, conn)
21932198 .await?
21942199 .is_none())
21952200 }
21962201
2197-async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Error> {
2202+async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), ServerError> {
21982203 ensure(!community::is_fixed(community_id, conn).await?)
21992204 }
22002205
@@ -2212,7 +2217,7 @@ async fn message_broadcast(
22122217 event: fn(Message) -> Event,
22132218 actor_id: &str,
22142219 conn: &Connection,
2215-) -> Result<Broadcast, Error> {
2220+) -> Result<Broadcast, ServerError> {
22162221 let members = user_community::members(&message.community_id, conn).await?;
22172222
22182223 Ok(broadcast_with(event(message.clone()), &members, actor_id))
@@ -2249,7 +2254,7 @@ async fn record_ghost_voice(
22492254 community_id: &str,
22502255 seconds: u64,
22512256 conn: &Connection,
2252-) -> Result<(), Error> {
2257+) -> Result<(), ServerError> {
22532258 let community = community::label(community_id, conn).await?;
22542259 admin_log::record(
22552260 Some(user_id),
@@ -2293,6 +2298,17 @@ mod tests {
22932298 db: &DB,
22942299 services: &Services,
22952300 ) -> Response {
2301+ send_result(request, state, db, services)
2302+ .await
2303+ .expect("request failed")
2304+ }
2305+
2306+ async fn send_result(
2307+ request: Request,
2308+ state: &Mutex<State>,
2309+ db: &DB,
2310+ services: &Services,
2311+ ) -> Result<Response, CommonError> {
22962312 handle(
22972313 request,
22982314 state,
@@ -2384,7 +2400,7 @@ mod tests {
23842400 };
23852401 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
23862402
2387- let response = send(
2403+ let response = send_result(
23882404 Request::UpdateCommunity {
23892405 community_id: community.id,
23902406 name: "Renamed".to_string(),
@@ -2395,7 +2411,7 @@ mod tests {
23952411 )
23962412 .await;
23972413
2398- assert!(matches!(response, Response::Error(CommonError::Forbidden)));
2414+ assert!(matches!(response, Err(CommonError::Forbidden)));
23992415 }
24002416
24012417 #[tokio::test]
crates/server/src/retention.rsmodified+5 -5
@@ -10,7 +10,7 @@ use turso::Connection;
1010 use crate::{
1111 attachment,
1212 database::{self, DB},
13- error::Error,
13+ error::ServerError,
1414 message, server_settings,
1515 };
1616
@@ -31,7 +31,7 @@ fn cutoff(now: u64, days: u32) -> String {
3131 time::id_bound(now.saturating_sub(u64::from(days) * time::DAY_MILLIS))
3232 }
3333
34-async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result<Vec<String>, Error> {
34+async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result<Vec<String>, ServerError> {
3535 let mut rows = conn
3636 .query(
3737 &format!("SELECT id FROM {table} WHERE id < ?1 ORDER BY id LIMIT ?2"),
@@ -51,7 +51,7 @@ async fn purge_messages(
5151 cutoff: &str,
5252 conn: &mut Connection,
5353 directory: &Path,
54-) -> Result<u64, Error> {
54+) -> Result<u64, ServerError> {
5555 let mut purged = 0;
5656 loop {
5757 let ids = expired("message", cutoff, conn).await?;
@@ -75,7 +75,7 @@ async fn purge_attachments(
7575 cutoff: &str,
7676 conn: &mut Connection,
7777 directory: &Path,
78-) -> Result<u64, Error> {
78+) -> Result<u64, ServerError> {
7979 let mut purged = 0;
8080 loop {
8181 let ids = expired("attachment", cutoff, conn).await?;
@@ -91,7 +91,7 @@ async fn purge_attachments(
9191 }
9292 }
9393
94-async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {
94+async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> {
9595 let mut conn = database::connect(db).await?;
9696 let settings = server_settings::read(&conn).await?;
9797 let now = time::now_ms();
crates/server/src/server_ban.rsmodified+7 -7
@@ -6,7 +6,7 @@ use turso::Connection;
66
77 use crate::{
88 database::{self, new_id},
9- error::Error,
9+ error::ServerError,
1010 };
1111
1212 pub async fn insert(
@@ -15,7 +15,7 @@ pub async fn insert(
1515 reason: Option<&str>,
1616 created_by: &str,
1717 conn: &Connection,
18-) -> Result<(), Error> {
18+) -> Result<(), ServerError> {
1919 conn.execute(
2020 "INSERT INTO server_ban (id, kind, value, reason, created_by)
2121 SELECT ?1, ?2, ?3, ?4, ?5 WHERE NOT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?2 AND value = ?3)",
@@ -26,7 +26,7 @@ pub async fn insert(
2626 Ok(())
2727 }
2828
29-pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> {
29+pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, ServerError> {
3030 let mut rows = conn
3131 .query(
3232 "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value",
@@ -48,7 +48,7 @@ pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> {
4848 Ok(bans)
4949 }
5050
51-async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, Error> {
51+async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, ServerError> {
5252 database::exists(
5353 conn,
5454 "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)",
@@ -57,7 +57,7 @@ async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<b
5757 .await
5858 }
5959
60-pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, Error> {
60+pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, ServerError> {
6161 exists(
6262 ServerBanKind::Username,
6363 &username.to_ascii_lowercase(),
@@ -66,11 +66,11 @@ pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool,
6666 .await
6767 }
6868
69-pub async fn ip_banned(ip: &str, conn: &Connection) -> Result<bool, Error> {
69+pub async fn ip_banned(ip: &str, conn: &Connection) -> Result<bool, ServerError> {
7070 exists(ServerBanKind::Ip, ip, conn).await
7171 }
7272
73-pub async fn remove(id: &str, conn: &Connection) -> Result<(), Error> {
73+pub async fn remove(id: &str, conn: &Connection) -> Result<(), ServerError> {
7474 let mut rows = conn
7575 .query("DELETE FROM server_ban WHERE id = ?1 RETURNING id", (id,))
7676 .await?;
crates/server/src/server_settings.rsmodified+4 -4
@@ -1,7 +1,7 @@
11 use common::model::ServerSettings;
22 use turso::Connection;
33
4-use crate::{error::Error, user};
4+use crate::{error::ServerError, user};
55
66 const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute";
77
@@ -14,7 +14,7 @@ fn assignments() -> String {
1414 .join(", ")
1515 }
1616
17-pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
17+pub async fn read(conn: &Connection) -> Result<ServerSettings, ServerError> {
1818 let mut rows = conn
1919 .query(
2020 &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"),
@@ -25,7 +25,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
2525 .next()
2626 .await?
2727 .ok_or(turso::Error::QueryReturnedNoRows)?;
28- let int = |index: usize| -> Result<i64, Error> { Ok(row.get(index)?) };
28+ let int = |index: usize| -> Result<i64, ServerError> { Ok(row.get(index)?) };
2929
3030 Ok(ServerSettings {
3131 name: row.get(0)?,
@@ -45,7 +45,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
4545 })
4646 }
4747
48-pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> {
48+pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), ServerError> {
4949 conn.execute(
5050 &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()),
5151 (
crates/server/src/stats.rsmodified+8 -4
@@ -4,11 +4,11 @@ use common::{
44 };
55 use turso::Connection;
66
7-use crate::{database, error::Error, user};
7+use crate::{database, error::ServerError, user};
88
99 const MAXIMUM_DAYS: u32 = 90;
1010
11-pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), Error> {
11+pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), ServerError> {
1212 if user::is_ghost(user_id, conn).await? {
1313 return Ok(());
1414 }
@@ -22,7 +22,7 @@ pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), Error>
2222 Ok(())
2323 }
2424
25-pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, Error> {
25+pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, ServerError> {
2626 let days = u64::from(days.clamp(1, MAXIMUM_DAYS));
2727 let today = time::now_ms() / DAY_MILLIS;
2828 let mut stats = Vec::new();
@@ -52,6 +52,10 @@ pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, Error>
5252 Ok(stats)
5353 }
5454
55-async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result<u64, Error> {
55+async fn count(
56+ conn: &Connection,
57+ sql: &str,
58+ params: impl turso::IntoParams,
59+) -> Result<u64, ServerError> {
5660 Ok(database::scalar_i64(conn, sql, params).await? as u64)
5761 }
crates/server/src/user.rsmodified+80 -45
@@ -1,6 +1,6 @@
11 use common::{
22 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3- error::{Error as CommonError, Field, InvalidInput},
3+ error::{Error as CommonError, Field, Problem},
44 model::{Account, Presence, Role, User},
55 permission, time,
66 validate::{validate_avatar_size, validate_status, validate_username},
@@ -10,14 +10,14 @@ use turso::{Connection, Row};
1010
1111 use crate::{
1212 database::{self, new_id},
13- error::Error,
13+ error::ServerError,
1414 };
1515
1616 pub fn user_columns(alias: &str) -> String {
1717 format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id")
1818 }
1919
20-pub fn from_row_at(row: &Row, start: usize) -> Result<Option<User>, Error> {
20+pub fn from_row_at(row: &Row, start: usize) -> Result<Option<User>, ServerError> {
2121 let Some(id) = row.get::<Option<String>>(start)? else {
2222 return Ok(None);
2323 };
@@ -32,24 +32,32 @@ pub fn from_row_at(row: &Row, start: usize) -> Result<Option<User>, Error> {
3232 }))
3333 }
3434
35-pub fn from_row(row: &Row) -> Result<User, Error> {
35+pub fn from_row(row: &Row) -> Result<User, ServerError> {
3636 Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?)
3737 }
3838
39-pub fn bool_at(row: &Row, index: usize) -> Result<bool, Error> {
39+pub fn bool_at(row: &Row, index: usize) -> Result<bool, ServerError> {
4040 let flag: i64 = row.get(index)?;
4141
4242 Ok(flag != 0)
4343 }
4444
45-async fn one(sql: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<User, Error> {
45+async fn one(
46+ sql: &str,
47+ params: impl turso::IntoParams,
48+ conn: &Connection,
49+) -> Result<User, ServerError> {
4650 let mut rows = conn.query(sql, params).await?;
4751 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
4852
4953 from_row(&row)
5054 }
5155
52-async fn set(column: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<(), Error> {
56+async fn set(
57+ column: &str,
58+ params: impl turso::IntoParams,
59+ conn: &Connection,
60+) -> Result<(), ServerError> {
5361 conn.execute(
5462 &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"),
5563 params,
@@ -63,7 +71,7 @@ async fn set_returning(
6371 column: &str,
6472 params: impl turso::IntoParams,
6573 conn: &Connection,
66-) -> Result<User, Error> {
74+) -> Result<User, ServerError> {
6775 one(
6876 &format!(
6977 "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}",
@@ -75,7 +83,11 @@ async fn set_returning(
7583 .await
7684 }
7785
78-pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {
86+pub async fn create(
87+ username: &str,
88+ password_hash: &str,
89+ conn: &Connection,
90+) -> Result<User, ServerError> {
7991 one(
8092 &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")),
8193 (
@@ -90,7 +102,7 @@ pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> R
90102 .await
91103 }
92104
93-pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
105+pub async fn read(user_id: &str, conn: &Connection) -> Result<User, ServerError> {
94106 one(
95107 &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")),
96108 (user_id,),
@@ -99,11 +111,11 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
99111 .await
100112 }
101113
102-pub async fn any(conn: &Connection) -> Result<bool, Error> {
114+pub async fn any(conn: &Connection) -> Result<bool, ServerError> {
103115 database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await
104116 }
105117
106-pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
118+pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, ServerError> {
107119 let mut rows = conn
108120 .query(
109121 &format!(
@@ -121,13 +133,13 @@ pub async fn is_taken(
121133 username: &str,
122134 except_id: Option<&str>,
123135 conn: &Connection,
124-) -> Result<bool, Error> {
136+) -> Result<bool, ServerError> {
125137 Ok(by_username(username, conn)
126138 .await?
127139 .is_some_and(|existing| Some(existing.id.as_str()) != except_id))
128140 }
129141
130-pub async fn by_session_token(token: &str, conn: &Connection) -> Result<User, Error> {
142+pub async fn by_session_token(token: &str, conn: &Connection) -> Result<User, ServerError> {
131143 let mut rows = conn
132144 .query(
133145 &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")),
@@ -142,7 +154,7 @@ pub async fn by_session_token(token: &str, conn: &Connection) -> Result<User, Er
142154 pub async fn credentials(
143155 username: &str,
144156 conn: &Connection,
145-) -> Result<Option<(User, String)>, Error> {
157+) -> Result<Option<(User, String)>, ServerError> {
146158 let mut rows = conn
147159 .query(
148160 &format!(
@@ -159,7 +171,7 @@ pub async fn credentials(
159171 Ok(Some((from_row(&row)?, row.get(5)?)))
160172 }
161173
162-pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> {
174+pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, ServerError> {
163175 validate_username(username)?;
164176
165177 if is_taken(username, Some(user_id), conn).await? {
@@ -169,24 +181,28 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<
169181 set_returning("username", (user_id, username), conn).await
170182 }
171183
172-pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> {
184+pub async fn update_status(
185+ user_id: &str,
186+ status: &str,
187+ conn: &Connection,
188+) -> Result<User, ServerError> {
173189 validate_status(status)?;
174190
175191 set_returning("status", (user_id, status), conn).await
176192 }
177193
178-pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
194+pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> {
179195 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
180196 let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| {
181197 CommonError::Invalid {
182198 field: Field::Avatar,
183- input: InvalidInput::NotJpeg,
199+ problem: Problem::NotJpeg,
184200 }
185201 })?;
186202 if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE {
187203 return Err(CommonError::Invalid {
188204 field: Field::Avatar,
189- input: InvalidInput::Dimensions {
205+ problem: Problem::Dimensions {
190206 expected: AVATAR_SIZE,
191207 },
192208 }
@@ -200,7 +216,7 @@ pub async fn set_avatar(
200216 user_id: &str,
201217 avatar: Option<&[u8]>,
202218 conn: &mut Connection,
203-) -> Result<User, Error> {
219+) -> Result<User, ServerError> {
204220 if let Some(bytes) = avatar {
205221 check_avatar(bytes)?;
206222 }
@@ -226,11 +242,11 @@ async fn set_avatar_id(
226242 user_id: &str,
227243 avatar_id: Option<&str>,
228244 conn: &Connection,
229-) -> Result<User, Error> {
245+) -> Result<User, ServerError> {
230246 set_returning("avatar_id", (user_id, avatar_id), conn).await
231247 }
232248
233-pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> {
249+pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, ServerError> {
234250 let mut rows = conn
235251 .query(
236252 "SELECT data FROM avatar WHERE id = ?1 UNION ALL SELECT data FROM community_avatar WHERE id = ?1",
@@ -242,11 +258,18 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error
242258 Ok(row.get(0)?)
243259 }
244260
245-pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {
261+pub async fn set_role_by_id(
262+ user_id: &str,
263+ role: Role,
264+ conn: &Connection,
265+) -> Result<User, ServerError> {
246266 set_returning("role", (user_id, role.as_str()), conn).await
247267 }
248268
249-pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error> {
269+pub async fn suspended(
270+ user_id: &str,
271+ conn: &Connection,
272+) -> Result<Option<Option<u64>>, ServerError> {
250273 let mut rows = conn
251274 .query(
252275 "SELECT suspended, suspended_until FROM user WHERE id = ?1",
@@ -254,16 +277,20 @@ pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error>
254277 )
255278 .await?;
256279 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
257- let until: Option<i64> = row.get(1)?;
280+ let until: Option<u64> = row.get::<Option<i64>>(1)?.map(|until| until as u64);
281+
282+ if bool_at(&row, 0)? {
283+ return Ok(Some(None));
284+ }
258285
259- Ok(bool_at(&row, 0)? || until.is_some_and(|until| until as u64 > time::now_ms()))
286+ Ok(until.filter(|until| *until > time::now_ms()).map(Some))
260287 }
261288
262289 pub async fn set_timeout(
263290 user_id: &str,
264291 until: Option<u64>,
265292 conn: &Connection,
266-) -> Result<(), Error> {
293+) -> Result<(), ServerError> {
267294 set(
268295 "suspended_until",
269296 (user_id, until.map(|until| until as i64)),
@@ -272,11 +299,11 @@ pub async fn set_timeout(
272299 .await
273300 }
274301
275-pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), Error> {
302+pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), ServerError> {
276303 set("last_ip", (user_id, ip), conn).await
277304 }
278305
279-pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, Error> {
306+pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, ServerError> {
280307 let mut rows = conn
281308 .query("SELECT last_ip FROM user WHERE id = ?1", (user_id,))
282309 .await?;
@@ -285,7 +312,7 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>,
285312 Ok(row.get(0)?)
286313 }
287314
288-pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> {
315+pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, ServerError> {
289316 database::ids(
290317 conn,
291318 "SELECT id FROM user WHERE role = ?1",
@@ -294,19 +321,27 @@ pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> {
294321 .await
295322 }
296323
297-pub async fn set_suspended(user_id: &str, suspended: bool, conn: &Connection) -> Result<(), Error> {
324+pub async fn set_suspended(
325+ user_id: &str,
326+ suspended: bool,
327+ conn: &Connection,
328+) -> Result<(), ServerError> {
298329 set("suspended", (user_id, i64::from(suspended)), conn).await
299330 }
300331
301-pub async fn set_voice_muted(user_id: &str, muted: bool, conn: &Connection) -> Result<(), Error> {
332+pub async fn set_voice_muted(
333+ user_id: &str,
334+ muted: bool,
335+ conn: &Connection,
336+) -> Result<(), ServerError> {
302337 set("voice_muted", (user_id, i64::from(muted)), conn).await
303338 }
304339
305-pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), Error> {
340+pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), ServerError> {
306341 set("ghost", (user_id, i64::from(ghost)), conn).await
307342 }
308343
309-pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> {
344+pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, ServerError> {
310345 let mut rows = conn
311346 .query("SELECT ghost FROM user WHERE id = ?1", (user_id,))
312347 .await?;
@@ -317,7 +352,7 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> {
317352 bool_at(&row, 0)
318353 }
319354
320-pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, Error> {
355+pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, ServerError> {
321356 let mut rows = conn
322357 .query("SELECT presence FROM user WHERE id = ?1", (user_id,))
323358 .await?;
@@ -331,11 +366,11 @@ pub async fn update_presence(
331366 user_id: &str,
332367 presence: Presence,
333368 conn: &Connection,
334-) -> Result<(), Error> {
369+) -> Result<(), ServerError> {
335370 set("presence", (user_id, presence.as_str()), conn).await
336371 }
337372
338-pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> {
373+pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, ServerError> {
339374 let mut rows = conn
340375 .query(
341376 "SELECT voice_muted, role FROM user WHERE id = ?1",
@@ -353,11 +388,11 @@ pub async fn set_password_hash(
353388 user_id: &str,
354389 password_hash: &str,
355390 conn: &Connection,
356-) -> Result<(), Error> {
391+) -> Result<(), ServerError> {
357392 set("password_hash", (user_id, password_hash), conn).await
358393 }
359394
360-pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> {
395+pub async fn all(conn: &Connection) -> Result<Vec<Account>, ServerError> {
361396 let mut rows = conn
362397 .query(
363398 &format!("SELECT {}, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", user_columns("user")),
@@ -380,7 +415,7 @@ pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> {
380415 Ok(accounts)
381416 }
382417
383-pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
418+pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, ServerError> {
384419 one(
385420 &format!(
386421 "DELETE FROM user WHERE id = ?1 RETURNING {}",
@@ -402,7 +437,7 @@ mod tests {
402437 };
403438 use image::{ImageFormat, RgbImage};
404439
405- use crate::{database, error::Error, test, user};
440+ use crate::{database, error::ServerError, test, user};
406441
407442 fn jpeg(size: u32) -> Vec<u8> {
408443 let mut bytes = Cursor::new(Vec::new());
@@ -428,14 +463,14 @@ mod tests {
428463
429464 assert!(matches!(
430465 small,
431- Err(Error::Common(CommonError::Invalid {
466+ Err(ServerError::Wire(CommonError::Invalid {
432467 field: Field::Avatar,
433468 ..
434469 }))
435470 ));
436471 assert!(matches!(
437472 not_jpeg,
438- Err(Error::Common(CommonError::Invalid {
473+ Err(ServerError::Wire(CommonError::Invalid {
439474 field: Field::Avatar,
440475 ..
441476 }))
@@ -503,7 +538,7 @@ mod tests {
503538
504539 assert!(matches!(
505540 updated_user,
506- Err(Error::Common(CommonError::NotFound))
541+ Err(ServerError::Wire(CommonError::NotFound))
507542 ));
508543 }
509544
crates/server/src/user_community.rsmodified+23 -15
@@ -6,9 +6,9 @@ use common::{
66 };
77 use turso::{Connection, Row};
88
9-use crate::{community, database, error::Error, user};
9+use crate::{community, database, error::ServerError, user};
1010
11-fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> {
11+fn rank_of(row: &Row, index: usize) -> Result<Rank, ServerError> {
1212 let text: String = row.get(index)?;
1313
1414 Ok(Rank::parse(&text).ok_or(CommonError::Server)?)
@@ -19,7 +19,7 @@ pub async fn join(
1919 community_id: &str,
2020 rank: Rank,
2121 conn: &Connection,
22-) -> Result<(), Error> {
22+) -> Result<(), ServerError> {
2323 conn.execute(
2424 "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)",
2525 (user_id, community_id, rank.as_str()),
@@ -29,7 +29,11 @@ pub async fn join(
2929 Ok(())
3030 }
3131
32-pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {
32+pub async fn leave(
33+ user_id: &str,
34+ community_id: &str,
35+ conn: &Connection,
36+) -> Result<(), ServerError> {
3337 conn.execute(
3438 "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2",
3539 (user_id, community_id),
@@ -43,7 +47,7 @@ pub async fn rank(
4347 user_id: &str,
4448 community_id: &str,
4549 conn: &Connection,
46-) -> Result<Option<Rank>, Error> {
50+) -> Result<Option<Rank>, ServerError> {
4751 let mut rows = conn
4852 .query(
4953 "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2",
@@ -63,7 +67,7 @@ pub async fn set_rank(
6367 community_id: &str,
6468 rank: Rank,
6569 conn: &Connection,
66-) -> Result<(), Error> {
70+) -> Result<(), ServerError> {
6771 conn.execute(
6872 "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2",
6973 (user_id, community_id, rank.as_str()),
@@ -78,7 +82,7 @@ pub async fn mark_read(
7882 community_id: &str,
7983 message_id: &str,
8084 conn: &Connection,
81-) -> Result<(), Error> {
85+) -> Result<(), ServerError> {
8286 conn.execute(
8387 "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)",
8488 (user_id, community_id, message_id),
@@ -92,7 +96,7 @@ pub async fn unreads(
9296 user_id: &str,
9397 username: &str,
9498 conn: &Connection,
95-) -> Result<Vec<Unread>, Error> {
99+) -> Result<Vec<Unread>, ServerError> {
96100 let mut rows = conn
97101 .query(
98102 "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), uc.last_read FROM user_community uc WHERE uc.user_id = ?1",
@@ -137,7 +141,7 @@ pub async fn unreads(
137141 Ok(unreads)
138142 }
139143
140-pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, Error> {
144+pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, ServerError> {
141145 let mut rows = conn
142146 .query(
143147 &format!("SELECT {}, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", user::user_columns("user")),
@@ -156,7 +160,7 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member
156160 Ok(members)
157161 }
158162
159-pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, Error> {
163+pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, ServerError> {
160164 let count = database::scalar_i64(
161165 conn,
162166 "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3",
@@ -167,7 +171,7 @@ pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, Err
167171 Ok(count as usize)
168172 }
169173
170-pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
174+pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> {
171175 database::ids(
172176 conn,
173177 "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2",
@@ -181,7 +185,7 @@ pub async fn ban(
181185 community_id: &str,
182186 reason: Option<&str>,
183187 conn: &Connection,
184-) -> Result<(), Error> {
188+) -> Result<(), ServerError> {
185189 conn.execute(
186190 "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)",
187191 (user_id, community_id, reason),
@@ -191,7 +195,11 @@ pub async fn ban(
191195 Ok(())
192196 }
193197
194-pub async fn unban(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {
198+pub async fn unban(
199+ user_id: &str,
200+ community_id: &str,
201+ conn: &Connection,
202+) -> Result<(), ServerError> {
195203 conn.execute(
196204 "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2",
197205 (user_id, community_id),
@@ -205,7 +213,7 @@ pub async fn is_banned(
205213 user_id: &str,
206214 community_id: &str,
207215 conn: &Connection,
208-) -> Result<bool, Error> {
216+) -> Result<bool, ServerError> {
209217 database::exists(
210218 conn,
211219 "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)",
@@ -214,7 +222,7 @@ pub async fn is_banned(
214222 .await
215223 }
216224
217-pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, Error> {
225+pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, ServerError> {
218226 let mut rows = conn
219227 .query(
220228 &format!("SELECT {}, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC", user::user_columns("user")),