One transport, one framing and a split error model
Browse files at this commite2d1bd5c083a732086a0070e23d86d362a42fad8Parent: d46d713- refactor
- one transport, one framing and a split error model
67 changed files +3430 -2981
- crates/client/Cargo.toml +3 -1
- crates/client/src/avatar.rs +11 -8
- crates/client/src/gui.rs +4 -18
- crates/client/src/gui/builder.rs +1 -1
- crates/client/src/gui/builder/overview.rs +3 -2
- crates/client/src/gui/builder/reports.rs +3 -6
- crates/client/src/gui/builder/users.rs +2 -3
- crates/client/src/gui/builder/voice.rs +3 -6
- crates/client/src/gui/chat.rs +1 -1
- crates/client/src/gui/community_settings.rs +10 -3
- crates/client/src/gui/composer.rs +5 -16
- crates/client/src/gui/media_view.rs +5 -5
- crates/client/src/gui/settings_page.rs +4 -3
- crates/client/src/gui/voice_note.rs +5 -1
- crates/client/src/gui/wave.rs +1 -1
- crates/client/src/lib.rs +1 -1
- crates/client/src/main.rs +2 -2
- crates/client/src/net/datagram.rs +34 -0
- crates/client/src/net/events.rs +28 -0
- crates/client/src/net/fail.rs +151 -0
- crates/client/src/net/fetch.rs +68 -0
- crates/client/src/net/link.rs +603 -0
- crates/client/src/net/mod.rs +1160 -0
- crates/client/src/net/share.rs +335 -0
- crates/client/src/net/voice.rs +87 -0
- crates/client/src/network.rs +0 -2047
- crates/client/src/share/encode.rs +13 -8
- crates/client/src/share/reassembly.rs +6 -0
- crates/common/src/config.rs +11 -5
- crates/common/src/error.rs +51 -93
- crates/common/src/frame.rs +89 -0
- crates/common/src/lib.rs +3 -1
- crates/common/src/network.rs +0 -193
- crates/common/src/open.rs +24 -0
- crates/common/src/request.rs +0 -16
- crates/common/src/response.rs +0 -2
- crates/common/src/transport.rs +69 -0
- crates/common/src/validate.rs +48 -49
- crates/pixel/src/lib.rs +13 -10
- crates/server/src/admin_log.rs +3 -3
- crates/server/src/attachment.rs +82 -84
- crates/server/src/authentication.rs +29 -24
- crates/server/src/backup.rs +15 -36
- crates/server/src/certificate.rs +11 -7
- crates/server/src/community.rs +24 -21
- crates/server/src/database.rs +9 -9
- crates/server/src/datagram.rs +19 -0
- crates/server/src/direct.rs +7 -3
- crates/server/src/error.rs +34 -22
- crates/server/src/friend.rs +10 -10
- crates/server/src/invitation.rs +9 -5
- crates/server/src/invite.rs +6 -6
- crates/server/src/lib.rs +6 -5
- crates/server/src/log.rs +3 -3
- crates/server/src/main.rs +1 -1
- crates/server/src/message.rs +41 -32
- crates/server/src/network.rs +52 -62
- crates/server/src/notes.rs +3 -3
- crates/server/src/overview.rs +3 -3
- crates/server/src/report.rs +8 -5
- crates/server/src/request.rs +71 -55
- crates/server/src/retention.rs +5 -5
- crates/server/src/server_ban.rs +7 -7
- crates/server/src/server_settings.rs +4 -4
- crates/server/src/stats.rs +8 -4
- crates/server/src/user.rs +80 -45
- crates/server/src/user_community.rs +23 -15
crates/client/Cargo.tomlmodified+3 -1
| @@ -9,7 +9,7 @@ pixel.workspace = true | ||
| 9 | 9 | spectrum.workspace = true |
| 10 | 10 | reed-solomon-simd = "3.1.0" |
| 11 | 11 | tokio.workspace = true |
| 12 | -quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } | |
| 12 | +quinn = { workspace = true, features = ["rustls-ring"] } | |
| 13 | 13 | |
| 14 | 14 | gpui-kit = { version = "0.11.0", features = ["syntect"] } |
| 15 | 15 | ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| @@ -31,6 +31,8 @@ jiff = "1.0.2" | ||
| 31 | 31 | dirs = "7.0.0" |
| 32 | 32 | image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } |
| 33 | 33 | rtrb = "0.4.1" |
| 34 | +gethostname = "1.1.0" | |
| 35 | +rustls-platform-verifier = "0.7.1" | |
| 34 | 36 | |
| 35 | 37 | [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] |
| 36 | 38 | 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; | |
| 1 | 2 | use common::{ |
| 2 | 3 | constant::AVATAR_SIZE, |
| 3 | - error::{Error, Field, InvalidInput}, | |
| 4 | + error::{Error, Field, Problem}, | |
| 4 | 5 | }; |
| 5 | 6 | use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; |
| 6 | 7 | |
| 7 | 8 | const QUALITIES: [u8; 3] = [85, 60, 40]; |
| 8 | 9 | |
| 9 | -pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> { | |
| 10 | +pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Fail> { | |
| 10 | 11 | let image = image::load_from_memory(bytes).map_err(image_error)?; |
| 11 | 12 | let square = center_square(image) |
| 12 | 13 | .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3) |
| @@ -22,11 +23,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> { | ||
| 22 | 23 | |
| 23 | 24 | Err(Error::Invalid { |
| 24 | 25 | field: Field::Avatar, |
| 25 | - input: InvalidInput::TooLarge { | |
| 26 | - maximum, | |
| 26 | + problem: Problem::Length { | |
| 27 | + min: 0, | |
| 28 | + max: maximum, | |
| 27 | 29 | actual: encoded.len() as u64, |
| 28 | 30 | }, |
| 29 | - }) | |
| 31 | + } | |
| 32 | + .into()) | |
| 30 | 33 | } |
| 31 | 34 | |
| 32 | 35 | fn center_square(image: DynamicImage) -> DynamicImage { |
| @@ -37,7 +40,7 @@ fn center_square(image: DynamicImage) -> DynamicImage { | ||
| 37 | 40 | image.crop_imm(x, y, side, side) |
| 38 | 41 | } |
| 39 | 42 | |
| 40 | -fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> { | |
| 43 | +fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Fail> { | |
| 41 | 44 | let mut bytes = Vec::new(); |
| 42 | 45 | JpegEncoder::new_with_quality(&mut bytes, quality) |
| 43 | 46 | .encode_image(image) |
| @@ -46,8 +49,8 @@ fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> { | ||
| 46 | 49 | Ok(bytes) |
| 47 | 50 | } |
| 48 | 51 | |
| 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()) | |
| 51 | 54 | } |
| 52 | 55 | |
| 53 | 56 | const HUE_BINS: usize = 24; |
crates/client/src/gui.rsmodified+4 -18
| @@ -37,7 +37,7 @@ use tokio::sync::mpsc; | ||
| 37 | 37 | use crate::{ |
| 38 | 38 | accounts::{self, Accounts}, |
| 39 | 39 | mutes, |
| 40 | - network::{NetworkEvent, NetworkHandle}, | |
| 40 | + net::{Fail, LinkError, NetworkEvent, NetworkHandle}, | |
| 41 | 41 | settings::{Look, Scale, Settings, ThemeChoice}, |
| 42 | 42 | }; |
| 43 | 43 | |
| @@ -540,32 +540,18 @@ impl Connection { | ||
| 540 | 540 | matches!(self, Self::Connected) |
| 541 | 541 | } |
| 542 | 542 | |
| 543 | - fn lost(&mut self, error: &Error) { | |
| 543 | + fn lost(&mut self, error: &LinkError) { | |
| 544 | 544 | let attempts = match self { |
| 545 | 545 | Self::Lost { attempts, .. } => *attempts + 1, |
| 546 | 546 | _ => 1, |
| 547 | 547 | }; |
| 548 | 548 | *self = Self::Lost { |
| 549 | - error: reason(error), | |
| 549 | + error: error.to_string(), | |
| 550 | 550 | attempts, |
| 551 | 551 | }; |
| 552 | 552 | } |
| 553 | 553 | } |
| 554 | 554 | |
| 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 | - | |
| 569 | 555 | fn connection_notice(connection: &Connection, palette: Palette) -> Option<Div> { |
| 570 | 556 | let (label, color) = match connection { |
| 571 | 557 | Connection::Connecting => ("Connecting…".to_string(), palette.muted), |
| @@ -755,7 +741,7 @@ impl Yumush { | ||
| 755 | 741 | let result = network.resume(&account.token).await; |
| 756 | 742 | let _ = this.update_in(cx, |yumush, window, cx| match result { |
| 757 | 743 | 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)) => { | |
| 759 | 745 | yumush.accounts.forget(&account.user_id); |
| 760 | 746 | window.push_notification(Notification::error(error.to_string()), cx); |
| 761 | 747 | cx.notify(); |
crates/client/src/gui/builder.rsmodified+1 -1
| @@ -32,7 +32,7 @@ use super::{ | ||
| 32 | 32 | Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, |
| 33 | 33 | text, widget::search_text, |
| 34 | 34 | }; |
| 35 | -use crate::network::NetworkHandle; | |
| 35 | +use crate::net::NetworkHandle; | |
| 36 | 36 | |
| 37 | 37 | pub(super) fn save_directory() -> PathBuf { |
| 38 | 38 | 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}; | |
| 2 | 3 | use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px}; |
| 3 | 4 | use jiff::Timestamp; |
| 4 | 5 | |
| @@ -107,7 +108,7 @@ impl Yumush { | ||
| 107 | 108 | window, |
| 108 | 109 | cx, |
| 109 | 110 | |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?)) | |
| 111 | 112 | }, |
| 112 | 113 | |yumush, (overview, stats), cx| { |
| 113 | 114 | yumush.chat.builder_overview = Some(overview); |
crates/client/src/gui/builder/reports.rsmodified+3 -6
| @@ -1,9 +1,6 @@ | ||
| 1 | 1 | use std::future::Future; |
| 2 | 2 | |
| 3 | -use common::{ | |
| 4 | - error::Error, | |
| 5 | - model::{BanScope, Report, ReportStatus}, | |
| 6 | -}; | |
| 3 | +use common::model::{BanScope, Report, ReportStatus}; | |
| 7 | 4 | use gpui_kit::{ |
| 8 | 5 | AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, |
| 9 | 6 | div, px, |
| @@ -20,7 +17,7 @@ use crate::{ | ||
| 20 | 17 | settings_page::{segment, segment_track}, |
| 21 | 18 | text, |
| 22 | 19 | }, |
| 23 | - network::NetworkHandle, | |
| 20 | + net::{Fail, NetworkHandle}, | |
| 24 | 21 | }; |
| 25 | 22 | |
| 26 | 23 | const REPORT_FILTERS: [Option<ReportStatus>; 4] = [ |
| @@ -91,7 +88,7 @@ impl Yumush { | ||
| 91 | 88 | cx: &mut Context<Self>, |
| 92 | 89 | action: impl FnOnce(NetworkHandle) -> Fut + 'static, |
| 93 | 90 | ) where |
| 94 | - Fut: Future<Output = Result<(), Error>> + 'static, | |
| 91 | + Fut: Future<Output = Result<(), Fail>> + 'static, | |
| 95 | 92 | { |
| 96 | 93 | let network = self.network.clone(); |
| 97 | 94 |
crates/client/src/gui/builder/users.rsmodified+2 -3
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | use std::future::Future; |
| 2 | 2 | |
| 3 | 3 | use common::{ |
| 4 | - error::Error, | |
| 5 | 4 | model::{Account, BanScope, Role, SessionInfo, User}, |
| 6 | 5 | permission, |
| 7 | 6 | time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, |
| @@ -26,7 +25,7 @@ use crate::{ | ||
| 26 | 25 | text, |
| 27 | 26 | widget::{field, search_text}, |
| 28 | 27 | }, |
| 29 | - network::NetworkHandle, | |
| 28 | + net::{Fail, NetworkHandle}, | |
| 30 | 29 | }; |
| 31 | 30 | |
| 32 | 31 | const MINUTES_PER_HOUR: u64 = HOUR_MILLIS / MINUTE_MILLIS; |
| @@ -143,7 +142,7 @@ impl Yumush { | ||
| 143 | 142 | cx: &mut Context<Self>, |
| 144 | 143 | action: impl FnOnce(NetworkHandle) -> Fut + 'static, |
| 145 | 144 | ) where |
| 146 | - Fut: Future<Output = Result<(), Error>> + 'static, | |
| 145 | + Fut: Future<Output = Result<(), Fail>> + 'static, | |
| 147 | 146 | { |
| 148 | 147 | let network = self.network.clone(); |
| 149 | 148 |
crates/client/src/gui/builder/voice.rsmodified+3 -6
| @@ -1,9 +1,6 @@ | ||
| 1 | 1 | use std::future::Future; |
| 2 | 2 | |
| 3 | -use common::{ | |
| 4 | - error::Error, | |
| 5 | - model::{User, VoiceRoom}, | |
| 6 | -}; | |
| 3 | +use common::model::{User, VoiceRoom}; | |
| 7 | 4 | use gpui_kit::{ |
| 8 | 5 | AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, |
| 9 | 6 | div, px, |
| @@ -12,7 +9,7 @@ use gpui_kit::{ | ||
| 12 | 9 | use super::ui::{card, card_header, icon_button, list_card, pill, rows_body}; |
| 13 | 10 | use crate::{ |
| 14 | 11 | gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text}, |
| 15 | - network::NetworkHandle, | |
| 12 | + net::{Fail, NetworkHandle}, | |
| 16 | 13 | }; |
| 17 | 14 | |
| 18 | 15 | impl Yumush { |
| @@ -34,7 +31,7 @@ impl Yumush { | ||
| 34 | 31 | cx: &mut Context<Self>, |
| 35 | 32 | action: impl FnOnce(NetworkHandle) -> Fut + 'static, |
| 36 | 33 | ) where |
| 37 | - Fut: Future<Output = Result<(), Error>> + 'static, | |
| 34 | + Fut: Future<Output = Result<(), Fail>> + 'static, | |
| 38 | 35 | { |
| 39 | 36 | let network = self.network.clone(); |
| 40 | 37 |
crates/client/src/gui/chat.rsmodified+1 -1
| @@ -28,7 +28,7 @@ use crate::gui::{ | ||
| 28 | 28 | voice_note::{self, VoiceNote}, |
| 29 | 29 | widget::{icon_button, ok_or_notify, search_text, spawn_done}, |
| 30 | 30 | }; |
| 31 | -use crate::network::Levels; | |
| 31 | +use crate::net::Levels; | |
| 32 | 32 | use crate::settings::VOLUME; |
| 33 | 33 | use crate::share::session::ShareSample; |
| 34 | 34 | use crate::voice::VoiceSample; |
crates/client/src/gui/community_settings.rsmodified+10 -3
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | use std::{collections::HashMap, sync::Arc}; |
| 2 | 2 | |
| 3 | +use crate::net::Fail; | |
| 3 | 4 | use common::{ |
| 4 | - error::Error, | |
| 5 | 5 | model::{Ban, Community, LogAction, LogEntry, User}, |
| 6 | 6 | permission, |
| 7 | 7 | validate::validate_community_name, |
| @@ -56,7 +56,7 @@ const LOG_SORTS: [(LogSort, &str); 2] = [(LogSort::Newest, "Newest"), (LogSort:: | ||
| 56 | 56 | fn apply_community( |
| 57 | 57 | this: &WeakEntity<Yumush>, |
| 58 | 58 | cx: &mut AsyncWindowContext, |
| 59 | - result: Result<Community, Error>, | |
| 59 | + result: Result<Community, Fail>, | |
| 60 | 60 | ) { |
| 61 | 61 | match result { |
| 62 | 62 | Ok(community) => { |
| @@ -225,7 +225,14 @@ impl Yumush { | ||
| 225 | 225 | let Some(community_id) = self.chat.selected_community_id.clone() else { |
| 226 | 226 | return; |
| 227 | 227 | }; |
| 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(); | |
| 229 | 236 | |
| 230 | 237 | if let Err(error) = validate_community_name(&name) { |
| 231 | 238 | window.push_notification(Notification::error(error.to_string()), cx); |
crates/client/src/gui/composer.rsmodified+5 -16
| @@ -2,6 +2,7 @@ use super::text; | ||
| 2 | 2 | use super::widget::{compact_field, icon_button, panel, spawn_done}; |
| 3 | 3 | use std::time::{Duration, Instant}; |
| 4 | 4 | |
| 5 | +use crate::net::Fail; | |
| 5 | 6 | use common::{ |
| 6 | 7 | constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS}, |
| 7 | 8 | error::Error, |
| @@ -275,19 +276,12 @@ impl Yumush { | ||
| 275 | 276 | .await |
| 276 | 277 | { |
| 277 | 278 | Ok(_) => {} |
| 278 | - Err(Error::RateLimited { | |
| 279 | + Err(Fail::Server(Error::RateLimited { | |
| 279 | 280 | retry_after_seconds, |
| 280 | - }) => { | |
| 281 | + })) => { | |
| 281 | 282 | 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) | |
| 291 | 285 | }); |
| 292 | 286 | } |
| 293 | 287 | Err(error) => { |
| @@ -330,14 +324,9 @@ impl Yumush { | ||
| 330 | 324 | fn slow_down( |
| 331 | 325 | &mut self, |
| 332 | 326 | seconds: u64, |
| 333 | - input: &Entity<InputState>, | |
| 334 | - community_id: &str, | |
| 335 | - body: String, | |
| 336 | - pending: Vec<Attachment>, | |
| 337 | 327 | window: &mut Window, |
| 338 | 328 | cx: &mut Context<Self>, |
| 339 | 329 | ) { |
| 340 | - self.restore_message(input, community_id, body, pending, window, cx); | |
| 341 | 330 | self.chat.slowed_until = Some(now_ms() + seconds * 1000); |
| 342 | 331 | |
| 343 | 332 | cx.spawn_in(window, async move |this, cx| { |
crates/client/src/gui/media_view.rsmodified+5 -5
| @@ -29,7 +29,7 @@ use super::{ | ||
| 29 | 29 | use crate::{ |
| 30 | 30 | embed::{self, Embed, EmbedKind}, |
| 31 | 31 | media::{Player, voice_note as note}, |
| 32 | - network::NetworkHandle, | |
| 32 | + net::{Fail, NetworkHandle}, | |
| 33 | 33 | }; |
| 34 | 34 | |
| 35 | 35 | const FRAME_TICK: Duration = Duration::from_millis(16); |
| @@ -152,7 +152,7 @@ pub(super) async fn upload_file( | ||
| 152 | 152 | path: PathBuf, |
| 153 | 153 | maximum: Option<u64>, |
| 154 | 154 | cx: &mut AsyncWindowContext, |
| 155 | -) -> Result<Attachment, common::error::Error> { | |
| 155 | +) -> Result<Attachment, Fail> { | |
| 156 | 156 | let _ = this.update(cx, |yumush, cx| { |
| 157 | 157 | yumush.chat.media.uploading += 1; |
| 158 | 158 | cx.notify(); |
| @@ -322,11 +322,11 @@ impl Yumush { | ||
| 322 | 322 | &self, |
| 323 | 323 | attachment: &Attachment, |
| 324 | 324 | cx: &mut Context<Self>, |
| 325 | - ) -> Task<Result<PathBuf, common::error::Error>> { | |
| 325 | + ) -> Task<Result<PathBuf, Fail>> { | |
| 326 | 326 | let network = self.network.clone(); |
| 327 | 327 | let attachment = attachment.clone(); |
| 328 | 328 | 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)?; | |
| 330 | 330 | if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { |
| 331 | 331 | return Ok(path); |
| 332 | 332 | } |
| @@ -337,7 +337,7 @@ impl Yumush { | ||
| 337 | 337 | async move { std::fs::write(&path, bytes) } |
| 338 | 338 | }) |
| 339 | 339 | .await |
| 340 | - .map_err(|_| common::error::Error::Server)?; | |
| 340 | + .map_err(|_| Fail::Protocol)?; | |
| 341 | 341 | Ok(path) |
| 342 | 342 | }) |
| 343 | 343 | } |
crates/client/src/gui/settings_page.rsmodified+4 -3
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | use std::future::Future; |
| 2 | 2 | |
| 3 | -use common::{error::Error, model::User}; | |
| 3 | +use crate::net::Fail; | |
| 4 | +use common::model::User; | |
| 4 | 5 | use gpui_kit::{ |
| 5 | 6 | AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla, |
| 6 | 7 | InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, |
| @@ -255,7 +256,7 @@ impl Yumush { | ||
| 255 | 256 | } |
| 256 | 257 | } |
| 257 | 258 | |
| 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>) { | |
| 259 | 260 | match result { |
| 260 | 261 | Ok(user) => { |
| 261 | 262 | 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 | ||
| 267 | 268 | pub(super) fn picked_avatar( |
| 268 | 269 | cx: &App, |
| 269 | 270 | maximum: u64, |
| 270 | -) -> impl Future<Output = Option<Result<Vec<u8>, Error>>> + 'static { | |
| 271 | +) -> impl Future<Output = Option<Result<Vec<u8>, Fail>>> + 'static { | |
| 271 | 272 | let picked = cx.prompt_for_paths(PathPromptOptions { |
| 272 | 273 | files: true, |
| 273 | 274 | directories: false, |
crates/client/src/gui/voice_note.rsmodified+5 -1
| @@ -153,7 +153,11 @@ pub fn recording_row( | ||
| 153 | 153 | .text_size(text(13.)) |
| 154 | 154 | .text_color(palette.text) |
| 155 | 155 | .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 | + )) | |
| 157 | 161 | .child(bars(levels, 1., palette, |_, _, _| {})), |
| 158 | 162 | ) |
| 159 | 163 | .child( |
crates/client/src/gui/wave.rsmodified+1 -1
| @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; | ||
| 2 | 2 | |
| 3 | 3 | use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; |
| 4 | 4 | |
| 5 | -use crate::network::Levels; | |
| 5 | +use crate::net::Levels; | |
| 6 | 6 | |
| 7 | 7 | const DECAY: f32 = 0.82; |
| 8 | 8 | const GONE: f32 = 0.02; |
crates/client/src/lib.rsmodified+1 -1
| @@ -9,7 +9,7 @@ pub mod embed; | ||
| 9 | 9 | pub mod gui; |
| 10 | 10 | pub mod media; |
| 11 | 11 | pub mod mutes; |
| 12 | -pub mod network; | |
| 12 | +pub mod net; | |
| 13 | 13 | pub mod settings; |
| 14 | 14 | pub mod share; |
| 15 | 15 | pub mod tray; |
crates/client/src/main.rsmodified+2 -2
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | use client::{ |
| 4 | 4 | ClientConfig, NAME, |
| 5 | 5 | gui::{self, Yumush}, |
| 6 | - network, settings, | |
| 6 | + net, settings, | |
| 7 | 7 | tray::{self, TrayAction, TrayState}, |
| 8 | 8 | }; |
| 9 | 9 | use gpui_kit::{ |
| @@ -25,7 +25,7 @@ fn main() { | ||
| 25 | 25 | .init(); |
| 26 | 26 | |
| 27 | 27 | 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()); | |
| 29 | 29 | let (mut tray_receiver, tray_handle) = tray::start(); |
| 30 | 30 | |
| 31 | 31 | 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 { | ||
| 64 | 64 | } |
| 65 | 65 | |
| 66 | 66 | enum Backend { |
| 67 | - Hardware(hardware::Encoder), | |
| 68 | - H264(ec_h264::Encoder), | |
| 67 | + Hardware(Box<hardware::Encoder>), | |
| 68 | + H264(Box<ec_h264::Encoder>), | |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | impl Backend { |
| @@ -75,10 +75,12 @@ impl Backend { | ||
| 75 | 75 | } else { |
| 76 | 76 | None |
| 77 | 77 | }; |
| 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 | + }) | |
| 82 | 84 | } |
| 83 | 85 | |
| 84 | 86 | fn software(settings: &Settings) -> Option<Self> { |
| @@ -90,7 +92,7 @@ impl Backend { | ||
| 90 | 92 | config.bitrate = settings.bitrate; |
| 91 | 93 | config.gop_size = settings.gop; |
| 92 | 94 | 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))) | |
| 94 | 96 | } |
| 95 | 97 | Codec::H265 | Codec::Av1 | Codec::Vp8 | Codec::Vp9 => None, |
| 96 | 98 | } |
| @@ -165,7 +167,10 @@ mod hardware { | ||
| 165 | 167 | timestamp: i64::from(frame.timestamp_ms), |
| 166 | 168 | force_keyframe: force, |
| 167 | 169 | }; |
| 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 | + { | |
| 169 | 174 | let rgb = ec_hw::RgbFrame { |
| 170 | 175 | data: &frame.bgra, |
| 171 | 176 | width: frame.width, |
crates/client/src/share/reassembly.rsmodified+6 -0
| @@ -92,6 +92,12 @@ pub struct Reassembler { | ||
| 92 | 92 | lost_frames: u32, |
| 93 | 93 | } |
| 94 | 94 | |
| 95 | +impl Default for Reassembler { | |
| 96 | + fn default() -> Self { | |
| 97 | + Self::new() | |
| 98 | + } | |
| 99 | +} | |
| 100 | + | |
| 95 | 101 | impl Reassembler { |
| 96 | 102 | pub fn new() -> Reassembler { |
| 97 | 103 | Reassembler { |
crates/common/src/config.rsmodified+11 -5
| @@ -1,11 +1,17 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 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 | +} | |
| 4 | 10 | |
| 5 | 11 | pub struct Config(HashMap<String, String>); |
| 6 | 12 | |
| 7 | 13 | impl Config { |
| 8 | - pub fn parse(content: &str) -> Result<Self, Error> { | |
| 14 | + pub fn parse(content: &str) -> Result<Self, ConfigError> { | |
| 9 | 15 | let mut fields = HashMap::new(); |
| 10 | 16 | |
| 11 | 17 | for line in content.lines().map(str::trim) { |
| @@ -15,7 +21,7 @@ impl Config { | ||
| 15 | 21 | |
| 16 | 22 | let (key, value) = line |
| 17 | 23 | .split_once('=') |
| 18 | - .ok_or_else(|| Error::Config(format!("invalid line: {line}")))?; | |
| 24 | + .ok_or_else(|| ConfigError::InvalidLine(line.to_string()))?; | |
| 19 | 25 | |
| 20 | 26 | fields.insert( |
| 21 | 27 | key.trim().to_string(), |
| @@ -26,10 +32,10 @@ impl Config { | ||
| 26 | 32 | Ok(Self(fields)) |
| 27 | 33 | } |
| 28 | 34 | |
| 29 | - pub fn get(&self, key: &str) -> Result<String, Error> { | |
| 35 | + pub fn get(&self, key: &str) -> Result<String, ConfigError> { | |
| 30 | 36 | self.0 |
| 31 | 37 | .get(key) |
| 32 | 38 | .cloned() |
| 33 | - .ok_or_else(|| Error::Config(format!("missing key: {key}"))) | |
| 39 | + .ok_or_else(|| ConfigError::MissingKey(key.to_string())) | |
| 34 | 40 | } |
| 35 | 41 | } |
crates/common/src/error.rsmodified+51 -93
| @@ -2,42 +2,14 @@ use std::fmt::Display; | ||
| 2 | 2 | |
| 3 | 3 | use bitcode::{Decode, Encode}; |
| 4 | 4 | |
| 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 | - | |
| 30 | 5 | #[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 }, | |
| 35 | 8 | Empty, |
| 9 | + Characters, | |
| 36 | 10 | MultiLine, |
| 37 | - ForbiddenCharacter, | |
| 38 | 11 | NotJpeg, |
| 39 | 12 | Dimensions { expected: u32 }, |
| 40 | - TooSmall { minimum: u64, actual: u64 }, | |
| 41 | 13 | } |
| 42 | 14 | |
| 43 | 15 | pub fn size_text(size: u64) -> String { |
| @@ -48,38 +20,40 @@ pub fn size_text(size: u64) -> String { | ||
| 48 | 20 | } |
| 49 | 21 | } |
| 50 | 22 | |
| 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 {})", | |
| 64 | 29 | size_text(*actual), |
| 65 | - size_text(*maximum) | |
| 30 | + size_text(*min) | |
| 66 | 31 | ) |
| 67 | 32 | } |
| 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 {})", | |
| 79 | 36 | size_text(*actual), |
| 80 | - size_text(*minimum) | |
| 37 | + size_text(*max) | |
| 81 | 38 | ) |
| 82 | 39 | } |
| 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"), | |
| 83 | 57 | } |
| 84 | 58 | } |
| 85 | 59 | } |
| @@ -101,6 +75,17 @@ pub enum Field { | ||
| 101 | 75 | BackupName, |
| 102 | 76 | Quota, |
| 103 | 77 | 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 | + } | |
| 104 | 89 | } |
| 105 | 90 | |
| 106 | 91 | impl Display for Field { |
| @@ -121,6 +106,8 @@ impl Display for Field { | ||
| 121 | 106 | Field::BackupName => "backup name:", |
| 122 | 107 | Field::Quota => "quota:", |
| 123 | 108 | Field::Announcement => "announcement:", |
| 109 | + Field::Poll => "poll:", | |
| 110 | + Field::Reaction => "reaction:", | |
| 124 | 111 | }; |
| 125 | 112 | write!(f, "{label}") |
| 126 | 113 | } |
| @@ -138,34 +125,16 @@ pub enum Error { | ||
| 138 | 125 | Taken, |
| 139 | 126 | #[error("wrong credentials")] |
| 140 | 127 | 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), | |
| 159 | 128 | #[error("already a member")] |
| 160 | 129 | AlreadyMember, |
| 161 | 130 | #[error("already invited")] |
| 162 | 131 | AlreadyInvited, |
| 163 | 132 | #[error("suspended")] |
| 164 | - Suspended, | |
| 165 | - #[error("registration closed")] | |
| 166 | - RegistrationClosed, | |
| 133 | + Suspended { until_ms: Option<u64> }, | |
| 167 | 134 | #[error("banned")] |
| 168 | 135 | Banned, |
| 136 | + #[error("registration closed")] | |
| 137 | + RegistrationClosed, | |
| 169 | 138 | #[error("maintenance")] |
| 170 | 139 | Maintenance, |
| 171 | 140 | #[error("storage quota exceeded")] |
| @@ -174,19 +143,8 @@ pub enum Error { | ||
| 174 | 143 | LimitReached, |
| 175 | 144 | #[error("too many requests, retry in {retry_after_seconds}s")] |
| 176 | 145 | 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, | |
| 179 | 150 | } |
| 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; | ||
| 3 | 3 | pub mod datagram; |
| 4 | 4 | pub mod error; |
| 5 | 5 | pub mod event; |
| 6 | +pub mod frame; | |
| 6 | 7 | pub mod model; |
| 7 | -pub mod network; | |
| 8 | +pub mod open; | |
| 8 | 9 | pub mod permission; |
| 9 | 10 | pub mod request; |
| 10 | 11 | pub mod response; |
| 11 | 12 | pub mod share; |
| 12 | 13 | pub mod time; |
| 14 | +pub mod transport; | |
| 13 | 15 | 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::{ | ||
| 5 | 5 | share::{Codec, Kind, Quality, Source}, |
| 6 | 6 | }; |
| 7 | 7 | |
| 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 | - | |
| 21 | 8 | #[derive(Debug, Clone, Encode, Decode)] |
| 22 | 9 | pub enum Request { |
| 23 | 10 | Register { |
| @@ -357,7 +344,4 @@ pub enum Request { | ||
| 357 | 344 | DeleteBackup { |
| 358 | 345 | name: String, |
| 359 | 346 | }, |
| 360 | - DownloadBackup { | |
| 361 | - name: String, | |
| 362 | - }, | |
| 363 | 347 | } |
crates/common/src/response.rsmodified+0 -2
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | |
| 3 | 3 | use crate::{ |
| 4 | - error::Error, | |
| 5 | 4 | model::{ |
| 6 | 5 | Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, |
| 7 | 6 | CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, |
| @@ -32,7 +31,6 @@ pub enum Response { | ||
| 32 | 31 | Friends(Friends), |
| 33 | 32 | Invitations(Vec<Invitation>), |
| 34 | 33 | Done, |
| 35 | - Error(Error), | |
| 36 | 34 | Logs(Vec<LogEntry>), |
| 37 | 35 | Users(Vec<Account>), |
| 38 | 36 | 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::{ | ||
| 11 | 11 | MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS, |
| 12 | 12 | MINIMUM_USERNAME_LENGTH, REACTIONS, |
| 13 | 13 | }, |
| 14 | - error::{Error, Field, InvalidInput}, | |
| 14 | + error::{Error, Field, Problem}, | |
| 15 | 15 | model::{Poll, ServerSettings}, |
| 16 | 16 | }; |
| 17 | 17 | |
| 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 } | |
| 20 | 20 | } |
| 21 | 21 | |
| 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 }); | |
| 29 | 25 | } |
| 30 | 26 | |
| 31 | 27 | Ok(()) |
| 32 | 28 | } |
| 33 | 29 | |
| 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> { | |
| 35 | 35 | check_length(text.chars().count(), minimum, maximum) |
| 36 | 36 | } |
| 37 | 37 | |
| 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' '); | |
| 40 | 42 | if !allowed || name != name.trim() { |
| 41 | - return Err(InvalidInput::ForbiddenCharacter); | |
| 43 | + return Err(Problem::Characters); | |
| 42 | 44 | } |
| 43 | 45 | |
| 44 | 46 | check_length(name.len(), minimum, maximum) |
| @@ -50,13 +52,21 @@ pub fn validate_username(username: &str) -> Result<(), Error> { | ||
| 50 | 52 | } |
| 51 | 53 | |
| 52 | 54 | 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)) | |
| 55 | 61 | } |
| 56 | 62 | |
| 57 | 63 | 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)) | |
| 60 | 70 | } |
| 61 | 71 | |
| 62 | 72 | 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 | ||
| 69 | 79 | } |
| 70 | 80 | |
| 71 | 81 | 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))?; | |
| 73 | 83 | check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS) |
| 74 | - .map_err(invalid(Field::Message))?; | |
| 84 | + .map_err(invalid(Field::Poll))?; | |
| 75 | 85 | 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))?; | |
| 77 | 87 | } |
| 78 | 88 | |
| 79 | 89 | Ok(()) |
| @@ -97,16 +107,14 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> { | ||
| 97 | 107 | return Ok(()); |
| 98 | 108 | } |
| 99 | 109 | |
| 100 | - Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter)) | |
| 110 | + Err(invalid(Field::Reaction)(Problem::Characters)) | |
| 101 | 111 | } |
| 102 | 112 | |
| 103 | 113 | pub fn validate_attachment_name(name: &str) -> Result<(), Error> { |
| 104 | 114 | check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(invalid(Field::AttachmentName))?; |
| 105 | 115 | |
| 106 | 116 | 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)); | |
| 110 | 118 | } |
| 111 | 119 | |
| 112 | 120 | Ok(()) |
| @@ -119,17 +127,16 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> { | ||
| 119 | 127 | character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') |
| 120 | 128 | }) |
| 121 | 129 | { |
| 122 | - return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter)); | |
| 130 | + return Err(invalid(Field::BackupName)(Problem::Characters)); | |
| 123 | 131 | } |
| 124 | 132 | |
| 125 | 133 | Ok(()) |
| 126 | 134 | } |
| 127 | 135 | |
| 128 | -fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> { | |
| 136 | +fn check_size(actual: u64, maximum: u64) -> Result<(), Problem> { | |
| 129 | 137 | 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), | |
| 133 | 140 | } |
| 134 | 141 | } |
| 135 | 142 | |
| @@ -138,27 +145,19 @@ pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> { | ||
| 138 | 145 | } |
| 139 | 146 | |
| 140 | 147 | 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)) | |
| 156 | 154 | } |
| 157 | 155 | |
| 158 | 156 | fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { |
| 159 | 157 | 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, | |
| 162 | 161 | actual: quota, |
| 163 | 162 | })); |
| 164 | 163 | } |
| @@ -166,9 +165,9 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { | ||
| 166 | 165 | Ok(()) |
| 167 | 166 | } |
| 168 | 167 | |
| 169 | -fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { | |
| 168 | +fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), Problem> { | |
| 170 | 169 | if text.contains(['\n', '\r']) { |
| 171 | - return Err(InvalidInput::MultiLine); | |
| 170 | + return Err(Problem::MultiLine); | |
| 172 | 171 | } |
| 173 | 172 | |
| 174 | 173 | check_text(text, minimum, maximum) |
crates/pixel/src/lib.rsmodified+13 -10
| @@ -30,6 +30,7 @@ pub struct I420 { | ||
| 30 | 30 | pub height: u32, |
| 31 | 31 | } |
| 32 | 32 | |
| 33 | +#[allow(clippy::too_many_arguments)] | |
| 33 | 34 | pub fn yuv_to_bgra( |
| 34 | 35 | y: &[u8], |
| 35 | 36 | y_stride: usize, |
| @@ -166,6 +167,18 @@ fn scale(source: &Bgra, width: u32, height: u32) -> Option<Vec<u8>> { | ||
| 166 | 167 | Some(target.into_vec()) |
| 167 | 168 | } |
| 168 | 169 | |
| 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 | + | |
| 169 | 182 | #[cfg(test)] |
| 170 | 183 | mod tests { |
| 171 | 184 | use super::*; |
| @@ -185,13 +198,3 @@ mod tests { | ||
| 185 | 198 | ); |
| 186 | 199 | } |
| 187 | 200 | } |
| 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::{ | ||
| 5 | 5 | }; |
| 6 | 6 | use turso::Connection; |
| 7 | 7 | |
| 8 | -use crate::{database::new_id, error::Error, user}; | |
| 8 | +use crate::{database::new_id, error::ServerError, user}; | |
| 9 | 9 | |
| 10 | 10 | fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> { |
| 11 | 11 | Some(match AdminActionKind::parse(text)? { |
| @@ -63,7 +63,7 @@ pub async fn record( | ||
| 63 | 63 | community: Option<&str>, |
| 64 | 64 | action: &AdminAction, |
| 65 | 65 | conn: &Connection, |
| 66 | -) -> Result<(), Error> { | |
| 66 | +) -> Result<(), ServerError> { | |
| 67 | 67 | let id = new_id(); |
| 68 | 68 | let detail = action_detail(action); |
| 69 | 69 | conn.execute( |
| @@ -89,7 +89,7 @@ pub async fn list( | ||
| 89 | 89 | after_ms: Option<u64>, |
| 90 | 90 | before_ms: Option<u64>, |
| 91 | 91 | conn: &Connection, |
| 92 | -) -> Result<Vec<AdminLogEntry>, Error> { | |
| 92 | +) -> Result<Vec<AdminLogEntry>, ServerError> { | |
| 93 | 93 | let (after, before) = time::range_bounds(after_ms, before_ms); |
| 94 | 94 | let mut rows = conn |
| 95 | 95 | .query( |
crates/server/src/attachment.rsmodified+82 -84
| @@ -10,22 +10,18 @@ use common::{ | ||
| 10 | 10 | ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE, |
| 11 | 11 | THUMBNAIL_SIZE, |
| 12 | 12 | }, |
| 13 | - error::Error as CommonError, | |
| 13 | + error::{Error as CommonError, Field, Problem}, | |
| 14 | + frame::{self, DOWN_MAX, Sending}, | |
| 14 | 15 | model::{ |
| 15 | 16 | Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, |
| 16 | 17 | }, |
| 17 | - network::{ | |
| 18 | - DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded, receive_upload_header, | |
| 19 | - send_download_reply, send_response, | |
| 20 | - }, | |
| 18 | + open::{Blob, Upload}, | |
| 21 | 19 | permission, |
| 22 | - request::{DownloadRequest, UploadHeader}, | |
| 23 | - response::Response, | |
| 24 | 20 | time::{self, HOUR_MILLIS}, |
| 25 | 21 | validate::{validate_attachment_name, validate_attachment_size}, |
| 26 | 22 | }; |
| 27 | 23 | use image::{ImageFormat, ImageReader, Limits}; |
| 28 | -use quinn::{RecvStream, SendStream, VarInt}; | |
| 24 | +use quinn::{RecvStream, VarInt}; | |
| 29 | 25 | use tokio::{ |
| 30 | 26 | fs::File, |
| 31 | 27 | io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, |
| @@ -34,9 +30,9 @@ use tracing::error; | ||
| 34 | 30 | use turso::{Connection, Row}; |
| 35 | 31 | |
| 36 | 32 | use crate::{ |
| 37 | - community, | |
| 33 | + backup, community, | |
| 38 | 34 | database::{self, DB, new_id}, |
| 39 | - error::Error, | |
| 35 | + error::ServerError, | |
| 40 | 36 | request::{actor_rank, ensure}, |
| 41 | 37 | server_settings, user, |
| 42 | 38 | }; |
| @@ -56,7 +52,7 @@ pub struct Stored { | ||
| 56 | 52 | pub message_id: Option<String>, |
| 57 | 53 | } |
| 58 | 54 | |
| 59 | -fn from_row(row: &Row) -> Result<Attachment, Error> { | |
| 55 | +fn from_row(row: &Row) -> Result<Attachment, ServerError> { | |
| 60 | 56 | let size: i64 = row.get(2)?; |
| 61 | 57 | let kind: String = row.get(3)?; |
| 62 | 58 | let width: Option<i64> = row.get(4)?; |
| @@ -76,7 +72,7 @@ pub async fn of_message( | ||
| 76 | 72 | message_id: &str, |
| 77 | 73 | snippet_position: Option<i64>, |
| 78 | 74 | conn: &Connection, |
| 79 | -) -> Result<Vec<Attachment>, Error> { | |
| 75 | +) -> Result<Vec<Attachment>, ServerError> { | |
| 80 | 76 | let mut rows = conn |
| 81 | 77 | .query( |
| 82 | 78 | "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( | ||
| 98 | 94 | community_id: &str, |
| 99 | 95 | attachment_ids: &[String], |
| 100 | 96 | conn: &Connection, |
| 101 | -) -> Result<(), Error> { | |
| 97 | +) -> Result<(), ServerError> { | |
| 102 | 98 | if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE { |
| 103 | 99 | return Err(CommonError::NotFound.into()); |
| 104 | 100 | } |
| @@ -128,7 +124,7 @@ fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> { | ||
| 128 | 124 | std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop)) |
| 129 | 125 | } |
| 130 | 126 | |
| 131 | -async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> { | |
| 127 | +async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { | |
| 132 | 128 | tokio::task::spawn_blocking(move || link_or_copy(&source, &target)) |
| 133 | 129 | .await |
| 134 | 130 | .map_err(|_| CommonError::Server)? |
| @@ -137,7 +133,7 @@ async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> { | ||
| 137 | 133 | Ok(()) |
| 138 | 134 | } |
| 139 | 135 | |
| 140 | -async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), Error> { | |
| 136 | +async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { | |
| 141 | 137 | if tokio::fs::try_exists(&source) |
| 142 | 138 | .await |
| 143 | 139 | .map_err(|_| CommonError::Server)? |
| @@ -156,7 +152,7 @@ pub async fn copy( | ||
| 156 | 152 | snippet_position: Option<i64>, |
| 157 | 153 | directory: &Path, |
| 158 | 154 | conn: &Connection, |
| 159 | -) -> Result<(), Error> { | |
| 155 | +) -> Result<(), ServerError> { | |
| 160 | 156 | let id = new_id(); |
| 161 | 157 | conn.execute( |
| 162 | 158 | "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( | ||
| 183 | 179 | .await |
| 184 | 180 | } |
| 185 | 181 | |
| 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> { | |
| 187 | 186 | database::ids( |
| 188 | 187 | conn, |
| 189 | 188 | "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 | ||
| 192 | 191 | .await |
| 193 | 192 | } |
| 194 | 193 | |
| 195 | -pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), Error> { | |
| 194 | +pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 196 | 195 | conn.execute("DELETE FROM attachment WHERE id = ?1", (attachment_id,)) |
| 197 | 196 | .await?; |
| 198 | 197 | |
| @@ -203,7 +202,7 @@ pub async fn all( | ||
| 203 | 202 | user_id: Option<&str>, |
| 204 | 203 | community_id: Option<&str>, |
| 205 | 204 | conn: &Connection, |
| 206 | -) -> Result<Vec<AttachmentInfo>, Error> { | |
| 205 | +) -> Result<Vec<AttachmentInfo>, ServerError> { | |
| 207 | 206 | let mut rows = conn |
| 208 | 207 | .query( |
| 209 | 208 | &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( | ||
| 230 | 229 | Ok(infos) |
| 231 | 230 | } |
| 232 | 231 | |
| 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> { | |
| 234 | 233 | let mut rows = conn |
| 235 | 234 | .query( |
| 236 | 235 | &format!( |
| @@ -250,7 +249,7 @@ async fn totals(column: &str, conn: &Connection) -> Result<Vec<(String, u64, u64 | ||
| 250 | 249 | Ok(totals) |
| 251 | 250 | } |
| 252 | 251 | |
| 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> { | |
| 254 | 253 | let mut users = Vec::new(); |
| 255 | 254 | for (user_id, bytes, count) in totals("uploader_id", conn).await? { |
| 256 | 255 | users.push(Usage { |
| @@ -279,7 +278,7 @@ async fn over_quota( | ||
| 279 | 278 | limit: u64, |
| 280 | 279 | size: u64, |
| 281 | 280 | conn: &Connection, |
| 282 | -) -> Result<bool, Error> { | |
| 281 | +) -> Result<bool, ServerError> { | |
| 283 | 282 | if limit == 0 { |
| 284 | 283 | return Ok(false); |
| 285 | 284 | } |
| @@ -294,7 +293,7 @@ async fn ensure_quota( | ||
| 294 | 293 | size: u64, |
| 295 | 294 | settings: &ServerSettings, |
| 296 | 295 | conn: &Connection, |
| 297 | -) -> Result<(), Error> { | |
| 296 | +) -> Result<(), ServerError> { | |
| 298 | 297 | if over_quota( |
| 299 | 298 | "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", |
| 300 | 299 | user_id, |
| @@ -321,7 +320,7 @@ async fn ensure_quota( | ||
| 321 | 320 | Ok(()) |
| 322 | 321 | } |
| 323 | 322 | |
| 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> { | |
| 325 | 324 | database::ids( |
| 326 | 325 | conn, |
| 327 | 326 | "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>, | ||
| 330 | 329 | .await |
| 331 | 330 | } |
| 332 | 331 | |
| 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> { | |
| 334 | 333 | conn.execute("DELETE FROM attachment WHERE uploader_id = ?1", (user_id,)) |
| 335 | 334 | .await?; |
| 336 | 335 | |
| @@ -344,7 +343,7 @@ pub fn remove_files(attachment_ids: &[String], directory: &Path) { | ||
| 344 | 343 | } |
| 345 | 344 | } |
| 346 | 345 | |
| 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> { | |
| 348 | 347 | let mut rows = conn |
| 349 | 348 | .query( |
| 350 | 349 | "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>( | ||
| 423 | 422 | reader: &mut R, |
| 424 | 423 | part: &Path, |
| 425 | 424 | 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 | + }; | |
| 428 | 434 | let mut file = File::create(part).await?; |
| 429 | 435 | |
| 430 | 436 | 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>( | ||
| 441 | 447 | |
| 442 | 448 | received += read as u64; |
| 443 | 449 | if received > size { |
| 444 | - return Err(mismatch().into()); | |
| 450 | + return Err(mismatch(received).into()); | |
| 445 | 451 | } |
| 446 | 452 | file.write_all(&buffer[..read]).await?; |
| 447 | 453 | } |
| 448 | 454 | |
| 449 | 455 | if received != size { |
| 450 | - return Err(mismatch().into()); | |
| 456 | + return Err(mismatch(received).into()); | |
| 451 | 457 | } |
| 452 | 458 | file.flush().await?; |
| 453 | 459 | |
| @@ -456,11 +462,11 @@ async fn receive_body<R: AsyncRead + Unpin>( | ||
| 456 | 462 | |
| 457 | 463 | pub async fn store<R: AsyncRead + Unpin>( |
| 458 | 464 | user: &User, |
| 459 | - header: &UploadHeader, | |
| 465 | + header: &Upload, | |
| 460 | 466 | reader: &mut R, |
| 461 | 467 | db: &DB, |
| 462 | 468 | directory: &Path, |
| 463 | -) -> Result<Attachment, Error> { | |
| 469 | +) -> Result<Attachment, ServerError> { | |
| 464 | 470 | let conn = database::connect(db).await?; |
| 465 | 471 | let rank = actor_rank(user, &header.community_id, &conn).await?; |
| 466 | 472 | ensure(permission::can_post(rank))?; |
| @@ -525,44 +531,44 @@ pub async fn store<R: AsyncRead + Unpin>( | ||
| 525 | 531 | |
| 526 | 532 | pub async fn upload( |
| 527 | 533 | user: Option<&User>, |
| 534 | + header: Upload, | |
| 528 | 535 | mut receive_stream: RecvStream, |
| 529 | - send_stream: SendStream, | |
| 536 | + mut send_stream: Sending, | |
| 530 | 537 | db: &DB, |
| 531 | 538 | directory: &Path, |
| 532 | -) -> Result<(), Error> { | |
| 533 | - let header = receive_upload_header(&mut receive_stream).await?; | |
| 539 | +) -> Result<(), ServerError> { | |
| 534 | 540 | let stored = match user { |
| 535 | 541 | Some(user) => store(user, &header, &mut receive_stream, db, directory).await, |
| 536 | 542 | None => Err(CommonError::Unauthenticated.into()), |
| 537 | 543 | }; |
| 544 | + let rejected = stored.is_err(); | |
| 545 | + let reply = stored.map_err(CommonError::from); | |
| 538 | 546 | |
| 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 | + } | |
| 547 | 552 | |
| 548 | 553 | Ok(()) |
| 549 | 554 | } |
| 550 | 555 | |
| 551 | -async fn locate( | |
| 556 | +pub async fn locate( | |
| 552 | 557 | user: Option<&User>, |
| 553 | - request: &DownloadRequest, | |
| 558 | + attachment_id: &str, | |
| 559 | + thumbnail: bool, | |
| 554 | 560 | db: &DB, |
| 555 | 561 | directory: &Path, |
| 556 | -) -> Result<(PathBuf, u64), Error> { | |
| 562 | +) -> Result<(PathBuf, u64), ServerError> { | |
| 557 | 563 | let user = user.ok_or(CommonError::Unauthenticated)?; |
| 558 | 564 | let conn = database::connect(db).await?; |
| 559 | - let stored = read(&request.attachment_id, &conn).await?; | |
| 565 | + let stored = read(attachment_id, &conn).await?; | |
| 560 | 566 | |
| 561 | 567 | let rank = actor_rank(user, &stored.community_id, &conn).await?; |
| 562 | 568 | ensure(permission::can_read(rank))?; |
| 563 | 569 | ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; |
| 564 | 570 | |
| 565 | - let path = if request.thumbnail { | |
| 571 | + let path = if thumbnail { | |
| 566 | 572 | thumb_path(directory, &stored.attachment.id) |
| 567 | 573 | } else { |
| 568 | 574 | directory.join(&stored.attachment.id) |
| @@ -575,46 +581,36 @@ async fn locate( | ||
| 575 | 581 | Ok((path, length)) |
| 576 | 582 | } |
| 577 | 583 | |
| 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( | |
| 592 | 585 | user: Option<&User>, |
| 593 | - mut receive_stream: RecvStream, | |
| 594 | - mut send_stream: SendStream, | |
| 586 | + blob: Blob, | |
| 587 | + mut send_stream: Sending, | |
| 595 | 588 | db: &DB, |
| 596 | 589 | 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); | |
| 611 | 598 | let reply = located |
| 612 | 599 | .as_ref() |
| 613 | 600 | .map(|(_, length)| *length) |
| 614 | 601 | .map_err(Clone::clone); |
| 615 | - send_download_reply(reply, send_stream).await?; | |
| 602 | + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | |
| 603 | + | |
| 616 | 604 | 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 | + } | |
| 618 | 614 | } |
| 619 | 615 | send_stream.finish()?; |
| 620 | 616 | |
| @@ -631,7 +627,7 @@ pub async fn collect(db: DB, directory: PathBuf) { | ||
| 631 | 627 | } |
| 632 | 628 | } |
| 633 | 629 | |
| 634 | -async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { | |
| 630 | +async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { | |
| 635 | 631 | let conn = database::connect(db).await?; |
| 636 | 632 | let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS); |
| 637 | 633 | let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); |
| @@ -676,7 +672,8 @@ mod tests { | ||
| 676 | 672 | |
| 677 | 673 | use common::{ |
| 678 | 674 | model::{AttachmentKind, Rank}, |
| 679 | - request::{Request, UploadHeader}, | |
| 675 | + open::Upload, | |
| 676 | + request::Request, | |
| 680 | 677 | }; |
| 681 | 678 | use image::{ImageFormat, RgbImage}; |
| 682 | 679 | |
| @@ -704,7 +701,7 @@ mod tests { | ||
| 704 | 701 | .unwrap(); |
| 705 | 702 | let png = png.into_inner(); |
| 706 | 703 | let directory = test::directory(); |
| 707 | - let header = UploadHeader { | |
| 704 | + let header = Upload { | |
| 708 | 705 | community_id: community.id.clone(), |
| 709 | 706 | name: "pixel.png".to_string(), |
| 710 | 707 | size: png.len() as u64, |
| @@ -717,7 +714,7 @@ mod tests { | ||
| 717 | 714 | user: user.clone(), |
| 718 | 715 | token: "token".to_string(), |
| 719 | 716 | }); |
| 720 | - handle( | |
| 717 | + let (reply, _) = handle( | |
| 721 | 718 | Request::CreateMessage { |
| 722 | 719 | community_id: community.id.clone(), |
| 723 | 720 | body: String::new(), |
| @@ -732,6 +729,7 @@ mod tests { | ||
| 732 | 729 | &test::directory(), |
| 733 | 730 | ) |
| 734 | 731 | .await; |
| 732 | + reply.unwrap(); | |
| 735 | 733 | |
| 736 | 734 | let messages = message::read_page(&community.id, None, &conn) |
| 737 | 735 | .await |
crates/server/src/authentication.rsmodified+29 -24
| @@ -7,34 +7,35 @@ use common::{ | ||
| 7 | 7 | }; |
| 8 | 8 | use turso::Connection; |
| 9 | 9 | |
| 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}; | |
| 11 | 11 | |
| 12 | 12 | const SALT_LENGTH: usize = 16; |
| 13 | 13 | const TOKEN_LENGTH: usize = 32; |
| 14 | 14 | |
| 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> { | |
| 16 | 16 | 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}")))?; | |
| 18 | 19 | |
| 19 | 20 | Ok(bytes) |
| 20 | 21 | } |
| 21 | 22 | |
| 22 | -fn hash(password: &str) -> Result<String, Error> { | |
| 23 | +fn hash(password: &str) -> Result<String, ServerError> { | |
| 23 | 24 | let salt = random_bytes::<SALT_LENGTH>()?; |
| 24 | 25 | let hash = Argon2::default() |
| 25 | 26 | .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()))?; | |
| 27 | 28 | |
| 28 | 29 | Ok(hash.to_string()) |
| 29 | 30 | } |
| 30 | 31 | |
| 31 | -fn verify(password: &str, password_hash: &str) -> Result<(), Error> { | |
| 32 | +fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> { | |
| 32 | 33 | Argon2::default() |
| 33 | 34 | .verify_password(password.as_bytes(), password_hash) |
| 34 | - .map_err(|_| Error::from(CommonError::WrongCredentials)) | |
| 35 | + .map_err(|_| ServerError::from(CommonError::WrongCredentials)) | |
| 35 | 36 | } |
| 36 | 37 | |
| 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> { | |
| 38 | 39 | let token: String = random_bytes::<TOKEN_LENGTH>()? |
| 39 | 40 | .iter() |
| 40 | 41 | .map(|byte| format!("{byte:02x}")) |
| @@ -50,7 +51,7 @@ async fn open_session(user_id: &str, conn: &Connection) -> Result<String, Error> | ||
| 50 | 51 | Ok(token) |
| 51 | 52 | } |
| 52 | 53 | |
| 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> { | |
| 54 | 55 | if user::is_ghost(user_id, conn).await? { |
| 55 | 56 | return Ok(()); |
| 56 | 57 | } |
| @@ -69,7 +70,7 @@ pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), E | ||
| 69 | 70 | Ok(()) |
| 70 | 71 | } |
| 71 | 72 | |
| 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> { | |
| 73 | 74 | validate_device(name)?; |
| 74 | 75 | conn.execute( |
| 75 | 76 | "UPDATE session SET device = ?2 WHERE token = ?1", |
| @@ -80,7 +81,7 @@ pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<() | ||
| 80 | 81 | Ok(()) |
| 81 | 82 | } |
| 82 | 83 | |
| 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> { | |
| 84 | 85 | let mut rows = conn |
| 85 | 86 | .query( |
| 86 | 87 | "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( | ||
| 104 | 105 | user_id: &str, |
| 105 | 106 | session_id: &str, |
| 106 | 107 | conn: &Connection, |
| 107 | -) -> Result<String, Error> { | |
| 108 | +) -> Result<String, ServerError> { | |
| 108 | 109 | let mut rows = conn |
| 109 | 110 | .query( |
| 110 | 111 | "DELETE FROM session WHERE id = ?1 AND user_id = ?2 RETURNING token", |
| @@ -120,7 +121,7 @@ pub async fn create_account( | ||
| 120 | 121 | username: &str, |
| 121 | 122 | password: &str, |
| 122 | 123 | conn: &Connection, |
| 123 | -) -> Result<User, Error> { | |
| 124 | +) -> Result<User, ServerError> { | |
| 124 | 125 | validate_username(username)?; |
| 125 | 126 | validate_password(password)?; |
| 126 | 127 | |
| @@ -136,7 +137,7 @@ pub async fn register( | ||
| 136 | 137 | password: &str, |
| 137 | 138 | invite_code: Option<&str>, |
| 138 | 139 | conn: &mut Connection, |
| 139 | -) -> Result<(User, String), Error> { | |
| 140 | +) -> Result<(User, String), ServerError> { | |
| 140 | 141 | let tx = conn.transaction().await?; |
| 141 | 142 | if server_ban::username_banned(username, &tx).await? { |
| 142 | 143 | return Err(CommonError::Banned.into()); |
| @@ -156,7 +157,7 @@ pub async fn login( | ||
| 156 | 157 | username: &str, |
| 157 | 158 | password: &str, |
| 158 | 159 | conn: &Connection, |
| 159 | -) -> Result<(User, String), Error> { | |
| 160 | +) -> Result<(User, String), ServerError> { | |
| 160 | 161 | let (user, password_hash) = user::credentials(username, conn) |
| 161 | 162 | .await? |
| 162 | 163 | .ok_or(CommonError::WrongCredentials)?; |
| @@ -167,12 +168,12 @@ pub async fn login( | ||
| 167 | 168 | Ok((user, token)) |
| 168 | 169 | } |
| 169 | 170 | |
| 170 | -async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { | |
| 171 | +async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> { | |
| 171 | 172 | if server_ban::username_banned(&user.username, conn).await? { |
| 172 | 173 | return Err(CommonError::Banned.into()); |
| 173 | 174 | } |
| 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()); | |
| 176 | 177 | } |
| 177 | 178 | if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance { |
| 178 | 179 | return Err(CommonError::Maintenance.into()); |
| @@ -181,7 +182,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { | ||
| 181 | 182 | Ok(()) |
| 182 | 183 | } |
| 183 | 184 | |
| 184 | -pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> { | |
| 185 | +pub async fn resume(token: &str, conn: &Connection) -> Result<User, ServerError> { | |
| 185 | 186 | let user = user::by_session_token(token, conn).await?; |
| 186 | 187 | admit(&user, conn).await?; |
| 187 | 188 | seen(&user.id, token, conn).await?; |
| @@ -189,21 +190,25 @@ pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> { | ||
| 189 | 190 | Ok(user) |
| 190 | 191 | } |
| 191 | 192 | |
| 192 | -pub async fn logout(token: &str, conn: &Connection) -> Result<(), Error> { | |
| 193 | +pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 193 | 194 | conn.execute("DELETE FROM session WHERE token = ?1", (token,)) |
| 194 | 195 | .await?; |
| 195 | 196 | |
| 196 | 197 | Ok(()) |
| 197 | 198 | } |
| 198 | 199 | |
| 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> { | |
| 200 | 201 | conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) |
| 201 | 202 | .await?; |
| 202 | 203 | |
| 203 | 204 | Ok(()) |
| 204 | 205 | } |
| 205 | 206 | |
| 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> { | |
| 207 | 212 | validate_password(password)?; |
| 208 | 213 | user::set_password_hash(user_id, &hash(password)?, conn).await?; |
| 209 | 214 | revoke_sessions(user_id, conn).await |
| @@ -213,7 +218,7 @@ pub async fn reset_password(user_id: &str, password: &str, conn: &Connection) -> | ||
| 213 | 218 | mod tests { |
| 214 | 219 | use common::error::Error as CommonError; |
| 215 | 220 | |
| 216 | - use crate::{authentication, database, error::Error, test}; | |
| 221 | + use crate::{authentication, database, error::ServerError, test}; | |
| 217 | 222 | |
| 218 | 223 | #[tokio::test] |
| 219 | 224 | async fn register_and_login() { |
| @@ -232,7 +237,7 @@ mod tests { | ||
| 232 | 237 | assert_eq!(registered_user, logged_in_user); |
| 233 | 238 | assert!(matches!( |
| 234 | 239 | wrong_password, |
| 235 | - Err(Error::Common(CommonError::WrongCredentials)) | |
| 240 | + Err(ServerError::Wire(CommonError::WrongCredentials)) | |
| 236 | 241 | )); |
| 237 | 242 | } |
| 238 | 243 | } |
crates/server/src/backup.rsmodified+15 -36
| @@ -3,19 +3,15 @@ use std::path::{Path, PathBuf}; | ||
| 3 | 3 | use common::{ |
| 4 | 4 | error::Error as CommonError, |
| 5 | 5 | model::{AdminAction, BackupInfo, User}, |
| 6 | - network::{DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded}, | |
| 7 | - permission, | |
| 8 | - request::Request, | |
| 9 | - time, | |
| 6 | + permission, time, | |
| 10 | 7 | validate::validate_backup_name, |
| 11 | 8 | }; |
| 12 | -use quinn::{RecvStream, SendStream}; | |
| 13 | 9 | use turso::Connection; |
| 14 | 10 | |
| 15 | 11 | use crate::{ |
| 16 | - admin_log, attachment, | |
| 12 | + admin_log, | |
| 17 | 13 | database::{self, DB}, |
| 18 | - error::Error, | |
| 14 | + error::ServerError, | |
| 19 | 15 | request::ensure, |
| 20 | 16 | user, |
| 21 | 17 | }; |
| @@ -30,7 +26,7 @@ fn created_secs(name: &str) -> Option<u64> { | ||
| 30 | 26 | .ok() |
| 31 | 27 | } |
| 32 | 28 | |
| 33 | -fn info(directory: &Path, name: &str) -> Result<BackupInfo, Error> { | |
| 29 | +fn info(directory: &Path, name: &str) -> Result<BackupInfo, ServerError> { | |
| 34 | 30 | let created_secs = created_secs(name).ok_or(CommonError::NotFound)?; |
| 35 | 31 | let size_bytes = std::fs::metadata(directory.join(name))?.len(); |
| 36 | 32 | |
| @@ -41,14 +37,14 @@ fn info(directory: &Path, name: &str) -> Result<BackupInfo, Error> { | ||
| 41 | 37 | }) |
| 42 | 38 | } |
| 43 | 39 | |
| 44 | -fn path_of(directory: &Path, name: &str) -> Result<PathBuf, Error> { | |
| 40 | +fn path_of(directory: &Path, name: &str) -> Result<PathBuf, ServerError> { | |
| 45 | 41 | validate_backup_name(name)?; |
| 46 | 42 | created_secs(name).ok_or(CommonError::NotFound)?; |
| 47 | 43 | |
| 48 | 44 | Ok(directory.join(name)) |
| 49 | 45 | } |
| 50 | 46 | |
| 51 | -pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, Error> { | |
| 47 | +pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, ServerError> { | |
| 52 | 48 | let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); |
| 53 | 49 | let path = directory.join(&name); |
| 54 | 50 | let statement = format!( |
| @@ -60,7 +56,7 @@ pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, E | ||
| 60 | 56 | info(directory, &name) |
| 61 | 57 | } |
| 62 | 58 | |
| 63 | -pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> { | |
| 59 | +pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, ServerError> { | |
| 64 | 60 | let mut backups = Vec::new(); |
| 65 | 61 | for entry in std::fs::read_dir(directory)? { |
| 66 | 62 | let name = entry?.file_name().to_string_lossy().into_owned(); |
| @@ -73,27 +69,24 @@ pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> { | ||
| 73 | 69 | Ok(backups) |
| 74 | 70 | } |
| 75 | 71 | |
| 76 | -pub fn delete(name: &str, directory: &Path) -> Result<(), Error> { | |
| 72 | +pub fn delete(name: &str, directory: &Path) -> Result<(), ServerError> { | |
| 77 | 73 | std::fs::remove_file(path_of(directory, name)?)?; |
| 78 | 74 | |
| 79 | 75 | Ok(()) |
| 80 | 76 | } |
| 81 | 77 | |
| 82 | -async fn locate( | |
| 78 | +pub async fn locate( | |
| 83 | 79 | user: Option<&User>, |
| 84 | - request: Request, | |
| 80 | + name: &str, | |
| 85 | 81 | db: &DB, |
| 86 | 82 | directory: &Path, |
| 87 | -) -> Result<(PathBuf, u64), Error> { | |
| 83 | +) -> Result<(PathBuf, u64), ServerError> { | |
| 88 | 84 | let user = user.ok_or(CommonError::Unauthenticated)?; |
| 89 | - let Request::DownloadBackup { name } = request else { | |
| 90 | - return Err(CommonError::Forbidden.into()); | |
| 91 | - }; | |
| 92 | 85 | let conn = database::connect(db).await?; |
| 93 | 86 | let me = user::read(&user.id, &conn).await?; |
| 94 | 87 | ensure(permission::is_builder(me.role))?; |
| 95 | 88 | |
| 96 | - let path = path_of(directory, &name)?; | |
| 89 | + let path = path_of(directory, name)?; | |
| 97 | 90 | let length = tokio::fs::metadata(&path) |
| 98 | 91 | .await |
| 99 | 92 | .map_err(|_| CommonError::NotFound)? |
| @@ -102,26 +95,12 @@ async fn locate( | ||
| 102 | 95 | Some(&me.id), |
| 103 | 96 | None, |
| 104 | 97 | None, |
| 105 | - &AdminAction::BackupDownloaded { name }, | |
| 98 | + &AdminAction::BackupDownloaded { | |
| 99 | + name: name.to_string(), | |
| 100 | + }, | |
| 106 | 101 | &conn, |
| 107 | 102 | ) |
| 108 | 103 | .await?; |
| 109 | 104 | |
| 110 | 105 | Ok((path, length)) |
| 111 | 106 | } |
| 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::{ | ||
| 13 | 13 | }; |
| 14 | 14 | use tracing::{error, info, warn}; |
| 15 | 15 | |
| 16 | -use crate::error::Error; | |
| 16 | +use crate::error::ServerError; | |
| 17 | 17 | |
| 18 | 18 | const RELOAD_INTERVAL: Duration = Duration::from_secs(600); |
| 19 | 19 | const SUBJECT_ALT_NAME: &str = "localhost"; |
| @@ -34,11 +34,11 @@ impl ResolvesServerCert for Reloader { | ||
| 34 | 34 | } |
| 35 | 35 | } |
| 36 | 36 | |
| 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}")) | |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | -fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { | |
| 41 | +fn generate(certificate_path: &str, key_path: &str) -> Result<(), ServerError> { | |
| 42 | 42 | let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) |
| 43 | 43 | .map_err(certificate_error)?; |
| 44 | 44 | |
| @@ -56,7 +56,7 @@ fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { | ||
| 56 | 56 | Ok(()) |
| 57 | 57 | } |
| 58 | 58 | |
| 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> { | |
| 60 | 60 | let chain = CertificateDer::pem_file_iter(certificate_path) |
| 61 | 61 | .map_err(certificate_error)? |
| 62 | 62 | .collect::<Result<Vec<_>, _>>() |
| @@ -101,7 +101,7 @@ async fn watch(reloader: Arc<Reloader>, certificate_path: String, key_path: Stri | ||
| 101 | 101 | } |
| 102 | 102 | } |
| 103 | 103 | |
| 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> { | |
| 105 | 105 | if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() { |
| 106 | 106 | generate(certificate_path, key_path)?; |
| 107 | 107 | 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 | ||
| 115 | 115 | .with_no_client_auth() |
| 116 | 116 | .with_cert_resolver(reloader.clone()); |
| 117 | 117 | tls.max_early_data_size = u32::MAX; |
| 118 | + tls.alpn_protocols = vec![common::transport::alpn()]; | |
| 118 | 119 | |
| 119 | 120 | let crypto = |
| 120 | 121 | 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 | ||
| 125 | 126 | key_path.to_string(), |
| 126 | 127 | )); |
| 127 | 128 | |
| 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) | |
| 129 | 133 | } |
crates/server/src/community.rsmodified+24 -21
| @@ -6,7 +6,7 @@ use common::{ | ||
| 6 | 6 | }; |
| 7 | 7 | use turso::{Connection, Row}; |
| 8 | 8 | |
| 9 | -use crate::{database::new_id, error::Error, user}; | |
| 9 | +use crate::{database::new_id, error::ServerError, user}; | |
| 10 | 10 | |
| 11 | 11 | string_enum! { |
| 12 | 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -19,7 +19,7 @@ string_enum! { | ||
| 19 | 19 | |
| 20 | 20 | type Raw = (String, String, Kind, Option<String>, bool); |
| 21 | 21 | |
| 22 | -fn raw_of(row: &Row) -> Result<Raw, Error> { | |
| 22 | +fn raw_of(row: &Row) -> Result<Raw, ServerError> { | |
| 23 | 23 | let text: String = row.get(2)?; |
| 24 | 24 | let kind = Kind::parse(&text).ok_or(CommonError::Server)?; |
| 25 | 25 | |
| @@ -32,7 +32,7 @@ fn raw_of(row: &Row) -> Result<Raw, Error> { | ||
| 32 | 32 | )) |
| 33 | 33 | } |
| 34 | 34 | |
| 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> { | |
| 36 | 36 | let mut rows = conn |
| 37 | 37 | .query( |
| 38 | 38 | &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( | ||
| 48 | 48 | community_id: &str, |
| 49 | 49 | viewer_id: &str, |
| 50 | 50 | conn: &Connection, |
| 51 | -) -> Result<Option<String>, Error> { | |
| 51 | +) -> Result<Option<String>, ServerError> { | |
| 52 | 52 | let mut rows = conn |
| 53 | 53 | .query( |
| 54 | 54 | "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( | ||
| 64 | 64 | Ok(Some(format!("{first} & {second}"))) |
| 65 | 65 | } |
| 66 | 66 | |
| 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> { | |
| 68 | 68 | let (id, mut name, kind, avatar_id, voice_enabled) = raw; |
| 69 | 69 | let kind = match kind { |
| 70 | 70 | Kind::Group => CommunityKind::Group, |
| @@ -88,7 +88,7 @@ async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community | ||
| 88 | 88 | }) |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | -pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> { | |
| 91 | +pub async fn create(name: &str, conn: &Connection) -> Result<Community, ServerError> { | |
| 92 | 92 | validate_community_name(name)?; |
| 93 | 93 | |
| 94 | 94 | let id = new_id(); |
| @@ -107,7 +107,7 @@ pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> { | ||
| 107 | 107 | }) |
| 108 | 108 | } |
| 109 | 109 | |
| 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> { | |
| 111 | 111 | let id = new_id(); |
| 112 | 112 | conn.execute( |
| 113 | 113 | "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", |
| @@ -122,7 +122,7 @@ pub async fn read( | ||
| 122 | 122 | community_id: &str, |
| 123 | 123 | viewer_id: &str, |
| 124 | 124 | conn: &Connection, |
| 125 | -) -> Result<Community, Error> { | |
| 125 | +) -> Result<Community, ServerError> { | |
| 126 | 126 | let raw = { |
| 127 | 127 | let mut rows = conn |
| 128 | 128 | .query( |
| @@ -138,7 +138,10 @@ pub async fn read( | ||
| 138 | 138 | build(raw, viewer_id, conn).await |
| 139 | 139 | } |
| 140 | 140 | |
| 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> { | |
| 142 | 145 | let raws = { |
| 143 | 146 | let mut rows = conn |
| 144 | 147 | .query( |
| @@ -163,7 +166,7 @@ pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Comm | ||
| 163 | 166 | Ok(communities) |
| 164 | 167 | } |
| 165 | 168 | |
| 166 | -pub async fn groups(conn: &Connection) -> Result<Vec<Community>, Error> { | |
| 169 | +pub async fn groups(conn: &Connection) -> Result<Vec<Community>, ServerError> { | |
| 167 | 170 | let mut rows = conn |
| 168 | 171 | .query( |
| 169 | 172 | "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( | ||
| 191 | 194 | name: &str, |
| 192 | 195 | viewer_id: &str, |
| 193 | 196 | conn: &Connection, |
| 194 | -) -> Result<Community, Error> { | |
| 197 | +) -> Result<Community, ServerError> { | |
| 195 | 198 | validate_community_name(name)?; |
| 196 | 199 | |
| 197 | 200 | conn.execute( |
| @@ -208,7 +211,7 @@ pub async fn set_avatar( | ||
| 208 | 211 | image: Option<&[u8]>, |
| 209 | 212 | viewer_id: &str, |
| 210 | 213 | conn: &mut Connection, |
| 211 | -) -> Result<Community, Error> { | |
| 214 | +) -> Result<Community, ServerError> { | |
| 212 | 215 | if let Some(bytes) = image { |
| 213 | 216 | user::check_avatar(bytes)?; |
| 214 | 217 | } |
| @@ -242,7 +245,7 @@ pub async fn delete( | ||
| 242 | 245 | community_id: &str, |
| 243 | 246 | viewer_id: &str, |
| 244 | 247 | conn: &Connection, |
| 245 | -) -> Result<Community, Error> { | |
| 248 | +) -> Result<Community, ServerError> { | |
| 246 | 249 | let deleted = read(community_id, viewer_id, conn).await?; |
| 247 | 250 | conn.execute("DELETE FROM community WHERE id = ?1", (community_id,)) |
| 248 | 251 | .await?; |
| @@ -250,7 +253,7 @@ pub async fn delete( | ||
| 250 | 253 | Ok(deleted) |
| 251 | 254 | } |
| 252 | 255 | |
| 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> { | |
| 254 | 257 | let mut rows = conn |
| 255 | 258 | .query("SELECT kind FROM community WHERE id = ?1", (community_id,)) |
| 256 | 259 | .await?; |
| @@ -260,11 +263,11 @@ pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error> | ||
| 260 | 263 | Ok(Kind::parse(&text).ok_or(CommonError::Server)?) |
| 261 | 264 | } |
| 262 | 265 | |
| 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> { | |
| 264 | 267 | Ok(kind(community_id, conn).await? == Kind::Direct) |
| 265 | 268 | } |
| 266 | 269 | |
| 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> { | |
| 268 | 271 | Ok(kind(community_id, conn).await? != Kind::Group) |
| 269 | 272 | } |
| 270 | 273 | |
| @@ -272,7 +275,7 @@ pub async fn set_voice_enabled( | ||
| 272 | 275 | community_id: &str, |
| 273 | 276 | enabled: bool, |
| 274 | 277 | conn: &Connection, |
| 275 | -) -> Result<(), Error> { | |
| 278 | +) -> Result<(), ServerError> { | |
| 276 | 279 | conn.execute( |
| 277 | 280 | "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", |
| 278 | 281 | (community_id, i64::from(enabled)), |
| @@ -282,7 +285,7 @@ pub async fn set_voice_enabled( | ||
| 282 | 285 | Ok(()) |
| 283 | 286 | } |
| 284 | 287 | |
| 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> { | |
| 286 | 289 | let mut rows = conn |
| 287 | 290 | .query( |
| 288 | 291 | "SELECT voice_enabled FROM community WHERE id = ?1", |
| @@ -294,7 +297,7 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool | ||
| 294 | 297 | user::bool_at(&row, 0) |
| 295 | 298 | } |
| 296 | 299 | |
| 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> { | |
| 298 | 301 | let prefix = match kind(community_id, conn).await? { |
| 299 | 302 | Kind::Group => { |
| 300 | 303 | let mut rows = conn |
| @@ -325,7 +328,7 @@ pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Erro | ||
| 325 | 328 | mod tests { |
| 326 | 329 | use common::error::Error as CommonError; |
| 327 | 330 | |
| 328 | - use crate::{community, database, error::Error, test, user}; | |
| 331 | + use crate::{community, database, error::ServerError, test, user}; | |
| 329 | 332 | |
| 330 | 333 | #[tokio::test] |
| 331 | 334 | async fn create() { |
| @@ -382,7 +385,7 @@ mod tests { | ||
| 382 | 385 | |
| 383 | 386 | assert!(matches!( |
| 384 | 387 | updated_community, |
| 385 | - Err(Error::Common(CommonError::NotFound)) | |
| 388 | + Err(ServerError::Wire(CommonError::NotFound)) | |
| 386 | 389 | )); |
| 387 | 390 | } |
| 388 | 391 |
crates/server/src/database.rsmodified+9 -9
| @@ -3,7 +3,7 @@ use std::time::Duration; | ||
| 3 | 3 | use common::error::Error as CommonError; |
| 4 | 4 | use turso::Connection; |
| 5 | 5 | |
| 6 | -use crate::error::Error; | |
| 6 | +use crate::error::ServerError; | |
| 7 | 7 | |
| 8 | 8 | pub type DB = turso::Database; |
| 9 | 9 | |
| @@ -292,14 +292,14 @@ const MIGRATIONS: &[&str] = &[ | ||
| 292 | 292 | "ALTER TABLE snippet_message ADD COLUMN poll BLOB;", |
| 293 | 293 | ]; |
| 294 | 294 | |
| 295 | -pub async fn open(path: &str) -> Result<DB, Error> { | |
| 295 | +pub async fn open(path: &str) -> Result<DB, ServerError> { | |
| 296 | 296 | let db = turso::Builder::new_local(path).build().await?; |
| 297 | 297 | migrate(&db).await?; |
| 298 | 298 | |
| 299 | 299 | Ok(db) |
| 300 | 300 | } |
| 301 | 301 | |
| 302 | -pub async fn connect(db: &DB) -> Result<Connection, Error> { | |
| 302 | +pub async fn connect(db: &DB) -> Result<Connection, ServerError> { | |
| 303 | 303 | let conn = db.connect()?; |
| 304 | 304 | conn.busy_timeout(BUSY_TIMEOUT)?; |
| 305 | 305 | conn.execute_batch("PRAGMA foreign_keys = ON;").await?; |
| @@ -311,7 +311,7 @@ pub async fn scalar_i64( | ||
| 311 | 311 | conn: &Connection, |
| 312 | 312 | sql: &str, |
| 313 | 313 | params: impl turso::IntoParams, |
| 314 | -) -> Result<i64, Error> { | |
| 314 | +) -> Result<i64, ServerError> { | |
| 315 | 315 | let mut rows = conn.query(sql, params).await?; |
| 316 | 316 | let row = rows |
| 317 | 317 | .next() |
| @@ -325,7 +325,7 @@ pub async fn exists( | ||
| 325 | 325 | conn: &Connection, |
| 326 | 326 | sql: &str, |
| 327 | 327 | params: impl turso::IntoParams, |
| 328 | -) -> Result<bool, Error> { | |
| 328 | +) -> Result<bool, ServerError> { | |
| 329 | 329 | Ok(scalar_i64(conn, sql, params).await? != 0) |
| 330 | 330 | } |
| 331 | 331 | |
| @@ -333,7 +333,7 @@ pub async fn ids( | ||
| 333 | 333 | conn: &Connection, |
| 334 | 334 | sql: &str, |
| 335 | 335 | params: impl turso::IntoParams, |
| 336 | -) -> Result<Vec<String>, Error> { | |
| 336 | +) -> Result<Vec<String>, ServerError> { | |
| 337 | 337 | let mut rows = conn.query(sql, params).await?; |
| 338 | 338 | |
| 339 | 339 | let mut ids = Vec::new(); |
| @@ -344,7 +344,7 @@ pub async fn ids( | ||
| 344 | 344 | Ok(ids) |
| 345 | 345 | } |
| 346 | 346 | |
| 347 | -pub fn expect_one(affected: u64) -> Result<(), Error> { | |
| 347 | +pub fn expect_one(affected: u64) -> Result<(), ServerError> { | |
| 348 | 348 | if affected != 1 { |
| 349 | 349 | return Err(CommonError::NotFound.into()); |
| 350 | 350 | } |
| @@ -352,7 +352,7 @@ pub fn expect_one(affected: u64) -> Result<(), Error> { | ||
| 352 | 352 | Ok(()) |
| 353 | 353 | } |
| 354 | 354 | |
| 355 | -async fn migrate(db: &DB) -> Result<(), Error> { | |
| 355 | +async fn migrate(db: &DB) -> Result<(), ServerError> { | |
| 356 | 356 | let mut conn = connect(db).await?; |
| 357 | 357 | let applied = user_version(&conn).await?; |
| 358 | 358 | |
| @@ -366,7 +366,7 @@ async fn migrate(db: &DB) -> Result<(), Error> { | ||
| 366 | 366 | Ok(()) |
| 367 | 367 | } |
| 368 | 368 | |
| 369 | -async fn user_version(conn: &Connection) -> Result<usize, Error> { | |
| 369 | +async fn user_version(conn: &Connection) -> Result<usize, ServerError> { | |
| 370 | 370 | Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) |
| 371 | 371 | } |
| 372 | 372 |
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 @@ | ||
| 1 | 1 | use common::model::{Community, Rank}; |
| 2 | 2 | use turso::Connection; |
| 3 | 3 | |
| 4 | -use crate::{community, error::Error, request::ensure, user, user_community}; | |
| 4 | +use crate::{community, error::ServerError, request::ensure, user, user_community}; | |
| 5 | 5 | |
| 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> { | |
| 7 | 11 | let mut rows = conn |
| 8 | 12 | .query( |
| 9 | 13 | "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", |
| @@ -19,7 +23,7 @@ pub enum Opening { | ||
| 19 | 23 | Existing(Community), |
| 20 | 24 | } |
| 21 | 25 | |
| 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> { | |
| 23 | 27 | ensure(me != other)?; |
| 24 | 28 | user::read(other, conn).await?; |
| 25 | 29 |
crates/server/src/error.rsmodified+34 -22
| @@ -1,22 +1,19 @@ | ||
| 1 | -use common::error_from; | |
| 2 | 1 | use tracing::error; |
| 3 | 2 | |
| 4 | 3 | #[derive(Debug, thiserror::Error)] |
| 5 | -pub enum Error { | |
| 4 | +pub enum ServerError { | |
| 6 | 5 | #[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), | |
| 12 | 9 | } |
| 13 | 10 | |
| 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 { | |
| 16 | 13 | match value { |
| 17 | - Error::Common(error) => error, | |
| 18 | - error => { | |
| 19 | - error!("{error}"); | |
| 14 | + ServerError::Wire(error) => error, | |
| 15 | + ServerError::Internal(message) => { | |
| 16 | + error!("{message}"); | |
| 20 | 17 | |
| 21 | 18 | common::error::Error::Server |
| 22 | 19 | } |
| @@ -24,13 +21,28 @@ impl From<Error> for common::error::Error { | ||
| 24 | 21 | } |
| 25 | 22 | } |
| 26 | 23 | |
| 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::{ | ||
| 4 | 4 | }; |
| 5 | 5 | use turso::Connection; |
| 6 | 6 | |
| 7 | -use crate::{database, error::Error, request::ensure_with, user}; | |
| 7 | +use crate::{database, error::ServerError, request::ensure_with, user}; | |
| 8 | 8 | |
| 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> { | |
| 10 | 10 | let mut rows = conn.query(sql, (user_id,)).await?; |
| 11 | 11 | |
| 12 | 12 | let mut users = Vec::new(); |
| @@ -22,11 +22,11 @@ async fn pair_exists( | ||
| 22 | 22 | first: &str, |
| 23 | 23 | second: &str, |
| 24 | 24 | conn: &Connection, |
| 25 | -) -> Result<bool, Error> { | |
| 25 | +) -> Result<bool, ServerError> { | |
| 26 | 26 | database::exists(conn, sql, (first, second)).await |
| 27 | 27 | } |
| 28 | 28 | |
| 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> { | |
| 30 | 30 | pair_exists( |
| 31 | 31 | "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2", |
| 32 | 32 | me, |
| @@ -36,7 +36,7 @@ async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Err | ||
| 36 | 36 | .await |
| 37 | 37 | } |
| 38 | 38 | |
| 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> { | |
| 40 | 40 | pair_exists( |
| 41 | 41 | "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2", |
| 42 | 42 | from, |
| @@ -46,7 +46,7 @@ async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, E | ||
| 46 | 46 | .await |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | -async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> { | |
| 49 | +async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 50 | 50 | conn.execute( |
| 51 | 51 | "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2", |
| 52 | 52 | (other, me), |
| @@ -66,7 +66,7 @@ async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> | ||
| 66 | 66 | Ok(()) |
| 67 | 67 | } |
| 68 | 68 | |
| 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> { | |
| 70 | 70 | Ok(Friends { |
| 71 | 71 | friends: users( |
| 72 | 72 | &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> { | ||
| 89 | 89 | }) |
| 90 | 90 | } |
| 91 | 91 | |
| 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> { | |
| 93 | 93 | ensure_with(me != other, CommonError::Forbidden)?; |
| 94 | 94 | user::read(other, conn).await?; |
| 95 | 95 | |
| @@ -112,7 +112,7 @@ pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Err | ||
| 112 | 112 | Ok(()) |
| 113 | 113 | } |
| 114 | 114 | |
| 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> { | |
| 116 | 116 | let tx = conn.transaction().await?; |
| 117 | 117 | if !is_requested(other, me, &tx).await? { |
| 118 | 118 | return Err(CommonError::NotFound.into()); |
| @@ -123,7 +123,7 @@ pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), | ||
| 123 | 123 | Ok(()) |
| 124 | 124 | } |
| 125 | 125 | |
| 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> { | |
| 127 | 127 | let tx = conn.transaction().await?; |
| 128 | 128 | tx.execute( |
| 129 | 129 | "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 @@ | ||
| 1 | 1 | use common::{error::Error as CommonError, model::Invitation}; |
| 2 | 2 | use turso::Connection; |
| 3 | 3 | |
| 4 | -use crate::{community, database, error::Error, user}; | |
| 4 | +use crate::{community, database, error::ServerError, user}; | |
| 5 | 5 | |
| 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> { | |
| 7 | 7 | let pairs = { |
| 8 | 8 | let mut rows = conn |
| 9 | 9 | .query( |
| @@ -31,7 +31,11 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Err | ||
| 31 | 31 | Ok(invitations) |
| 32 | 32 | } |
| 33 | 33 | |
| 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> { | |
| 35 | 39 | database::exists( |
| 36 | 40 | conn, |
| 37 | 41 | "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", |
| @@ -45,7 +49,7 @@ pub async fn insert( | ||
| 45 | 49 | user_id: &str, |
| 46 | 50 | inviter_id: &str, |
| 47 | 51 | conn: &Connection, |
| 48 | -) -> Result<(), Error> { | |
| 52 | +) -> Result<(), ServerError> { | |
| 49 | 53 | conn.execute( |
| 50 | 54 | "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", |
| 51 | 55 | (community_id, user_id, inviter_id), |
| @@ -55,7 +59,7 @@ pub async fn insert( | ||
| 55 | 59 | Ok(()) |
| 56 | 60 | } |
| 57 | 61 | |
| 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> { | |
| 59 | 63 | let mut rows = conn |
| 60 | 64 | .query( |
| 61 | 65 | "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::{ | ||
| 5 | 5 | }; |
| 6 | 6 | use turso::Connection; |
| 7 | 7 | |
| 8 | -use crate::{authentication, error::Error}; | |
| 8 | +use crate::{authentication, error::ServerError}; | |
| 9 | 9 | |
| 10 | 10 | const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| 11 | 11 | const CODE_LENGTH: usize = 8; |
| 12 | 12 | |
| 13 | -fn generate() -> Result<String, Error> { | |
| 13 | +fn generate() -> Result<String, ServerError> { | |
| 14 | 14 | let bytes = authentication::random_bytes::<CODE_LENGTH>()?; |
| 15 | 15 | |
| 16 | 16 | Ok(bytes |
| @@ -24,7 +24,7 @@ pub async fn create( | ||
| 24 | 24 | hours: Option<u32>, |
| 25 | 25 | created_by: &User, |
| 26 | 26 | conn: &Connection, |
| 27 | -) -> Result<InviteCode, Error> { | |
| 27 | +) -> Result<InviteCode, ServerError> { | |
| 28 | 28 | let code = generate()?; |
| 29 | 29 | let expires_at = hours.map(|hours| time::now_ms() + u64::from(hours) * HOUR_MILLIS); |
| 30 | 30 | conn.execute( |
| @@ -45,7 +45,7 @@ pub async fn create( | ||
| 45 | 45 | }) |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | -pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> { | |
| 48 | +pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, ServerError> { | |
| 49 | 49 | let mut rows = conn |
| 50 | 50 | .query("SELECT code, uses_left, expires_at FROM invite_code", ()) |
| 51 | 51 | .await?; |
| @@ -64,7 +64,7 @@ pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> { | ||
| 64 | 64 | Ok(codes) |
| 65 | 65 | } |
| 66 | 66 | |
| 67 | -pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> { | |
| 67 | +pub async fn delete(code: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 68 | 68 | let mut rows = conn |
| 69 | 69 | .query( |
| 70 | 70 | "DELETE FROM invite_code WHERE code = ?1 RETURNING code", |
| @@ -76,7 +76,7 @@ pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> { | ||
| 76 | 76 | Ok(()) |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | -pub async fn consume(code: &str, conn: &Connection) -> Result<(), Error> { | |
| 79 | +pub async fn consume(code: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 80 | 80 | let mut rows = conn |
| 81 | 81 | .query( |
| 82 | 82 | "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; | ||
| 5 | 5 | pub mod certificate; |
| 6 | 6 | pub mod community; |
| 7 | 7 | pub mod database; |
| 8 | +pub mod datagram; | |
| 8 | 9 | pub mod direct; |
| 9 | 10 | pub mod error; |
| 10 | 11 | pub mod friend; |
| @@ -34,7 +35,7 @@ use std::path::{Path, PathBuf}; | ||
| 34 | 35 | |
| 35 | 36 | use common::{config::Config, error::Error as CommonError, model::Role}; |
| 36 | 37 | |
| 37 | -use crate::error::Error; | |
| 38 | +use crate::error::ServerError; | |
| 38 | 39 | |
| 39 | 40 | const SERVER_CONFIG_FILE_PATH: &str = concat!( |
| 40 | 41 | env!("CARGO_MANIFEST_DIR"), |
| @@ -54,7 +55,7 @@ pub struct ServerConfig { | ||
| 54 | 55 | pub key_path: String, |
| 55 | 56 | } |
| 56 | 57 | |
| 57 | -fn load_config() -> Result<ServerConfig, Error> { | |
| 58 | +fn load_config() -> Result<ServerConfig, ServerError> { | |
| 58 | 59 | let content = std::fs::read_to_string(config_path())?; |
| 59 | 60 | let config = Config::parse(&content)?; |
| 60 | 61 | |
| @@ -66,7 +67,7 @@ fn load_config() -> Result<ServerConfig, Error> { | ||
| 66 | 67 | }) |
| 67 | 68 | } |
| 68 | 69 | |
| 69 | -fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> { | |
| 70 | +fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, ServerError> { | |
| 70 | 71 | let directory = Path::new(database_path) |
| 71 | 72 | .parent() |
| 72 | 73 | .unwrap_or_else(|| Path::new("")) |
| @@ -76,7 +77,7 @@ fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> | ||
| 76 | 77 | Ok(directory) |
| 77 | 78 | } |
| 78 | 79 | |
| 79 | -pub async fn showtime() -> Result<(), Error> { | |
| 80 | +pub async fn showtime() -> Result<(), ServerError> { | |
| 80 | 81 | let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); |
| 81 | 82 | |
| 82 | 83 | let config = load_config()?; |
| @@ -98,7 +99,7 @@ pub async fn showtime() -> Result<(), Error> { | ||
| 98 | 99 | .await |
| 99 | 100 | } |
| 100 | 101 | |
| 101 | -pub async fn set_role(username: &str, role: Role) -> Result<(), Error> { | |
| 102 | +pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { | |
| 102 | 103 | let config = load_config()?; |
| 103 | 104 | let database = database::open(&config.database_path).await?; |
| 104 | 105 | let conn = database::connect(&database).await?; |
crates/server/src/log.rsmodified+3 -3
| @@ -4,7 +4,7 @@ use common::{ | ||
| 4 | 4 | }; |
| 5 | 5 | use turso::Connection; |
| 6 | 6 | |
| 7 | -use crate::{database::new_id, error::Error, user}; | |
| 7 | +use crate::{database::new_id, error::ServerError, user}; | |
| 8 | 8 | |
| 9 | 9 | common::string_enum! { |
| 10 | 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -67,7 +67,7 @@ pub async fn record( | ||
| 67 | 67 | target_id: Option<&str>, |
| 68 | 68 | action: &LogAction, |
| 69 | 69 | conn: &Connection, |
| 70 | -) -> Result<(), Error> { | |
| 70 | +) -> Result<(), ServerError> { | |
| 71 | 71 | let id = new_id(); |
| 72 | 72 | let (action, detail) = parts(action); |
| 73 | 73 | conn.execute( |
| @@ -79,7 +79,7 @@ pub async fn record( | ||
| 79 | 79 | Ok(()) |
| 80 | 80 | } |
| 81 | 81 | |
| 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> { | |
| 83 | 83 | let mut rows = conn |
| 84 | 84 | .query( |
| 85 | 85 | &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; | ||
| 2 | 2 | use server::{set_role, showtime}; |
| 3 | 3 | |
| 4 | 4 | #[tokio::main] |
| 5 | -async fn main() -> Result<(), server::error::Error> { | |
| 5 | +async fn main() -> Result<(), server::error::ServerError> { | |
| 6 | 6 | tracing_subscriber::fmt() |
| 7 | 7 | .with_max_level(tracing::Level::INFO) |
| 8 | 8 | .init(); |
crates/server/src/message.rsmodified+41 -32
| @@ -2,7 +2,7 @@ use std::{collections::HashMap, path::Path}; | ||
| 2 | 2 | |
| 3 | 3 | use common::{ |
| 4 | 4 | constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, |
| 5 | - error::{Error as CommonError, Field, InvalidInput}, | |
| 5 | + error::{Error as CommonError, Field, Problem}, | |
| 6 | 6 | model::{ |
| 7 | 7 | CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, |
| 8 | 8 | User, |
| @@ -11,13 +11,13 @@ use common::{ | ||
| 11 | 11 | }; |
| 12 | 12 | use turso::{Connection, Row}; |
| 13 | 13 | |
| 14 | -use crate::{attachment, community, database, database::new_id, error::Error, user}; | |
| 14 | +use crate::{attachment, community, database, database::new_id, error::ServerError, user}; | |
| 15 | 15 | |
| 16 | 16 | const SEARCH_LIMIT: usize = 200; |
| 17 | 17 | |
| 18 | 18 | 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"; |
| 19 | 19 | |
| 20 | -fn from_row(row: &Row) -> Result<Message, Error> { | |
| 20 | +fn from_row(row: &Row) -> Result<Message, ServerError> { | |
| 21 | 21 | let edited: i64 = row.get(4)?; |
| 22 | 22 | let call_seconds: i64 = row.get(10)?; |
| 23 | 23 | let pinned: i64 = row.get(11)?; |
| @@ -64,7 +64,7 @@ fn placeholders(count: usize) -> String { | ||
| 64 | 64 | async fn reactions_of( |
| 65 | 65 | message_ids: &[String], |
| 66 | 66 | conn: &Connection, |
| 67 | -) -> Result<HashMap<String, Vec<Reaction>>, Error> { | |
| 67 | +) -> Result<HashMap<String, Vec<Reaction>>, ServerError> { | |
| 68 | 68 | let mut reactions: HashMap<String, Vec<Reaction>> = HashMap::new(); |
| 69 | 69 | if message_ids.is_empty() { |
| 70 | 70 | return Ok(reactions); |
| @@ -103,7 +103,7 @@ async fn reactions_of( | ||
| 103 | 103 | async fn polls_of( |
| 104 | 104 | message_ids: &[String], |
| 105 | 105 | conn: &Connection, |
| 106 | -) -> Result<HashMap<String, Poll>, Error> { | |
| 106 | +) -> Result<HashMap<String, Poll>, ServerError> { | |
| 107 | 107 | let mut polls: HashMap<String, Poll> = HashMap::new(); |
| 108 | 108 | if message_ids.is_empty() { |
| 109 | 109 | return Ok(polls); |
| @@ -174,7 +174,7 @@ async fn polls_of( | ||
| 174 | 174 | Ok(polls) |
| 175 | 175 | } |
| 176 | 176 | |
| 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> { | |
| 178 | 178 | let mut rows = conn |
| 179 | 179 | .query( |
| 180 | 180 | "SELECT origin FROM snippet WHERE message_id = ?1", |
| @@ -222,7 +222,7 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippe | ||
| 222 | 222 | Ok(Some(Snippet { origin, messages })) |
| 223 | 223 | } |
| 224 | 224 | |
| 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> { | |
| 226 | 226 | let ids: Vec<String> = messages.iter().map(|message| message.id.clone()).collect(); |
| 227 | 227 | let mut reactions = reactions_of(&ids, conn).await?; |
| 228 | 228 | let mut polls = polls_of(&ids, conn).await?; |
| @@ -245,7 +245,7 @@ async fn insert( | ||
| 245 | 245 | body: &str, |
| 246 | 246 | reply_to: Option<&str>, |
| 247 | 247 | conn: &Connection, |
| 248 | -) -> Result<String, Error> { | |
| 248 | +) -> Result<String, ServerError> { | |
| 249 | 249 | let message_id = new_id(); |
| 250 | 250 | conn.execute( |
| 251 | 251 | "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( | ||
| 260 | 260 | message_id: &str, |
| 261 | 261 | community_id: &str, |
| 262 | 262 | conn: &Connection, |
| 263 | -) -> Result<(), Error> { | |
| 263 | +) -> Result<(), ServerError> { | |
| 264 | 264 | let mut rows = conn |
| 265 | 265 | .query( |
| 266 | 266 | "SELECT id FROM message WHERE id = ?1 AND community_id = ?2", |
| @@ -279,7 +279,7 @@ pub async fn create_call_log( | ||
| 279 | 279 | user_id: &str, |
| 280 | 280 | call: CallLog, |
| 281 | 281 | conn: &Connection, |
| 282 | -) -> Result<Message, Error> { | |
| 282 | +) -> Result<Message, ServerError> { | |
| 283 | 283 | let message_id = new_id(); |
| 284 | 284 | conn.execute( |
| 285 | 285 | "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( | ||
| 303 | 303 | attachments: &[String], |
| 304 | 304 | reply_to: Option<&str>, |
| 305 | 305 | conn: &Connection, |
| 306 | -) -> Result<Message, Error> { | |
| 306 | +) -> Result<Message, ServerError> { | |
| 307 | 307 | if let Some(reply_to) = reply_to { |
| 308 | 308 | ensure_in_community(reply_to, community_id, conn).await?; |
| 309 | 309 | } |
| @@ -314,7 +314,7 @@ pub async fn create( | ||
| 314 | 314 | read(&message_id, conn).await |
| 315 | 315 | } |
| 316 | 316 | |
| 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> { | |
| 318 | 318 | let mut rows = conn |
| 319 | 319 | .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,)) |
| 320 | 320 | .await?; |
| @@ -332,7 +332,7 @@ pub async fn read_page( | ||
| 332 | 332 | community_id: &str, |
| 333 | 333 | before: Option<&str>, |
| 334 | 334 | conn: &Connection, |
| 335 | -) -> Result<Vec<Message>, Error> { | |
| 335 | +) -> Result<Vec<Message>, ServerError> { | |
| 336 | 336 | let mut rows = conn |
| 337 | 337 | .query( |
| 338 | 338 | &format!( |
| @@ -359,7 +359,7 @@ pub async fn create_poll( | ||
| 359 | 359 | options: &[String], |
| 360 | 360 | multiple: bool, |
| 361 | 361 | conn: &Connection, |
| 362 | -) -> Result<Message, Error> { | |
| 362 | +) -> Result<Message, ServerError> { | |
| 363 | 363 | let message_id = insert(user_id, community_id, "", None, conn).await?; |
| 364 | 364 | conn.execute( |
| 365 | 365 | "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", |
| @@ -382,7 +382,7 @@ pub async fn vote( | ||
| 382 | 382 | user_id: &str, |
| 383 | 383 | positions: &[u32], |
| 384 | 384 | conn: &Connection, |
| 385 | -) -> Result<Message, Error> { | |
| 385 | +) -> Result<Message, ServerError> { | |
| 386 | 386 | conn.execute( |
| 387 | 387 | "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", |
| 388 | 388 | (message_id, user_id), |
| @@ -399,7 +399,7 @@ pub async fn vote( | ||
| 399 | 399 | read(message_id, conn).await |
| 400 | 400 | } |
| 401 | 401 | |
| 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> { | |
| 403 | 403 | let updated = conn |
| 404 | 404 | .execute( |
| 405 | 405 | "UPDATE poll SET closed = 1 WHERE message_id = ?1", |
| @@ -416,7 +416,7 @@ pub async fn react( | ||
| 416 | 416 | user_id: &str, |
| 417 | 417 | emoji: &str, |
| 418 | 418 | conn: &Connection, |
| 419 | -) -> Result<Message, Error> { | |
| 419 | +) -> Result<Message, ServerError> { | |
| 420 | 420 | let removed = conn |
| 421 | 421 | .execute( |
| 422 | 422 | "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", |
| @@ -434,7 +434,11 @@ pub async fn react( | ||
| 434 | 434 | read(message_id, conn).await |
| 435 | 435 | } |
| 436 | 436 | |
| 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> { | |
| 438 | 442 | conn.execute( |
| 439 | 443 | "UPDATE message SET pinned = ?2 WHERE id = ?1", |
| 440 | 444 | (message_id, pinned as i64), |
| @@ -444,7 +448,7 @@ pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result<Me | ||
| 444 | 448 | read(message_id, conn).await |
| 445 | 449 | } |
| 446 | 450 | |
| 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> { | |
| 448 | 452 | let mut rows = conn |
| 449 | 453 | .query( |
| 450 | 454 | &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 | ||
| 461 | 465 | hydrate(messages, conn).await |
| 462 | 466 | } |
| 463 | 467 | |
| 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> { | |
| 465 | 473 | let updated = conn |
| 466 | 474 | .execute( |
| 467 | 475 | "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 | ||
| 473 | 481 | read(message_id, conn).await |
| 474 | 482 | } |
| 475 | 483 | |
| 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> { | |
| 477 | 485 | let message = read(message_id, conn).await?; |
| 478 | 486 | conn.execute("DELETE FROM message WHERE id = ?1", (message_id,)) |
| 479 | 487 | .await?; |
| @@ -481,7 +489,7 @@ pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Erro | ||
| 481 | 489 | Ok(message) |
| 482 | 490 | } |
| 483 | 491 | |
| 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> { | |
| 485 | 493 | database::ids( |
| 486 | 494 | conn, |
| 487 | 495 | "SELECT id FROM message WHERE user_id = ?1", |
| @@ -497,7 +505,7 @@ pub async fn search( | ||
| 497 | 505 | after_ms: Option<u64>, |
| 498 | 506 | before_ms: Option<u64>, |
| 499 | 507 | conn: &Connection, |
| 500 | -) -> Result<Vec<MessageHit>, Error> { | |
| 508 | +) -> Result<Vec<MessageHit>, ServerError> { | |
| 501 | 509 | let (after, before) = time::range_bounds(after_ms, before_ms); |
| 502 | 510 | let mut rows = conn |
| 503 | 511 | .query( |
| @@ -534,7 +542,7 @@ pub async fn search( | ||
| 534 | 542 | Ok(hits) |
| 535 | 543 | } |
| 536 | 544 | |
| 537 | -async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, Error> { | |
| 545 | +async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, ServerError> { | |
| 538 | 546 | let Some(first) = sources.first() else { |
| 539 | 547 | return Ok(None); |
| 540 | 548 | }; |
| @@ -558,7 +566,7 @@ async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String> | ||
| 558 | 566 | }) |
| 559 | 567 | } |
| 560 | 568 | |
| 561 | -async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Error> { | |
| 569 | +async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, ServerError> { | |
| 562 | 570 | let author: User = user::read(&source.user_id, conn).await?; |
| 563 | 571 | |
| 564 | 572 | Ok(SnippetMessage { |
| @@ -580,7 +588,7 @@ async fn write_snippet( | ||
| 580 | 588 | entries: &[SnippetMessage], |
| 581 | 589 | directory: &Path, |
| 582 | 590 | conn: &Connection, |
| 583 | -) -> Result<(), Error> { | |
| 591 | +) -> Result<(), ServerError> { | |
| 584 | 592 | conn.execute( |
| 585 | 593 | "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", |
| 586 | 594 | (message_id, origin), |
| @@ -634,7 +642,7 @@ pub async fn forward( | ||
| 634 | 642 | mode: ForwardMode, |
| 635 | 643 | directory: &Path, |
| 636 | 644 | conn: &Connection, |
| 637 | -) -> Result<Vec<Message>, Error> { | |
| 645 | +) -> Result<Vec<Message>, ServerError> { | |
| 638 | 646 | if mode == ForwardMode::Copy { |
| 639 | 647 | let mut created = Vec::new(); |
| 640 | 648 | for source in sources { |
| @@ -679,9 +687,10 @@ pub async fn forward( | ||
| 679 | 687 | if entries.len() > MAXIMUM_FORWARD_MESSAGES { |
| 680 | 688 | return Err(CommonError::Invalid { |
| 681 | 689 | 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, | |
| 685 | 694 | }, |
| 686 | 695 | } |
| 687 | 696 | .into()); |
| @@ -707,7 +716,7 @@ pub async fn forward( | ||
| 707 | 716 | mod tests { |
| 708 | 717 | use common::error::Error as CommonError; |
| 709 | 718 | |
| 710 | - use crate::{community, database, error::Error, message, test, user}; | |
| 719 | + use crate::{community, database, error::ServerError, message, test, user}; | |
| 711 | 720 | |
| 712 | 721 | #[tokio::test] |
| 713 | 722 | async fn create() { |
| @@ -802,7 +811,7 @@ mod tests { | ||
| 802 | 811 | |
| 803 | 812 | assert!(matches!( |
| 804 | 813 | updated_message, |
| 805 | - Err(Error::Common(CommonError::NotFound)) | |
| 814 | + Err(ServerError::Wire(CommonError::NotFound)) | |
| 806 | 815 | )); |
| 807 | 816 | } |
| 808 | 817 |
crates/server/src/network.rsmodified+52 -62
| @@ -6,21 +6,21 @@ use std::{ | ||
| 6 | 6 | |
| 7 | 7 | use common::{ |
| 8 | 8 | event::Event as Push, |
| 9 | + frame::{self, DOWN_MAX, Sending, UP_MAX}, | |
| 9 | 10 | model::User, |
| 10 | - network::{ | |
| 11 | - REQUEST_MAX_READ_LENGTH, StreamKind, receive_decoded, receive_stream_kind, send_event, | |
| 12 | - send_response, | |
| 13 | - }, | |
| 11 | + open::Open, | |
| 14 | 12 | request::Request, |
| 13 | + transport::Close, | |
| 15 | 14 | }; |
| 16 | 15 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; |
| 17 | 16 | use tokio::{sync::mpsc, task::JoinHandle}; |
| 18 | 17 | use tracing::{info, warn}; |
| 19 | 18 | |
| 20 | 19 | use crate::{ |
| 21 | - attachment, authentication, backup, | |
| 20 | + attachment, authentication, | |
| 22 | 21 | database::{self, DB}, |
| 23 | - error::Error, | |
| 22 | + datagram, | |
| 23 | + error::ServerError, | |
| 24 | 24 | rate_limit::RateLimit, |
| 25 | 25 | request::{self, Broadcast}, |
| 26 | 26 | server_ban, |
| @@ -139,7 +139,7 @@ impl Presence { | ||
| 139 | 139 | self.user_ids().len() |
| 140 | 140 | } |
| 141 | 141 | |
| 142 | - fn close_where(&self, matches: impl Fn(&Signed) -> bool, reason: &[u8]) { | |
| 142 | + fn close_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { | |
| 143 | 143 | let connections: Vec<Connection> = self |
| 144 | 144 | .0 |
| 145 | 145 | .lock() |
| @@ -149,20 +149,20 @@ impl Presence { | ||
| 149 | 149 | .map(|signed| signed.connection.clone()) |
| 150 | 150 | .collect(); |
| 151 | 151 | for connection in connections { |
| 152 | - connection.close(0u32.into(), reason); | |
| 152 | + connection.close(close.code(), close.reason().as_bytes()); | |
| 153 | 153 | } |
| 154 | 154 | } |
| 155 | 155 | |
| 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); | |
| 158 | 158 | } |
| 159 | 159 | |
| 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); | |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | 164 | 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); | |
| 166 | 166 | } |
| 167 | 167 | } |
| 168 | 168 | |
| @@ -194,10 +194,10 @@ struct Session { | ||
| 194 | 194 | } |
| 195 | 195 | |
| 196 | 196 | #[derive(Clone)] |
| 197 | -struct Shared { | |
| 197 | +pub(crate) struct Shared { | |
| 198 | 198 | event_sender: mpsc::Sender<Event>, |
| 199 | 199 | db: DB, |
| 200 | - services: Services, | |
| 200 | + pub(crate) services: Services, | |
| 201 | 201 | directory: PathBuf, |
| 202 | 202 | backups: PathBuf, |
| 203 | 203 | } |
| @@ -208,7 +208,7 @@ pub async fn serve( | ||
| 208 | 208 | db: DB, |
| 209 | 209 | directory: PathBuf, |
| 210 | 210 | backups: PathBuf, |
| 211 | -) -> Result<(), Error> { | |
| 211 | +) -> Result<(), ServerError> { | |
| 212 | 212 | let endpoint = Endpoint::server(server_config, server_address.parse()?)?; |
| 213 | 213 | info!("listening on {server_address}"); |
| 214 | 214 | |
| @@ -236,11 +236,14 @@ async fn handle_connection(incoming: Incoming, shared: Shared) { | ||
| 236 | 236 | } |
| 237 | 237 | } |
| 238 | 238 | |
| 239 | -async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Error> { | |
| 239 | +async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { | |
| 240 | 240 | let ip = incoming.remote_address().ip().to_string(); |
| 241 | 241 | let conn = database::connect(&shared.db).await?; |
| 242 | 242 | 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()); | |
| 244 | 247 | return Ok(()); |
| 245 | 248 | } |
| 246 | 249 | let connection = incoming.await?; |
| @@ -256,7 +259,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | ||
| 256 | 259 | |
| 257 | 260 | let state = Arc::new(Mutex::new(State::Anonymous)); |
| 258 | 261 | |
| 259 | - tokio::spawn(relay_datagrams( | |
| 262 | + tokio::spawn(datagram::relay_datagrams( | |
| 260 | 263 | connection.clone(), |
| 261 | 264 | Arc::clone(&state), |
| 262 | 265 | shared.clone(), |
| @@ -297,31 +300,21 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | ||
| 297 | 300 | Ok(()) |
| 298 | 301 | } |
| 299 | 302 | |
| 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 | - | |
| 310 | 303 | async fn route( |
| 311 | 304 | connection: Connection, |
| 312 | 305 | state: Arc<Mutex<State>>, |
| 313 | 306 | (send_stream, mut receive_stream): (SendStream, RecvStream), |
| 314 | 307 | 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?; | |
| 317 | 311 | 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) => { | |
| 323 | 315 | attachment::upload( |
| 324 | 316 | user.as_ref(), |
| 317 | + upload, | |
| 325 | 318 | receive_stream, |
| 326 | 319 | send_stream, |
| 327 | 320 | &shared.db, |
| @@ -329,22 +322,13 @@ async fn route( | ||
| 329 | 322 | ) |
| 330 | 323 | .await |
| 331 | 324 | } |
| 332 | - StreamKind::Download => { | |
| 333 | - attachment::download( | |
| 325 | + Open::Fetch(blob) => { | |
| 326 | + attachment::fetch( | |
| 334 | 327 | user.as_ref(), |
| 335 | - receive_stream, | |
| 328 | + blob, | |
| 336 | 329 | send_stream, |
| 337 | 330 | &shared.db, |
| 338 | 331 | &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, | |
| 348 | 332 | &shared.backups, |
| 349 | 333 | ) |
| 350 | 334 | .await |
| @@ -355,11 +339,10 @@ async fn route( | ||
| 355 | 339 | async fn answer( |
| 356 | 340 | connection: Connection, |
| 357 | 341 | state: Arc<Mutex<State>>, |
| 358 | - (send_stream, mut receive_stream): (SendStream, RecvStream), | |
| 342 | + request: Request, | |
| 343 | + mut send_stream: Sending, | |
| 359 | 344 | shared: Shared, |
| 360 | -) -> Result<(), Error> { | |
| 361 | - let request: Request = receive_decoded(&mut receive_stream, REQUEST_MAX_READ_LENGTH).await?; | |
| 362 | - | |
| 345 | +) -> Result<(), ServerError> { | |
| 363 | 346 | let before = signed_in(&state); |
| 364 | 347 | let (response, broadcasts) = request::handle( |
| 365 | 348 | request, |
| @@ -377,7 +360,10 @@ async fn answer( | ||
| 377 | 360 | let connection_id = connection.stable_id(); |
| 378 | 361 | shared.services.visits.forget(connection_id); |
| 379 | 362 | 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), | |
| 381 | 367 | None => shared.services.presence.sign_out(connection_id), |
| 382 | 368 | } |
| 383 | 369 | let before_id = before.map(|(user_id, _)| user_id); |
| @@ -392,21 +378,22 @@ async fn answer( | ||
| 392 | 378 | if let Some(user_id) = &before_id { |
| 393 | 379 | broadcast_presence(&shared, user_id).await; |
| 394 | 380 | } |
| 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; | |
| 399 | 385 | } |
| 400 | 386 | } |
| 401 | 387 | |
| 402 | 388 | publish(&shared, broadcasts).await; |
| 403 | 389 | |
| 404 | - send_response(&response, send_stream).await?; | |
| 390 | + frame::write(&mut send_stream, &response, DOWN_MAX).await?; | |
| 391 | + send_stream.finish()?; | |
| 405 | 392 | |
| 406 | 393 | Ok(()) |
| 407 | 394 | } |
| 408 | 395 | |
| 409 | -async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | |
| 396 | +pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | |
| 410 | 397 | for broadcast in broadcasts { |
| 411 | 398 | let _ = shared |
| 412 | 399 | .event_sender |
| @@ -440,9 +427,10 @@ fn signed_in(state: &Mutex<State>) -> Option<(String, String)> { | ||
| 440 | 427 | } |
| 441 | 428 | } |
| 442 | 429 | |
| 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); | |
| 444 | 432 | 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 { | |
| 446 | 434 | warn!("session write: {error}"); |
| 447 | 435 | break; |
| 448 | 436 | } |
| @@ -505,7 +493,9 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) { | ||
| 505 | 493 | Err(error) => { |
| 506 | 494 | warn!("session dropped {user_id}: {error}"); |
| 507 | 495 | 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()); | |
| 509 | 499 | false |
| 510 | 500 | } |
| 511 | 501 | } |
crates/server/src/notes.rsmodified+3 -3
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | use common::model::{Community, Rank}; |
| 2 | 2 | use turso::Connection; |
| 3 | 3 | |
| 4 | -use crate::{community, error::Error, user_community}; | |
| 4 | +use crate::{community, error::ServerError, user_community}; | |
| 5 | 5 | |
| 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> { | |
| 7 | 7 | let mut rows = conn |
| 8 | 8 | .query( |
| 9 | 9 | "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> | ||
| 14 | 14 | Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) |
| 15 | 15 | } |
| 16 | 16 | |
| 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> { | |
| 18 | 18 | let tx = conn.transaction().await?; |
| 19 | 19 | let community_id = match find(me, &tx).await? { |
| 20 | 20 | Some(community_id) => community_id, |
crates/server/src/overview.rsmodified+3 -3
| @@ -1,13 +1,13 @@ | ||
| 1 | 1 | use common::model::{Overview, Role}; |
| 2 | 2 | use turso::Connection; |
| 3 | 3 | |
| 4 | -use crate::{community::Kind, error::Error, network::Presence, voice::Voice}; | |
| 4 | +use crate::{community::Kind, error::ServerError, network::Presence, voice::Voice}; | |
| 5 | 5 | |
| 6 | 6 | pub async fn read( |
| 7 | 7 | presence: &Presence, |
| 8 | 8 | voice: &Voice, |
| 9 | 9 | conn: &Connection, |
| 10 | -) -> Result<Overview, Error> { | |
| 10 | +) -> Result<Overview, ServerError> { | |
| 11 | 11 | let mut rows = conn |
| 12 | 12 | .query( |
| 13 | 13 | "SELECT |
| @@ -24,7 +24,7 @@ pub async fn read( | ||
| 24 | 24 | .next() |
| 25 | 25 | .await? |
| 26 | 26 | .ok_or(turso::Error::QueryReturnedNoRows)?; |
| 27 | - let count = |index: usize| -> Result<u64, Error> { | |
| 27 | + let count = |index: usize| -> Result<u64, ServerError> { | |
| 28 | 28 | let value: i64 = row.get(index)?; |
| 29 | 29 | Ok(value as u64) |
| 30 | 30 | }; |
crates/server/src/report.rsmodified+8 -5
| @@ -7,7 +7,7 @@ use turso::Connection; | ||
| 7 | 7 | |
| 8 | 8 | use crate::{ |
| 9 | 9 | database::{self, new_id}, |
| 10 | - error::Error, | |
| 10 | + error::ServerError, | |
| 11 | 11 | user, |
| 12 | 12 | }; |
| 13 | 13 | |
| @@ -16,7 +16,7 @@ pub async fn is_open( | ||
| 16 | 16 | target_id: &str, |
| 17 | 17 | message_id: Option<&str>, |
| 18 | 18 | conn: &Connection, |
| 19 | -) -> Result<bool, Error> { | |
| 19 | +) -> Result<bool, ServerError> { | |
| 20 | 20 | database::exists( |
| 21 | 21 | conn, |
| 22 | 22 | "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( | ||
| 33 | 33 | body: Option<&str>, |
| 34 | 34 | reason: &str, |
| 35 | 35 | conn: &Connection, |
| 36 | -) -> Result<(), Error> { | |
| 36 | +) -> Result<(), ServerError> { | |
| 37 | 37 | conn.execute( |
| 38 | 38 | "INSERT INTO report (id, reporter_id, target_id, message_id, community_id, body, reason) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| 39 | 39 | (new_id(), reporter_id, target_id, message_id, community_id, body, reason), |
| @@ -43,7 +43,10 @@ pub async fn insert( | ||
| 43 | 43 | Ok(()) |
| 44 | 44 | } |
| 45 | 45 | |
| 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> { | |
| 47 | 50 | let mut rows = conn |
| 48 | 51 | .query( |
| 49 | 52 | &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( | ||
| 76 | 79 | status: ReportStatus, |
| 77 | 80 | handled_by: &str, |
| 78 | 81 | conn: &Connection, |
| 79 | -) -> Result<Option<String>, Error> { | |
| 82 | +) -> Result<Option<String>, ServerError> { | |
| 80 | 83 | let mut rows = conn |
| 81 | 84 | .query( |
| 82 | 85 | "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::{ | ||
| 16 | 16 | response::Response, |
| 17 | 17 | share::{Kind, Share}, |
| 18 | 18 | time::{self, MINUTE_MILLIS}, |
| 19 | + transport::Close, | |
| 19 | 20 | validate::{ |
| 20 | 21 | validate_avatar_size, validate_forward, validate_new_message, validate_poll, |
| 21 | 22 | validate_reaction, validate_reason, validate_server_settings, validate_vote, |
| @@ -27,7 +28,7 @@ use crate::{ | ||
| 27 | 28 | admin_log, attachment, authentication, backup, community, |
| 28 | 29 | database::{self, DB}, |
| 29 | 30 | direct, |
| 30 | - error::Error, | |
| 31 | + error::ServerError, | |
| 31 | 32 | friend, invitation, invite, log, message, |
| 32 | 33 | network::{self, Services, State}, |
| 33 | 34 | notes, overview, |
| @@ -53,10 +54,10 @@ pub async fn handle( | ||
| 53 | 54 | connection: Option<&quinn::Connection>, |
| 54 | 55 | directory: &Path, |
| 55 | 56 | backups: &Path, |
| 56 | -) -> Outcome { | |
| 57 | +) -> (Result<Response, CommonError>, Vec<Broadcast>) { | |
| 57 | 58 | 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()), | |
| 60 | 61 | } |
| 61 | 62 | } |
| 62 | 63 | |
| @@ -68,7 +69,7 @@ async fn dispatch( | ||
| 68 | 69 | connection: Option<&quinn::Connection>, |
| 69 | 70 | directory: &Path, |
| 70 | 71 | backups: &Path, |
| 71 | -) -> Result<Outcome, Error> { | |
| 72 | +) -> Result<Outcome, ServerError> { | |
| 72 | 73 | let Services { |
| 73 | 74 | voice, |
| 74 | 75 | share, |
| @@ -146,7 +147,7 @@ async fn dispatch( | ||
| 146 | 147 | .await?; |
| 147 | 148 | if settings.maintenance { |
| 148 | 149 | let builders = user::builder_ids(&conn).await?; |
| 149 | - presence.disconnect_except(&builders, b"maintenance"); | |
| 150 | + presence.disconnect_except(&builders, Close::Maintenance); | |
| 150 | 151 | } |
| 151 | 152 | let broadcasts = if settings.announcement == previous.announcement { |
| 152 | 153 | Vec::new() |
| @@ -275,7 +276,7 @@ async fn dispatch( | ||
| 275 | 276 | admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; |
| 276 | 277 | if suspended { |
| 277 | 278 | authentication::revoke_sessions(&user_id, &conn).await?; |
| 278 | - presence.disconnect(&user_id); | |
| 279 | + presence.disconnect(&user_id, Close::Revoked); | |
| 279 | 280 | } |
| 280 | 281 | (Response::Done, Vec::new()) |
| 281 | 282 | } |
| @@ -283,7 +284,7 @@ async fn dispatch( | ||
| 283 | 284 | let me = authenticated(state, &conn).await?; |
| 284 | 285 | managed(&me, &user_id, &conn).await?; |
| 285 | 286 | authentication::revoke_sessions(&user_id, &conn).await?; |
| 286 | - presence.disconnect(&user_id); | |
| 287 | + presence.disconnect(&user_id, Close::Revoked); | |
| 287 | 288 | admin_log::record( |
| 288 | 289 | Some(&me.id), |
| 289 | 290 | Some(&user_id), |
| @@ -298,7 +299,7 @@ async fn dispatch( | ||
| 298 | 299 | let me = authenticated(state, &conn).await?; |
| 299 | 300 | managed(&me, &user_id, &conn).await?; |
| 300 | 301 | authentication::reset_password(&user_id, &password, &conn).await?; |
| 301 | - presence.disconnect(&user_id); | |
| 302 | + presence.disconnect(&user_id, Close::Revoked); | |
| 302 | 303 | admin_log::record( |
| 303 | 304 | Some(&me.id), |
| 304 | 305 | Some(&user_id), |
| @@ -342,7 +343,7 @@ async fn dispatch( | ||
| 342 | 343 | broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); |
| 343 | 344 | } else { |
| 344 | 345 | user::set_ghost(&user_id, false, &conn).await?; |
| 345 | - presence.disconnect(&user_id); | |
| 346 | + presence.disconnect(&user_id, Close::Revoked); | |
| 346 | 347 | } |
| 347 | 348 | (Response::User(user), broadcasts) |
| 348 | 349 | } |
| @@ -435,7 +436,7 @@ async fn dispatch( | ||
| 435 | 436 | if me.id == user_id { |
| 436 | 437 | set_state(state, State::Anonymous); |
| 437 | 438 | } else { |
| 438 | - presence.disconnect(&user_id); | |
| 439 | + presence.disconnect(&user_id, Close::Revoked); | |
| 439 | 440 | } |
| 440 | 441 | (Response::User(deleted), broadcasts) |
| 441 | 442 | } |
| @@ -1291,7 +1292,7 @@ async fn dispatch( | ||
| 1291 | 1292 | user::set_timeout(&user_id, until, &conn).await?; |
| 1292 | 1293 | if until.is_some() { |
| 1293 | 1294 | authentication::revoke_sessions(&user_id, &conn).await?; |
| 1294 | - presence.disconnect(&user_id); | |
| 1295 | + presence.disconnect(&user_id, Close::Revoked); | |
| 1295 | 1296 | } |
| 1296 | 1297 | admin_log::record( |
| 1297 | 1298 | Some(&me.id), |
| @@ -1337,7 +1338,7 @@ async fn dispatch( | ||
| 1337 | 1338 | ) |
| 1338 | 1339 | .await?; |
| 1339 | 1340 | tx.commit().await?; |
| 1340 | - presence.disconnect(&user_id); | |
| 1341 | + presence.disconnect(&user_id, Close::Banned); | |
| 1341 | 1342 | (Response::Done, Vec::new()) |
| 1342 | 1343 | } |
| 1343 | 1344 | Request::ServerBans => { |
| @@ -1549,9 +1550,6 @@ async fn dispatch( | ||
| 1549 | 1550 | admin_log::record(Some(&me.id), None, None, &action, &conn).await?; |
| 1550 | 1551 | (Response::Done, Vec::new()) |
| 1551 | 1552 | } |
| 1552 | - Request::DownloadBackup { .. } => { | |
| 1553 | - return Err(CommonError::Server.into()); | |
| 1554 | - } | |
| 1555 | 1553 | Request::VoiceRooms => { |
| 1556 | 1554 | builder(state, &conn).await?; |
| 1557 | 1555 | ( |
| @@ -1687,7 +1685,7 @@ async fn dispatch( | ||
| 1687 | 1685 | Ok(outcome) |
| 1688 | 1686 | } |
| 1689 | 1687 | |
| 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> { | |
| 1691 | 1689 | let mut rooms = Vec::new(); |
| 1692 | 1690 | for (community_id, user_ids, ghosts) in voice.rooms() { |
| 1693 | 1691 | let community = community::label(&community_id, conn).await?; |
| @@ -1713,7 +1711,7 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>, | ||
| 1713 | 1711 | Ok(rooms) |
| 1714 | 1712 | } |
| 1715 | 1713 | |
| 1716 | -async fn report_created(conn: &Connection) -> Result<Broadcast, Error> { | |
| 1714 | +async fn report_created(conn: &Connection) -> Result<Broadcast, ServerError> { | |
| 1717 | 1715 | Ok(Broadcast { |
| 1718 | 1716 | event: Event::ReportCreated, |
| 1719 | 1717 | user_ids: user::builder_ids(conn).await?, |
| @@ -1728,7 +1726,7 @@ async fn limit_logins( | ||
| 1728 | 1726 | rate_limit: &RateLimit, |
| 1729 | 1727 | connection: Option<&quinn::Connection>, |
| 1730 | 1728 | conn: &Connection, |
| 1731 | -) -> Result<(), Error> { | |
| 1729 | +) -> Result<(), ServerError> { | |
| 1732 | 1730 | let limit = server_settings::read(conn).await?.logins_per_minute; |
| 1733 | 1731 | |
| 1734 | 1732 | Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?) |
| @@ -1738,7 +1736,7 @@ fn limit_messages( | ||
| 1738 | 1736 | me: &User, |
| 1739 | 1737 | rate_limit: &RateLimit, |
| 1740 | 1738 | settings: &ServerSettings, |
| 1741 | -) -> Result<(), Error> { | |
| 1739 | +) -> Result<(), ServerError> { | |
| 1742 | 1740 | if permission::is_builder(me.role) { |
| 1743 | 1741 | return Ok(()); |
| 1744 | 1742 | } |
| @@ -1750,7 +1748,7 @@ async fn record_address( | ||
| 1750 | 1748 | user: &User, |
| 1751 | 1749 | connection: Option<&quinn::Connection>, |
| 1752 | 1750 | conn: &Connection, |
| 1753 | -) -> Result<(), Error> { | |
| 1751 | +) -> Result<(), ServerError> { | |
| 1754 | 1752 | if let Some(ip) = ip_of(connection) { |
| 1755 | 1753 | user::set_last_ip(&user.id, &ip, conn).await?; |
| 1756 | 1754 | } |
| @@ -1771,7 +1769,7 @@ async fn remove_member( | ||
| 1771 | 1769 | voice: &Voice, |
| 1772 | 1770 | share: &Shares, |
| 1773 | 1771 | conn: &mut Connection, |
| 1774 | -) -> Result<Outcome, Error> { | |
| 1772 | +) -> Result<Outcome, ServerError> { | |
| 1775 | 1773 | let Removal { |
| 1776 | 1774 | community_id, |
| 1777 | 1775 | user_id, |
| @@ -1821,7 +1819,7 @@ async fn remove_member( | ||
| 1821 | 1819 | Ok((Response::Done, broadcasts)) |
| 1822 | 1820 | } |
| 1823 | 1821 | |
| 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> { | |
| 1825 | 1823 | let mut user_ids = BTreeSet::from([user_id.to_string()]); |
| 1826 | 1824 | for community in community::communities_of(user_id, conn).await? { |
| 1827 | 1825 | 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 | ||
| 1835 | 1833 | Ok(user_ids.into_iter().collect()) |
| 1836 | 1834 | } |
| 1837 | 1835 | |
| 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> { | |
| 1839 | 1837 | Ok(vec![Broadcast { |
| 1840 | 1838 | event: Event::UserUpdated(user.clone()), |
| 1841 | 1839 | user_ids: related_user_ids(&user.id, conn).await?, |
| @@ -1846,7 +1844,7 @@ async fn effective_presence( | ||
| 1846 | 1844 | presence: &network::Presence, |
| 1847 | 1845 | user_id: &str, |
| 1848 | 1846 | conn: &Connection, |
| 1849 | -) -> Result<Presence, Error> { | |
| 1847 | +) -> Result<Presence, ServerError> { | |
| 1850 | 1848 | if !presence.is_online(user_id) { |
| 1851 | 1849 | return Ok(Presence::Offline); |
| 1852 | 1850 | } |
| @@ -1858,7 +1856,7 @@ pub async fn presence_changed( | ||
| 1858 | 1856 | presence: &network::Presence, |
| 1859 | 1857 | user_id: &str, |
| 1860 | 1858 | conn: &Connection, |
| 1861 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1859 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1862 | 1860 | let presence = effective_presence(presence, user_id, conn).await?; |
| 1863 | 1861 | |
| 1864 | 1862 | Ok(vec![Broadcast { |
| @@ -1870,7 +1868,10 @@ pub async fn presence_changed( | ||
| 1870 | 1868 | }]) |
| 1871 | 1869 | } |
| 1872 | 1870 | |
| 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> { | |
| 1874 | 1875 | let mut broadcasts = Vec::new(); |
| 1875 | 1876 | for user_id in user_ids { |
| 1876 | 1877 | broadcasts.push(Broadcast { |
| @@ -1882,7 +1883,7 @@ async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result<Vec<Bro | ||
| 1882 | 1883 | Ok(broadcasts) |
| 1883 | 1884 | } |
| 1884 | 1885 | |
| 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> { | |
| 1886 | 1887 | Ok(Broadcast { |
| 1887 | 1888 | event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?), |
| 1888 | 1889 | user_ids: vec![user_id.to_string()], |
| @@ -1894,7 +1895,7 @@ async fn leave_user_voice( | ||
| 1894 | 1895 | share: &Shares, |
| 1895 | 1896 | user_id: &str, |
| 1896 | 1897 | conn: &Connection, |
| 1897 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1898 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1898 | 1899 | match voice.leave(user_id) { |
| 1899 | 1900 | Some(left) => voice_left(share, left, conn).await, |
| 1900 | 1901 | None => Ok(Vec::new()), |
| @@ -1906,7 +1907,7 @@ pub async fn leave_connection_voice( | ||
| 1906 | 1907 | share: &Shares, |
| 1907 | 1908 | connection: Option<&quinn::Connection>, |
| 1908 | 1909 | conn: &Connection, |
| 1909 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1910 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1910 | 1911 | match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { |
| 1911 | 1912 | Some(left) => voice_left(share, left, conn).await, |
| 1912 | 1913 | None => Ok(Vec::new()), |
| @@ -1919,7 +1920,7 @@ async fn leave_room_voice( | ||
| 1919 | 1920 | community_id: &str, |
| 1920 | 1921 | user_id: &str, |
| 1921 | 1922 | conn: &Connection, |
| 1922 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1923 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1923 | 1924 | match voice.leave_room(community_id, user_id) { |
| 1924 | 1925 | Some(left) => voice_left(share, left, conn).await, |
| 1925 | 1926 | None => Ok(Vec::new()), |
| @@ -1930,7 +1931,7 @@ async fn voice_unmuted( | ||
| 1930 | 1931 | voice: &Voice, |
| 1931 | 1932 | user_id: &str, |
| 1932 | 1933 | conn: &Connection, |
| 1933 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1934 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1934 | 1935 | let Some(community_id) = voice.set_muted(user_id, false) else { |
| 1935 | 1936 | return Ok(Vec::new()); |
| 1936 | 1937 | }; |
| @@ -1958,7 +1959,7 @@ async fn voice_silenced( | ||
| 1958 | 1959 | share: &Shares, |
| 1959 | 1960 | community_id: &str, |
| 1960 | 1961 | conn: &Connection, |
| 1961 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1962 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1962 | 1963 | let mut broadcasts = Vec::new(); |
| 1963 | 1964 | for user_id in voice.room_users(community_id) { |
| 1964 | 1965 | if permission::is_builder(user::read(&user_id, conn).await?.role) { |
| @@ -1977,7 +1978,7 @@ async fn voice_closed( | ||
| 1977 | 1978 | share: &Shares, |
| 1978 | 1979 | community_id: &str, |
| 1979 | 1980 | conn: &Connection, |
| 1980 | -) -> Result<Vec<Broadcast>, Error> { | |
| 1981 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 1981 | 1982 | let mut broadcasts = Vec::new(); |
| 1982 | 1983 | for left in voice.remove_room(community_id) { |
| 1983 | 1984 | broadcasts.extend(voice_left(share, left, conn).await?); |
| @@ -2000,7 +2001,7 @@ async fn call_ended( | ||
| 2000 | 2001 | call: Option<CallEnd>, |
| 2001 | 2002 | members: &[Member], |
| 2002 | 2003 | conn: &Connection, |
| 2003 | -) -> Result<Vec<Broadcast>, Error> { | |
| 2004 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 2004 | 2005 | let Some(call) = call else { |
| 2005 | 2006 | return Ok(Vec::new()); |
| 2006 | 2007 | }; |
| @@ -2019,7 +2020,7 @@ async fn voice_left( | ||
| 2019 | 2020 | share: &Shares, |
| 2020 | 2021 | left: Left, |
| 2021 | 2022 | conn: &Connection, |
| 2022 | -) -> Result<Vec<Broadcast>, Error> { | |
| 2023 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 2023 | 2024 | let mut broadcasts = share_left(share, &left.user_id, conn).await?; |
| 2024 | 2025 | let Some(seconds) = left.ghost_seconds else { |
| 2025 | 2026 | let members = user_community::members(&left.community_id, conn).await?; |
| @@ -2044,7 +2045,7 @@ async fn share_ended( | ||
| 2044 | 2045 | user_id: &str, |
| 2045 | 2046 | kind: Kind, |
| 2046 | 2047 | conn: &Connection, |
| 2047 | -) -> Result<Broadcast, Error> { | |
| 2048 | +) -> Result<Broadcast, ServerError> { | |
| 2048 | 2049 | let members = user_community::members(community_id, conn).await?; |
| 2049 | 2050 | let event = Event::ShareStopped { |
| 2050 | 2051 | community_id: community_id.to_string(), |
| @@ -2060,7 +2061,7 @@ async fn share_stopped( | ||
| 2060 | 2061 | user_id: &str, |
| 2061 | 2062 | kind: Kind, |
| 2062 | 2063 | conn: &Connection, |
| 2063 | -) -> Result<Vec<Broadcast>, Error> { | |
| 2064 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 2064 | 2065 | let Some(community_id) = share.stop(user_id, kind) else { |
| 2065 | 2066 | return Ok(Vec::new()); |
| 2066 | 2067 | }; |
| @@ -2072,7 +2073,7 @@ async fn share_left( | ||
| 2072 | 2073 | share: &Shares, |
| 2073 | 2074 | user_id: &str, |
| 2074 | 2075 | conn: &Connection, |
| 2075 | -) -> Result<Vec<Broadcast>, Error> { | |
| 2076 | +) -> Result<Vec<Broadcast>, ServerError> { | |
| 2076 | 2077 | let mut broadcasts = Vec::new(); |
| 2077 | 2078 | for (community_id, kind) in share.stop_all(user_id) { |
| 2078 | 2079 | broadcasts.push(share_ended(&community_id, user_id, kind, conn).await?); |
| @@ -2090,7 +2091,7 @@ async fn enter( | ||
| 2090 | 2091 | share: &Shares, |
| 2091 | 2092 | connection: Option<&quinn::Connection>, |
| 2092 | 2093 | conn: &Connection, |
| 2093 | -) -> Result<Outcome, Error> { | |
| 2094 | +) -> Result<Outcome, ServerError> { | |
| 2094 | 2095 | stats::mark_active(&user.id, conn).await?; |
| 2095 | 2096 | record_address(&user, connection, conn).await?; |
| 2096 | 2097 | let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; |
| @@ -2114,14 +2115,14 @@ fn set_state(state: &Mutex<State>, new_state: State) { | ||
| 2114 | 2115 | *state.lock().unwrap() = new_state; |
| 2115 | 2116 | } |
| 2116 | 2117 | |
| 2117 | -fn session(state: &Mutex<State>) -> Result<(User, String), Error> { | |
| 2118 | +fn session(state: &Mutex<State>) -> Result<(User, String), ServerError> { | |
| 2118 | 2119 | match state.lock().unwrap().clone() { |
| 2119 | 2120 | State::Anonymous => Err(CommonError::Unauthenticated.into()), |
| 2120 | 2121 | State::Authenticated { user, token } => Ok((user, token)), |
| 2121 | 2122 | } |
| 2122 | 2123 | } |
| 2123 | 2124 | |
| 2124 | -fn session_token(state: &Mutex<State>) -> Result<String, Error> { | |
| 2125 | +fn session_token(state: &Mutex<State>) -> Result<String, ServerError> { | |
| 2125 | 2126 | Ok(session(state)?.1) |
| 2126 | 2127 | } |
| 2127 | 2128 | |
| @@ -2131,7 +2132,7 @@ fn cache_user(state: &Mutex<State>, user: User) { | ||
| 2131 | 2132 | } |
| 2132 | 2133 | } |
| 2133 | 2134 | |
| 2134 | -async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> { | |
| 2135 | +async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, ServerError> { | |
| 2135 | 2136 | let (cached, _) = session(state)?; |
| 2136 | 2137 | let user = user::read(&cached.id, conn).await?; |
| 2137 | 2138 | cache_user(state, user.clone()); |
| @@ -2139,7 +2140,7 @@ async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, | ||
| 2139 | 2140 | Ok(user) |
| 2140 | 2141 | } |
| 2141 | 2142 | |
| 2142 | -async fn builder(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> { | |
| 2143 | +async fn builder(state: &Mutex<State>, conn: &Connection) -> Result<User, ServerError> { | |
| 2143 | 2144 | let user = authenticated(state, conn).await?; |
| 2144 | 2145 | ensure(permission::is_builder(user.role))?; |
| 2145 | 2146 | |
| @@ -2150,13 +2151,13 @@ pub async fn actor_rank( | ||
| 2150 | 2151 | me: &User, |
| 2151 | 2152 | community_id: &str, |
| 2152 | 2153 | conn: &Connection, |
| 2153 | -) -> Result<Option<Rank>, Error> { | |
| 2154 | +) -> Result<Option<Rank>, ServerError> { | |
| 2154 | 2155 | let rank = user_community::rank(&me.id, community_id, conn).await?; |
| 2155 | 2156 | |
| 2156 | 2157 | Ok(permission::effective_rank(me.role, rank)) |
| 2157 | 2158 | } |
| 2158 | 2159 | |
| 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> { | |
| 2160 | 2161 | let target = user::read(user_id, conn).await?; |
| 2161 | 2162 | ensure(permission::can_manage_user( |
| 2162 | 2163 | me.role, |
| @@ -2167,11 +2168,11 @@ async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, Er | ||
| 2167 | 2168 | Ok(target) |
| 2168 | 2169 | } |
| 2169 | 2170 | |
| 2170 | -pub fn ensure(allowed: bool) -> Result<(), Error> { | |
| 2171 | +pub fn ensure(allowed: bool) -> Result<(), ServerError> { | |
| 2171 | 2172 | ensure_with(allowed, CommonError::Forbidden) |
| 2172 | 2173 | } |
| 2173 | 2174 | |
| 2174 | -pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), Error> { | |
| 2175 | +pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> { | |
| 2175 | 2176 | if !allowed { |
| 2176 | 2177 | return Err(error.into()); |
| 2177 | 2178 | } |
| @@ -2184,17 +2185,21 @@ async fn allowed( | ||
| 2184 | 2185 | community_id: &str, |
| 2185 | 2186 | conn: &Connection, |
| 2186 | 2187 | check: fn(Option<Rank>) -> bool, |
| 2187 | -) -> Result<(), Error> { | |
| 2188 | +) -> Result<(), ServerError> { | |
| 2188 | 2189 | ensure(check(actor_rank(me, community_id, conn).await?)) |
| 2189 | 2190 | } |
| 2190 | 2191 | |
| 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> { | |
| 2192 | 2197 | Ok(user_community::rank(user_id, community_id, conn) |
| 2193 | 2198 | .await? |
| 2194 | 2199 | .is_none()) |
| 2195 | 2200 | } |
| 2196 | 2201 | |
| 2197 | -async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Error> { | |
| 2202 | +async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 2198 | 2203 | ensure(!community::is_fixed(community_id, conn).await?) |
| 2199 | 2204 | } |
| 2200 | 2205 | |
| @@ -2212,7 +2217,7 @@ async fn message_broadcast( | ||
| 2212 | 2217 | event: fn(Message) -> Event, |
| 2213 | 2218 | actor_id: &str, |
| 2214 | 2219 | conn: &Connection, |
| 2215 | -) -> Result<Broadcast, Error> { | |
| 2220 | +) -> Result<Broadcast, ServerError> { | |
| 2216 | 2221 | let members = user_community::members(&message.community_id, conn).await?; |
| 2217 | 2222 | |
| 2218 | 2223 | Ok(broadcast_with(event(message.clone()), &members, actor_id)) |
| @@ -2249,7 +2254,7 @@ async fn record_ghost_voice( | ||
| 2249 | 2254 | community_id: &str, |
| 2250 | 2255 | seconds: u64, |
| 2251 | 2256 | conn: &Connection, |
| 2252 | -) -> Result<(), Error> { | |
| 2257 | +) -> Result<(), ServerError> { | |
| 2253 | 2258 | let community = community::label(community_id, conn).await?; |
| 2254 | 2259 | admin_log::record( |
| 2255 | 2260 | Some(user_id), |
| @@ -2293,6 +2298,17 @@ mod tests { | ||
| 2293 | 2298 | db: &DB, |
| 2294 | 2299 | services: &Services, |
| 2295 | 2300 | ) -> 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> { | |
| 2296 | 2312 | handle( |
| 2297 | 2313 | request, |
| 2298 | 2314 | state, |
| @@ -2384,7 +2400,7 @@ mod tests { | ||
| 2384 | 2400 | }; |
| 2385 | 2401 | invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; |
| 2386 | 2402 | |
| 2387 | - let response = send( | |
| 2403 | + let response = send_result( | |
| 2388 | 2404 | Request::UpdateCommunity { |
| 2389 | 2405 | community_id: community.id, |
| 2390 | 2406 | name: "Renamed".to_string(), |
| @@ -2395,7 +2411,7 @@ mod tests { | ||
| 2395 | 2411 | ) |
| 2396 | 2412 | .await; |
| 2397 | 2413 | |
| 2398 | - assert!(matches!(response, Response::Error(CommonError::Forbidden))); | |
| 2414 | + assert!(matches!(response, Err(CommonError::Forbidden))); | |
| 2399 | 2415 | } |
| 2400 | 2416 | |
| 2401 | 2417 | #[tokio::test] |
crates/server/src/retention.rsmodified+5 -5
| @@ -10,7 +10,7 @@ use turso::Connection; | ||
| 10 | 10 | use crate::{ |
| 11 | 11 | attachment, |
| 12 | 12 | database::{self, DB}, |
| 13 | - error::Error, | |
| 13 | + error::ServerError, | |
| 14 | 14 | message, server_settings, |
| 15 | 15 | }; |
| 16 | 16 | |
| @@ -31,7 +31,7 @@ fn cutoff(now: u64, days: u32) -> String { | ||
| 31 | 31 | time::id_bound(now.saturating_sub(u64::from(days) * time::DAY_MILLIS)) |
| 32 | 32 | } |
| 33 | 33 | |
| 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> { | |
| 35 | 35 | let mut rows = conn |
| 36 | 36 | .query( |
| 37 | 37 | &format!("SELECT id FROM {table} WHERE id < ?1 ORDER BY id LIMIT ?2"), |
| @@ -51,7 +51,7 @@ async fn purge_messages( | ||
| 51 | 51 | cutoff: &str, |
| 52 | 52 | conn: &mut Connection, |
| 53 | 53 | directory: &Path, |
| 54 | -) -> Result<u64, Error> { | |
| 54 | +) -> Result<u64, ServerError> { | |
| 55 | 55 | let mut purged = 0; |
| 56 | 56 | loop { |
| 57 | 57 | let ids = expired("message", cutoff, conn).await?; |
| @@ -75,7 +75,7 @@ async fn purge_attachments( | ||
| 75 | 75 | cutoff: &str, |
| 76 | 76 | conn: &mut Connection, |
| 77 | 77 | directory: &Path, |
| 78 | -) -> Result<u64, Error> { | |
| 78 | +) -> Result<u64, ServerError> { | |
| 79 | 79 | let mut purged = 0; |
| 80 | 80 | loop { |
| 81 | 81 | let ids = expired("attachment", cutoff, conn).await?; |
| @@ -91,7 +91,7 @@ async fn purge_attachments( | ||
| 91 | 91 | } |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | -async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { | |
| 94 | +async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { | |
| 95 | 95 | let mut conn = database::connect(db).await?; |
| 96 | 96 | let settings = server_settings::read(&conn).await?; |
| 97 | 97 | let now = time::now_ms(); |
crates/server/src/server_ban.rsmodified+7 -7
| @@ -6,7 +6,7 @@ use turso::Connection; | ||
| 6 | 6 | |
| 7 | 7 | use crate::{ |
| 8 | 8 | database::{self, new_id}, |
| 9 | - error::Error, | |
| 9 | + error::ServerError, | |
| 10 | 10 | }; |
| 11 | 11 | |
| 12 | 12 | pub async fn insert( |
| @@ -15,7 +15,7 @@ pub async fn insert( | ||
| 15 | 15 | reason: Option<&str>, |
| 16 | 16 | created_by: &str, |
| 17 | 17 | conn: &Connection, |
| 18 | -) -> Result<(), Error> { | |
| 18 | +) -> Result<(), ServerError> { | |
| 19 | 19 | conn.execute( |
| 20 | 20 | "INSERT INTO server_ban (id, kind, value, reason, created_by) |
| 21 | 21 | 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( | ||
| 26 | 26 | Ok(()) |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | -pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> { | |
| 29 | +pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, ServerError> { | |
| 30 | 30 | let mut rows = conn |
| 31 | 31 | .query( |
| 32 | 32 | "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> { | ||
| 48 | 48 | Ok(bans) |
| 49 | 49 | } |
| 50 | 50 | |
| 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> { | |
| 52 | 52 | database::exists( |
| 53 | 53 | conn, |
| 54 | 54 | "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 | ||
| 57 | 57 | .await |
| 58 | 58 | } |
| 59 | 59 | |
| 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> { | |
| 61 | 61 | exists( |
| 62 | 62 | ServerBanKind::Username, |
| 63 | 63 | &username.to_ascii_lowercase(), |
| @@ -66,11 +66,11 @@ pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, | ||
| 66 | 66 | .await |
| 67 | 67 | } |
| 68 | 68 | |
| 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> { | |
| 70 | 70 | exists(ServerBanKind::Ip, ip, conn).await |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | -pub async fn remove(id: &str, conn: &Connection) -> Result<(), Error> { | |
| 73 | +pub async fn remove(id: &str, conn: &Connection) -> Result<(), ServerError> { | |
| 74 | 74 | let mut rows = conn |
| 75 | 75 | .query("DELETE FROM server_ban WHERE id = ?1 RETURNING id", (id,)) |
| 76 | 76 | .await?; |
crates/server/src/server_settings.rsmodified+4 -4
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | use common::model::ServerSettings; |
| 2 | 2 | use turso::Connection; |
| 3 | 3 | |
| 4 | -use crate::{error::Error, user}; | |
| 4 | +use crate::{error::ServerError, user}; | |
| 5 | 5 | |
| 6 | 6 | 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"; |
| 7 | 7 | |
| @@ -14,7 +14,7 @@ fn assignments() -> String { | ||
| 14 | 14 | .join(", ") |
| 15 | 15 | } |
| 16 | 16 | |
| 17 | -pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> { | |
| 17 | +pub async fn read(conn: &Connection) -> Result<ServerSettings, ServerError> { | |
| 18 | 18 | let mut rows = conn |
| 19 | 19 | .query( |
| 20 | 20 | &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"), |
| @@ -25,7 +25,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> { | ||
| 25 | 25 | .next() |
| 26 | 26 | .await? |
| 27 | 27 | .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)?) }; | |
| 29 | 29 | |
| 30 | 30 | Ok(ServerSettings { |
| 31 | 31 | name: row.get(0)?, |
| @@ -45,7 +45,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> { | ||
| 45 | 45 | }) |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | -pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> { | |
| 48 | +pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), ServerError> { | |
| 49 | 49 | conn.execute( |
| 50 | 50 | &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()), |
| 51 | 51 | ( |
crates/server/src/stats.rsmodified+8 -4
| @@ -4,11 +4,11 @@ use common::{ | ||
| 4 | 4 | }; |
| 5 | 5 | use turso::Connection; |
| 6 | 6 | |
| 7 | -use crate::{database, error::Error, user}; | |
| 7 | +use crate::{database, error::ServerError, user}; | |
| 8 | 8 | |
| 9 | 9 | const MAXIMUM_DAYS: u32 = 90; |
| 10 | 10 | |
| 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> { | |
| 12 | 12 | if user::is_ghost(user_id, conn).await? { |
| 13 | 13 | return Ok(()); |
| 14 | 14 | } |
| @@ -22,7 +22,7 @@ pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), Error> | ||
| 22 | 22 | Ok(()) |
| 23 | 23 | } |
| 24 | 24 | |
| 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> { | |
| 26 | 26 | let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); |
| 27 | 27 | let today = time::now_ms() / DAY_MILLIS; |
| 28 | 28 | let mut stats = Vec::new(); |
| @@ -52,6 +52,10 @@ pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, Error> | ||
| 52 | 52 | Ok(stats) |
| 53 | 53 | } |
| 54 | 54 | |
| 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> { | |
| 56 | 60 | Ok(database::scalar_i64(conn, sql, params).await? as u64) |
| 57 | 61 | } |
crates/server/src/user.rsmodified+80 -45
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | use common::{ |
| 2 | 2 | constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, |
| 3 | - error::{Error as CommonError, Field, InvalidInput}, | |
| 3 | + error::{Error as CommonError, Field, Problem}, | |
| 4 | 4 | model::{Account, Presence, Role, User}, |
| 5 | 5 | permission, time, |
| 6 | 6 | validate::{validate_avatar_size, validate_status, validate_username}, |
| @@ -10,14 +10,14 @@ use turso::{Connection, Row}; | ||
| 10 | 10 | |
| 11 | 11 | use crate::{ |
| 12 | 12 | database::{self, new_id}, |
| 13 | - error::Error, | |
| 13 | + error::ServerError, | |
| 14 | 14 | }; |
| 15 | 15 | |
| 16 | 16 | pub fn user_columns(alias: &str) -> String { |
| 17 | 17 | format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") |
| 18 | 18 | } |
| 19 | 19 | |
| 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> { | |
| 21 | 21 | let Some(id) = row.get::<Option<String>>(start)? else { |
| 22 | 22 | return Ok(None); |
| 23 | 23 | }; |
| @@ -32,24 +32,32 @@ pub fn from_row_at(row: &Row, start: usize) -> Result<Option<User>, Error> { | ||
| 32 | 32 | })) |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | -pub fn from_row(row: &Row) -> Result<User, Error> { | |
| 35 | +pub fn from_row(row: &Row) -> Result<User, ServerError> { | |
| 36 | 36 | Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | -pub fn bool_at(row: &Row, index: usize) -> Result<bool, Error> { | |
| 39 | +pub fn bool_at(row: &Row, index: usize) -> Result<bool, ServerError> { | |
| 40 | 40 | let flag: i64 = row.get(index)?; |
| 41 | 41 | |
| 42 | 42 | Ok(flag != 0) |
| 43 | 43 | } |
| 44 | 44 | |
| 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> { | |
| 46 | 50 | let mut rows = conn.query(sql, params).await?; |
| 47 | 51 | let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 48 | 52 | |
| 49 | 53 | from_row(&row) |
| 50 | 54 | } |
| 51 | 55 | |
| 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> { | |
| 53 | 61 | conn.execute( |
| 54 | 62 | &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), |
| 55 | 63 | params, |
| @@ -63,7 +71,7 @@ async fn set_returning( | ||
| 63 | 71 | column: &str, |
| 64 | 72 | params: impl turso::IntoParams, |
| 65 | 73 | conn: &Connection, |
| 66 | -) -> Result<User, Error> { | |
| 74 | +) -> Result<User, ServerError> { | |
| 67 | 75 | one( |
| 68 | 76 | &format!( |
| 69 | 77 | "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", |
| @@ -75,7 +83,11 @@ async fn set_returning( | ||
| 75 | 83 | .await |
| 76 | 84 | } |
| 77 | 85 | |
| 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> { | |
| 79 | 91 | one( |
| 80 | 92 | &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")), |
| 81 | 93 | ( |
| @@ -90,7 +102,7 @@ pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> R | ||
| 90 | 102 | .await |
| 91 | 103 | } |
| 92 | 104 | |
| 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> { | |
| 94 | 106 | one( |
| 95 | 107 | &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), |
| 96 | 108 | (user_id,), |
| @@ -99,11 +111,11 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> { | ||
| 99 | 111 | .await |
| 100 | 112 | } |
| 101 | 113 | |
| 102 | -pub async fn any(conn: &Connection) -> Result<bool, Error> { | |
| 114 | +pub async fn any(conn: &Connection) -> Result<bool, ServerError> { | |
| 103 | 115 | database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await |
| 104 | 116 | } |
| 105 | 117 | |
| 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> { | |
| 107 | 119 | let mut rows = conn |
| 108 | 120 | .query( |
| 109 | 121 | &format!( |
| @@ -121,13 +133,13 @@ pub async fn is_taken( | ||
| 121 | 133 | username: &str, |
| 122 | 134 | except_id: Option<&str>, |
| 123 | 135 | conn: &Connection, |
| 124 | -) -> Result<bool, Error> { | |
| 136 | +) -> Result<bool, ServerError> { | |
| 125 | 137 | Ok(by_username(username, conn) |
| 126 | 138 | .await? |
| 127 | 139 | .is_some_and(|existing| Some(existing.id.as_str()) != except_id)) |
| 128 | 140 | } |
| 129 | 141 | |
| 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> { | |
| 131 | 143 | let mut rows = conn |
| 132 | 144 | .query( |
| 133 | 145 | &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 | ||
| 142 | 154 | pub async fn credentials( |
| 143 | 155 | username: &str, |
| 144 | 156 | conn: &Connection, |
| 145 | -) -> Result<Option<(User, String)>, Error> { | |
| 157 | +) -> Result<Option<(User, String)>, ServerError> { | |
| 146 | 158 | let mut rows = conn |
| 147 | 159 | .query( |
| 148 | 160 | &format!( |
| @@ -159,7 +171,7 @@ pub async fn credentials( | ||
| 159 | 171 | Ok(Some((from_row(&row)?, row.get(5)?))) |
| 160 | 172 | } |
| 161 | 173 | |
| 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> { | |
| 163 | 175 | validate_username(username)?; |
| 164 | 176 | |
| 165 | 177 | 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< | ||
| 169 | 181 | set_returning("username", (user_id, username), conn).await |
| 170 | 182 | } |
| 171 | 183 | |
| 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> { | |
| 173 | 189 | validate_status(status)?; |
| 174 | 190 | |
| 175 | 191 | set_returning("status", (user_id, status), conn).await |
| 176 | 192 | } |
| 177 | 193 | |
| 178 | -pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { | |
| 194 | +pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { | |
| 179 | 195 | validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; |
| 180 | 196 | let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { |
| 181 | 197 | CommonError::Invalid { |
| 182 | 198 | field: Field::Avatar, |
| 183 | - input: InvalidInput::NotJpeg, | |
| 199 | + problem: Problem::NotJpeg, | |
| 184 | 200 | } |
| 185 | 201 | })?; |
| 186 | 202 | if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { |
| 187 | 203 | return Err(CommonError::Invalid { |
| 188 | 204 | field: Field::Avatar, |
| 189 | - input: InvalidInput::Dimensions { | |
| 205 | + problem: Problem::Dimensions { | |
| 190 | 206 | expected: AVATAR_SIZE, |
| 191 | 207 | }, |
| 192 | 208 | } |
| @@ -200,7 +216,7 @@ pub async fn set_avatar( | ||
| 200 | 216 | user_id: &str, |
| 201 | 217 | avatar: Option<&[u8]>, |
| 202 | 218 | conn: &mut Connection, |
| 203 | -) -> Result<User, Error> { | |
| 219 | +) -> Result<User, ServerError> { | |
| 204 | 220 | if let Some(bytes) = avatar { |
| 205 | 221 | check_avatar(bytes)?; |
| 206 | 222 | } |
| @@ -226,11 +242,11 @@ async fn set_avatar_id( | ||
| 226 | 242 | user_id: &str, |
| 227 | 243 | avatar_id: Option<&str>, |
| 228 | 244 | conn: &Connection, |
| 229 | -) -> Result<User, Error> { | |
| 245 | +) -> Result<User, ServerError> { | |
| 230 | 246 | set_returning("avatar_id", (user_id, avatar_id), conn).await |
| 231 | 247 | } |
| 232 | 248 | |
| 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> { | |
| 234 | 250 | let mut rows = conn |
| 235 | 251 | .query( |
| 236 | 252 | "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 | ||
| 242 | 258 | Ok(row.get(0)?) |
| 243 | 259 | } |
| 244 | 260 | |
| 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> { | |
| 246 | 266 | set_returning("role", (user_id, role.as_str()), conn).await |
| 247 | 267 | } |
| 248 | 268 | |
| 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> { | |
| 250 | 273 | let mut rows = conn |
| 251 | 274 | .query( |
| 252 | 275 | "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> | ||
| 254 | 277 | ) |
| 255 | 278 | .await?; |
| 256 | 279 | 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 | + } | |
| 258 | 285 | |
| 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)) | |
| 260 | 287 | } |
| 261 | 288 | |
| 262 | 289 | pub async fn set_timeout( |
| 263 | 290 | user_id: &str, |
| 264 | 291 | until: Option<u64>, |
| 265 | 292 | conn: &Connection, |
| 266 | -) -> Result<(), Error> { | |
| 293 | +) -> Result<(), ServerError> { | |
| 267 | 294 | set( |
| 268 | 295 | "suspended_until", |
| 269 | 296 | (user_id, until.map(|until| until as i64)), |
| @@ -272,11 +299,11 @@ pub async fn set_timeout( | ||
| 272 | 299 | .await |
| 273 | 300 | } |
| 274 | 301 | |
| 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> { | |
| 276 | 303 | set("last_ip", (user_id, ip), conn).await |
| 277 | 304 | } |
| 278 | 305 | |
| 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> { | |
| 280 | 307 | let mut rows = conn |
| 281 | 308 | .query("SELECT last_ip FROM user WHERE id = ?1", (user_id,)) |
| 282 | 309 | .await?; |
| @@ -285,7 +312,7 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, | ||
| 285 | 312 | Ok(row.get(0)?) |
| 286 | 313 | } |
| 287 | 314 | |
| 288 | -pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> { | |
| 315 | +pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, ServerError> { | |
| 289 | 316 | database::ids( |
| 290 | 317 | conn, |
| 291 | 318 | "SELECT id FROM user WHERE role = ?1", |
| @@ -294,19 +321,27 @@ pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> { | ||
| 294 | 321 | .await |
| 295 | 322 | } |
| 296 | 323 | |
| 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> { | |
| 298 | 329 | set("suspended", (user_id, i64::from(suspended)), conn).await |
| 299 | 330 | } |
| 300 | 331 | |
| 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> { | |
| 302 | 337 | set("voice_muted", (user_id, i64::from(muted)), conn).await |
| 303 | 338 | } |
| 304 | 339 | |
| 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> { | |
| 306 | 341 | set("ghost", (user_id, i64::from(ghost)), conn).await |
| 307 | 342 | } |
| 308 | 343 | |
| 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> { | |
| 310 | 345 | let mut rows = conn |
| 311 | 346 | .query("SELECT ghost FROM user WHERE id = ?1", (user_id,)) |
| 312 | 347 | .await?; |
| @@ -317,7 +352,7 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> { | ||
| 317 | 352 | bool_at(&row, 0) |
| 318 | 353 | } |
| 319 | 354 | |
| 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> { | |
| 321 | 356 | let mut rows = conn |
| 322 | 357 | .query("SELECT presence FROM user WHERE id = ?1", (user_id,)) |
| 323 | 358 | .await?; |
| @@ -331,11 +366,11 @@ pub async fn update_presence( | ||
| 331 | 366 | user_id: &str, |
| 332 | 367 | presence: Presence, |
| 333 | 368 | conn: &Connection, |
| 334 | -) -> Result<(), Error> { | |
| 369 | +) -> Result<(), ServerError> { | |
| 335 | 370 | set("presence", (user_id, presence.as_str()), conn).await |
| 336 | 371 | } |
| 337 | 372 | |
| 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> { | |
| 339 | 374 | let mut rows = conn |
| 340 | 375 | .query( |
| 341 | 376 | "SELECT voice_muted, role FROM user WHERE id = ?1", |
| @@ -353,11 +388,11 @@ pub async fn set_password_hash( | ||
| 353 | 388 | user_id: &str, |
| 354 | 389 | password_hash: &str, |
| 355 | 390 | conn: &Connection, |
| 356 | -) -> Result<(), Error> { | |
| 391 | +) -> Result<(), ServerError> { | |
| 357 | 392 | set("password_hash", (user_id, password_hash), conn).await |
| 358 | 393 | } |
| 359 | 394 | |
| 360 | -pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> { | |
| 395 | +pub async fn all(conn: &Connection) -> Result<Vec<Account>, ServerError> { | |
| 361 | 396 | let mut rows = conn |
| 362 | 397 | .query( |
| 363 | 398 | &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> { | ||
| 380 | 415 | Ok(accounts) |
| 381 | 416 | } |
| 382 | 417 | |
| 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> { | |
| 384 | 419 | one( |
| 385 | 420 | &format!( |
| 386 | 421 | "DELETE FROM user WHERE id = ?1 RETURNING {}", |
| @@ -402,7 +437,7 @@ mod tests { | ||
| 402 | 437 | }; |
| 403 | 438 | use image::{ImageFormat, RgbImage}; |
| 404 | 439 | |
| 405 | - use crate::{database, error::Error, test, user}; | |
| 440 | + use crate::{database, error::ServerError, test, user}; | |
| 406 | 441 | |
| 407 | 442 | fn jpeg(size: u32) -> Vec<u8> { |
| 408 | 443 | let mut bytes = Cursor::new(Vec::new()); |
| @@ -428,14 +463,14 @@ mod tests { | ||
| 428 | 463 | |
| 429 | 464 | assert!(matches!( |
| 430 | 465 | small, |
| 431 | - Err(Error::Common(CommonError::Invalid { | |
| 466 | + Err(ServerError::Wire(CommonError::Invalid { | |
| 432 | 467 | field: Field::Avatar, |
| 433 | 468 | .. |
| 434 | 469 | })) |
| 435 | 470 | )); |
| 436 | 471 | assert!(matches!( |
| 437 | 472 | not_jpeg, |
| 438 | - Err(Error::Common(CommonError::Invalid { | |
| 473 | + Err(ServerError::Wire(CommonError::Invalid { | |
| 439 | 474 | field: Field::Avatar, |
| 440 | 475 | .. |
| 441 | 476 | })) |
| @@ -503,7 +538,7 @@ mod tests { | ||
| 503 | 538 | |
| 504 | 539 | assert!(matches!( |
| 505 | 540 | updated_user, |
| 506 | - Err(Error::Common(CommonError::NotFound)) | |
| 541 | + Err(ServerError::Wire(CommonError::NotFound)) | |
| 507 | 542 | )); |
| 508 | 543 | } |
| 509 | 544 |
crates/server/src/user_community.rsmodified+23 -15
| @@ -6,9 +6,9 @@ use common::{ | ||
| 6 | 6 | }; |
| 7 | 7 | use turso::{Connection, Row}; |
| 8 | 8 | |
| 9 | -use crate::{community, database, error::Error, user}; | |
| 9 | +use crate::{community, database, error::ServerError, user}; | |
| 10 | 10 | |
| 11 | -fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> { | |
| 11 | +fn rank_of(row: &Row, index: usize) -> Result<Rank, ServerError> { | |
| 12 | 12 | let text: String = row.get(index)?; |
| 13 | 13 | |
| 14 | 14 | Ok(Rank::parse(&text).ok_or(CommonError::Server)?) |
| @@ -19,7 +19,7 @@ pub async fn join( | ||
| 19 | 19 | community_id: &str, |
| 20 | 20 | rank: Rank, |
| 21 | 21 | conn: &Connection, |
| 22 | -) -> Result<(), Error> { | |
| 22 | +) -> Result<(), ServerError> { | |
| 23 | 23 | conn.execute( |
| 24 | 24 | "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)", |
| 25 | 25 | (user_id, community_id, rank.as_str()), |
| @@ -29,7 +29,11 @@ pub async fn join( | ||
| 29 | 29 | Ok(()) |
| 30 | 30 | } |
| 31 | 31 | |
| 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> { | |
| 33 | 37 | conn.execute( |
| 34 | 38 | "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", |
| 35 | 39 | (user_id, community_id), |
| @@ -43,7 +47,7 @@ pub async fn rank( | ||
| 43 | 47 | user_id: &str, |
| 44 | 48 | community_id: &str, |
| 45 | 49 | conn: &Connection, |
| 46 | -) -> Result<Option<Rank>, Error> { | |
| 50 | +) -> Result<Option<Rank>, ServerError> { | |
| 47 | 51 | let mut rows = conn |
| 48 | 52 | .query( |
| 49 | 53 | "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2", |
| @@ -63,7 +67,7 @@ pub async fn set_rank( | ||
| 63 | 67 | community_id: &str, |
| 64 | 68 | rank: Rank, |
| 65 | 69 | conn: &Connection, |
| 66 | -) -> Result<(), Error> { | |
| 70 | +) -> Result<(), ServerError> { | |
| 67 | 71 | conn.execute( |
| 68 | 72 | "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", |
| 69 | 73 | (user_id, community_id, rank.as_str()), |
| @@ -78,7 +82,7 @@ pub async fn mark_read( | ||
| 78 | 82 | community_id: &str, |
| 79 | 83 | message_id: &str, |
| 80 | 84 | conn: &Connection, |
| 81 | -) -> Result<(), Error> { | |
| 85 | +) -> Result<(), ServerError> { | |
| 82 | 86 | conn.execute( |
| 83 | 87 | "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", |
| 84 | 88 | (user_id, community_id, message_id), |
| @@ -92,7 +96,7 @@ pub async fn unreads( | ||
| 92 | 96 | user_id: &str, |
| 93 | 97 | username: &str, |
| 94 | 98 | conn: &Connection, |
| 95 | -) -> Result<Vec<Unread>, Error> { | |
| 99 | +) -> Result<Vec<Unread>, ServerError> { | |
| 96 | 100 | let mut rows = conn |
| 97 | 101 | .query( |
| 98 | 102 | "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( | ||
| 137 | 141 | Ok(unreads) |
| 138 | 142 | } |
| 139 | 143 | |
| 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> { | |
| 141 | 145 | let mut rows = conn |
| 142 | 146 | .query( |
| 143 | 147 | &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 | ||
| 156 | 160 | Ok(members) |
| 157 | 161 | } |
| 158 | 162 | |
| 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> { | |
| 160 | 164 | let count = database::scalar_i64( |
| 161 | 165 | conn, |
| 162 | 166 | "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 | ||
| 167 | 171 | Ok(count as usize) |
| 168 | 172 | } |
| 169 | 173 | |
| 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> { | |
| 171 | 175 | database::ids( |
| 172 | 176 | conn, |
| 173 | 177 | "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", |
| @@ -181,7 +185,7 @@ pub async fn ban( | ||
| 181 | 185 | community_id: &str, |
| 182 | 186 | reason: Option<&str>, |
| 183 | 187 | conn: &Connection, |
| 184 | -) -> Result<(), Error> { | |
| 188 | +) -> Result<(), ServerError> { | |
| 185 | 189 | conn.execute( |
| 186 | 190 | "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", |
| 187 | 191 | (user_id, community_id, reason), |
| @@ -191,7 +195,11 @@ pub async fn ban( | ||
| 191 | 195 | Ok(()) |
| 192 | 196 | } |
| 193 | 197 | |
| 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> { | |
| 195 | 203 | conn.execute( |
| 196 | 204 | "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2", |
| 197 | 205 | (user_id, community_id), |
| @@ -205,7 +213,7 @@ pub async fn is_banned( | ||
| 205 | 213 | user_id: &str, |
| 206 | 214 | community_id: &str, |
| 207 | 215 | conn: &Connection, |
| 208 | -) -> Result<bool, Error> { | |
| 216 | +) -> Result<bool, ServerError> { | |
| 209 | 217 | database::exists( |
| 210 | 218 | conn, |
| 211 | 219 | "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", |
| @@ -214,7 +222,7 @@ pub async fn is_banned( | ||
| 214 | 222 | .await |
| 215 | 223 | } |
| 216 | 224 | |
| 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> { | |
| 218 | 226 | let mut rows = conn |
| 219 | 227 | .query( |
| 220 | 228 | &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")), |