From c473ab216e3f28ae07780845cdd039f4418ee715 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 22:13:07 +0300 Subject: [PATCH] Run the engine on voelin_proto::link::Session The engine's voice source is now a voelin_proto::link::Session obtained from a registry of connectors (docs/session-seam.md, slice 1): - link::Backends keeps the plain connectors of voelin_proto::link::Connectors and the in-process ones that also hand the engine a port for TeamSpeak 6 streams; the scheme of the address picks the connector, an address without one is a TeamSpeak bookmark. - link::SessionLink is the engine's ServerLink. session.rs is unchanged and still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a voelin_model::replica::Replica, projects it into the client's older model (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives who talks from the media (link/media.rs), and turns every command into the Session call of its row. Transfers copy through read_file and write_file. - ts_session makes a TeamSpeak connection a Session: LinkSession over any ServerLink translates the link's commands, events and presence snapshots to v1 entities, pushes, answers and RTP; TsConnector makes them for ts3server:// and teamspeak:// addresses with TsLink inside, and LinkConnector for the link of Engine::start_with_link. - voice.rs opens the transfer connection itself for the new OpenRead and OpenWrite commands; files::download and upload are generic over the stream. - Engine::start_with_backends is new; start_with and start_with_link go through the registry. tests/link_fake.rs runs through both adapters; its fixtures are normalised as the design says (an order chain, database ids, talking from media, the server named, channel chat for the channel we are in), and the request id the link sees is the session's own. New unit tests cover every row of the mapping with a recording link, the TeamSpeak session on its own, media framing both ways, the talk tracker, the close table, the error texts, the backend and capability tables, the connect parameters, and the presence round trip on book fixtures and generated presences. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-core/Cargo.toml | 5 +- crates/voelin-core/src/book.rs | 300 +++ crates/voelin-core/src/cache.rs | 11 + crates/voelin-core/src/files.rs | 62 +- crates/voelin-core/src/lib.rs | 22 +- crates/voelin-core/src/link/backends.rs | 240 +++ crates/voelin-core/src/link/media.rs | 256 +++ .../voelin-core/src/{link.rs => link/mod.rs} | 85 +- crates/voelin-core/src/link/project.rs | 214 +++ crates/voelin-core/src/link/session_link.rs | 1674 +++++++++++++++++ crates/voelin-core/src/link/tests.rs | 1319 +++++++++++++ crates/voelin-core/src/ts_session/driver.rs | 1442 ++++++++++++++ crates/voelin-core/src/ts_session/entities.rs | 495 +++++ crates/voelin-core/src/ts_session/ids.rs | 115 ++ crates/voelin-core/src/ts_session/media.rs | 245 +++ crates/voelin-core/src/ts_session/mod.rs | 769 ++++++++ crates/voelin-core/src/voice.rs | 106 +- crates/voelin-core/tests/link_fake.rs | 53 +- 18 files changed, 7345 insertions(+), 68 deletions(-) create mode 100644 crates/voelin-core/src/link/backends.rs create mode 100644 crates/voelin-core/src/link/media.rs rename crates/voelin-core/src/{link.rs => link/mod.rs} (77%) create mode 100644 crates/voelin-core/src/link/project.rs create mode 100644 crates/voelin-core/src/link/session_link.rs create mode 100644 crates/voelin-core/src/link/tests.rs create mode 100644 crates/voelin-core/src/ts_session/driver.rs create mode 100644 crates/voelin-core/src/ts_session/entities.rs create mode 100644 crates/voelin-core/src/ts_session/ids.rs create mode 100644 crates/voelin-core/src/ts_session/media.rs create mode 100644 crates/voelin-core/src/ts_session/mod.rs diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 098e697..517a856 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -25,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"] [dependencies] anyhow = "1" base64 = "0.22" +# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`). +bytes = "1" dirs = "6" futures = "0.3" # Finding a server's gateway in DNS (the voice resolver's version). @@ -68,8 +70,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" } tsproto-types = { path = "../proto/tsproto-types" } [dev-dependencies] -# An HTTP/2 connection in a test (both already in the tree through h2). -bytes = "1" +# An HTTP/2 connection in a test (already in the tree through h2). http = "1" # Already in the app's graph (reqwest); for one_rustls_crypto_provider. rustls = { version = "0.23", default-features = false } diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index 98cc7f7..8d8e23b 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -331,4 +331,304 @@ mod tests { let p = presence_from_book(&book, None, |_| false); assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png")); } + + // ---- across the session seam --------------------------------------------- + + /// A presence made into the entities the TeamSpeak session writes + /// (`ts_session::entities`), pushed the way a host syncs them, and + /// projected back by the engine (`link::project`): what the UI is shown + /// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1). + fn through_the_seam(presence: &Presence, ts6: bool, own: Option) -> Presence { + use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId}; + use voelin_proto::link::Features; + use voelin_proto::v1::{self, push::Body}; + + use crate::link::media::TalkTracker; + use crate::link::project::{View, presence as project}; + use crate::ts_session::entities::build; + + let built = build(presence, ts6, own); + let mut replica = Replica::new(SCHEMA_GENERATION); + for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)] + { + replica.subscribe(scope); + let pushes = [ + Body::SyncBegin(v1::SyncBegin { + scope: Some(scope.to_proto()), + mode: v1::SyncMode::Full as i32, + epoch: 1, + }), + Body::Change(v1::Change { + scope: Some(scope.to_proto()), + rev: 1, + put: layer.values().cloned().collect(), + del: Vec::new(), + }), + Body::SyncEnd(v1::SyncEnd { + scope: Some(scope.to_proto()), + cursor: Some(v1::Cursor { epoch: 1, rev: 1 }), + gap: false, + }), + ]; + for body in pushes { + replica.apply_push(&v1::Push { body: Some(body) }); + } + } + let features = Features::new(["voice"]); + let talking = TalkTracker::default(); + project(&View { + replica: &replica, + server: 1, + teamspeak: true, + version: "", + features: &features, + streams: ts6, + talking: &talking, + }) + } + + /// A TeamSpeak 6 server and some clients with what the book holds of them. + fn ts6_presence() -> Presence { + let mut book = ts6_book(); + let list = format!( + "channellist {}|{}|{}", + channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), + channel( + 12, + 1, + "Raid", + r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2" + ), + channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"), + ); + book.handle_command(&message(&list)).unwrap(); + let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| { + format!( + "notifycliententerview reasonid=0 ctid={channel} clid={clid} \ + client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \ + client_unique_identifier=u{clid}= client_flag_avatar=abcdef \ + client_description=about\\sme client_icon_id=777 client_input_muted=1 \ + client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \ + client_output_hardware=1 client_meta_data client_is_recording=1 \ + client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \ + client_servergroups={groups} client_away={} client_away_message={away} \ + client_talk_power=75 client_talk_request=0 client_talk_request_msg \ + client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \ + client_nickname_phonetic client_needed_serverquery_view_power=75 \ + client_is_channel_commander=1 client_country=RU client_badges \ + client_myteamspeak_id=m{clid} client_integrations{avatar}", + 100 + u64::from(clid), + u8::from(!away.is_empty()), + ) + }; + for text in [ + enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"), + enter(6, 12, "8,9", "gone\\sfishing", ""), + enter(7, 12, "", "", " client_myteamspeak_avatar"), + ] { + book.handle_command(&message(&text)).unwrap(); + } + presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false) + } + + #[test] + fn a_book_is_what_the_ui_is_shown_across_the_seam() { + let p = ts6_presence(); + assert_eq!(p.clients.len(), 3, "the fixture has clients"); + assert!(p.clients.values().any(|c| c.away.is_some()), "one is away"); + // A TeamSpeak 6 client the book has no streaming flag of (it was not + // sent) is not streaming: v1 has no "unknown" for it. + let mut expected = p.clone(); + for client in expected.clients.values_mut() { + client.streaming = Some(client.streaming.unwrap_or(false)); + } + assert_eq!(through_the_seam(&p, true, Some(5)), expected); + // The same server as a TeamSpeak 3 one has no streams to tell of. + let mut ts3 = p.clone(); + for client in ts3.clients.values_mut() { + client.streaming = None; + } + assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3); + } + + /// A deterministic stream of numbers for the generated presences. + struct Numbers(u64); + + impl Numbers { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + fn flag(&mut self) -> bool { + self.below(2) == 0 + } + + fn text(&mut self, prefix: &str) -> String { + format!("{prefix}{}", self.below(1000)) + } + } + + /// A presence of the shape a TeamSpeak link reports: sibling channels in an + /// order chain, every client with a database id, unique ids that are base64 + /// (TeamSpeak 3 and 6) or login names, groups of both kinds. + fn generated(seed: u64, ts6: bool) -> Presence { + use base64::Engine as _; + use voelin_model::{ + BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, + HostMessageMode, + }; + let mut n = Numbers(seed | 1); + let mut p = Presence::default(); + let name = n.text("Server "); + p.server_name = name.clone(); + p.server = voelin_model::ServerDetails { + name, + uid: Some(n.text("uid")), + welcome_message: n.text("welcome "), + host_message: n.text("host "), + host_message_mode: [ + HostMessageMode::None, + HostMessageMode::Log, + HostMessageMode::Modal, + ][n.below(3) as usize], + banner_url: if n.flag() { n.text("https://b/") } else { String::new() }, + banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() }, + banner_gfx_interval_s: n.below(100), + banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect] + [n.below(3) as usize], + host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() }, + host_button_url: String::new(), + host_button_gfx_url: String::new(), + icon: n.below(5) as u32 * 1000, + platform: "Linux".into(), + version: n.text("6.0."), + max_clients: n.below(500) as u16, + priority_speaker_dimm_db: -(n.below(30) as i32), + default_server_group: Some(1 + n.below(9)), + default_channel_group: Some(1 + n.below(9)), + }; + // Groups. + for id in 1..=(2 + n.below(4)) { + let group = |id: u64, n: &mut Numbers| GroupInfo { + id, + name: n.text("group "), + icon: n.below(3) as u32 * 100, + sort_id: n.below(1000) as i32 - 500, + naming_mode: [ + GroupNamingMode::None, + GroupNamingMode::Before, + GroupNamingMode::After, + ][n.below(3) as usize], + group_type: [GroupType::Regular, GroupType::Template, GroupType::Query] + [n.below(3) as usize], + }; + p.server_groups.insert(id, group(id, &mut n)); + p.channel_groups.insert(id, group(id, &mut n)); + } + // Channels: a tree whose siblings follow each other. + let mut next_id = 1; + let mut parents = vec![0u64]; + for _ in 0..(3 + n.below(8)) { + let parent = parents[n.below(parents.len() as u64) as usize]; + let order = p + .channels + .values() + .filter(|c| c.parent == parent) + .map(|c| c.id) + .next_back() + .unwrap_or(0); + let id = next_id; + next_id += 1; + parents.push(id); + p.channels.insert( + id, + ChannelInfo { + id, + parent, + order, + name: n.text("channel "), + topic: n.flag().then(|| n.text("topic ")), + has_password: n.flag(), + max_clients: match n.below(3) { + 0 => None, + 1 => Some(0), + _ => Some(1 + n.below(50) as i32), + }, + needed_subscribe_power: n.below(3) as i32 * 10, + needed_talk_power: n.below(3) as i32 * 25, + is_default: id == 1, + icon: n.below(3) as u32 * 500, + banner_gfx_url: n.flag().then(|| n.text("https://c/")), + banner_mode: [ + BannerMode::NoAdjust, + BannerMode::IgnoreAspect, + BannerMode::KeepAspect, + ][n.below(3) as usize], + }, + ); + } + // Clients. + let channels: Vec = p.channels.keys().copied().collect(); + for id in 1..=(1 + n.below(12)) { + let id = id as u16; + let uid = match n.below(4) { + 0 => None, + 1 => Some(n.text("login")), + _ => { + let bytes: Vec = + (0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect(); + Some(base64::engine::general_purpose::STANDARD.encode(bytes)) + } + }; + let channel = channels[n.below(channels.len() as u64) as usize]; + p.clients.insert( + id, + ClientInfo { + id, + uid, + nickname: n.text("nick "), + channel, + is_query: n.below(5) == 0, + away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }), + input_muted: n.flag(), + output_muted: n.flag(), + talking: Some(false), + streaming: ts6.then(|| n.flag()), + server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(), + country: n.flag().then(|| "DE".into()), + avatar: n.flag().then(|| n.text("hash")), + myts_avatar: n.flag().then(|| n.text("https://a/")), + description: n.flag().then(|| n.text("about ")), + talk_power: n.below(100) as i32, + talker: n.flag(), + channel_group: n.flag().then(|| 1 + n.below(9)), + badges: (0..n.below(3)).map(|_| n.text("badge")).collect(), + icon: n.below(3) as u32 * 111, + recording: n.flag(), + priority_speaker: n.flag(), + channel_commander: n.flag(), + database_id: Some(1_000 + u64::from(id)), + }, + ); + } + p + } + + #[test] + fn generated_presences_survive_the_seam() { + for seed in 1..=200u64 { + for ts6 in [false, true] { + let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6); + let own = p.clients.keys().next().copied(); + assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}"); + } + } + } } diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index 4410be4..b2c1ae1 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20; /// does not hold a download slot. pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10; +/// How long a picture of `size` bytes may take to arrive: a minute, plus +/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow +/// links while a stalled transfer still ends. +pub(crate) fn image_download_time(size: u64) -> std::time::Duration { + std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE) +} + +/// How long the server may take to start an image transfer (a busy server +/// answers the requests of a large channel tree in turn). +pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30); + /// The cache key of a picture on the web: only `http` and `https` /// addresses (blanks around one are not part of it). pub(crate) fn picture_key(url: &str) -> Option { diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs index 493ff74..02ee04c 100644 --- a/crates/voelin-core/src/files.rs +++ b/crates/voelin-core/src/files.rs @@ -32,13 +32,13 @@ //! never downloaded). [`crate::Command::SetAvatar`] uploads our own. use std::fmt; +use std::future::Future; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; use serde::Serialize; -use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; -use tokio::net::TcpStream; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt}; /// Picked by the caller; the answer carries it back. pub type RequestId = u64; @@ -168,9 +168,10 @@ impl Progress<'_> { const CHUNK: usize = 64 * 1024; /// Receive a file: `size` bytes in total, `offset` of them already in the -/// sink. Reports `Started`, `Progress` and the final state. -pub(crate) async fn download( - mut stream: TcpStream, +/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the +/// final state. +pub(crate) async fn download( + mut stream: R, size: u64, offset: u64, sink: Sink, @@ -185,8 +186,8 @@ pub(crate) async fn download( }); } -async fn receive( - stream: &mut TcpStream, +async fn receive( + stream: &mut R, size: u64, offset: u64, sink: &Sink, @@ -253,26 +254,57 @@ async fn receive( } } -/// Send `file` from `offset` (`size` bytes in total). Reports `Started`, +/// How long a server may take to close a transfer connection after the last +/// byte before the upload counts as done anyway. +const CLOSE_WAIT: Duration = Duration::from_secs(30); + +/// Send `file` from `offset` (`size` bytes in total) over `stream`, a +/// connection the server closes once it has everything. Reports `Started`, /// `Progress` and the final state. -pub(crate) async fn upload( - mut stream: TcpStream, +pub(crate) async fn upload( + stream: S, file: PathBuf, size: u64, offset: u64, progress_every: Duration, report: Report, ) { + let (mut read, write) = tokio::io::split(stream); + let closed = async move { + let _ = tokio::time::timeout(CLOSE_WAIT, read.read(&mut [0u8; 1])).await; + Ok(()) + }; + upload_to(write, closed, file, size, offset, progress_every, report).await; +} + +/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end +/// it and wait for `stored`, which resolves once the server has the file. +/// Reports `Started`, `Progress` and the final state. +pub(crate) async fn upload_to( + mut writer: W, + stored: F, + file: PathBuf, + size: u64, + offset: u64, + progress_every: Duration, + report: Report, +) where + W: AsyncWrite + Unpin, + F: Future>, +{ report(TransferState::Started { size, offset }); - let result = send(&mut stream, &file, size, offset, progress_every, &report).await; + let result = match send(&mut writer, &file, size, offset, progress_every, &report).await { + Ok(()) => stored.await, + Err(e) => Err(e), + }; report(match result { Ok(()) => TransferState::Done { size, path: Some(file), data: None }, Err(e) => TransferState::Failed(e), }); } -async fn send( - stream: &mut TcpStream, +async fn send( + stream: &mut W, path: &Path, size: u64, offset: u64, @@ -300,8 +332,6 @@ async fn send( } stream.flush().await.map_err(|e| e.to_string())?; stream.shutdown().await.map_err(|e| e.to_string())?; - // The server closes the connection once it has everything. - let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await; Ok(()) } @@ -421,7 +451,7 @@ fn percent_decode(text: &str) -> Option { mod tests { use std::sync::Mutex; - use tokio::net::TcpListener; + use tokio::net::{TcpListener, TcpStream}; use super::*; diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 8cda54b..3ee7868 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -67,6 +67,7 @@ mod stream_types; #[cfg(feature = "media")] pub mod studio; mod ts_link; +mod ts_session; pub mod versions; mod voice; mod web; @@ -91,6 +92,7 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta pub use gateway::{GatewayRequest, GatewayUpdate}; use history::SharedHistory; pub use history::{History, HistoryMessage, HistorySource}; +pub use link::Backends; pub use link::ConnectOptions; pub use link::ConnectOptions as VoiceOptions; pub use link::ServerLink; @@ -792,19 +794,33 @@ impl Engine { } /// Start the engine on the current tokio runtime with `settings` and - /// chat `history`, connecting voice with [`TsLink`]. + /// chat `history`, connecting voice with the engine's own connectors + /// ([`Backends::default`]: TeamSpeak 3 and 6). pub fn start_with(settings: Settings, history: History) -> Self { - Self::start_with_link(settings, history, Arc::new(TsLink)) + Self::start_with_backends(settings, history, Backends::default()) } /// Start the engine on the current tokio runtime with `settings` and /// chat `history`, connecting voice with `link` (every session's voice - /// source is one of its connections, see [`link`]). + /// source is one of its connections, see [`link`]). The engine reaches + /// `link` as a `voelin_proto::link::Session` of its own, for every + /// address, like it does a connector's. pub fn start_with_link( settings: Settings, history: History, link: Arc, ) -> Self { + let mut backends = Backends::empty(); + backends.register_local(Arc::new(ts_session::LinkConnector::any(link))); + Self::start_with_backends(settings, history, backends) + } + + /// Start the engine on the current tokio runtime with `settings` and + /// chat `history`, connecting voice with the connectors in `backends`: + /// the one for the scheme of a session's address makes its + /// `voelin_proto::link::Session`. + pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self { + let link: Arc = Arc::new(link::SessionLink::new(backends)); let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. diff --git a/crates/voelin-core/src/link/backends.rs b/crates/voelin-core/src/link/backends.rs new file mode 100644 index 0000000..bca8c29 --- /dev/null +++ b/crates/voelin-core/src/link/backends.rs @@ -0,0 +1,240 @@ +//! The registry of the engine's connectors, by address scheme. +//! +//! A session's voice source is a `voelin_proto::link::Session` +//! (`docs/session-seam.md` section 4.1). Which backend makes it is the +//! scheme of the address: [`Backends`] holds the plain connectors of +//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector +//! later, `FakeConnector` in tests) and the in-process connectors, which +//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6 +//! stream task, [`StreamPort`]). + +use std::sync::Arc; + +use tokio::sync::{mpsc, watch}; +use voelin_proto::link::{ + AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity, + HostTrust, SessionError, +}; +use voelin_stream::PeerConfig; + +use super::LinkCtx; +use crate::stream::{OwnStreamEvent, StreamCmd}; + +/// The scheme of the TeamSpeak servers a bookmark names without one. +pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server"; + +/// What comes back from the stream task of a connection that has one. +#[derive(Debug)] +pub(crate) enum StreamEvent { + /// Our own stream's life, for the gateway directory. + OwnStream(OwnStreamEvent), + /// An Opus frame of a watched stream, for the audio thread. + Audio { stream: String, time: u64, data: Arc<[u8]> }, + /// A watched stream ended. + AudioEnded(String), +} + +/// The in-process channel of TeamSpeak 6 streams past the `Session` trait +/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer +/// and not v1 entities yet, so the commands go to the connection's stream +/// task and its events come back here. +pub(crate) struct StreamPort { + send: Box, + /// What the stream task reports. + pub(crate) events: mpsc::UnboundedReceiver, +} + +impl StreamPort { + /// A port whose commands go to `send`. + pub(crate) fn new( + send: impl Fn(StreamCmd) + Send + Sync + 'static, + events: mpsc::UnboundedReceiver, + ) -> Self { + Self { send: Box::new(send), events } + } + + /// Give the stream task a command. + pub(crate) fn send(&self, cmd: StreamCmd) { + (self.send)(cmd); + } +} + +/// What an in-process backend needs besides the connect parameters. +#[derive(Clone)] +pub(crate) struct LocalCtx { + /// The session's side of the engine: its id, event bus, frames and + /// settings, and the account proof watches. + pub(crate) link: LinkCtx, + /// Open the audio devices (the stream task plays what streams carry). + pub(crate) audio: bool, + /// Network settings for stream peer connections. + pub(crate) stream_peer: PeerConfig, + /// Keeps the senders of `link`'s watches alive when there is no engine. + _keep: Option>, +} + +impl LocalCtx { + pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self { + Self { link, audio, stream_peer, _keep: None } + } + + /// A context for a connection made outside an engine (a test or a tool + /// that calls a connector itself): a session of its own that nobody + /// listens to. + pub(crate) fn standalone() -> Self { + let (events, _) = tokio::sync::broadcast::channel(16); + let (frames, _) = tokio::sync::broadcast::channel(16); + let (identity_tx, myts_identity) = watch::channel(None); + let (data_tx, myts_data) = watch::channel(None); + let link = LinkCtx { + session: 0, + events, + frames, + settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()), + myts_identity, + myts_data, + }; + Self { + link, + audio: false, + stream_peer: PeerConfig::default(), + _keep: Some(Arc::new((identity_tx, data_tx))), + } + } +} + +/// A connection an in-process connector made. +pub(crate) struct LocalConnected { + pub(crate) connected: Connected, + /// The stream task's port, for a backend that runs one. + pub(crate) streams: Option, +} + +/// A connector that runs in this process and can use the engine's context +/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`]. +pub(crate) trait LocalConnector: Connector { + /// Whether this connector serves addresses of `scheme`. By default, the + /// schemes it names. + fn accepts(&self, scheme: &str) -> bool { + self.schemes().contains(&scheme) + } + + /// Connect with the engine's context. + fn connect_local( + &self, + params: ConnectParams, + ctx: LocalCtx, + ) -> BoxFuture>; +} + +/// The connectors of an engine, found by the scheme of an address. +/// +/// A scheme served by an in-process connector goes to it, one served by a +/// plain connector ([`Backends::register`]) to that. An address without a +/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one. +#[derive(Clone)] +pub struct Backends { + connectors: Connectors, + locals: Vec>, + account: Option>, + /// The connections' trust in hosts that are neither valid nor pinned. + trust: Option>, +} + +impl Default for Backends { + /// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and + /// `teamspeak://`, and an address without a scheme). + fn default() -> Self { + let mut backends = Self::empty(); + backends.register_local(Arc::new(crate::ts_session::TsConnector::new())); + backends + } +} + +impl Backends { + /// No connector at all. ([`Backends::default`] has the TeamSpeak one.) + pub fn empty() -> Self { + Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None } + } + + /// Register a connector for the schemes it names. + pub fn register(&mut self, connector: Arc) { + self.connectors.register(connector); + } + + pub(crate) fn register_local(&mut self, connector: Arc) { + self.locals.push(connector); + } + + /// The device's Voelin account, for the connectors that use it (the QUIC + /// connector's certificate, the TeamSpeak connector's myTS ID proof). + /// None is the default: nothing uses an account yet. + pub fn set_account(&mut self, agent: Option>) { + self.account = agent; + } + + /// The account agent, if one was set ([`Backends::set_account`]). + pub fn account(&self) -> Option> { + self.account.clone() + } + + /// Decide about hosts that are neither valid nor pinned. The default + /// refuses them: there is no trust dialog yet, and TeamSpeak has no host + /// key. + pub fn set_trust(&mut self, trust: Option>) { + self.trust = trust; + } + + pub(crate) fn trust(&self) -> Arc { + self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts)) + } + + /// The scheme of an address, lowercase; a TeamSpeak bookmark's when there + /// is none. + pub(crate) fn scheme(address: &str) -> String { + match address.split_once("://") { + Some((scheme, _)) => scheme.to_ascii_lowercase(), + None => TEAMSPEAK_SCHEME.to_owned(), + } + } + + /// Open a session to `params.address` with the connector of its scheme. + pub(crate) fn connect( + &self, + params: ConnectParams, + ctx: LocalCtx, + ) -> BoxFuture> { + let scheme = Self::scheme(¶ms.address); + if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) { + return local.connect_local(params, ctx); + } + let connect = self.connectors.connect(params); + Box::pin(async move { + let connected = connect.await?; + Ok(LocalConnected { connected, streams: None }) + }) + } +} + +/// Refuses every host that asks to be trusted. +struct RefuseUnknownHosts; + +impl HostTrust for RefuseUnknownHosts { + fn confirm(&self, _host: HostIdentity) -> BoxFuture { + Box::pin(async { false }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_bookmark_without_a_scheme_is_a_teamspeak_server() { + assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server"); + assert_eq!(Backends::scheme("[::1]:9987"), "ts3server"); + assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server"); + assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak"); + assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin"); + } +} diff --git a/crates/voelin-core/src/link/media.rs b/crates/voelin-core/src/link/media.rs new file mode 100644 index 0000000..efd63f8 --- /dev/null +++ b/crates/voelin-core/src/link/media.rs @@ -0,0 +1,256 @@ +//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1): +//! our encoded frames as RTP on our voice slot, the RTP of other slots as +//! the audio thread's packets, and who is talking from the media. +//! +//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio +//! thread speaks; this is the framing in the v1 media codec +//! (`voelin_proto::media`, protocol section 6). + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use bytes::BytesMut; +use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket}; +use voelin_proto::link::{FlowId, MediaPacket, voice_sub}; +use voelin_proto::media::opus::{self, Toc}; +use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS}; +use voelin_proto::media::{RtpHeader, RtpView}; + +/// A talker is silent after this long without a packet. +pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400); + +/// Our voice as RTP: the sequence number counts every packet from 0, the +/// timestamp starts at 0 and advances by the duration of the previous +/// packet, the marker is set on the first packet of a spurt, and the end of a +/// spurt is a packet with an empty payload, sent once. +#[derive(Default)] +pub(crate) struct Uplink { + sequence: u16, + timestamp: u32, + /// The ticks the last voice packet spans. + ticks: u32, + in_spurt: bool, +} + +impl Uplink { + /// `voice` as the RTP packet of our voice slot. + pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option { + let flow = FlowId::new(slot, voice_sub::CHANNEL); + // The previous packet's duration has passed. + self.timestamp = self.timestamp.wrapping_add(self.ticks); + let end = voice.is_end(); + let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp); + header.marker = !end && !self.in_spurt; + self.ticks = + if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) }; + self.in_spurt = !end; + self.sequence = self.sequence.wrapping_add(1); + let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len()); + header.write(flow, &mut out).ok()?; + out.extend_from_slice(&voice.payload); + Some(MediaPacket { flow, rtp: out.freeze() }) + } +} + +/// A voice packet of some slot, taken from its RTP. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Incoming { + pub(crate) slot: u32, + /// Sent on a whisper sub-flow (1 to 6). + pub(crate) whisper: bool, + pub(crate) sequence: u16, + pub(crate) codec: VoiceCodec, + /// Empty: the spurt ends. + pub(crate) payload: Vec, +} + +impl Incoming { + /// Parse a media packet. `None` for what is not the voice of a slot: + /// feedback, probes, a flow that is no media, a packet that is no RTP. + pub(crate) fn parse(packet: &MediaPacket) -> Option { + if !packet.flow.is_media() { + return None; + } + let view = RtpView::parse(&packet.rtp).ok()?; + let payload = view.payload(); + // Stereo Opus is music; the jitter buffer decodes both the same way. + let codec = match Toc::parse(payload) { + Ok(toc) if toc.stereo() => VoiceCodec::Music, + _ => VoiceCodec::Voice, + }; + Some(Incoming { + slot: packet.flow.slot(), + whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET) + .contains(&packet.flow.sub()), + sequence: view.sequence(), + codec, + payload: payload.to_vec(), + }) + } + + /// The packet for the audio thread, from `talker`. + pub(crate) fn voice(self, talker: u16) -> VoicePacket { + VoicePacket { + talker: TalkerId(talker), + seq: self.sequence, + codec: self.codec, + whisper: self.whisper, + payload: self.payload, + } + } +} + +/// Who is talking: derived from the media (protocol section 6.4). A talker +/// starts with its first packet and stops after [`TALK_SILENCE`] without one. +#[derive(Default)] +pub(crate) struct TalkTracker { + last: HashMap, +} + +impl TalkTracker { + /// A packet of `client` arrived; whether this starts its talking. + pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool { + self.last.insert(client, now).is_none() + } + + /// The talkers that have been silent long enough, no longer talking. + pub(crate) fn expire(&mut self, now: Instant) -> Vec { + let mut silent: Vec = self + .last + .iter() + .filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE) + .map(|(client, _)| *client) + .collect(); + silent.sort_unstable(); + for client in &silent { + self.last.remove(client); + } + silent + } + + pub(crate) fn is_talking(&self, client: u16) -> bool { + self.last.contains_key(&client) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 20 ms of CELT, mono, one frame. + const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02]; + + fn voice(payload: &[u8]) -> EncodedVoice { + EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() } + } + + fn view(packet: &MediaPacket) -> RtpView<'_> { + RtpView::parse(&packet.rtp).unwrap() + } + + #[test] + fn our_voice_is_sequenced_stamped_and_marked() { + let mut up = Uplink::default(); + let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0)); + let (a, b) = (view(&first), view(&second)); + assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true)); + assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false)); + assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS)); + assert_eq!(a.payload(), OPUS_20_MS); + } + + #[test] + fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() { + let mut up = Uplink::default(); + up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + let end = up.frame(8, &voice(&[])).unwrap(); + assert!(view(&end).payload().is_empty() && !view(&end).marker()); + assert_eq!(view(&end).sequence(), 1); + let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + assert!(view(&next).marker()); + assert_eq!(view(&next).sequence(), 2); + } + + #[test] + fn the_sequence_wraps() { + let mut up = Uplink { sequence: u16::MAX, ..Default::default() }; + up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap(); + assert_eq!(view(&wrapped).sequence(), 0); + } + + #[test] + fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() { + let flow = FlowId::new(9, 0); + let mut header = RtpHeader::new(PT_OPUS, 513, 0); + header.marker = true; + let mut rtp = BytesMut::new(); + header.write(flow, &mut rtp).unwrap(); + rtp.extend_from_slice(&OPUS_20_MS); + let packet = MediaPacket { flow, rtp: rtp.freeze() }; + let got = Incoming::parse(&packet).unwrap(); + assert_eq!( + got, + Incoming { + slot: 9, + whisper: false, + sequence: 513, + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec() + } + ); + let voice = got.voice(8); + assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false)); + } + + #[test] + fn whispers_stereo_ends_and_what_is_no_voice() { + let packet = |flow: FlowId, payload: &[u8]| { + let mut rtp = BytesMut::new(); + RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap(); + rtp.extend_from_slice(payload); + MediaPacket { flow, rtp: rtp.freeze() } + }; + assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper); + assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper); + let stereo = [OPUS_20_MS[0] | 0x04, 1, 2]; + assert_eq!( + Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec, + VoiceCodec::Music + ); + let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap(); + assert!(end.payload.is_empty() && end.voice(8).is_end()); + // Feedback and probes are no voice. + assert!( + Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() }) + .is_none() + ); + assert!( + Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() }) + .is_none() + ); + assert!( + Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() }) + .is_none() + ); + } + + #[test] + fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() { + let mut talk = TalkTracker::default(); + let t0 = Instant::now(); + assert!(talk.heard(8, t0)); + assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking"); + assert!(talk.heard(9, t0 + Duration::from_millis(150))); + assert!(talk.is_talking(8)); + // 399 ms after 8's last packet: still talking. + assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty()); + assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]); + assert!(!talk.is_talking(8) && talk.is_talking(9)); + assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]); + // A packet after the silence starts it again. + assert!(talk.heard(8, t0 + Duration::from_secs(2))); + } +} diff --git a/crates/voelin-core/src/link.rs b/crates/voelin-core/src/link/mod.rs similarity index 77% rename from crates/voelin-core/src/link.rs rename to crates/voelin-core/src/link/mod.rs index 52369ad..dc71d09 100644 --- a/crates/voelin-core/src/link.rs +++ b/crates/voelin-core/src/link/mod.rs @@ -54,20 +54,34 @@ //! //! # Implementations //! +//! The engine's own implementation is [`SessionLink`]: it connects through +//! [`Backends`], the registry of connectors by address scheme, and talks to +//! the `voelin_proto::link::Session` it gets (`session_link.rs`, with +//! `project.rs` and `media.rs`). Nothing of a backend shows above it: +//! `session.rs` keeps speaking [`LinkCmd`] and [`LinkEvent`], and SessionLink +//! turns them into `Session` calls and the session's pushes and media into +//! events (`docs/session-seam.md` describes the mapping row by row). +//! //! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the -//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now, -//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes -//! another (the tests drive the session with an in-memory one, -//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this -//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and -//! the Voelin protocol's QUIC transport becomes the other implementation, -//! both behind the backend-neutral `voelin_proto::link::Session` of -//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then. +//! TeamSpeak 3 and 6 connection of `tsclientlib`. It is a `ServerLink` of this +//! older vocabulary, and the engine reaches it as a `Session`: the +//! `ts_session` module wraps any `ServerLink` in a `Session` (`LinkSession`, +//! made by `TsConnector` for `ts3server://` and `teamspeak://` addresses). +//! [`Engine::start_with_link`](crate::Engine::start_with_link) takes another +//! link the same way (the tests drive the session with an in-memory one, +//! `tests/link_fake.rs`), and +//! [`Engine::start_with_backends`](crate::Engine::start_with_backends) takes +//! connectors of `Session`s. The decoupling plan moves the TeamSpeak side out +//! of this crate into the TeamSpeak gateway (VoelinGateWay, +//! `voelin-gateway-ts`), and the Voelin protocol's QUIC transport becomes the +//! other implementation, both behind the backend-neutral +//! `voelin_proto::link::Session` of VoelinProtocol. //! //! # What is still TeamSpeak's //! -//! The seam is not backend-neutral yet. What still has TeamSpeak types or -//! TeamSpeak's shape, and changes when `TsLink` leaves: +//! The vocabulary of [`ServerLink`], and of the engine above it, is not +//! backend-neutral yet. What still has TeamSpeak types or TeamSpeak's shape, +//! and changes when the TeamSpeak side leaves: //! //! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and //! [`ConnectOptions::client_version`] (`tsclientlib`), and the account @@ -84,12 +98,27 @@ //! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame` //! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in //! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same -//! API (re-exported from [`crate::stream`]). +//! API (re-exported from [`crate::stream`]). TeamSpeak 6 streams are peer +//! to peer, so their commands and events pass the `Session` through a local +//! port for now. + +mod backends; +pub(crate) mod media; +pub(crate) mod project; +mod session_link; +#[cfg(test)] +mod tests; + +pub use backends::Backends; +pub(crate) use backends::{LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort}; +pub(crate) use session_link::SessionLink; use std::path::PathBuf; +use std::pin::Pin; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc, watch}; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; use voelin_audio::{EncodedVoice, VoicePacket}; use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence}; use voelin_stream::PeerConfig; @@ -197,6 +226,17 @@ pub struct Remote { pub path: String, } +/// A boxed stream of bytes to read: the body of a file the server sends. +pub type BoxRead = Pin>; + +/// A connection that can be read and written: a file transfer connection. +pub trait Duplex: AsyncRead + AsyncWrite + Send {} + +impl Duplex for T {} + +/// A boxed [`Duplex`]. +pub type BoxDuplex = Pin>; + /// What the session asks of a connection. pub enum LinkCmd { SendChat(ChatTarget, String), @@ -232,6 +272,27 @@ pub enum LinkCmd { report: Report, }, CancelTransfer(TransferId), + /// Open a file of the server for reading, from `offset`: the transfer + /// connection itself, and the file's size in all, once the server has + /// agreed (the text of the failure otherwise). The engine copies the + /// bytes, reports the progress and cancels by dropping the connection, so + /// this does not use [`LinkCmd::Download`]'s sink and report. + OpenRead { + file: Remote, + offset: u64, + reply: oneshot::Sender>, + }, + /// Open a file of the server for writing: the transfer connection and the + /// position the server wants the bytes from (the size it already has, if + /// `resume`). The engine writes the bytes and ends the connection. + OpenWrite { + file: Remote, + /// The file's size in all. + size: u64, + overwrite: bool, + resume: bool, + reply: oneshot::Sender>, + }, DeleteFiles { /// `None`: best effort, nobody waits for the answer. request: Option, diff --git a/crates/voelin-core/src/link/project.rs b/crates/voelin-core/src/link/project.rs new file mode 100644 index 0000000..d152a6c --- /dev/null +++ b/crates/voelin-core/src/link/project.rs @@ -0,0 +1,214 @@ +//! The engine's view of a session's replica, in the client's older model +//! (`docs/session-seam.md` section 5.3). +//! +//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`, +//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and +//! [`chat_message`] project the replica into them with +//! `voelin_model::replica::convert`, and fix up where that says less than the +//! older model does (F1 to F10 of the design). The fix-ups apply the +//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the +//! ids it has; they go when the UI reads the replica. + +use std::collections::BTreeMap; + +use voelin_model::replica::{Replica, convert}; +use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails}; +use voelin_proto::link::Features; +use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope}; + +use super::media::TalkTracker; +use crate::ts_session::entities::user_uid; +use crate::ts_session::ids::{self, FOREIGN_SYSTEM}; + +/// What the projection needs to know besides the replica. +pub(crate) struct View<'a> { + pub(crate) replica: &'a Replica, + /// The server of the session. + pub(crate) server: u64, + /// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules + /// (channel groups) are undone. + pub(crate) teamspeak: bool, + /// The version the host said (`Welcome.host.backend.version`). + pub(crate) version: &'a str, + pub(crate) features: &'a Features, + /// Whether the connection has streams (a port, not just the feature). + pub(crate) streams: bool, + pub(crate) talking: &'a TalkTracker, +} + +/// What a `Foreign` of TeamSpeak holds under `key`. +fn foreign_value( + foreign: Option<&v1::Foreign>, + kind: &str, + key: &str, +) -> Option { + let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?; + serde_json::from_slice::(&foreign.json).ok()?.get(key).cloned() +} + +/// The server's unique id as the client keys its history and aliases by it: +/// the host's without the `ts:` of protocol section 11.2 (F3). +pub(crate) fn server_key(uid: &str) -> String { + uid.strip_prefix("ts:").unwrap_or(uid).to_owned() +} + +/// The client's older model of the server (what `LinkEvent::Presence` holds). +pub(crate) fn presence(view: &View<'_>) -> Presence { + let replica = view.replica; + let server = view.server; + // F1: only what the older model calls channels. + let channels: Vec<&v1::Channel> = replica + .channels(server) + .filter(|channel| { + !matches!( + ChannelKind::try_from(channel.kind), + Ok(ChannelKind::ServerChat + | ChannelKind::Dm + | ChannelKind::GroupDm + | ChannelKind::Thread) + ) + }) + .collect(); + let by_id: BTreeMap = channels.iter().map(|c| (c.id, *c)).collect(); + let channel_infos = convert::channel_infos(&channels) + .into_iter() + .map(|mut info| { + // F7: a limit of 0 is a limit, not "unlimited". + let zero = by_id + .get(&info.id) + .and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients")); + if zero.and_then(|v| v.as_i64()) == Some(0) { + info.max_clients = Some(0); + } + (info.id, info) + }) + .collect(); + + let clients = replica + .voice_states(server) + .filter_map(|voice| { + let user = replica.user(voice.user_id); + let member = replica.member(server, voice.user_id); + let mut client = + convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?; + // F10: a unique id that is no base64 rides in `Foreign`. + client.uid = user.and_then(user_uid); + // F2: the client's channel group is TeamSpeak's own number. + if view.teamspeak { + client.channel_group = client.channel_group.map(ids::channel_group); + } + // F6: the client's icon. + client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon") + .and_then(|v| v.as_u64()) + .and_then(|v| u32::try_from(v).ok()) + .unwrap_or(0); + // F8: who is talking comes from the media. + client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id)); + // F9: the stream flag only where there are streams. + if !view.streams { + client.streaming = None; + } + Some((client.id, client)) + }) + .collect(); + + let mut server_groups: BTreeMap = BTreeMap::new(); + let mut channel_groups: BTreeMap = BTreeMap::new(); + for role in replica.roles(server) { + let mut info = convert::group_info(role); + if role.scope == RoleScope::Channel as i32 { + if view.teamspeak { + info.id = ids::channel_group(info.id); + } + channel_groups.insert(info.id, info); + } else { + server_groups.insert(info.id, info); + } + } + + let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default(); + Presence { + server_name: details.name.clone(), + channels: channel_infos, + clients, + server: details, + server_groups, + channel_groups, + } +} + +/// `convert::server_details` with F2 to F5. +fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails { + let mut details = convert::server_details(server); + // F3: the unique id as the client keys it. + details.uid = details.uid.as_deref().map(server_key); + let foreign = server.foreign.as_ref(); + // F4: the version the server sent, else the one the host reports. + details.version = foreign_value(foreign, "server", "version") + .and_then(|v| v.as_str().map(str::to_owned)) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| view.version.to_owned()); + // F5: the server's platform. + details.platform = foreign_value(foreign, "server", "platform") + .and_then(|v| v.as_str().map(str::to_owned)) + .unwrap_or_default(); + // F2: the default channel group is TeamSpeak's own number. + if view.teamspeak { + details.default_channel_group = details.default_channel_group.map(ids::channel_group); + } + details +} + +/// Where the older model files the messages of a channel (the replica's +/// `chat_target`, with the unique id of F10). +fn chat_target(replica: &Replica, channel: u64) -> ChatTarget { + let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) }; + match ChannelKind::try_from(info.kind) { + Ok(ChannelKind::ServerChat) => ChatTarget::Server, + Ok(ChannelKind::Dm | ChannelKind::GroupDm) => { + let own = replica.own_user(); + info.recipients + .iter() + .copied() + .find(|id| *id != own) + .and_then(|id| replica.user(id)) + .and_then(user_uid) + .map_or(ChatTarget::Channel(channel), ChatTarget::Private) + } + _ => ChatTarget::Channel(channel), + } +} + +/// A message of the replica as the older model has it. +pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option { + let message = replica.message(channel, id)?; + let author = replica.user(message.author_id); + let name = Some(message.author_name.as_str()) + .filter(|name| !name.is_empty()) + .or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty())) + .unwrap_or_default(); + Some(ChatMessage { + target: chat_target(replica, channel), + author_name: name.to_owned(), + author_uid: author.and_then(user_uid), + author_id: (message.author_participant != 0) + .then(|| u16::try_from(message.author_participant).ok()) + .flatten(), + text: message.text.clone(), + ts_ms: message.ts_ms, + via_relay: message.flags & MessageFlag::Relayed as u32 != 0, + blocked: false, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_ts_prefix_of_a_server_uid_goes() { + assert_eq!(server_key("ts:abc="), "abc="); + assert_eq!(server_key("abc="), "abc="); + assert_eq!(server_key(""), ""); + } +} diff --git a/crates/voelin-core/src/link/session_link.rs b/crates/voelin-core/src/link/session_link.rs new file mode 100644 index 0000000..0359274 --- /dev/null +++ b/crates/voelin-core/src/link/session_link.rs @@ -0,0 +1,1674 @@ +//! [`SessionLink`]: the engine's [`ServerLink`], over a +//! `voelin_proto::link::Session` (`docs/session-seam.md` sections 3 and 4). +//! +//! `session.rs` hands a link its [`ConnectOptions`] and a [`LinkCtx`] and +//! talks to it with [`LinkCmd`]s and [`LinkEvent`]s. SessionLink opens the +//! session through [`Backends`], runs the connect sequence (the server, the +//! HOME, SERVER and LIVE scopes, the seat in voice), keeps a replica of what +//! the host pushes and projects it into the older model, and turns every +//! command into the `Session` call that stands for it. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use tokio::sync::mpsc; +use tokio::task::AbortHandle; +use tracing::{debug, info, warn}; +use voelin_audio::EncodedVoice; +use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId}; +use voelin_model::{Capabilities, ChatTarget, Presence, split_channel_path}; +use voelin_proto::link::{ + CloseReason, Connected, Download, Features, MediaClass, MediaPacket, MediaSink, Sent, Session, + SessionError, Upload, +}; +use voelin_proto::v1::{ + self, Entity, ErrorCode, ScopeKind, entity::Kind, push::Body, request::Op, + response::Result as Answer, +}; + +use super::media::{Incoming, TalkTracker, Uplink}; +use super::project::{self, View}; +use super::{ + Backends, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalCtx, Remote, + ServerLink, StreamEvent, StreamPort, +}; +use crate::files::{self, FileEntry, Report, Sink, TransferId, TransferState}; +use crate::offline::{OfflineMessage, OfflineMessageInfo}; +use crate::settings::FILES_PROGRESS_MS; +use crate::{BackendInfo, Event, JoinFailure}; + +/// How long the connect sequence may take after the connection is made. +const SYNC_TIME: Duration = Duration::from_secs(30); +/// How long a closing session may take to end. +const CLOSE_TIME: Duration = Duration::from_secs(10); +/// Most CHAT scopes the engine subscribes (`Limits.max_chat_subscriptions`). +const MAX_CHAT_SCOPES: usize = 16; + +/// Starts the voice connections of an engine: each one a `Session` from the +/// connector of its address (`docs/session-seam.md` section 4). +pub(crate) struct SessionLink { + backends: Arc, +} + +impl SessionLink { + pub(crate) fn new(backends: Backends) -> Self { + Self { backends: Arc::new(backends) } + } +} + +impl ServerLink for SessionLink { + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + tokio::spawn(run(self.backends.clone(), options, ctx, cmds, events)); + } +} + +/// Receives media on the transport's task and queues it for the loop. +struct MediaQueue(mpsc::UnboundedSender); + +impl MediaSink for MediaQueue { + fn media(&self, packet: MediaPacket) { + let _ = self.0.send(packet); + } +} + +// ---- texts ------------------------------------------------------------------ + +/// What a `SessionError` says to the user (`docs/session-seam.md` 4.6). +pub(crate) fn text(error: &SessionError, connecting: bool) -> String { + match error { + SessionError::Rejected(e) => e.message.clone(), + SessionError::Closed(reason) => close_text(reason).unwrap_or_default(), + SessionError::Timeout if connecting => "timed out while connecting".into(), + SessionError::Timeout => "timed out".into(), + SessionError::Unsupported(feature) => format!("not offered by this server: {feature}"), + SessionError::HostIdentity(text) | SessionError::Protocol(text) => text.clone(), + SessionError::Io(e) => e.to_string(), + } +} + +/// Why a connection ended, as `LinkEvent::Disconnected` says it (4.5): `None` +/// when we asked for it, or the host closed it normally without a reason. +pub(crate) fn close_text(reason: &CloseReason) -> Option { + match reason { + CloseReason::Local(_) => None, + CloseReason::Network(reason) => Some(reason.clone()), + CloseReason::TimedOut => Some("timed out".into()), + CloseReason::Remote { code, reason } if !reason.is_empty() => { + let _ = code; + Some(reason.clone()) + } + CloseReason::Remote { code, .. } => { + let named = i32::try_from(*code).ok().and_then(|c| v1::CloseCode::try_from(c).ok()); + match named { + Some(v1::CloseCode::Normal) => None, + Some(v1::CloseCode::AuthFailed) => Some("authentication failed".into()), + Some(v1::CloseCode::Protocol) => Some("protocol error".into()), + Some(v1::CloseCode::Kicked) => Some("kicked".into()), + Some(v1::CloseCode::Banned) => Some("banned".into()), + Some(v1::CloseCode::Shutdown) => Some("server shut down".into()), + Some(v1::CloseCode::Replaced) => Some("replaced by another connection".into()), + Some(v1::CloseCode::Version) => Some("version not supported".into()), + Some(v1::CloseCode::Idle) => Some("idle timeout".into()), + Some(v1::CloseCode::RateLimited) => Some("rate limited".into()), + Some(v1::CloseCode::TooSlow) => Some("too slow".into()), + Some(v1::CloseCode::Revoked) => Some("access revoked".into()), + None => Some(format!("closed by the host (code {code})")), + } + } + } +} + +/// How a failed connect shows: the reason of `Disconnected`. +fn connect_failure(error: &SessionError) -> Option { + match error { + SessionError::Closed(reason) => close_text(reason), + other => Some(text(other, true)), + } +} + +/// The software of a host as the engine names it (`docs/session-seam.md` +/// 4.7): a TeamSpeak flavor becomes the product and generation people know. +pub(crate) fn backend_info(backend: &v1::BackendInfo) -> BackendInfo { + let product = match (backend.product.as_str(), backend.flavor.as_str()) { + ("teamspeak", "ts3") => "TeamSpeak 3".to_owned(), + ("teamspeak", "ts6") => "TeamSpeak 6".to_owned(), + // A TeamSpeak server that was not recognised: only the version the + // server sent. + ("teamspeak", _) => String::new(), + (other, _) => other.to_owned(), + }; + BackendInfo { product, version: backend.version.clone() } +} + +/// What the host can do, as the UI hides and shows things by it (4.7). The +/// ServerQuery access modes describe a TeamSpeak server, not the session: +/// they follow the flavor. +pub(crate) fn capabilities( + features: &Features, + backend: &v1::BackendInfo, + streams: bool, +) -> Capabilities { + let teamspeak = backend.product == "teamspeak"; + Capabilities { + streams: features.has("streams") && streams, + raw_query: teamspeak && backend.flavor == "ts3", + ssh_query: teamspeak && matches!(backend.flavor.as_str(), "ts3" | "ts6"), + http_query: teamspeak && backend.flavor == "ts6", + file_transfer: features.has("files"), + offline_messages: features.has("mailbox"), + } +} + +// ---- the connection ----------------------------------------------------------- + +async fn run( + backends: Arc, + options: ConnectOptions, + ctx: LinkCtx, + mut cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +) { + let reason = drive(&backends, &options, &ctx, &mut cmds, &events).await; + let _ = events.send(LinkEvent::Disconnected(reason)); +} + +/// Wait until the session is told to go; commands that come before are kept. +async fn until_disconnect( + cmds: &mut mpsc::UnboundedReceiver, + early: &mut VecDeque, +) { + loop { + match cmds.recv().await { + None | Some(LinkCmd::Disconnect) => return, + Some(cmd) => early.push_back(cmd), + } + } +} + +/// Connect and run the connection; the reason it ended with. +async fn drive( + backends: &Backends, + options: &ConnectOptions, + ctx: &LinkCtx, + cmds: &mut mpsc::UnboundedReceiver, + events: &mpsc::UnboundedSender, +) -> Option { + let (media_tx, media_rx) = mpsc::unbounded_channel(); + let sink: Arc = Arc::new(MediaQueue(media_tx)); + let params = crate::ts_session::connect_params(options, sink, backends); + let local = LocalCtx::new(ctx.clone(), options.audio, options.stream_peer.clone()); + let mut early: VecDeque = VecDeque::new(); + + let connecting = backends.connect(params, local); + tokio::pin!(connecting); + let LocalConnected { connected, streams } = loop { + tokio::select! { + result = &mut connecting => match result { + Ok(connected) => break connected, + Err(e) => return connect_failure(&e), + }, + cmd = cmds.recv() => match cmd { + None | Some(LinkCmd::Disconnect) => return None, + Some(cmd) => early.push_back(cmd), + }, + } + }; + let Connected { session, pushes, .. } = connected; + let mut conn = + Conn::new(session.clone(), pushes, media_rx, streams, ctx.clone(), events.clone()); + let sequence = tokio::select! { + result = conn.establish(options) => result, + () = until_disconnect(cmds, &mut early) => { + session.close(v1::CloseCode::Normal, ""); + return conn.finish().await; + } + }; + if let Err(reason) = sequence { + session.close(v1::CloseCode::Normal, ""); + let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; + return reason; + } + conn.run(cmds, early).await +} + +/// A transfer a user can cancel. +struct Running { + task: AbortHandle, + part: Option, + report: Report, + /// The server has opened it (a part file may exist). + started: Arc, +} + +/// What a task started by a command tells the loop. +enum Internal { + /// A CHAT scope could not be subscribed. + Unsubscribed(ScopeId), +} + +/// What a batch of pushes changed, for the events that follow it. +#[derive(Default)] +struct Batch { + /// SERVER or LIVE changed. + view: bool, + /// HOME changed. + home: bool, + /// Messages that arrived, as (channel, id). + messages: Vec<(u64, u64)>, + signals: Vec, + /// A scope of the server was closed, with the host's words. + closed: Vec, +} + +impl Batch { + fn merge(&mut self, other: Batch) { + self.view |= other.view; + self.home |= other.home; + self.messages.extend(other.messages); + self.signals.extend(other.signals); + self.closed.extend(other.closed); + } +} + +struct Conn { + session: Arc, + pushes: mpsc::Receiver, + media: mpsc::UnboundedReceiver, + streams: Option, + ctx: LinkCtx, + events: mpsc::UnboundedSender, + internal_tx: mpsc::UnboundedSender, + internal: mpsc::UnboundedReceiver, + replica: Replica, + features: Features, + welcome: v1::Welcome, + server: u64, + participant: u32, + slot: u32, + input_muted: bool, + output_muted: bool, + talk: TalkTracker, + uplink: Uplink, + /// Voice slots of the participants in view, by slot. + slots: HashMap, + /// Messages reported already, as (channel, id). + seen: HashSet<(u64, u64)>, + /// The CHAT scopes subscribed (or being subscribed). + chats: HashSet, + transfers: HashMap, + nonce: u64, + /// The last presence reported. + reported: Option, + /// Warned about once per connection. + warned: HashSet<&'static str>, + stats_at: Instant, + degraded: bool, +} + +impl Conn { + fn new( + session: Arc, + pushes: mpsc::Receiver, + media: mpsc::UnboundedReceiver, + streams: Option, + ctx: LinkCtx, + events: mpsc::UnboundedSender, + ) -> Self { + let (internal_tx, internal) = mpsc::unbounded_channel(); + let welcome = session.welcome().clone(); + let features = session.features(); + Self { + session, + pushes, + media, + streams, + ctx, + events, + internal_tx, + internal, + replica: Replica::new(SCHEMA_GENERATION), + features, + welcome, + server: 0, + participant: 0, + slot: 0, + input_muted: false, + output_muted: false, + talk: TalkTracker::default(), + uplink: Uplink::default(), + slots: HashMap::new(), + seen: HashSet::new(), + chats: HashSet::new(), + transfers: HashMap::new(), + nonce: 0, + reported: None, + warned: HashSet::new(), + stats_at: Instant::now(), + degraded: false, + } + } + + fn send(&self, event: LinkEvent) { + let _ = self.events.send(event); + } + + fn backend(&self) -> v1::BackendInfo { + self.welcome.host.as_ref().and_then(|h| h.backend.clone()).unwrap_or_default() + } + + /// Warn about `what` the first time only. + fn warn_once(&mut self, what: &'static str, detail: &str) { + if self.warned.insert(what) { + warn!(what, detail, "voice session"); + } + } + + // ---- connect sequence ----------------------------------------------------- + + /// Find the server, subscribe, wait for the syncs, take the seat in voice, + /// and tell the session it is connected (`docs/session-seam.md` 4.2). + async fn establish(&mut self, options: &ConnectOptions) -> Result<(), Option> { + let fail = |e: SessionError| Some(text(&e, true)).filter(|t| !t.is_empty()); + // The server: the only one listed, or the lowest. + let listed = self + .session + .request(Op::List(v1::List { + kind: v1::EntityKind::Server as i32, + ..Default::default() + })) + .await + .map_err(fail)?; + self.server = match listed { + Answer::Entities(entities) => entities + .items + .iter() + .filter_map(|e| match &e.kind { + Some(Kind::Server(server)) => Some(server.id), + _ => None, + }) + .min(), + _ => None, + } + .ok_or_else(|| Some("the host offers no server".to_owned()))?; + self.replica.set_own_user(self.welcome.user_id); + + for scope in [ScopeId::Home, ScopeId::Server(self.server), ScopeId::Live(self.server)] { + self.subscribe(scope).await.map_err(fail)?; + } + // The three syncs. + let mut batch = Batch::default(); + let waited = tokio::time::timeout(SYNC_TIME, async { + let mut ended = 0; + while ended < 3 { + let push = self.pushes.recv().await?; + if matches!(push.body, Some(Body::SyncEnd(_))) { + ended += 1; + } + batch.merge(self.apply(&push)); + } + Some(()) + }) + .await; + match waited { + Ok(Some(())) => {} + Ok(None) => return Err(None), + Err(_) => return Err(Some("timed out while connecting".into())), + } + + // The seat in voice. + let join = v1::JoinVoice { + server_id: self.server, + channel_id: self.join_channel(options), + password: options.channel_password.clone().unwrap_or_default(), + ..Default::default() + }; + let seated = self.session.request(Op::JoinVoice(join)).await.map_err(fail)?; + let voice = match seated { + Answer::Entities(entities) => entities.items.into_iter().find_map(|e| match e.kind { + Some(Kind::Voice(voice)) => Some(voice), + _ => None, + }), + _ => None, + } + .ok_or_else(|| Some("the host did not seat us in voice".to_owned()))?; + self.participant = voice.participant_id; + self.slot = voice.slot; + self.replica.set_own_user(self.own_user()); + + let backend = self.backend(); + let own_uid = + self.replica.user(self.own_user()).and_then(crate::ts_session::entities::user_uid); + let name = self + .replica + .server(self.server) + .map(|s| s.name.clone()) + .filter(|n| !n.is_empty()) + .or_else(|| self.welcome.host.as_ref().map(|h| h.name.clone())) + .unwrap_or_default(); + let server_uid = self + .replica + .server(self.server) + .map(|s| project::server_key(&s.uid)) + .unwrap_or_default(); + let capabilities = capabilities(&self.features, &backend, self.streams.is_some()); + self.send(LinkEvent::Connected { + name, + backend: backend_info(&backend), + capabilities, + own_client: u16::try_from(self.participant).unwrap_or_default(), + server_uid, + own_uid, + }); + // What the connect sequence collected, then the chats. + batch.view = true; + self.after(batch).await; + Ok(()) + } + + /// The channel to join: the bookmark's (`/` or a path of names), else + /// the server's default. + fn join_channel(&self, options: &ConnectOptions) -> u64 { + let wanted = options.channel.as_deref().filter(|c| !c.is_empty()); + if let Some(path) = wanted { + if let Some(id) = voelin_model::channel_path_id(path) { + return id; + } + let mut parent = 0; + let mut found = None; + for name in split_channel_path(path) { + found = self + .replica + .channels(self.server) + .find(|c| c.parent_id == parent && c.name == name) + .map(|c| c.id); + match found { + Some(id) => parent = id, + None => break, + } + } + if let Some(id) = found { + return id; + } + } + self.replica.server(self.server).map_or(0, |s| s.default_channel_id) + } + + /// The user id we are: our voice state's, else the host's word. + fn own_user(&self) -> u64 { + self.replica + .voice_state(self.server, self.participant) + .map(|v| v.user_id) + .filter(|id| *id != 0) + .unwrap_or(self.welcome.user_id) + } + + /// Subscribe a scope: the replica first, then the host. + async fn subscribe(&mut self, scope: ScopeId) -> Result<(), SessionError> { + let since = self.replica.subscribe(scope).map(Into::into); + self.session + .request(Op::Subscribe(v1::Subscribe { + scope: Some(scope.to_proto()), + since, + ..Default::default() + })) + .await + .map(|_| ()) + } + + // ---- the loop --------------------------------------------------------------- + + /// The commands that came while connecting, then the loop; the reason the + /// connection ended with. + async fn run( + &mut self, + cmds: &mut mpsc::UnboundedReceiver, + early: VecDeque, + ) -> Option { + for cmd in early { + if matches!(cmd, LinkCmd::Disconnect) { + self.session.close(v1::CloseCode::Normal, ""); + return self.finish().await; + } + self.command(cmd); + } + let mut closed = self.session.closed(); + let mut tick = tokio::time::interval(Duration::from_millis(250)); + let mut media_open = true; + loop { + tokio::select! { + biased; + cmd = cmds.recv() => match cmd { + Some(LinkCmd::Disconnect) | None => { + self.session.close(v1::CloseCode::Normal, ""); + return self.finish().await; + } + Some(cmd) => self.command(cmd), + }, + // Media before pushes: a talker is heard as soon as its packet is + // there (a packet from a slot not known yet fetches the pushes first, + // see `on_media`). + packet = self.media.recv(), if media_open => match packet { + Some(packet) => self.on_media(&packet).await, + None => media_open = false, + }, + push = self.pushes.recv() => match push { + Some(push) => { + let mut batch = self.apply(&push); + while let Ok(more) = self.pushes.try_recv() { + batch.merge(self.apply(&more)); + } + self.after(batch).await; + } + None => return self.finish().await, + }, + event = port_event(&mut self.streams) => self.on_stream(event), + internal = self.internal.recv() => { + if let Some(Internal::Unsubscribed(scope)) = internal { + self.replica.unsubscribe(scope); + if let ScopeId::Chat(channel) = scope { + self.chats.remove(&channel); + } + } + }, + reason = &mut closed => return close_text(&reason), + _ = tick.tick() => self.tick(), + } + } + } + + /// The session is closing: its end, and the reason it ended with. + async fn finish(&mut self) -> Option { + match tokio::time::timeout(CLOSE_TIME, self.session.closed()).await { + Ok(reason) => close_text(&reason), + Err(_) => { + self.warn_once("close", "the session did not end in time"); + None + } + } + } + + fn tick(&mut self) { + let now = Instant::now(); + for client in self.talk.expire(now) { + self.send(LinkEvent::Talking { client, talking: false }); + } + if now.duration_since(self.stats_at) >= Duration::from_secs(10) { + self.stats_at = now; + let stats = self.session.stats(); + debug!(?stats, "voice session path"); + } + let degraded = self.session.stats().degraded; + if degraded != self.degraded { + self.degraded = degraded; + info!(degraded, "voice session path quality changed"); + } + } + + // ---- pushes --------------------------------------------------------------- + + /// Apply a push to the replica; what the events that follow need to know. + fn apply(&mut self, push: &v1::Push) -> Batch { + let mut batch = Batch::default(); + match &push.body { + Some(Body::Change(change)) => { + batch.messages.extend(change.put.iter().filter_map(|e| match &e.kind { + Some(Kind::Message(m)) => Some((m.channel_id, m.id)), + _ => None, + })); + self.note_scope(change.scope.as_ref(), &mut batch); + } + Some(Body::SyncEnd(end)) => self.note_scope(end.scope.as_ref(), &mut batch), + Some(Body::Signal(signal)) => batch.signals.push(signal.clone()), + Some(Body::HostUpdate(update)) => { + self.features = Features::new(update.features.clone()); + } + Some(Body::ScopeClosed(closed)) => { + self.note_scope(closed.scope.as_ref(), &mut batch); + if matches!( + closed.scope.as_ref().map(|s| ScopeKind::try_from(s.kind)), + Some(Ok(ScopeKind::Server | ScopeKind::Live)) + ) { + batch.closed.push(closed.message.clone()); + } + } + _ => {} + } + self.replica.apply_push(push); + batch + } + + fn note_scope(&self, scope: Option<&v1::Scope>, batch: &mut Batch) { + match scope.and_then(ScopeId::from_proto) { + Some(ScopeId::Server(id) | ScopeId::Live(id)) if id == self.server => batch.view = true, + Some(ScopeId::Home) => batch.home = true, + _ => {} + } + } + + /// The events of a batch of pushes: the presence, the own channel, the + /// messages, the signals; and the CHAT scopes that follow. + async fn after(&mut self, batch: Batch) { + let Batch { view, home, messages, signals, closed } = batch; + if view || home { + self.replica.set_own_user(self.own_user()); + } + for message in closed { + self.send(LinkEvent::Error(message)); + } + if view { + self.report_presence(); + } + if view || home { + self.update_chat_scopes(); + } + for (channel, id) in messages { + if !self.seen.insert((channel, id)) { + continue; + } + if let Some(message) = project::chat_message(&self.replica, channel, id) { + self.send(LinkEvent::Chat(message)); + } + } + for signal in signals { + self.signal(signal); + } + } + + /// Project the replica into the older model and report it, with the own + /// channel, when it differs from the last report. + fn report_presence(&mut self) { + let backend = self.backend(); + let presence = project::presence(&View { + replica: &self.replica, + server: self.server, + teamspeak: backend.product == "teamspeak", + version: &backend.version, + features: &self.features, + streams: self.streams.is_some(), + talking: &self.talk, + }); + self.slots = self + .replica + .voice_states(self.server) + .filter_map(|v| Some((v.slot, u16::try_from(v.participant_id).ok()?))) + .collect(); + if self.reported.as_ref() == Some(&presence) { + return; + } + self.reported = Some(presence.clone()); + self.send(LinkEvent::Presence(Box::new(presence))); + if let Some(channel) = self.own_channel() { + self.send(LinkEvent::OwnChannel(channel)); + } + } + + fn own_channel(&self) -> Option { + self.replica + .voice_state(self.server, self.participant) + .map(|v| v.channel_id) + .filter(|c| *c != 0) + } + + /// The scopes whose messages the engine reads: the server chat, the + /// channel we are in, the direct-message channels HOME holds. + fn update_chat_scopes(&mut self) { + let mut wanted: Vec = Vec::new(); + let server_chat = self + .replica + .channels(self.server) + .find(|c| c.kind == v1::ChannelKind::ServerChat as i32) + .map(|c| c.id); + wanted.extend(server_chat); + let own = self.own_channel().filter(|c| self.replica.channel(*c).is_some()); + wanted.extend(own); + let mut dms: Vec = self.replica.channels(0).map(|c| c.id).collect(); + dms.sort_unstable(); + wanted.extend(dms); + wanted.truncate(MAX_CHAT_SCOPES); + let wanted: HashSet = wanted.into_iter().collect(); + let leave: Vec = self.chats.difference(&wanted).copied().collect(); + let join: Vec = wanted.difference(&self.chats).copied().collect(); + for channel in leave { + self.chats.remove(&channel); + let scope = ScopeId::Chat(channel); + self.replica.unsubscribe(scope); + // Dropping the future would withdraw the request. + let request = self + .session + .request(Op::Unsubscribe(v1::Unsubscribe { scope: Some(scope.to_proto()) })); + tokio::spawn(async move { + let _ = request.await; + }); + } + for channel in join { + self.chats.insert(channel); + let scope = ScopeId::Chat(channel); + let since = self.replica.subscribe(scope).map(Into::into); + let request = self.session.request(Op::Subscribe(v1::Subscribe { + scope: Some(scope.to_proto()), + since, + ..Default::default() + })); + let internal = self.internal_tx.clone(); + tokio::spawn(async move { + if let Err(e) = request.await { + debug!(?scope, error = %e, "a chat scope could not be subscribed"); + let _ = internal.send(Internal::Unsubscribed(scope)); + } + }); + } + } + + /// An ephemeral signal of the host. + fn signal(&mut self, signal: v1::Signal) { + use v1::signal::Body as Signal; + match signal.body { + Some(Signal::Poke(poke)) => { + let user = self.replica.user(signal.from_user); + let nick = self + .replica + .voice_state(self.server, signal.from_participant) + .map(|v| v.nick.clone()) + .filter(|n| !n.is_empty()); + self.send(LinkEvent::Poke { + from: u16::try_from(signal.from_participant).unwrap_or_default(), + from_uid: user.and_then(crate::ts_session::entities::user_uid), + from_name: nick.or_else(|| user.map(|u| u.name.clone())).unwrap_or_default(), + message: poke.message, + }); + } + Some(Signal::Notice(notice)) => { + if notice.level == v1::NoticeLevel::Info as i32 { + info!(code = %notice.code, text = %notice.text, "notice from the host"); + } else { + self.send(LinkEvent::Error(notice.text)); + } + } + // Nothing in the engine shows typing, reminders or hints yet. + _ => debug!("signal of the host ignored"), + } + } + + // ---- media ------------------------------------------------------------------ + + async fn on_media(&mut self, packet: &MediaPacket) { + let Some(incoming) = Incoming::parse(packet) else { return }; + if !self.slots.contains_key(&incoming.slot) { + // The push that tells who has this slot may be on its way: media and + // pushes travel apart. + let mut batch = Batch::default(); + while let Ok(push) = self.pushes.try_recv() { + batch.merge(self.apply(&push)); + } + self.after(batch).await; + } + let Some(client) = self.slots.get(&incoming.slot).copied() else { + self.warn_once("media", "a voice packet from a slot nobody has"); + return; + }; + if self.talk.heard(client, Instant::now()) { + self.send(LinkEvent::Talking { client, talking: true }); + } + self.send(LinkEvent::Audio(incoming.voice(client))); + } + + fn on_stream(&mut self, event: Option) { + match event { + Some(StreamEvent::OwnStream(event)) => self.send(LinkEvent::OwnStream(event)), + Some(StreamEvent::Audio { stream, time, data }) => { + self.send(LinkEvent::StreamAudio { stream, time, data }); + } + Some(StreamEvent::AudioEnded(stream)) => self.send(LinkEvent::StreamAudioEnded(stream)), + // The stream task has ended: nothing more comes through the port. + None => self.streams = None, + } + } + + fn send_voice(&mut self, voice: &EncodedVoice) { + let Some(packet) = self.uplink.frame(self.slot, voice) else { return }; + match self.session.send_media(MediaClass::Voice, packet) { + Ok(Sent::Queued) => {} + Ok(Sent::Dropped) => debug!("a voice frame was too stale to send"), + Err(e) => self.warn_once("send", &e.to_string()), + } + } + + // ---- commands ---------------------------------------------------------------- + + /// A request whose answer only reports: queued now, awaited on a task. + fn spawn_request( + &self, + op: Op, + answered: impl FnOnce(Result) + Send + 'static, + ) { + let request = self.session.request(op); + tokio::spawn(async move { answered(request.await) }); + } + + /// A request that fails with a user-visible `label: text` error. + fn report_failure(&self, op: Op, what: &'static str) { + let events = self.events.clone(); + self.spawn_request(op, move |answer| { + if let Err(e) = answer { + let _ = events.send(LinkEvent::Error(format!("{what}: {}", text(&e, false)))); + } + }); + } + + /// A request answered by an `Event::RequestDone`. + fn finish_request(&self, request: files::RequestId, op: Result) { + let ctx = self.ctx.clone(); + match op { + Ok(op) => self.spawn_request(op, move |answer| { + ctx.done(request, answer.map(|_| ()).map_err(|e| text(&e, false))); + }), + Err(e) => ctx.done(request, Err(text(&e, false))), + } + } + + fn command(&mut self, cmd: LinkCmd) { + match cmd { + LinkCmd::SendChat(target, body) => self.send_chat(target, body), + LinkCmd::Move(channel, password) => self.join(channel, password), + LinkCmd::SetInputMuted(muted) => { + self.input_muted = muted; + self.voice_flag("self_mute", |voice| voice.self_mute = muted); + } + LinkCmd::SetOutputMuted(muted) => { + self.output_muted = muted; + self.voice_flag("self_deaf", |voice| voice.self_deaf = muted); + } + LinkCmd::Audio(voice) => self.send_voice(&voice), + LinkCmd::Stream(cmd) => match &self.streams { + Some(port) => port.send(cmd), + None => debug!("a stream command without a stream port dropped"), + }, + LinkCmd::Poke { client, message } => { + let op = Op::Signal(v1::Signal { + to: Some(v1::SignalTarget { + server_id: self.server, + participant_id: u32::from(client), + ..Default::default() + }), + body: Some(v1::signal::Body::Poke(v1::Poke { message })), + ..Default::default() + }); + self.report_failure(op, "poke"); + } + LinkCmd::ListFiles { request, dir } => self.list_files(request, dir), + LinkCmd::Download { transfer, file, sink, report } => { + self.download(transfer, file, sink, report); + } + LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => { + self.upload(transfer, file, from, overwrite, resume, report); + } + LinkCmd::CancelTransfer(id) => self.cancel(id), + LinkCmd::DeleteFiles { request, channel, password, paths } => { + self.delete_files(request, channel, password, paths); + } + LinkCmd::RenameFile { request, from, to } => { + let (dir, name) = split_path(&to.path); + let entity = Entity { + kind: Some(Kind::File(v1::FileEntry { + channel_id: to.channel, + path: dir, + name, + password: to.password.unwrap_or_default(), + from_channel_id: from.channel, + from_path: from.path, + from_password: from.password.unwrap_or_default(), + ..Default::default() + })), + }; + self.finish_request(request, Ok(put(entity))); + } + LinkCmd::CreateDirectory { request, dir } => { + let (parent, name) = split_path(&dir.path); + let entity = Entity { + kind: Some(Kind::File(v1::FileEntry { + channel_id: dir.channel, + path: parent, + name, + is_dir: true, + password: dir.password.unwrap_or_default(), + ..Default::default() + })), + }; + self.finish_request(request, Ok(put(entity))); + } + LinkCmd::SetAvatarHash { request, hash } => self.set_avatar(request, hash), + LinkCmd::OfflineList { request } => self.offline_list(request), + LinkCmd::OfflineGet { request, id } => self.offline_get(request, id), + LinkCmd::OfflineAdd { request, to_uid, subject, text } => { + let mail = v1::Mail { to_uid, subject, text, ..Default::default() }; + let op = self + .features + .require("mailbox") + .map(|()| put(Entity { kind: Some(Kind::Mail(mail)) })); + self.finish_request(request, op); + } + LinkCmd::OfflineDelete { request, id } => { + let key = Entity { + kind: Some(Kind::Mail(v1::Mail { id: u64::from(id), ..Default::default() })), + }; + let op = self + .features + .require("mailbox") + .map(|()| Op::Delete(v1::Delete { keys: vec![key], ..Default::default() })); + self.finish_request(request, op); + } + LinkCmd::OfflineFlag { request, id, read } => { + let mail = v1::Mail { id: u64::from(id), read, ..Default::default() }; + let op = self + .features + .require("mailbox") + .and_then(|()| patch(Entity { kind: Some(Kind::Mail(mail)) }, "read")); + self.finish_request(request, op); + } + // Both are handled by the loop; the inner commands of a link are not + // the engine's. + LinkCmd::OpenRead { .. } | LinkCmd::OpenWrite { .. } | LinkCmd::Disconnect => {} + } + } + + /// Our own voice flags: fire and forget (protocol 4.7). + fn voice_flag(&self, path: &str, set: impl FnOnce(&mut v1::VoiceState)) { + let mut voice = v1::VoiceState { + server_id: self.server, + participant_id: self.participant, + ..Default::default() + }; + set(&mut voice); + if let Ok(write) = v1::Write::patch(Entity { kind: Some(Kind::Voice(voice)) }, [path]) { + let op = Op::Put(v1::Put { writes: vec![write], ..Default::default() }); + if let Err(e) = self.session.notify(op) { + debug!(error = %e, "a voice flag was not sent"); + } + } + } + + fn join(&mut self, channel: u64, password: Option) { + let op = Op::JoinVoice(v1::JoinVoice { + server_id: self.server, + channel_id: channel, + password: password.unwrap_or_default(), + self_mute: self.input_muted, + self_deaf: self.output_muted, + }); + let ctx = self.ctx.clone(); + self.spawn_request(op, move |answer| { + if let Err(SessionError::Rejected(e)) = answer { + let reason = match e.code() { + ErrorCode::Password => JoinFailure::Password, + ErrorCode::Full => JoinFailure::Full, + _ => JoinFailure::Other(e.message), + }; + ctx.emit(Event::JoinFailed { session: ctx.session(), channel, reason }); + } + }); + } + + // ---- chat ------------------------------------------------------------------- + + fn send_chat(&mut self, target: ChatTarget, body: String) { + let events = self.events.clone(); + let failure = move |reason: String| { + let _ = events.send(LinkEvent::Error(format!("message: {reason}"))); + }; + let format = if self.features.has("chat.bbcode") { + v1::TextFormat::Bbcode + } else { + v1::TextFormat::Markdown + }; + self.nonce += 1; + let nonce = self.nonce; + let message = move |channel_id: u64| { + Op::Put(v1::Put { + writes: vec![v1::Write { + entity: Some(Entity { + kind: Some(Kind::Message(v1::Message { + channel_id, + text: body.clone(), + format: format as i32, + nonce, + ..Default::default() + })), + }), + paths: Vec::new(), + }], + ..Default::default() + }) + }; + match target { + ChatTarget::Channel(channel) => self.chat_request(message(channel), failure), + ChatTarget::Server => { + let channel = self + .replica + .channels(self.server) + .find(|c| c.kind == v1::ChannelKind::ServerChat as i32) + .map(|c| c.id); + match channel { + Some(channel) => self.chat_request(message(channel), failure), + None => failure("the server has no chat".into()), + } + } + ChatTarget::Private(uid) => match self.direct_channel(&uid) { + Direct::Channel(channel) => self.chat_request(message(channel), failure), + Direct::User(user) => { + // The conversation does not exist yet: make it, then write to it. + let own = self.own_user(); + let create = Op::Put(v1::Put { + writes: vec![v1::Write { + entity: Some(Entity { + kind: Some(Kind::Channel(v1::Channel { + server_id: 0, + kind: v1::ChannelKind::Dm as i32, + recipients: vec![own, user], + ..Default::default() + })), + }), + paths: Vec::new(), + }], + ..Default::default() + }); + let created = self.session.request(create); + let session = self.session.clone(); + tokio::spawn(async move { + let channel = match created.await { + Ok(Answer::Entities(entities)) => { + entities.items.into_iter().find_map(|e| match e.kind { + Some(Kind::Channel(channel)) => Some(channel.id), + _ => None, + }) + } + Ok(_) => None, + Err(e) => return failure(text(&e, false)), + }; + let Some(channel) = channel else { + return failure("the conversation could not be made".into()); + }; + if let Err(e) = session.request(message(channel)).await { + failure(text(&e, false)); + } + }); + } + Direct::Nobody => self.send(LinkEvent::Error( + "private message: the client is not on the server (send an offline message \ + instead)" + .into(), + )), + }, + } + } + + fn chat_request(&self, op: Op, failure: impl FnOnce(String) + Send + 'static) { + self.spawn_request(op, move |answer| { + if let Err(e) = answer { + failure(text(&e, false)); + } + }); + } + + /// The direct-message channel with the client of this unique id, or the + /// user to make one with. + fn direct_channel(&self, uid: &str) -> Direct { + let user_of = |id: u64| { + self.replica.user(id).and_then(crate::ts_session::entities::user_uid).as_deref() + == Some(uid) + }; + let own = self.own_user(); + let existing = self.replica.channels(0).find(|channel| { + channel.kind == v1::ChannelKind::Dm as i32 + && channel.recipients.iter().any(|id| *id != own && user_of(*id)) + }); + if let Some(channel) = existing { + return Direct::Channel(channel.id); + } + // The client has to be on the server to be written to. + let present = + self.replica.voice_states(self.server).map(|v| v.user_id).find(|id| user_of(*id)); + present.map_or(Direct::Nobody, Direct::User) + } + + // ---- files ------------------------------------------------------------------ + + fn progress_every(&self) -> Duration { + Duration::from_millis(self.ctx.settings.current().get(&FILES_PROGRESS_MS).into()) + } + + fn list_files(&self, request: files::RequestId, dir: Remote) { + let channel = dir.channel; + let path = files::normalize_dir(&dir.path); + let ctx = self.ctx.clone(); + if let Err(e) = self.features.require("files") { + let result = Err(text(&e, false)); + ctx.emit(Event::FileList { session: ctx.session(), request, channel, path, result }); + return; + } + let op = Op::List(v1::List { + kind: v1::EntityKind::File as i32, + parent: channel, + path: dir.path, + password: dir.password.unwrap_or_default(), + ..Default::default() + }); + self.spawn_request(op, move |answer| { + let result = match answer { + Ok(Answer::Entities(entities)) => Ok(entities + .items + .into_iter() + .filter_map(|e| match e.kind { + Some(Kind::File(file)) => Some(FileEntry { + name: file.name, + size: file.size, + modified_s: file.modified_ms / 1000, + is_dir: file.is_dir, + }), + _ => None, + }) + .collect()), + Ok(_) => Err("unexpected answer".to_owned()), + Err(e) => Err(text(&e, false)), + }; + ctx.emit(Event::FileList { session: ctx.session(), request, channel, path, result }); + }); + } + + fn delete_files( + &self, + request: Option, + channel: u64, + password: Option, + paths: Vec, + ) { + let keys = paths + .iter() + .map(|path| { + let (dir, name) = split_path(path); + Entity { + kind: Some(Kind::File(v1::FileEntry { + channel_id: channel, + path: dir, + name, + password: password.clone().unwrap_or_default(), + ..Default::default() + })), + } + }) + .collect(); + let op = Op::Delete(v1::Delete { keys, ..Default::default() }); + match request { + Some(request) => self.finish_request(request, Ok(op)), + // Best effort: nobody waits for the answer. + None => self.spawn_request(op, |_| {}), + } + } + + fn download(&mut self, transfer: Option, file: Remote, sink: Sink, report: Report) { + let picture = transfer.is_none(); + let offset = sink.offset(); + let part = sink.part().map(ToOwned::to_owned); + let progress = self.progress_every(); + let started = Arc::new(AtomicBool::new(false)); + let mark = started.clone(); + let task_report = report.clone(); + report(TransferState::Requested); + let request = self.session.read_file(v1::FileRead { + target: Some(v1::file_read::Target::Path(v1::FilePath { + channel_id: file.channel, + path: file.path, + password: file.password.unwrap_or_default(), + })), + offset, + length: 0, + }); + let task = tokio::spawn(async move { + let opened = if picture { + // Pictures (avatars, icons, banners) are background work: a + // server that does not answer is given up on. + match tokio::time::timeout(crate::cache::IMAGE_NEGOTIATION, request).await { + Ok(opened) => opened, + Err(_) => { + task_report(TransferState::Failed( + "image transfer negotiation timed out".into(), + )); + return; + } + } + } else { + request.await + }; + let Download { head, body } = match opened { + Ok(download) => download, + Err(e) => return task_report(TransferState::Failed(text(&e, false))), + }; + let size = head + .items + .iter() + .find_map(|e| match &e.kind { + Some(Kind::File(file)) => Some(file.size), + _ => None, + }) + .unwrap_or(0); + // Pictures are bounded like the banners on the web, the user's own + // files are not. + if picture && size > crate::cache::MAX_PICTURE_BYTES { + let limit = crate::cache::MAX_PICTURE_BYTES >> 20; + return task_report(TransferState::Failed(format!("larger than {limit} MiB"))); + } + mark.store(true, Ordering::Release); + let receive = files::download(body, size, offset, sink, progress, task_report.clone()); + if picture { + let deadline = crate::cache::image_download_time(size); + if tokio::time::timeout(deadline, receive).await.is_err() { + task_report(TransferState::Failed("image download timed out".into())); + } + } else { + receive.await; + } + }); + self.running(transfer, Running { task: task.abort_handle(), part, report, started }); + } + + fn upload( + &mut self, + transfer: Option, + file: Remote, + from: PathBuf, + overwrite: bool, + resume: bool, + report: Report, + ) { + let size = match std::fs::metadata(&from) { + Ok(m) if m.is_file() => m.len(), + Ok(_) => { + return report(TransferState::Failed(format!("{} is not a file", from.display()))); + } + Err(e) => return report(TransferState::Failed(format!("{}: {e}", from.display()))), + }; + if let Err(e) = self.features.require("files.upload") { + return report(TransferState::Failed(text(&e, false))); + } + report(TransferState::Requested); + let session = self.session.clone(); + let progress = self.progress_every(); + let started = Arc::new(AtomicBool::new(true)); + let task_report = report.clone(); + let task = tokio::spawn(async move { + let path = |channel: u64, path: &str, password: &Option| v1::FilePath { + channel_id: channel, + path: path.to_owned(), + password: password.clone().unwrap_or_default(), + }; + // A resumed upload goes on where the server's copy ends. + let offset = if resume { + let (dir, name) = split_path(&file.path); + let listing = session + .request(Op::List(v1::List { + kind: v1::EntityKind::File as i32, + parent: file.channel, + path: dir, + password: file.password.clone().unwrap_or_default(), + ..Default::default() + })) + .await; + match listing { + Ok(Answer::Entities(entities)) => entities + .items + .iter() + .find_map(|e| match &e.kind { + Some(Kind::File(f)) if f.name == name && !f.is_dir => Some(f.size), + _ => None, + }) + .unwrap_or(0) + .min(size), + Ok(_) => 0, + Err(e) => return task_report(TransferState::Failed(text(&e, false))), + } + } else { + 0 + }; + let write = session + .write_file(v1::FileWrite { + target: Some(v1::file_write::Target::Path(path( + file.channel, + &file.path, + &file.password, + ))), + size, + offset, + overwrite, + sha256: Default::default(), + }) + .await; + let Upload { body, done } = match write { + Ok(upload) => upload, + Err(e) => return task_report(TransferState::Failed(text(&e, false))), + }; + let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) }; + files::upload_to(body, stored, from, size, offset, progress, task_report).await; + }); + self.running(transfer, Running { task: task.abort_handle(), part: None, report, started }); + } + + fn running(&mut self, transfer: Option, running: Running) { + self.transfers.retain(|_, r| !r.task.is_finished()); + if let Some(id) = transfer { + self.transfers.insert(id, running); + } + } + + fn cancel(&mut self, id: TransferId) { + match self.transfers.remove(&id) { + Some(running) if !running.task.is_finished() => { + running.task.abort(); + // A part file exists once the server has opened the transfer. + if running.started.load(Ordering::Acquire) + && let Some(part) = running.part + { + let _ = std::fs::remove_file(part); + } + (running.report)(TransferState::Cancelled); + } + _ => debug!(id, "cancel: no such transfer (finished?)"), + } + } + + // ---- avatar and offline messages ------------------------------------------- + + fn set_avatar(&self, request: Option, hash: String) { + let user = Entity { + kind: Some(Kind::User(v1::User { + id: self.own_user(), + avatar: Some(v1::Image { hash, ..Default::default() }), + ..Default::default() + })), + }; + let op = patch(user, "avatar.hash"); + match request { + Some(request) => self.finish_request(request, op), + None => match op { + Ok(op) => self.report_failure(op, "avatar"), + Err(e) => { + let _ = + self.events.send(LinkEvent::Error(format!("avatar: {}", text(&e, false)))); + } + }, + } + } + + fn offline_list(&self, request: files::RequestId) { + let ctx = self.ctx.clone(); + if let Err(e) = self.features.require("mailbox") { + let result = Err(text(&e, false)); + return ctx.emit(Event::OfflineMessages { session: ctx.session(), request, result }); + } + let op = Op::List(v1::List { kind: v1::EntityKind::Mail as i32, ..Default::default() }); + self.spawn_request(op, move |answer| { + let result = match answer { + Ok(Answer::Entities(entities)) => Ok(entities + .items + .into_iter() + .filter_map(|e| match e.kind { + Some(Kind::Mail(mail)) => Some(OfflineMessageInfo { + id: u32::try_from(mail.id).unwrap_or_default(), + from_uid: mail.from_uid, + subject: mail.subject, + ts_s: mail.ts_ms / 1000, + read: mail.read, + }), + _ => None, + }) + .collect()), + Ok(_) => Err("unexpected answer".to_owned()), + Err(e) => Err(text(&e, false)), + }; + ctx.emit(Event::OfflineMessages { session: ctx.session(), request, result }); + }); + } + + fn offline_get(&self, request: files::RequestId, id: u32) { + let ctx = self.ctx.clone(); + if let Err(e) = self.features.require("mailbox") { + let result = Err(text(&e, false)); + return ctx.emit(Event::OfflineMessage { session: ctx.session(), request, result }); + } + let op = Op::List(v1::List { + kind: v1::EntityKind::Mail as i32, + ids: vec![u64::from(id)], + ..Default::default() + }); + self.spawn_request(op, move |answer| { + let result = match answer { + Ok(Answer::Entities(entities)) => entities + .items + .into_iter() + .find_map(|e| match e.kind { + Some(Kind::Mail(mail)) => Some(OfflineMessage { + id, + from_uid: mail.from_uid, + subject: mail.subject, + text: mail.text, + ts_s: mail.ts_ms / 1000, + }), + _ => None, + }) + .ok_or_else(|| format!("offline message {id} not found")), + Ok(_) => Err("unexpected answer".to_owned()), + Err(e) => Err(text(&e, false)), + }; + ctx.emit(Event::OfflineMessage { session: ctx.session(), request, result }); + }); + } +} + +/// A conversation with a client we write to. +enum Direct { + Channel(u64), + /// No conversation yet: the user to make one with. + User(u64), + /// The client is not on the server. + Nobody, +} + +/// The next event of the stream port, or never when there is none. +async fn port_event(streams: &mut Option) -> Option { + match streams { + Some(port) => port.events.recv().await, + None => std::future::pending().await, + } +} + +/// A path's directory and file name: `/docs/a.txt` is (`/docs`, `a.txt`). +fn split_path(path: &str) -> (String, String) { + match path.rsplit_once('/') { + Some((dir, name)) => (files::normalize_dir(dir), name.to_owned()), + None => ("/".into(), path.to_owned()), + } +} + +/// A `Put` that creates `entity`. +fn put(entity: Entity) -> Op { + Op::Put(v1::Put { + writes: vec![v1::Write { entity: Some(entity), paths: Vec::new() }], + ..Default::default() + }) +} + +/// A `Put` that patches the field `path` of `entity`. +fn patch(entity: Entity, path: &str) -> Result { + v1::Write::patch(entity, [path]) + .map(|write| Op::Put(v1::Put { writes: vec![write], ..Default::default() })) + .map_err(|e| SessionError::Protocol(e.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn error(code: ErrorCode, message: &str) -> SessionError { + SessionError::Rejected(Box::new(v1::Error { + code: code as i32, + message: message.into(), + ..Default::default() + })) + } + + #[test] + fn errors_read_as_the_link_wrote_them() { + assert_eq!(text(&error(ErrorCode::Forbidden, "nope"), false), "nope"); + assert_eq!(text(&SessionError::Timeout, true), "timed out while connecting"); + assert_eq!(text(&SessionError::Timeout, false), "timed out"); + assert_eq!( + text(&SessionError::Unsupported("files".into()), false), + "not offered by this server: files" + ); + assert_eq!( + text(&SessionError::Protocol("no connector for x".into()), true), + "no connector for x" + ); + assert_eq!(text(&SessionError::HostIdentity("changed".into()), true), "changed"); + let io = SessionError::Io(std::io::Error::other("broken pipe")); + assert_eq!(text(&io, false), "broken pipe"); + assert_eq!( + text(&SessionError::Closed(CloseReason::Network("server shut down".into())), false), + "server shut down" + ); + } + + #[test] + fn a_connection_ends_with_the_reason_of_the_table() { + let normal = v1::CloseCode::Normal as u64; + let kicked = v1::CloseCode::Kicked as u64; + assert_eq!(close_text(&CloseReason::Local(v1::CloseCode::Normal)), None); + assert_eq!(close_text(&CloseReason::Remote { code: normal, reason: String::new() }), None); + assert_eq!( + close_text(&CloseReason::Remote { code: normal, reason: "bye".into() }).as_deref(), + Some("bye") + ); + assert_eq!( + close_text(&CloseReason::Remote { code: kicked, reason: String::new() }).as_deref(), + Some("kicked") + ); + assert_eq!( + close_text(&CloseReason::Remote { code: kicked, reason: "spam".into() }).as_deref(), + Some("spam") + ); + assert_eq!( + close_text(&CloseReason::Remote { code: 999, reason: String::new() }).as_deref(), + Some("closed by the host (code 999)") + ); + assert_eq!(close_text(&CloseReason::TimedOut).as_deref(), Some("timed out")); + assert_eq!(close_text(&CloseReason::Network("reset".into())).as_deref(), Some("reset")); + } + + #[test] + fn a_connect_that_fails_says_why_or_nothing() { + assert_eq!( + connect_failure(&SessionError::Timeout).as_deref(), + Some("timed out while connecting") + ); + let quiet = SessionError::Closed(CloseReason::Remote { + code: v1::CloseCode::Normal as u64, + reason: String::new(), + }); + assert_eq!(connect_failure(&quiet), None); + assert_eq!( + connect_failure(&SessionError::Closed(CloseReason::Network("refused".into()))) + .as_deref(), + Some("refused") + ); + } + + fn backend(product: &str, version: &str, flavor: &str) -> v1::BackendInfo { + v1::BackendInfo { product: product.into(), version: version.into(), flavor: flavor.into() } + } + + #[test] + fn the_backend_of_a_host_is_named_as_the_engine_names_it() { + let named = |p: &str, v: &str, f: &str| backend_info(&backend(p, v, f)); + assert_eq!(named("teamspeak", "3.13.8", "ts3").label(), "TeamSpeak 3 3.13.8"); + assert_eq!( + named("teamspeak", "6.0.0-beta13.1", "ts6").label(), + "TeamSpeak 6 6.0.0-beta13.1" + ); + // A TeamSpeak server not recognised: only what it said. + let unknown = named("teamspeak", "9.9", ""); + assert_eq!((unknown.product.as_str(), unknown.version.as_str()), ("", "9.9")); + assert_eq!(named("Fake", "1.2", "").label(), "Fake 1.2"); + // And back, through the TeamSpeak side's writer. + for (product, version) in [ + ("TeamSpeak 3", "3.13.8"), + ("TeamSpeak 6", "6.0.0-beta13.1"), + ("", "9.9"), + ("Fake", "1.2"), + ] { + let info = BackendInfo { product: product.into(), version: version.into() }; + assert_eq!(backend_info(&crate::ts_session::backend_to_v1(&info)), info); + } + } + + #[test] + fn capabilities_follow_the_features_and_the_flavor() { + let features = |f: &[&str]| Features::new(f.iter().copied()); + let ts3 = backend("teamspeak", "3.13.8", "ts3"); + let ts6 = backend("teamspeak", "6.0.0", "ts6"); + let other = backend("Fake", "1", ""); + let all = features(&["voice", "files", "mailbox", "streams"]); + let caps = capabilities(&all, &ts3, true); + assert_eq!( + caps, + Capabilities { + streams: true, + raw_query: true, + ssh_query: true, + http_query: false, + file_transfer: true, + offline_messages: true, + } + ); + let caps = capabilities(&all, &ts6, true); + assert_eq!((caps.raw_query, caps.ssh_query, caps.http_query), (false, true, true)); + // Streams need the feature and a port for the stream task. + assert!(!capabilities(&all, &ts6, false).streams); + assert!(!capabilities(&features(&["voice"]), &ts6, true).streams); + let plain = capabilities(&features(&["files"]), &other, false); + assert_eq!( + plain, + Capabilities { file_transfer: true, ..Default::default() }, + "the query modes belong to TeamSpeak" + ); + } + + #[test] + fn the_capabilities_of_a_link_come_back_through_its_features() { + for (streams, file_transfer, offline_messages) in + [(false, true, false), (true, true, true), (false, false, false)] + { + let caps = + Capabilities { streams, file_transfer, offline_messages, ..Default::default() }; + let features = Features::new(crate::ts_session::features_of(&caps)); + let host = crate::ts_session::backend_to_v1(&BackendInfo::default()); + let back = capabilities(&features, &host, true); + assert_eq!( + (back.streams, back.file_transfer, back.offline_messages), + (streams, file_transfer, offline_messages) + ); + } + } + + #[test] + fn paths_split_for_keys() { + assert_eq!(split_path("/docs/a.txt"), ("/docs".into(), "a.txt".into())); + assert_eq!(split_path("/a.txt"), ("/".into(), "a.txt".into())); + } +} diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs new file mode 100644 index 0000000..246e1c4 --- /dev/null +++ b/crates/voelin-core/src/link/tests.rs @@ -0,0 +1,1319 @@ +//! The seam from both sides, with a recording link inside: every `LinkCmd` +//! the engine gives becomes the `Session` call of its row in +//! `docs/session-seam.md` (table 3.1) and reaches the link as the inner +//! `LinkCmd` of the same row; every `LinkEvent` of the link comes back as the +//! row of table 3.2 says. `the_teamspeak_session` talks to the `Session` of +//! the TeamSpeak side directly. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use tokio::io::AsyncReadExt; +use tokio::sync::{broadcast, mpsc}; +use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket}; +use voelin_model::{ + Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails, +}; +use voelin_proto::link::{ + CloseReason, Connector, Credential, FlowId, MediaClass, MediaError, MediaPacket, Session, + SessionError, +}; +use voelin_proto::test_util::connect_params; +use voelin_proto::v1; + +use super::*; +use crate::files::{DownloadTo, FileEntry, TransferState}; +use crate::offline::OfflineMessage; +use crate::offline::OfflineMessageInfo; +use crate::stream::{OwnStreamEvent, StreamCmd, StreamKind}; +use crate::ts_session::LinkConnector; +use crate::{BackendInfo, Event, JoinFailure}; + +const ME: u16 = 7; +const LOBBY: u64 = 1; +const GAMES: u64 = 2; +const WAIT: Duration = Duration::from_secs(10); + +/// A connection the engine asked the link for. +struct Inner { + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +} + +/// Hands every connection to the test. +struct Recorder(mpsc::UnboundedSender); + +impl ServerLink for Recorder { + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + let _ = self.0.send(Inner { options, ctx, cmds, events }); + } +} + +fn client(id: u16, name: &str, channel: u64) -> ClientInfo { + ClientInfo { + id, + uid: Some(format!("{name}=")), + nickname: name.into(), + channel, + database_id: Some(1_000 + u64::from(id)), + talking: Some(false), + ..Default::default() + } +} + +/// Two channels; us in the second, alice (8) in the same one, bob (9) in the +/// first. +fn presence() -> Presence { + let channel = + |id, order| ChannelInfo { id, name: format!("c{id}"), order, ..Default::default() }; + let mut presence = Presence { + server_name: "Test Server".into(), + server: ServerDetails { + name: "Test Server".into(), + uid: Some("server=".into()), + version: "1.2".into(), + ..Default::default() + }, + ..Default::default() + }; + presence.channels.insert(LOBBY, channel(LOBBY, 0)); + presence.channels.insert(GAMES, channel(GAMES, LOBBY)); + for c in [client(ME, "me", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] { + presence.clients.insert(c.id, c); + } + presence +} + +fn connected(capabilities: Capabilities) -> LinkEvent { + LinkEvent::Connected { + name: "Test Server".into(), + backend: BackendInfo { product: "Fake".into(), version: "1.2".into() }, + capabilities, + own_client: ME, + server_uid: "server=".into(), + own_uid: Some("me=".into()), + } +} + +/// Every feature a link can have. +fn everything() -> Capabilities { + Capabilities { + streams: true, + file_transfer: true, + offline_messages: true, + ..Default::default() + } +} + +async fn within(what: &str, f: impl std::future::Future>) -> T { + tokio::time::timeout(WAIT, f) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}")) + .unwrap_or_else(|| panic!("{what}: the channel closed")) +} + +/// The engine's side (a `SessionLink` driven with `LinkCmd`s), the link's side +/// (what the recorder saw), and the engine's event bus. +struct Rig { + inner: Inner, + cmds: mpsc::UnboundedSender, + events: mpsc::UnboundedReceiver, + bus: broadcast::Receiver, +} + +impl Rig { + /// Connect and let the link report its server; the first events are + /// consumed up to the own channel. + async fn new(capabilities: Capabilities) -> Rig { + let (conns, mut seen) = mpsc::unbounded_channel(); + let mut backends = Backends::empty(); + backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); + let link = SessionLink::new(backends); + let ctx = LocalCtx::standalone().link; + let bus = ctx.events.subscribe(); + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, events) = mpsc::unbounded_channel(); + link.spawn(ConnectOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(connected(capabilities)).unwrap(); + inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); + let mut rig = Rig { inner, cmds: cmd_tx, events, bus }; + rig.event(|e| matches!(e, LinkEvent::Connected { .. }).then_some(())).await; + rig.event(|e| matches!(e, LinkEvent::OwnChannel(_)).then_some(())).await; + rig + } + + fn give(&self, cmd: LinkCmd) { + self.cmds.send(cmd).expect("the connection listens"); + } + + fn play(&self, event: LinkEvent) { + self.inner.events.send(event).expect("the session listens"); + } + + /// The next inner command. + async fn inner_cmd(&mut self) -> LinkCmd { + within("an inner command", self.inner.cmds.recv()).await + } + + /// The next event `f` picks, skipping the others. + async fn event(&mut self, mut f: impl FnMut(LinkEvent) -> Option) -> T { + within("an event", async { + loop { + if let Some(t) = f(self.events.recv().await?) { + return Some(t); + } + } + }) + .await + } + + /// The next bus event `f` picks, skipping the others. + async fn bus(&mut self, mut f: impl FnMut(Event) -> Option) -> T { + within("a bus event", async { + loop { + if let Some(t) = f(self.bus.recv().await.ok()?) { + return Some(t); + } + } + }) + .await + } + + /// The engine told the link nothing it did not ask for. + fn quiet(&mut self) { + assert!(self.inner.cmds.try_recv().is_err(), "a command reached the link"); + } +} + +fn recorder() -> (Report, Arc>>) { + let states = Arc::new(Mutex::new(Vec::new())); + let sink = states.clone(); + (Arc::new(move |state| sink.lock().unwrap().push(state)), states) +} + +async fn final_state(states: &Arc>>) -> TransferState { + for _ in 0..500 { + if let Some(last) = states.lock().unwrap().last().filter(|s| s.is_final()) { + return last.clone(); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("the transfer did not end: {:?}", states.lock().unwrap()); +} + +fn remote(channel: u64, password: Option<&str>, path: &str) -> Remote { + Remote { channel, password: password.map(str::to_owned), path: path.into() } +} + +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-seam-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// 20 ms of CELT, mono, one frame. +const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02]; + +// ---- the engine's side -------------------------------------------------------- + +#[tokio::test(flavor = "multi_thread")] +async fn chat_moves_flags_pokes_and_voice_reach_the_link() { + let mut rig = Rig::new(everything()).await; + // The link was given the options the session was asked to connect with. + assert_eq!( + (rig.inner.options.address.as_str(), rig.inner.options.nickname.as_str()), + ("fake.test:9987", "tester") + ); + + // SendChat: a channel, the server chat, a client on the server. + rig.give(LinkCmd::SendChat(ChatTarget::Channel(GAMES), "hello".into())); + let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello")); + rig.give(LinkCmd::SendChat(ChatTarget::Server, "to all".into())); + let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Server, "to all")); + rig.give(LinkCmd::SendChat(ChatTarget::Private("alice=".into()), "psst".into())); + let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Private("alice=".into()), "psst")); + // A channel we are not in is refused by the session, with the words of a + // refusal; the link hears nothing. + rig.give(LinkCmd::SendChat(ChatTarget::Channel(LOBBY), "elsewhere".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert!(error.starts_with("message: "), "{error}"); + // Someone who is not on the server cannot be written to. + rig.give(LinkCmd::SendChat(ChatTarget::Private("ghost=".into()), "boo".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert_eq!( + error, + "private message: the client is not on the server (send an offline message instead)" + ); + rig.quiet(); + + // Move: with and without a password. + rig.give(LinkCmd::Move(LOBBY, Some("pw".into()))); + let LinkCmd::Move(channel, password) = rig.inner_cmd().await else { panic!("a move") }; + assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); + rig.give(LinkCmd::Move(LOBBY, None)); + let LinkCmd::Move(_, password) = rig.inner_cmd().await else { panic!("a move") }; + assert_eq!(password, None); + + // The mute flags. + rig.give(LinkCmd::SetInputMuted(true)); + assert!(matches!(rig.inner_cmd().await, LinkCmd::SetInputMuted(true))); + rig.give(LinkCmd::SetOutputMuted(true)); + assert!(matches!(rig.inner_cmd().await, LinkCmd::SetOutputMuted(true))); + + // A poke. + rig.give(LinkCmd::Poke { client: 8, message: "wake up".into() }); + let LinkCmd::Poke { client, message } = rig.inner_cmd().await else { panic!("a poke") }; + assert_eq!((client, message.as_str()), (8, "wake up")); + + // Voice: the payload and the codec survive the RTP between. + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; + assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..])); + let stereo = [OPUS_20_MS[0] | 0x04, 1, 2]; + rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Music, payload: stereo.to_vec() })); + let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; + assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Music, &stereo[..])); + // The end of a transmission is an empty packet, once. + rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Voice, payload: Vec::new() })); + let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; + assert!(voice.is_end()); + + // Streams go to the stream task, in order with everything else. + rig.give(LinkCmd::Stream(StreamCmd::Directory(Vec::new()))); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Directory(_)))); + rig.quiet(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn files_avatars_and_offline_messages_reach_the_link() { + let mut rig = Rig::new(everything()).await; + + // A listing is answered on the bus, with the engine's request id and the + // directory as the server echoes it. + rig.give(LinkCmd::ListFiles { request: 5, dir: remote(GAMES, Some("pw"), "/docs/") }); + let LinkCmd::ListFiles { request, dir } = rig.inner_cmd().await else { panic!("a listing") }; + assert_eq!( + (dir.channel, dir.password.as_deref(), dir.path.as_str()), + (GAMES, Some("pw"), "/docs/") + ); + let entry = + FileEntry { name: "a.txt".into(), size: 12, modified_s: 1_700_000_000, is_dir: false }; + rig.inner.ctx.emit(Event::FileList { + session: 0, + request, + channel: GAMES, + path: "/docs".into(), + result: Ok(vec![entry.clone()]), + }); + let listed = rig + .bus(|e| match e { + Event::FileList { request, channel, path, result, .. } => { + Some((request, channel, path, result)) + } + _ => None, + }) + .await; + assert_eq!(listed, (5, GAMES, "/docs".into(), Ok(vec![entry]))); + + // A listing that fails says why. + rig.give(LinkCmd::ListFiles { request: 6, dir: remote(GAMES, None, "/") }); + let LinkCmd::ListFiles { request, .. } = rig.inner_cmd().await else { panic!("a listing") }; + rig.inner.ctx.emit(Event::FileList { + session: 0, + request, + channel: GAMES, + path: "/".into(), + result: Err("no access".into()), + }); + let failed = rig + .bus(|e| match e { + Event::FileList { request: 6, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(failed, Err("no access".into())); + + // Delete, rename and create answer with the engine's request id. + let done = |rig: &Rig, request, result| { + rig.inner.ctx.emit(Event::RequestDone { session: 0, request, result }); + }; + rig.give(LinkCmd::DeleteFiles { + request: Some(7), + channel: GAMES, + password: Some("pw".into()), + paths: vec!["/docs/a.txt".into(), "/b.txt".into()], + }); + let LinkCmd::DeleteFiles { request: Some(inner), channel, password, paths } = + rig.inner_cmd().await + else { + panic!("a deletion") + }; + assert_eq!((channel, password.as_deref()), (GAMES, Some("pw"))); + assert_eq!(paths, ["/docs/a.txt", "/b.txt"]); + done(&rig, inner, Ok(())); + assert_eq!( + rig.bus(|e| match e { + Event::RequestDone { request: 7, result, .. } => Some(result), + _ => None, + }) + .await, + Ok(()) + ); + // Best effort: nobody waits for the answer. + rig.give(LinkCmd::DeleteFiles { + request: None, + channel: GAMES, + password: None, + paths: vec!["/c.txt".into()], + }); + // The link is asked like for any other deletion (the session has its own + // request ids); nobody listens to the answer. + let LinkCmd::DeleteFiles { paths, .. } = rig.inner_cmd().await else { + panic!("a best-effort deletion") + }; + assert_eq!(paths, ["/c.txt"]); + + rig.give(LinkCmd::RenameFile { + request: 8, + from: remote(GAMES, Some("pw"), "/docs/a.txt"), + to: remote(LOBBY, None, "/moved/b.txt"), + }); + let LinkCmd::RenameFile { request: inner, from, to } = rig.inner_cmd().await else { + panic!("a rename") + }; + assert_eq!( + (from.channel, from.password.as_deref(), from.path.as_str()), + (GAMES, Some("pw"), "/docs/a.txt") + ); + assert_eq!( + (to.channel, to.password.as_deref(), to.path.as_str()), + (LOBBY, None, "/moved/b.txt") + ); + done(&rig, inner, Err("exists".into())); + assert_eq!( + rig.bus(|e| match e { + Event::RequestDone { request: 8, result, .. } => Some(result), + _ => None, + }) + .await, + Err("exists".into()) + ); + + rig.give(LinkCmd::CreateDirectory { request: 9, dir: remote(GAMES, None, "/new") }); + let LinkCmd::CreateDirectory { request: inner, dir } = rig.inner_cmd().await else { + panic!("a directory") + }; + assert_eq!((dir.channel, dir.path.as_str()), (GAMES, "/new")); + done(&rig, inner, Ok(())); + rig.bus(|e| matches!(e, Event::RequestDone { request: 9, .. }).then_some(())).await; + + // The avatar. + rig.give(LinkCmd::SetAvatarHash { request: Some(10), hash: "abc123".into() }); + let LinkCmd::SetAvatarHash { request: Some(inner), hash } = rig.inner_cmd().await else { + panic!("an avatar") + }; + assert_eq!(hash, "abc123"); + done(&rig, inner, Ok(())); + rig.bus(|e| matches!(e, Event::RequestDone { request: 10, .. }).then_some(())).await; + // With no request, a failure is an error of the session. + rig.give(LinkCmd::SetAvatarHash { request: None, hash: String::new() }); + let LinkCmd::SetAvatarHash { request: Some(inner), .. } = rig.inner_cmd().await else { + panic!("an avatar") + }; + done(&rig, inner, Err("denied".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert_eq!(error, "avatar: denied"); + + // Offline messages. + rig.give(LinkCmd::OfflineList { request: 11 }); + let LinkCmd::OfflineList { request } = rig.inner_cmd().await else { panic!("a mailbox list") }; + let info = OfflineMessageInfo { + id: 3, + from_uid: "alice=".into(), + subject: "hi".into(), + ts_s: 1_700_000_000, + read: true, + }; + rig.inner.ctx.emit(Event::OfflineMessages { + session: 0, + request, + result: Ok(vec![info.clone()]), + }); + let listed = rig + .bus(|e| match e { + Event::OfflineMessages { request: 11, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(listed, Ok(vec![info])); + rig.give(LinkCmd::OfflineGet { request: 12, id: 3 }); + let LinkCmd::OfflineGet { request, id } = rig.inner_cmd().await else { panic!("a mail") }; + assert_eq!(id, 3); + rig.inner.ctx.emit(Event::OfflineMessage { + session: 0, + request, + result: Ok(OfflineMessage { + id: 3, + from_uid: "alice=".into(), + subject: "hi".into(), + text: "the text".into(), + ts_s: 1_700_000_000, + }), + }); + let mail = rig + .bus(|e| match e { + Event::OfflineMessage { request: 12, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(mail.unwrap().text, "the text"); + rig.give(LinkCmd::OfflineAdd { + request: 13, + to_uid: "alice=".into(), + subject: "re".into(), + text: "body".into(), + }); + let LinkCmd::OfflineAdd { request: inner, to_uid, subject, text } = rig.inner_cmd().await + else { + panic!("a mail to send") + }; + assert_eq!((to_uid.as_str(), subject.as_str(), text.as_str()), ("alice=", "re", "body")); + done(&rig, inner, Ok(())); + rig.bus(|e| matches!(e, Event::RequestDone { request: 13, .. }).then_some(())).await; + rig.give(LinkCmd::OfflineDelete { request: 14, id: 3 }); + let LinkCmd::OfflineDelete { request: inner, id } = rig.inner_cmd().await else { + panic!("a mail to delete") + }; + assert_eq!(id, 3); + done(&rig, inner, Ok(())); + rig.bus(|e| matches!(e, Event::RequestDone { request: 14, .. }).then_some(())).await; + rig.give(LinkCmd::OfflineFlag { request: 15, id: 3, read: true }); + let LinkCmd::OfflineFlag { request: inner, id, read } = rig.inner_cmd().await else { + panic!("a mail to flag") + }; + assert_eq!((id, read), (3, true)); + done(&rig, inner, Ok(())); + rig.bus(|e| matches!(e, Event::RequestDone { request: 15, .. }).then_some(())).await; + rig.quiet(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_is_downloaded_through_the_connection_the_link_opens() { + let mut rig = Rig::new(everything()).await; + let (report, states) = recorder(); + rig.give(LinkCmd::Download { + transfer: Some(1), + file: remote(GAMES, Some("pw"), "/docs/a.txt"), + sink: Sink::Memory, + report, + }); + let LinkCmd::OpenRead { file, offset, reply } = rig.inner_cmd().await else { + panic!("a connection to read") + }; + assert_eq!( + (file.channel, file.password.as_deref(), file.path.as_str()), + (GAMES, Some("pw"), "/docs/a.txt") + ); + assert_eq!(offset, 0); + let _ = reply.send(Ok((5, Box::pin(std::io::Cursor::new(b"hello".to_vec()))))); + let TransferState::Done { size, data: Some(data), .. } = final_state(&states).await else { + panic!("a download in memory: {:?}", states.lock().unwrap()) + }; + assert_eq!((size, &*data.0), (5, &b"hello"[..])); + { + let states = states.lock().unwrap(); + assert_eq!(states[0], TransferState::Requested); + assert_eq!(states[1], TransferState::Started { size: 5, offset: 0 }); + } + + // A refusal is the transfer's failure, with the link's words. + let (report, states) = recorder(); + rig.give(LinkCmd::Download { + transfer: Some(2), + file: remote(GAMES, None, "/gone.txt"), + sink: Sink::Memory, + report, + }); + let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") }; + let _ = reply.send(Err("file not found".into())); + assert_eq!(final_state(&states).await, TransferState::Failed("file not found".into())); + + // Cancelling ends the copy, and the part file goes. + let dir = temp("cancel"); + let sink = Sink::from_target(&DownloadTo::Path { path: dir.join("big.bin"), resume: false }); + let part = sink.part().unwrap().to_owned(); + let (report, states) = recorder(); + rig.give(LinkCmd::Download { + transfer: Some(3), + file: remote(GAMES, None, "/big.bin"), + sink, + report, + }); + let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") }; + // A file whose bytes do not come: the transfer waits in the middle. + let (server, client) = tokio::io::duplex(64); + let _ = reply.send(Ok((1 << 20, Box::pin(client)))); + for _ in 0..500 { + if states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })) { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + rig.give(LinkCmd::CancelTransfer(3)); + assert_eq!(final_state(&states).await, TransferState::Cancelled); + rig.quiet(); + drop(server); + // The part file was removed (or never made) after the cancel. + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(!part.exists()); + let _ = std::fs::remove_dir_all(dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_is_uploaded_and_resumed_through_the_connection_the_link_opens() { + let mut rig = Rig::new(everything()).await; + let dir = temp("upload"); + let from = dir.join("up.bin"); + std::fs::write(&from, b"0123456789").unwrap(); + + let (report, states) = recorder(); + rig.give(LinkCmd::Upload { + transfer: Some(1), + file: remote(GAMES, None, "/up.bin"), + from: from.clone(), + overwrite: true, + resume: false, + report, + }); + let LinkCmd::OpenWrite { file, size, overwrite, resume, reply } = rig.inner_cmd().await else { + panic!("a connection to write") + }; + assert_eq!( + (file.channel, file.path.as_str(), size, overwrite, resume), + (GAMES, "/up.bin", 10, true, false) + ); + let (server, client) = tokio::io::duplex(1024); + let _ = reply.send(Ok((0, Box::pin(client)))); + let server = tokio::spawn(async move { + let mut server = server; + let mut got = Vec::new(); + server.read_to_end(&mut got).await.unwrap(); + // The server closes the connection once it has everything. + drop(server); + got + }); + assert!(matches!(final_state(&states).await, TransferState::Done { size: 10, .. })); + assert_eq!(server.await.unwrap(), b"0123456789"); + + // A resumed upload goes on where the server's copy ends. + let (report, states) = recorder(); + rig.give(LinkCmd::Upload { + transfer: Some(2), + file: remote(GAMES, None, "/up.bin"), + from, + overwrite: false, + resume: true, + report, + }); + let LinkCmd::ListFiles { request, dir: listed } = rig.inner_cmd().await else { + panic!("the size of the server's copy is asked") + }; + assert_eq!((listed.channel, listed.path.as_str()), (GAMES, "/")); + let entry = FileEntry { name: "up.bin".into(), size: 4, modified_s: 0, is_dir: false }; + rig.inner.ctx.emit(Event::FileList { + session: 0, + request, + channel: GAMES, + path: "/".into(), + result: Ok(vec![entry]), + }); + let LinkCmd::OpenWrite { resume, reply, .. } = rig.inner_cmd().await else { + panic!("a connection to write") + }; + assert!(resume); + let (server, client) = tokio::io::duplex(1024); + // The server wants the bytes from where its copy ends. + let _ = reply.send(Ok((4, Box::pin(client)))); + let server = tokio::spawn(async move { + let mut server = server; + let mut got = Vec::new(); + server.read_to_end(&mut got).await.unwrap(); + drop(server); + got + }); + assert!(matches!(final_state(&states).await, TransferState::Done { .. })); + assert_eq!(server.await.unwrap(), b"456789"); + let started = states.lock().unwrap().iter().find_map(|s| match s { + TransferState::Started { size, offset } => Some((*size, *offset)), + _ => None, + }); + assert_eq!(started, Some((10, 4))); + + // A file that is not there fails before the link is asked. + let (report, states) = recorder(); + rig.give(LinkCmd::Upload { + transfer: None, + file: remote(GAMES, None, "/x"), + from: dir.join("missing"), + overwrite: false, + resume: false, + report, + }); + let TransferState::Failed(why) = final_state(&states).await else { panic!("a failure") }; + assert!(why.contains("missing"), "{why}"); + rig.quiet(); + let _ = std::fs::remove_dir_all(dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn what_the_link_reports_comes_back_as_events() { + let mut rig = Rig::new(everything()).await; + + // Chat: our channel, the server chat, a private message. + let message = |target: ChatTarget, text: &str| ChatMessage { + target, + author_name: "alice".into(), + author_uid: Some("alice=".into()), + author_id: Some(8), + text: text.into(), + ts_ms: 1_700_000_000_000, + via_relay: false, + blocked: false, + }; + rig.play(LinkEvent::Chat(message(ChatTarget::Channel(GAMES), "in the channel"))); + rig.play(LinkEvent::Chat(message(ChatTarget::Server, "to the server"))); + rig.play(LinkEvent::Chat(message(ChatTarget::Private("alice=".into()), "psst"))); + let mut got = Vec::new(); + while got.len() < 3 { + let chat = rig + .event(|e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + got.push(chat); + } + got.sort_by_key(|m| m.text.clone()); + let targets: Vec<_> = got.iter().map(|m| (m.text.as_str(), m.target.clone())).collect(); + assert_eq!( + targets, + [ + ("in the channel", ChatTarget::Channel(GAMES)), + ("psst", ChatTarget::Private("alice=".into())), + ("to the server", ChatTarget::Server), + ] + ); + assert!( + got.iter().all(|m| m.author_uid.as_deref() == Some("alice=") && m.author_id == Some(8)) + ); + assert!(got.iter().all(|m| m.author_name == "alice" && m.ts_ms == 1_700_000_000_000)); + + // A poke, named by the sender's nickname and unique id. + rig.play(LinkEvent::Poke { + from: 8, + from_uid: Some("alice=".into()), + from_name: "alice".into(), + message: "wake up".into(), + }); + let poke = rig + .event(|e| match e { + LinkEvent::Poke { from, from_uid, from_name, message } => { + Some((from, from_uid, from_name, message)) + } + _ => None, + }) + .await; + assert_eq!(poke, (8, Some("alice=".into()), "alice".into(), "wake up".into())); + // A poke from somebody the snapshot does not hold is named all the same. + rig.play(LinkEvent::Poke { + from: 77, + from_uid: Some("hidden=".into()), + from_name: "hidden".into(), + message: "boo".into(), + }); + let poke = rig + .event(|e| match e { + LinkEvent::Poke { from: 77, from_uid, from_name, .. } => Some((from_uid, from_name)), + _ => None, + }) + .await; + assert_eq!(poke, (Some("hidden=".into()), "hidden".into())); + + // Voice: audio from alice's slot, talking from the media. + let voice = VoicePacket { + talker: TalkerId(8), + seq: 513, + codec: VoiceCodec::Voice, + whisper: false, + payload: OPUS_20_MS.to_vec(), + }; + rig.play(LinkEvent::Audio(voice.clone())); + let talking = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(talking, (8, true)); + let heard = rig + .event(|e| match e { + LinkEvent::Audio(packet) => Some(packet), + _ => None, + }) + .await; + assert_eq!(heard, voice); + // And silent 400 ms after her last packet. + let off = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(off, (8, false)); + // A whisper is marked, the end of a talk arrives empty. + rig.play(LinkEvent::Audio(VoicePacket { whisper: true, seq: 514, ..voice.clone() })); + let heard = rig + .event(|e| match e { + LinkEvent::Audio(packet) => Some(packet), + _ => None, + }) + .await; + assert!(heard.whisper && heard.seq == 514); + rig.play(LinkEvent::Audio(VoicePacket { seq: 515, payload: Vec::new(), ..voice })); + let heard = rig + .event(|e| match e { + LinkEvent::Audio(packet) => Some(packet), + _ => None, + }) + .await; + assert!(heard.is_end()); + + // Streams come through the port. + rig.play(LinkEvent::OwnStream(OwnStreamEvent::Live { + id: "s1".into(), + title: "screen".into(), + kind: StreamKind::Screen, + })); + let own = rig + .event(|e| match e { + LinkEvent::OwnStream(event) => Some(event), + _ => None, + }) + .await; + assert!(matches!(own, OwnStreamEvent::Live { ref id, .. } if id == "s1")); + rig.play(LinkEvent::StreamAudio { + stream: "s2".into(), + time: 960, + data: Arc::from(&[1u8, 2][..]), + }); + let audio = rig + .event(|e| match e { + LinkEvent::StreamAudio { stream, time, data } => Some((stream, time, data)), + _ => None, + }) + .await; + assert_eq!((audio.0.as_str(), audio.1, &*audio.2), ("s2", 960, &[1u8, 2][..])); + rig.play(LinkEvent::StreamAudioEnded("s2".into())); + let ended = rig + .event(|e| match e { + LinkEvent::StreamAudioEnded(stream) => Some(stream), + _ => None, + }) + .await; + assert_eq!(ended, "s2"); + + // An error of the link is an error of the session. + rig.play(LinkEvent::Error("move refused".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert_eq!(error, "move refused"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_change_of_presence_is_reported_once_with_the_own_channel() { + let mut rig = Rig::new(everything()).await; + // The same snapshot again changes nothing. + rig.play(LinkEvent::Presence(Box::new(presence()))); + // Bob leaves, alice moves, and we move. + let mut next = presence(); + next.clients.remove(&9); + next.clients.get_mut(&8).unwrap().channel = LOBBY; + next.clients.get_mut(&ME).unwrap().channel = LOBBY; + rig.play(LinkEvent::Presence(Box::new(next.clone()))); + let shown = rig + .event(|e| match e { + LinkEvent::Presence(p) => Some(*p), + _ => None, + }) + .await; + assert_eq!(shown.clients.len(), 2); + assert_eq!(shown.clients[&8].channel, LOBBY); + let own = rig + .event(|e| match e { + LinkEvent::OwnChannel(c) => Some(c), + _ => None, + }) + .await; + assert_eq!(own, LOBBY); +} + +// ---- how a connection ends ------------------------------------------------------ + +#[tokio::test(flavor = "multi_thread")] +async fn a_disconnect_command_ends_the_link_and_reports_no_reason() { + let mut rig = Rig::new(everything()).await; + rig.give(LinkCmd::Stream(StreamCmd::Shutdown("going".into()))); + rig.give(LinkCmd::Disconnect); + // The streams hear of their end before the link is told to go. + assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Shutdown(_)))); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Disconnect)); + rig.play(LinkEvent::Disconnected(None)); + let reason = rig + .event(|e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, None); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_link_that_ends_says_why_or_nothing() { + let mut rig = Rig::new(everything()).await; + rig.play(LinkEvent::Disconnected(Some("kicked: spam".into()))); + let reason = rig + .event(|e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason.as_deref(), Some("kicked: spam")); + + let mut rig = Rig::new(everything()).await; + rig.play(LinkEvent::Disconnected(None)); + let reason = rig + .event(|e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, None); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_connect_that_fails_is_a_disconnect_with_the_reason() { + let (conns, mut seen) = mpsc::unbounded_channel(); + let mut backends = Backends::empty(); + backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); + let link = SessionLink::new(backends); + let ctx = LocalCtx::standalone().link; + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + link.spawn(ConnectOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(LinkEvent::Disconnected(Some("connection refused".into()))).unwrap(); + let event = within("the end", events.recv()).await; + assert!(matches!(event, LinkEvent::Disconnected(Some(ref why)) if why == "connection refused")); + drop(cmd_tx); + + // No connector for the address's scheme. + let ctx = LocalCtx::standalone().link; + let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + let link = SessionLink::new(Backends::empty()); + link.spawn(ConnectOptions::new("voelin://host", "tester"), ctx, cmd_rx, event_tx); + let event = within("the end", events.recv()).await; + assert!( + matches!(event, LinkEvent::Disconnected(Some(ref why)) if why == "no connector for voelin://host"), + "a disconnect with the reason of the failed connect" + ); +} + +// ---- the TeamSpeak side alone --------------------------------------------------- + +/// A `LinkSession` over a recorder, made the way a connector makes it. +async fn open(capabilities: Capabilities) -> (Arc, mpsc::Receiver, Inner) { + let (conns, mut seen) = mpsc::unbounded_channel(); + let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); + let (mut params, _media) = connect_params("ts3server://fake.test?port=9987"); + params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; + params.hello.nickname = "tester".into(); + let connecting = tokio::spawn(connector.connect(params)); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(connected(capabilities)).unwrap(); + inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); + let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; + (connected.session, connected.pushes, inner) +} + +fn request(op: v1::request::Op) -> v1::request::Op { + op +} + +fn subscribe(scope: voelin_model::replica::ScopeId) -> v1::request::Op { + request(v1::request::Op::Subscribe(v1::Subscribe { + scope: Some(scope.to_proto()), + ..Default::default() + })) +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_welcome_names_the_host_the_user_and_what_the_link_can_do() { + let (session, _pushes, inner) = open(everything()).await; + assert_eq!(inner.options.address, "fake.test:9987"); + assert_eq!(inner.options.nickname, "tester"); + let welcome = session.welcome(); + // The own user is the own client's database id. + assert_eq!(welcome.user_id, 1_007); + let host = welcome.host.as_ref().unwrap(); + assert_eq!(host.name, "Test Server"); + let backend = host.backend.as_ref().unwrap(); + assert_eq!( + (backend.product.as_str(), backend.version.as_str(), backend.flavor.as_str()), + ("Fake", "1.2", "") + ); + let features = session.features(); + for feature in [ + "voice", + "chat", + "chat.bbcode", + "dm", + "sync.delta", + "roles", + "roles.channel", + "files", + "files.upload", + "mailbox", + "streams", + "streams.p2p", + "streams.audio", + "streams.approval", + ] { + assert!(features.has(feature), "{feature}"); + } + assert!(!features.has("voice.whisper") && !features.has("chat.typing")); + let limits = welcome.limits.as_ref().unwrap(); + assert_eq!(limits.max_chat_subscriptions, 16); + + // A link without files, mail and streams offers none of them. + let (plain, _pushes, _inner) = session_of_plain().await; + let features = plain.features(); + assert!( + features.has("chat") + && !features.has("files") + && !features.has("mailbox") + && !features.has("streams") + ); +} + +async fn session_of_plain() -> (Arc, mpsc::Receiver, Inner) { + open(Capabilities::default()).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_scope_is_synced_whole_and_then_by_changes_with_growing_revs() { + use v1::push::Body; + use voelin_model::replica::ScopeId; + let (session, mut pushes, _inner) = open(everything()).await; + // The server is the only one listed. + let listed = session + .request(v1::request::Op::List(v1::List { + kind: v1::EntityKind::Server as i32, + ..Default::default() + })) + .await + .unwrap(); + let v1::response::Result::Entities(entities) = listed else { panic!("the servers") }; + let [v1::Entity { kind: Some(v1::entity::Kind::Server(server)) }] = entities.items.as_slice() + else { + panic!("one server") + }; + assert_eq!( + (server.id, server.uid.as_str(), server.name.as_str()), + (1, "ts:server=", "Test Server") + ); + + session.request(subscribe(ScopeId::Server(1))).await.unwrap(); + let Body::SyncBegin(begin) = next_body(&mut pushes).await else { panic!("a sync begins") }; + assert_eq!(begin.mode, v1::SyncMode::Full as i32); + let Body::Change(first) = next_body(&mut pushes).await else { panic!("the channels") }; + let kinds: Vec<_> = first + .put + .iter() + .filter_map(|e| match &e.kind { + Some(v1::entity::Kind::Channel(c)) => Some(c.id), + _ => None, + }) + .collect(); + assert!(kinds.contains(&LOBBY) && kinds.contains(&GAMES), "{kinds:?}"); + let Body::SyncEnd(end) = next_body(&mut pushes).await else { panic!("a sync ends") }; + let cursor = end.cursor.unwrap(); + assert_eq!(cursor.rev, first.rev); + + // A change of the snapshot is a Change with a newer rev. + let mut next = presence(); + next.channels.get_mut(&LOBBY).unwrap().name = "renamed".into(); + _inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); + let Body::Change(change) = + within("a change", async { pushes.recv().await }).await.body.unwrap() + else { + panic!("a change") + }; + assert!(change.rev > cursor.rev); + assert_eq!(change.put.len(), 1); + assert!(change.del.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_first_join_is_the_seat_and_a_move_waits_for_the_link() { + let (session, _pushes, mut inner) = open(everything()).await; + let join = |channel: u64, password: &str| { + request(v1::request::Op::JoinVoice(v1::JoinVoice { + server_id: 1, + channel_id: channel, + password: password.into(), + ..Default::default() + })) + }; + // The seat: our voice state, nothing moved. + let seat = session.request(join(LOBBY, "")).await.unwrap(); + let v1::response::Result::Entities(seat) = seat else { panic!("a voice state") }; + let Some(v1::entity::Kind::Voice(voice)) = &seat.items[0].kind else { panic!("a voice state") }; + assert_eq!((voice.participant_id, voice.slot, voice.channel_id), (u32::from(ME), 8, GAMES)); + assert!(inner.cmds.try_recv().is_err(), "the seat moves nothing"); + + // A move: the link is asked, and the answer is our voice state in the new channel. + let moving = session.request(join(LOBBY, "pw")); + let LinkCmd::Move(channel, password) = within("a move", inner.cmds.recv()).await else { + panic!("a move") + }; + assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); + let mut next = presence(); + next.clients.get_mut(&ME).unwrap().channel = LOBBY; + inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); + let moved = within("the move", async { moving.await.ok() }).await; + let v1::response::Result::Entities(moved) = moved else { panic!("a voice state") }; + let Some(v1::entity::Kind::Voice(voice)) = &moved.items[0].kind else { + panic!("a voice state") + }; + assert_eq!(voice.channel_id, LOBBY); + + // A refusal of the link: the code says why. + let refused = session.request(join(GAMES, "wrong")); + let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; + inner.ctx.emit(Event::JoinFailed { session: 0, channel: GAMES, reason: JoinFailure::Password }); + let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; + assert_eq!(error.code(), Some(v1::ErrorCode::Password)); + let refused = session.request(join(GAMES, "")); + let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; + inner.ctx.emit(Event::JoinFailed { session: 0, channel: GAMES, reason: JoinFailure::Full }); + let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; + assert_eq!(error.code(), Some(v1::ErrorCode::Full)); + let refused = session.request(join(GAMES, "")); + let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; + inner.ctx.emit(Event::JoinFailed { + session: 0, + channel: GAMES, + reason: JoinFailure::Other("You are not allowed to join this channel.".into()), + }); + let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; + assert_eq!(error.code(), Some(v1::ErrorCode::Forbidden)); + assert!(error.to_string().contains("not allowed")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn requests_the_link_cannot_do_are_refused_with_the_feature() { + let (session, _pushes, mut inner) = open(everything()).await; + let error = session + .request(request(v1::request::Op::LeaveVoice(v1::LeaveVoice { server_id: 1 }))) + .await + .unwrap_err(); + assert_eq!(error.code(), Some(v1::ErrorCode::Unsupported)); + // A message into a voice channel we are not in. + let put = |channel_id: u64| { + request(v1::request::Op::Put(v1::Put { + writes: vec![v1::Write { + entity: Some(v1::Entity { + kind: Some(v1::entity::Kind::Message(v1::Message { + channel_id, + text: "hi".into(), + ..Default::default() + })), + }), + paths: Vec::new(), + }], + ..Default::default() + })) + }; + let error = session.request(put(LOBBY)).await.unwrap_err(); + assert_eq!(error.code(), Some(v1::ErrorCode::NotInChannel)); + // Our own channel's message is answered as written, and handed to the link. + let answer = session.request(put(GAMES)).await.unwrap(); + let v1::response::Result::Entities(stored) = answer else { panic!("the message") }; + let Some(v1::entity::Kind::Message(message)) = &stored.items[0].kind else { + panic!("a message") + }; + assert_eq!((message.text.as_str(), message.channel_id), ("hi", GAMES)); + assert!(message.id != 0); + assert!(matches!( + within("a chat", inner.cmds.recv()).await, + LinkCmd::SendChat(ChatTarget::Channel(GAMES), _) + )); + // A hello is part of connecting. + let hello = session.request(request(v1::request::Op::Hello(Default::default()))).await; + assert!(matches!(hello, Err(SessionError::Protocol(_)))); + // Without the feature, the file browser is refused before the link hears of it. + let (plain, _pushes, mut plain_inner) = session_of_plain().await; + let list = plain + .request(request(v1::request::Op::List(v1::List { + kind: v1::EntityKind::File as i32, + parent: GAMES, + ..Default::default() + }))) + .await + .unwrap_err(); + let SessionError::Rejected(error) = list else { panic!("a refusal") }; + assert_eq!((error.code(), error.feature.as_str()), (v1::ErrorCode::Unsupported, "files")); + assert!(plain_inner.cmds.try_recv().is_err()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn media_is_checked_before_it_reaches_the_link() { + let (session, _pushes, mut inner) = open(everything()).await; + let own = FlowId::new(8, 0); + let rtp = |flow: FlowId, payload: &[u8]| { + let mut header = voelin_proto::media::RtpHeader::new(111, 0, 0); + header.marker = true; + let mut out = bytes::BytesMut::new(); + header.write(flow, &mut out).unwrap(); + out.extend_from_slice(payload); + MediaPacket { flow, rtp: out.freeze() } + }; + assert_eq!( + session.send_media(MediaClass::Voice, rtp(own, &OPUS_20_MS)).unwrap(), + voelin_proto::link::Sent::Queued + ); + assert!(matches!(within("voice", inner.cmds.recv()).await, LinkCmd::Audio(_))); + // Somebody else's slot, a whisper flow, a class that is not voice. + let other = FlowId::new(9, 0); + assert!(matches!( + session.send_media(MediaClass::Voice, rtp(other, &OPUS_20_MS)), + Err(MediaError::NotOwned(_)) + )); + let whisper = FlowId::new(8, 1); + assert!(matches!( + session.send_media(MediaClass::Voice, rtp(whisper, &OPUS_20_MS)), + Err(MediaError::NotOwned(_)) + )); + assert!(matches!( + session.send_media(MediaClass::Video, rtp(own, &OPUS_20_MS)), + Err(MediaError::NotOwned(_)) + )); + // Over the limit. + let big = vec![0u8; voelin_proto::link::MAX_RTP]; + assert!(matches!( + session.send_media(MediaClass::Voice, rtp(own, &big)), + Err(MediaError::TooLarge { .. }) + )); + assert!(inner.cmds.try_recv().is_err()); + // After the end, nothing is sent. + session.close(v1::CloseCode::Normal, ""); + let _ = within("the disconnect", inner.cmds.recv()).await; + inner.events.send(LinkEvent::Disconnected(None)).unwrap(); + let reason = session.closed().await; + assert_eq!(reason, CloseReason::Local(v1::CloseCode::Normal)); + assert!(matches!( + session.send_media(MediaClass::Voice, rtp(own, &OPUS_20_MS)), + Err(MediaError::Closed) + )); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_session_closes_as_the_table_says() { + // We close it: a local, normal close. + let (session, _pushes, mut inner) = open(everything()).await; + session.close(v1::CloseCode::Normal, "bye"); + assert!(matches!(within("a disconnect", inner.cmds.recv()).await, LinkCmd::Disconnect)); + inner.events.send(LinkEvent::Disconnected(None)).unwrap(); + assert_eq!(session.closed().await, CloseReason::Local(v1::CloseCode::Normal)); + + // The link ends with a reason: the network, with the words. + let (session, _pushes, inner) = open(everything()).await; + inner.events.send(LinkEvent::Disconnected(Some("server shut down".into()))).unwrap(); + assert_eq!(session.closed().await, CloseReason::Network("server shut down".into())); + + // The link ends unasked and without a reason: a normal close by the host. + let (session, _pushes, inner) = open(everything()).await; + inner.events.send(LinkEvent::Disconnected(None)).unwrap(); + assert_eq!( + session.closed().await, + CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() } + ); + // What was asked of a closed session is refused with the reason. + let error = + session.request(request(v1::request::Op::List(Default::default()))).await.unwrap_err(); + assert!(matches!(error, SessionError::Closed(_)), "{error:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_connect_that_the_link_fails_is_an_error_with_its_reason() { + let (conns, mut seen) = mpsc::unbounded_channel(); + let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); + let (mut params, _media) = connect_params("ts3server://fake.test"); + params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; + let connecting = tokio::spawn(connector.connect(params)); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(LinkEvent::Disconnected(Some("connection refused".into()))).unwrap(); + let Err(error) = connecting.await.expect("the connect task") else { + panic!("a failed connect") + }; + assert!( + matches!(&error, SessionError::Closed(CloseReason::Network(why)) if why == "connection refused") + ); + + // A credential that is no TeamSpeak identity is refused before the link is asked. + let (params, _media) = connect_params("ts3server://fake.test"); + let Err(error) = connector.connect(params).await else { panic!("a refusal") }; + assert!(matches!(error, SessionError::Protocol(_)), "{error:?}"); +} + +/// The next push of the session, as its body. +async fn next_body(pushes: &mut mpsc::Receiver) -> v1::push::Body { + within("a push", pushes.recv()).await.body.expect("a push with a body") +} diff --git a/crates/voelin-core/src/ts_session/driver.rs b/crates/voelin-core/src/ts_session/driver.rs new file mode 100644 index 0000000..d832c55 --- /dev/null +++ b/crates/voelin-core/src/ts_session/driver.rs @@ -0,0 +1,1442 @@ +//! The task behind a [`LinkSession`](super::LinkSession): it plays the host +//! of a v1 session on top of a link's `LinkCmd`s and `LinkEvent`s +//! (`docs/session-seam.md` sections 3 to 5). +//! +//! It owns the state a host has: the entities of the scopes with a counter +//! of revs, the messages of the connection, the direct-message channels, +//! the requests that wait for the link's answer. Everything that reaches the +//! link goes through the one queue this task reads, in the order it was +//! issued. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use tracing::warn; +use voelin_audio::EncodedVoice; +use voelin_model::replica::{Key, ScopeId}; +use voelin_model::{ChatMessage, ChatTarget, Presence}; +use voelin_proto::link::{CloseReason, Download, MediaSink, SessionError, Upload}; +use voelin_proto::v1::{ + self, Entity, ErrorCode, entity::Kind, push::Body, request::Op, response::Result as Answer, + signal::Body as SignalBody, +}; + +use super::entities::{self, Built, Layer}; +use super::ids::{self, SERVER_CHAT, SERVER_ID}; +use super::media::Downlink; +use crate::files::{self, FileEntry, RequestId}; +use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkEvent, Remote, StreamEvent}; +use crate::offline::{OfflineMessage, OfflineMessageInfo}; +use crate::stream::StreamCmd; +use crate::{Event, JoinFailure}; + +/// How long a request waits for the link's answer. +const ANSWER_TIME: Duration = Duration::from_secs(30); +/// How long a move waits for our channel to change. +const MOVE_TIME: Duration = Duration::from_secs(10); +/// The messages of a channel kept for a CHAT scope that is subscribed later +/// (the default window of protocol section 5.4). +const WINDOW: usize = 50; +/// Entities in one `Change` frame of a sync. +const SYNC_CHUNK: usize = 256; +/// Most CHAT scopes at once (`Limits.max_chat_subscriptions`). +pub(super) const MAX_CHAT_SUBSCRIPTIONS: u32 = 16; +/// A request that waits on this task's answer. +pub(super) type Reply = oneshot::Sender>; + +/// What a [`LinkSession`](super::LinkSession) hands its task. +pub(super) enum Cmd { + Request { op: Op, reply: Reply }, + Notify(Op), + Read { request: v1::FileRead, reply: oneshot::Sender> }, + Write { request: v1::FileWrite, reply: oneshot::Sender> }, + Audio(EncodedVoice), + Stream(StreamCmd), + Close { code: v1::CloseCode, reason: String }, +} + +/// What the connection is, as the link told it. +pub(super) struct Config { + pub ts6: bool, + pub own_client: u16, + pub nickname: String, + pub own_uid: Option, + pub files: bool, + pub mail: bool, +} + +/// Everything the task is made of. +pub(super) struct Parts { + pub cfg: Config, + pub inner: mpsc::UnboundedSender, + pub events: mpsc::UnboundedReceiver, + /// What the link reported before the session was handed out (its first + /// snapshot), to be handled first. + pub early: Vec, + pub bus: broadcast::Receiver, + pub engine_bus: broadcast::Sender, + pub pushes: mpsc::Sender, + pub media: Arc, + pub port: Option>, + pub closed: watch::Sender>, + /// The `Server` entity made of the link's `Connected`. + pub server: v1::Server, + pub epoch: u64, +} + +/// A request the link has to answer. +enum Waiting { + Files, + Done(Vec), + /// A delete of files in several channels: how many answers are left. + Deleted { + left: usize, + failed: Option, + }, + MailList, + MailGet, + Move { + channel: u64, + }, +} + +struct Pending { + waiting: Waiting, + reply: Option, + deadline: Instant, +} + +/// The state of the task. +pub(super) struct Driver { + cfg: Config, + inner: mpsc::UnboundedSender, + events: mpsc::UnboundedReceiver, + early: Vec, + bus: broadcast::Receiver, + bus_open: bool, + engine_bus: broadcast::Sender, + pushes: mpsc::Sender, + media: Arc, + port: Option>, + closed: watch::Sender>, + /// We asked for the connection to end, and with what code. + closing: Option, + /// The receiver of the pushes is gone: nobody is listening any more. + gone: bool, + + epoch: u64, + rev: u64, + subs: HashSet, + /// Entities by scope, as a subscriber would have them. + server: Layer, + live: Layer, + home: Layer, + /// Users of messages and pokes who are on no snapshot (LIVE). + extras: BTreeMap, + /// The clients of the last snapshot by unique id: user and participant. + by_uid: HashMap, + /// The clients of the last snapshot by client id: their user ids. + by_client: BTreeMap, + own_user: Option, + own_channel: Option, + /// Direct-message channels: the peer's unique id and user id. + dms: BTreeMap, + /// The newest messages of each channel with the rev they came at. + chats: HashMap>, + last_message_id: u64, + /// The first `JoinVoice` has been answered. + seated: bool, + next_request: RequestId, + pending: HashMap, + downlink: Downlink, +} + +fn now_ms() -> i64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or_default() +} + +/// An error the link answers a request with. +pub(super) fn rejected(code: ErrorCode, message: impl Into) -> SessionError { + SessionError::Rejected(Box::new(v1::Error { + code: code as i32, + message: message.into(), + ..Default::default() + })) +} + +/// A request that needs a feature this session does not offer. +fn unsupported(feature: &str, what: &str) -> SessionError { + SessionError::Rejected(Box::new(v1::Error { + code: ErrorCode::Unsupported as i32, + message: format!("{what} is not offered by this connection"), + feature: feature.into(), + ..Default::default() + })) +} + +fn entity(kind: Kind) -> Entity { + Entity { kind: Some(kind) } +} + +fn entities_answer(items: Vec, rev: u64) -> Answer { + Answer::Entities(v1::Entities { items, next: Default::default(), rev }) +} + +fn ack(rev: u64) -> Answer { + Answer::Ack(v1::Ack { rev }) +} + +/// A path's directory and file name: `/docs/a.txt` is (`/docs`, `a.txt`), +/// `/a.txt` is (`/`, `a.txt`). +fn split_path(path: &str) -> (String, String) { + match path.rsplit_once('/') { + Some((dir, name)) => (files::normalize_dir(dir), name.to_owned()), + None => ("/".into(), path.to_owned()), + } +} + +/// The reverse of [`split_path`] for what a key says. +fn join(dir: &str, name: &str) -> String { + if dir.is_empty() { name.to_owned() } else { files::join_path(dir, name) } +} + +fn remote(channel: u64, password: &str, path: String) -> Remote { + Remote { channel, password: (!password.is_empty()).then(|| password.to_owned()), path } +} + +impl Driver { + pub(super) fn new(parts: Parts) -> Self { + let Parts { + cfg, + inner, + events, + early, + bus, + engine_bus, + pushes, + media, + port, + closed, + server, + epoch, + } = parts; + let mut server_layer = Layer::new(); + let server_entity = entity(Kind::Server(server)); + if let Some(key) = Key::of(&server_entity) { + server_layer.insert(key, server_entity); + } + let chat = entity(Kind::Channel(v1::Channel { + id: SERVER_CHAT, + server_id: SERVER_ID, + kind: v1::ChannelKind::ServerChat as i32, + name: "Server chat".into(), + ..Default::default() + })); + if let Some(key) = Key::of(&chat) { + server_layer.insert(key, chat); + } + let mut driver = Self { + cfg, + inner, + events, + early, + bus, + bus_open: true, + engine_bus, + pushes, + media, + port, + closed, + closing: None, + gone: false, + epoch, + rev: 1, + subs: HashSet::new(), + server: server_layer, + live: Layer::new(), + home: Layer::new(), + extras: BTreeMap::new(), + by_uid: HashMap::new(), + by_client: BTreeMap::new(), + own_user: None, + own_channel: None, + dms: BTreeMap::new(), + chats: HashMap::new(), + last_message_id: 0, + seated: false, + next_request: 1, + pending: HashMap::new(), + downlink: Downlink::default(), + }; + driver.own_user = driver.initial_own_user(); + driver.home = driver.home_layer(); + driver + } + + /// The own user before a snapshot names it: the unique id the link told. + fn initial_own_user(&self) -> Option { + let uid = self.cfg.own_uid.as_deref()?; + Some(entities::bare_user(uid, &self.cfg.nickname, self.cfg.ts6)) + } + + /// The user id we are (the own client's database id once a snapshot says + /// it). + pub(super) fn own_user_id(&self) -> u64 { + self.own_user.as_ref().map_or(0, |user| user.id) + } + + pub(super) async fn run(mut self, mut cmds: mpsc::UnboundedReceiver) { + let mut tick = tokio::time::interval(Duration::from_millis(250)); + let mut commands_open = true; + // What the link said before the session was handed out. + for event in std::mem::take(&mut self.early) { + self.event(event).await; + } + loop { + tokio::select! { + biased; + cmd = cmds.recv(), if commands_open => match cmd { + Some(cmd) => self.command(cmd).await, + None => { + // Every handle is gone: nobody can ask for the end any more. + commands_open = false; + self.close(v1::CloseCode::Normal, String::new()); + } + }, + event = self.events.recv() => match event { + Some(LinkEvent::Disconnected(reason)) => { + self.ended(reason); + return; + } + Some(event) => self.event(event).await, + None => { + self.ended(None); + return; + } + }, + bus = self.bus.recv(), if self.bus_open => match bus { + Ok(event) => self.bus_event(event), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(missed = n, "the link's answers lagged; requests may time out"); + } + Err(broadcast::error::RecvError::Closed) => self.bus_open = false, + }, + _ = tick.tick() => self.tick(), + } + if self.gone { + // Nobody listens: end the connection as a closed session does. + let _ = self.inner.send(LinkCmd::Disconnect); + self.ended(None); + return; + } + } + } + + /// The connection ended, in whatever way: tell `closed()`. + fn ended(&mut self, reason: Option) { + let close = match (self.closing.take(), reason) { + (Some(local), _) => local, + (None, Some(reason)) => CloseReason::Network(reason), + (None, None) => { + CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() } + } + }; + // What still waits will not be answered. + self.pending.clear(); + self.closed.send_replace(Some(close)); + } + + fn send_inner(&self, cmd: LinkCmd) { + let _ = self.inner.send(cmd); + } + + /// A push to the session; false once nobody listens. + async fn push(&mut self, body: Body) { + if self.pushes.send(v1::Push { body: Some(body) }).await.is_err() { + self.gone = true; + } + } + + async fn notice(&mut self, level: v1::NoticeLevel, text: String) { + let signal = v1::Signal { + body: Some(SignalBody::Notice(v1::Notice { + level: level as i32, + text, + server_id: SERVER_ID, + ..Default::default() + })), + ..Default::default() + }; + self.push(Body::Signal(signal)).await; + } + + // ---- commands --------------------------------------------------------- + + async fn command(&mut self, cmd: Cmd) { + match cmd { + Cmd::Request { op, reply } => self.request(op, reply).await, + Cmd::Notify(op) => self.notify(op), + Cmd::Read { request, reply } => self.read(request, reply), + Cmd::Write { request, reply } => self.write(request, reply), + Cmd::Audio(voice) => self.send_inner(LinkCmd::Audio(voice)), + Cmd::Stream(cmd) => self.send_inner(LinkCmd::Stream(cmd)), + Cmd::Close { code, reason } => self.close(code, reason), + } + } + + fn close(&mut self, code: v1::CloseCode, _reason: String) { + if self.closing.is_none() { + self.closing = Some(CloseReason::Local(code)); + } + self.send_inner(LinkCmd::Disconnect); + } + + async fn request(&mut self, op: Op, reply: Reply) { + let answer = match op { + Op::Subscribe(subscribe) => self.subscribe(subscribe).await, + Op::Unsubscribe(unsubscribe) => { + if let Some(scope) = unsubscribe.scope.as_ref().and_then(ScopeId::from_proto) { + self.subs.remove(&scope); + } + Ok(ack(self.rev)) + } + Op::List(list) => return self.list(list, reply), + Op::Put(put) => return self.put(put, reply).await, + Op::Delete(delete) => return self.delete(delete, reply), + Op::Signal(signal) => self.signal(signal), + Op::JoinVoice(join) => return self.join(join, reply), + Op::LeaveVoice(_) => Err(unsupported("voice.leave", "leaving voice")), + _ => Err(rejected( + ErrorCode::Unsupported, + "this request is not offered by this connection", + )), + }; + let _ = reply.send(answer); + } + + /// Fire and forget: our own mute flags. Everything else is ignored. + fn notify(&mut self, op: Op) { + let Op::Put(put) = op else { return }; + for write in put.writes { + let Some(Entity { kind: Some(Kind::Voice(voice)) }) = write.entity else { continue }; + let mute = path_of("voelin.v1.VoiceState", "self_mute"); + let deaf = path_of("voelin.v1.VoiceState", "self_deaf"); + for path in &write.paths { + if Some(path.numbers.as_slice()) == mute.as_deref() { + self.send_inner(LinkCmd::SetInputMuted(voice.self_mute)); + } else if Some(path.numbers.as_slice()) == deaf.as_deref() { + self.send_inner(LinkCmd::SetOutputMuted(voice.self_deaf)); + } + } + } + } + + // ---- subscriptions and syncs ----------------------------------------- + + async fn subscribe(&mut self, subscribe: v1::Subscribe) -> Result { + let scope = subscribe + .scope + .as_ref() + .and_then(ScopeId::from_proto) + .ok_or_else(|| rejected(ErrorCode::BadRequest, "no scope"))?; + match scope { + ScopeId::Home => {} + ScopeId::Server(id) | ScopeId::Live(id) if id == SERVER_ID => {} + ScopeId::Server(_) | ScopeId::Live(_) => { + return Err(rejected(ErrorCode::NotFound, "no such server")); + } + ScopeId::Chat(channel) => { + if !self.chat_channel(channel) { + return Err(rejected(ErrorCode::NotFound, "no such channel")); + } + let chats = self.subs.iter().filter(|s| matches!(s, ScopeId::Chat(_))).count(); + if !self.subs.contains(&scope) && chats as u32 >= MAX_CHAT_SUBSCRIPTIONS { + return Err(rejected(ErrorCode::QuotaExceeded, "too many chat subscriptions")); + } + } + } + self.subs.insert(scope); + self.sync(scope, subscribe.since.as_ref(), subscribe.limit).await; + Ok(ack(self.rev)) + } + + /// Whether a channel's chat can be subscribed: the server chat, a channel + /// of the server, a direct-message channel. + fn chat_channel(&self, channel: u64) -> bool { + channel == SERVER_CHAT + || self.dms.contains_key(&channel) + || self.server.contains_key(&Key::Channel { id: channel }) + } + + /// The entities of a scope. + fn layer(&self, scope: ScopeId) -> Vec { + match scope { + ScopeId::Home => self.home.values().cloned().collect(), + ScopeId::Server(_) => self.server.values().cloned().collect(), + ScopeId::Live(_) => self.live.values().cloned().collect(), + ScopeId::Chat(channel) => self + .chats + .get(&channel) + .map(|window| { + window.iter().map(|(_, m)| entity(Kind::Message(m.clone()))).collect() + }) + .unwrap_or_default(), + } + } + + /// Send a scope's sync: its whole state, or (CHAT, with a cursor of this + /// connection) the messages after the cursor. + async fn sync(&mut self, scope: ScopeId, since: Option<&v1::Cursor>, limit: u32) { + let window = if limit == 0 { WINDOW } else { (limit as usize).min(WINDOW) }; + let delta = match (scope, since) { + (ScopeId::Chat(_), Some(cursor)) => { + cursor.epoch == self.epoch && cursor.rev <= self.rev + } + _ => false, + }; + let items: Vec = match (scope, delta) { + (ScopeId::Chat(channel), true) => { + let after = since.map_or(0, |c| c.rev); + self.chats + .get(&channel) + .map(|w| { + w.iter() + .filter(|(rev, _)| *rev > after) + .map(|(_, m)| entity(Kind::Message(m.clone()))) + .collect() + }) + .unwrap_or_default() + } + (ScopeId::Chat(_), false) => { + let all = self.layer(scope); + let skip = all.len().saturating_sub(window); + all.into_iter().skip(skip).collect() + } + _ => self.layer(scope), + }; + let mode = if delta { v1::SyncMode::Delta } else { v1::SyncMode::Full }; + let proto = scope.to_proto(); + self.push(Body::SyncBegin(v1::SyncBegin { + scope: Some(proto), + mode: mode as i32, + epoch: self.epoch, + })) + .await; + for chunk in items.chunks(SYNC_CHUNK) { + self.push(Body::Change(v1::Change { + scope: Some(proto), + rev: self.rev, + put: chunk.to_vec(), + del: Vec::new(), + })) + .await; + } + self.push(Body::SyncEnd(v1::SyncEnd { + scope: Some(proto), + cursor: Some(v1::Cursor { epoch: self.epoch, rev: self.rev }), + gap: false, + })) + .await; + } + + /// A change of a scope, pushed to its subscribers (the rev counts either + /// way). + async fn commit(&mut self, scope: ScopeId, put: Vec, del: Vec) { + if put.is_empty() && del.is_empty() { + return; + } + self.rev += 1; + if self.subs.contains(&scope) { + let change = v1::Change { scope: Some(scope.to_proto()), rev: self.rev, put, del }; + self.push(Body::Change(change)).await; + } + } + + // ---- what the link reports ------------------------------------------- + + async fn event(&mut self, event: LinkEvent) { + match event { + LinkEvent::Connected { .. } => {} + LinkEvent::Presence(presence) => self.presence(*presence).await, + LinkEvent::OwnChannel(channel) => { + self.own_channel = Some(channel); + self.settle_moves(); + } + LinkEvent::Chat(message) => self.chat(message).await, + LinkEvent::Poke { from, from_uid, from_name, message } => { + let (user, _) = self.sender(from_uid.as_deref(), &from_name, Some(from)).await; + let signal = v1::Signal { + from_user: user, + from_participant: u32::from(from), + to: Some(v1::SignalTarget { + server_id: SERVER_ID, + participant_id: u32::from(self.cfg.own_client), + ..Default::default() + }), + body: Some(SignalBody::Poke(v1::Poke { message })), + }; + self.push(Body::Signal(signal)).await; + } + LinkEvent::Audio(packet) => { + if let Some(rtp) = self.downlink.wrap(&packet, Instant::now()) { + self.media.media(rtp); + } + } + // Who is talking is derived from the media (protocol section 6.4). + LinkEvent::Talking { .. } => {} + LinkEvent::OwnStream(event) => self.stream_event(StreamEvent::OwnStream(event)), + LinkEvent::StreamAudio { stream, time, data } => { + self.stream_event(StreamEvent::Audio { stream, time, data }); + } + LinkEvent::StreamAudioEnded(stream) => { + self.stream_event(StreamEvent::AudioEnded(stream)) + } + LinkEvent::Error(text) => self.notice(v1::NoticeLevel::Error, text).await, + LinkEvent::Disconnected(_) => {} + } + } + + fn stream_event(&mut self, event: StreamEvent) { + if let Some(port) = &self.port { + let _ = port.send(event); + } + } + + /// A snapshot of the server: the entities of the scopes that changed. + async fn presence(&mut self, presence: Presence) { + let own = Some(self.cfg.own_client); + let Built { server, live, own_user, by_uid } = + entities::build(&presence, self.cfg.ts6, own); + self.by_client = presence + .clients + .values() + .filter_map(|client| { + let key = Key::Voice { server_id: SERVER_ID, participant_id: u32::from(client.id) }; + let Some(Entity { kind: Some(Kind::Voice(voice)) }) = live.get(&key) else { + return None; + }; + Some((client.id, voice.user_id)) + }) + .collect(); + self.by_uid = by_uid; + if let Some(own) = presence.clients.get(&self.cfg.own_client) { + self.own_channel = Some(own.channel); + } + if own_user.is_some() { + self.own_user = own_user; + } + // Clients that left take their talk state with them. + let gone: Vec = self + .by_client + .keys() + .copied() + .filter(|id| !presence.clients.contains_key(id)) + .collect(); + for id in gone { + self.downlink.forget(id); + } + + let (put, del) = entities::diff(&self.server, &server); + self.server = server; + self.commit(ScopeId::Server(SERVER_ID), put, del).await; + + let mut live = live; + for (id, user) in &self.extras { + let key = Key::User { id: *id }; + live.entry(key).or_insert_with(|| entity(Kind::User(user.clone()))); + } + let (put, del) = entities::diff(&self.live, &live); + self.live = live; + self.commit(ScopeId::Live(SERVER_ID), put, del).await; + + self.refresh_home().await; + self.settle_moves(); + } + + fn home_layer(&self) -> Layer { + let mut home = Layer::new(); + if let Some(user) = &self.own_user { + let entity = entity(Kind::User(user.clone())); + if let Some(key) = Key::of(&entity) { + home.insert(key, entity); + } + } + let own = self.own_user_id(); + for (channel, (_, peer)) in &self.dms { + let name = self.dm_name(*peer); + let entity = entity(Kind::Channel(v1::Channel { + id: *channel, + server_id: 0, + kind: v1::ChannelKind::Dm as i32, + name, + recipients: vec![own, *peer], + ..Default::default() + })); + if let Some(key) = Key::of(&entity) { + home.insert(key, entity); + } + } + home + } + + fn dm_name(&self, peer: u64) -> String { + match self.live.get(&Key::User { id: peer }) { + Some(Entity { kind: Some(Kind::User(user)) }) => user.name.clone(), + _ => String::new(), + } + } + + async fn refresh_home(&mut self) { + let home = self.home_layer(); + let (put, del) = entities::diff(&self.home, &home); + self.home = home; + self.commit(ScopeId::Home, put, del).await; + } + + /// The user and participant a message or poke is from: a client of the + /// snapshot, or a user made up for the sender (put into LIVE first). + async fn sender(&mut self, uid: Option<&str>, name: &str, client: Option) -> (u64, u32) { + if let Some(uid) = uid.filter(|u| !u.is_empty()) + && let Some((user, participant)) = self.by_uid.get(uid).copied() + { + return (user, participant); + } + if let Some(client) = client + && let Some(user) = self.by_client.get(&client).copied() + { + return (user, u32::from(client)); + } + let participant = client.map_or(0, u32::from); + match uid.filter(|u| !u.is_empty()) { + Some(uid) => (self.extra_user(uid, name).await, participant), + None if client.is_some() => { + // A sender with no unique id: by its client id. + let id = ids::synthetic_user(&format!("client:{}", participant)); + (id, participant) + } + None => (0, participant), + } + } + + /// A user for a unique id the snapshot does not hold, put into LIVE. + async fn extra_user(&mut self, uid: &str, name: &str) -> u64 { + let id = ids::synthetic_user(uid); + if let std::collections::btree_map::Entry::Vacant(slot) = self.extras.entry(id) { + let user = entities::bare_user(uid, name, self.cfg.ts6); + slot.insert(user.clone()); + let entity = entity(Kind::User(user)); + if let Some(key) = Key::of(&entity) + && !self.live.contains_key(&key) + { + self.live.insert(key, entity.clone()); + self.commit(ScopeId::Live(SERVER_ID), vec![entity], Vec::new()).await; + } + } + id + } + + /// A message of the book: kept per channel, and pushed to the channel's + /// subscribers. + async fn chat(&mut self, message: ChatMessage) { + let (channel, peer) = match &message.target { + ChatTarget::Server => (SERVER_CHAT, None), + ChatTarget::Channel(channel) => (*channel, None), + ChatTarget::Private(uid) => (ids::dm_channel(uid), Some(uid.clone())), + }; + let (user, _) = self + .sender(message.author_uid.as_deref(), &message.author_name, message.author_id) + .await; + if let Some(uid) = peer { + // The author is the peer, unless the message is our own echo. + let name = if message.author_uid.as_deref() == Some(uid.as_str()) { + message.author_name.as_str() + } else { + "" + }; + self.ensure_dm(channel, &uid, name).await; + } + let id = self.next_message_id(); + let stored = v1::Message { + id, + channel_id: channel, + author_id: user, + author_name: message.author_name, + ts_ms: message.ts_ms, + text: message.text, + format: v1::TextFormat::Bbcode as i32, + flags: if message.via_relay { v1::MessageFlag::Relayed as u32 } else { 0 }, + // Only what the link said: a message the link names no client for has + // no participant. + author_participant: message.author_id.map_or(0, u32::from), + ..Default::default() + }; + self.store(channel, stored).await; + } + + /// Remember a message and push it to its channel's subscribers. + async fn store(&mut self, channel: u64, mut message: v1::Message) { + self.rev += 1; + message.rev = 0; + let rev = self.rev; + let window = self.chats.entry(channel).or_default(); + window.push_back((rev, message.clone())); + while window.len() > WINDOW { + window.pop_front(); + } + if self.subs.contains(&ScopeId::Chat(channel)) { + let change = v1::Change { + scope: Some(ScopeId::Chat(channel).to_proto()), + rev, + put: vec![entity(Kind::Message(message))], + del: Vec::new(), + }; + self.push(Body::Change(change)).await; + } + } + + /// Message ids grow with time: the milliseconds since the epoch shifted + /// left by 12 bits, plus a counter in the low bits (protocol 11.1). + fn next_message_id(&mut self) -> u64 { + let now = (now_ms().max(0) as u64) << 12; + self.last_message_id = now.max(self.last_message_id + 1); + self.last_message_id + } + + /// The direct-message channel with a peer (made in HOME on first use). + async fn ensure_dm(&mut self, channel: u64, uid: &str, name: &str) { + if self.dms.contains_key(&channel) { + return; + } + let peer = match self.by_uid.get(uid) { + Some((user, _)) => *user, + None => self.extra_user(uid, name).await, + }; + self.dms.insert(channel, (uid.to_owned(), peer)); + self.refresh_home().await; + } + + // ---- answers from the link ------------------------------------------- + + fn bus_event(&mut self, event: Event) { + match event { + Event::FileList { request, channel, path, result, .. } => { + let Some(Pending { waiting: Waiting::Files, reply, .. }) = + self.pending.remove(&request) + else { + return; + }; + let answer = result.map_err(|e| rejected(ErrorCode::Unavailable, e)).map(|list| { + let items = list.into_iter().map(|e| file_entity(channel, &path, e)).collect(); + entities_answer(items, self.rev) + }); + reply_to(reply, answer); + } + Event::RequestDone { request, result, .. } => self.done(request, result), + Event::OfflineMessages { request, result, .. } => { + let Some(Pending { waiting: Waiting::MailList, reply, .. }) = + self.pending.remove(&request) + else { + return; + }; + let answer = result.map_err(|e| rejected(ErrorCode::Unavailable, e)).map(|list| { + entities_answer(list.into_iter().map(mail_info).collect(), self.rev) + }); + reply_to(reply, answer); + } + Event::OfflineMessage { request, result, .. } => { + let Some(Pending { waiting: Waiting::MailGet, reply, .. }) = + self.pending.remove(&request) + else { + return; + }; + let answer = result + .map_err(|e| rejected(ErrorCode::NotFound, e)) + .map(|mail| entities_answer(vec![mail_full(mail)], self.rev)); + reply_to(reply, answer); + } + Event::JoinFailed { channel, reason, .. } => { + let found = self.pending.iter().find_map(|(id, p)| { + matches!(p.waiting, Waiting::Move { channel: c } if c == channel).then_some(*id) + }); + if let Some(id) = found + && let Some(pending) = self.pending.remove(&id) + { + let error = match reason { + JoinFailure::Password => rejected( + ErrorCode::Password, + "the channel's password is missing or wrong", + ), + JoinFailure::Full => rejected(ErrorCode::Full, "the channel is full"), + JoinFailure::Other(text) => rejected(ErrorCode::Forbidden, text), + }; + reply_to(pending.reply, Err(error)); + } + } + // What the stream task says (its own bus events) goes to the engine. + other => { + let _ = self.engine_bus.send(other); + } + } + } + + /// The link answered a request that has no data. + fn done(&mut self, request: RequestId, result: Result<(), String>) { + let Some(mut pending) = self.pending.remove(&request) else { return }; + match &mut pending.waiting { + Waiting::Done(items) => { + let answer = result + .map_err(|e| rejected(ErrorCode::Unavailable, e)) + .map(|()| entities_answer(std::mem::take(items), self.rev)); + reply_to(pending.reply, answer); + } + Waiting::Deleted { left, failed } => { + *left -= 1; + if let Err(e) = result { + failed.get_or_insert(e); + } + if *left == 0 { + let answer = match failed.take() { + Some(e) => Err(rejected(ErrorCode::Unavailable, e)), + None => Ok(ack(self.rev)), + }; + reply_to(pending.reply, answer); + } else { + self.pending.insert(request, pending); + } + } + _ => {} + } + } + + /// A move that has reached its channel is answered with our voice state. + fn settle_moves(&mut self) { + let Some(channel) = self.own_channel else { return }; + let settled: Vec = self + .pending + .iter() + .filter(|(_, p)| matches!(p.waiting, Waiting::Move { channel: c } if c == channel)) + .map(|(id, _)| *id) + .collect(); + for id in settled { + if let Some(pending) = self.pending.remove(&id) { + reply_to(pending.reply, Ok(self.own_voice())); + } + } + } + + /// Our own voice state: the snapshot's, or what the seat says. + fn own_voice(&self) -> Answer { + let key = + Key::Voice { server_id: SERVER_ID, participant_id: u32::from(self.cfg.own_client) }; + let voice = match self.live.get(&key) { + Some(Entity { kind: Some(Kind::Voice(voice)) }) => voice.clone(), + _ => v1::VoiceState { + server_id: SERVER_ID, + participant_id: u32::from(self.cfg.own_client), + user_id: self.own_user_id(), + channel_id: self.own_channel.unwrap_or(0), + slot: entities::slot(self.cfg.own_client), + nick: self.cfg.nickname.clone(), + ..Default::default() + }, + }; + entities_answer(vec![entity(Kind::Voice(voice))], self.rev) + } + + fn tick(&mut self) { + let now = Instant::now(); + let expired: Vec = + self.pending.iter().filter(|(_, p)| p.deadline <= now).map(|(id, _)| *id).collect(); + for id in expired { + if let Some(pending) = self.pending.remove(&id) { + reply_to(pending.reply, Err(SessionError::Timeout)); + } + } + } + + fn wait(&mut self, waiting: Waiting, reply: Reply, time: Duration) -> RequestId { + let id = self.next_request; + self.next_request += 1; + self.pending + .insert(id, Pending { waiting, reply: Some(reply), deadline: Instant::now() + time }); + id + } + + // ---- requests --------------------------------------------------------- + + fn list(&mut self, list: v1::List, reply: Reply) { + match v1::EntityKind::try_from(list.kind) { + Ok(v1::EntityKind::Server) => { + let items = + self.server.get(&Key::Server { id: SERVER_ID }).cloned().into_iter().collect(); + let _ = reply.send(Ok(entities_answer(items, self.rev))); + } + Ok(v1::EntityKind::File) if self.cfg.files => { + let dir = remote(list.parent, &list.password, list.path); + let request = self.wait(Waiting::Files, reply, ANSWER_TIME); + self.send_inner(LinkCmd::ListFiles { request, dir }); + } + Ok(v1::EntityKind::File) => { + let _ = reply.send(Err(unsupported("files", "the file browser"))); + } + Ok(v1::EntityKind::Mail) if self.cfg.mail => { + if list.ids.len() == 1 { + let id = u32::try_from(list.ids[0]).unwrap_or(u32::MAX); + let request = self.wait(Waiting::MailGet, reply, ANSWER_TIME); + self.send_inner(LinkCmd::OfflineGet { request, id }); + } else { + let request = self.wait(Waiting::MailList, reply, ANSWER_TIME); + self.send_inner(LinkCmd::OfflineList { request }); + } + } + Ok(v1::EntityKind::Mail) => { + let _ = reply.send(Err(unsupported("mailbox", "offline messages"))); + } + Ok(v1::EntityKind::Message) => { + let _ = reply.send(Err(unsupported("chat.history", "the message history"))); + } + _ => { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "this kind cannot be listed on this connection", + ))); + } + } + } + + async fn put(&mut self, put: v1::Put, reply: Reply) { + let mut writes = put.writes; + if writes.len() != 1 { + let _ = reply.send(Err(rejected( + ErrorCode::BadRequest, + "this connection takes one write at a time", + ))); + return; + } + let write = writes.remove(0); + let Some(Entity { kind: Some(kind) }) = write.entity else { + let _ = reply.send(Err(rejected(ErrorCode::BadRequest, "a write without an entity"))); + return; + }; + match kind { + Kind::Message(message) => { + let answer = self.put_message(message); + let _ = reply.send(answer); + } + Kind::Channel(channel) if channel.kind == v1::ChannelKind::Dm as i32 => { + let answer = self.put_dm(channel).await; + let _ = reply.send(answer); + } + Kind::Voice(voice) => { + // Our own flags, as a request that wants its answer. + self.notify(Op::Put(v1::Put { + writes: vec![v1::Write { + entity: Some(entity(Kind::Voice(voice))), + paths: write.paths, + }], + ..Default::default() + })); + let _ = reply.send(Ok(self.own_voice())); + } + Kind::User(user) => { + let hash = path_of("voelin.v1.User", "avatar.hash"); + if write.paths.iter().any(|p| Some(p.numbers.as_slice()) == hash.as_deref()) { + let image = user.avatar.clone().unwrap_or_default(); + let items = vec![entity(Kind::User(user))]; + let request = self.wait(Waiting::Done(items), reply, ANSWER_TIME); + self.send_inner(LinkCmd::SetAvatarHash { + request: Some(request), + hash: image.hash, + }); + } else { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "only the avatar of a user can be written", + ))); + } + } + Kind::File(file) => self.put_file(file, reply), + Kind::Mail(mail) => self.put_mail(mail, &write.paths, reply), + _ => { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "this kind cannot be written on this connection", + ))); + } + } + } + + /// A message of ours: handed to the link, answered at once as written. The + /// link reports failures later, as a notice, and its echo of the message + /// arrives as a `Change` with an id of its own. + fn put_message(&mut self, message: v1::Message) -> Result { + let channel = message.channel_id; + let target = if channel == SERVER_CHAT { + ChatTarget::Server + } else if let Some((uid, _)) = self.dms.get(&channel) { + ChatTarget::Private(uid.clone()) + } else if self.server.contains_key(&Key::Channel { id: channel }) { + if self.own_channel.is_some_and(|own| own != channel) { + return Err(rejected( + ErrorCode::NotInChannel, + "channel chat reaches the channel we are in only", + )); + } + ChatTarget::Channel(channel) + } else if self.own_channel.is_none() || self.own_channel == Some(channel) { + // Nothing is known of the tree yet: the link decides. + ChatTarget::Channel(channel) + } else { + return Err(rejected(ErrorCode::NotFound, "no such channel")); + }; + self.send_inner(LinkCmd::SendChat(target, message.text.clone())); + let id = self.next_message_id(); + let stored = v1::Message { + id, + rev: self.rev, + author_id: self.own_user_id(), + ts_ms: now_ms(), + author_participant: u32::from(self.cfg.own_client), + ..message + }; + Ok(entities_answer(vec![entity(Kind::Message(stored))], self.rev)) + } + + /// The channel of a direct conversation with a user (made in HOME). + async fn put_dm(&mut self, channel: v1::Channel) -> Result { + let own = self.own_user_id(); + let Some(peer) = channel.recipients.iter().copied().find(|id| *id != own) else { + return Err(rejected(ErrorCode::BadRequest, "a direct channel needs another user")); + }; + let uid = self + .by_uid + .iter() + .find(|(_, (user, _))| *user == peer) + .map(|(uid, _)| uid.clone()) + .or_else(|| self.extras.get(&peer).and_then(entities::user_uid)); + let Some(uid) = uid else { + return Err(rejected(ErrorCode::NotFound, "the client is not on the server")); + }; + let id = ids::dm_channel(&uid); + self.dms.entry(id).or_insert((uid, peer)); + self.refresh_home().await; + let item = self.home.get(&Key::Channel { id }).cloned().into_iter().collect(); + Ok(entities_answer(item, self.rev)) + } + + fn put_file(&mut self, file: v1::FileEntry, reply: Reply) { + if !self.cfg.files { + let _ = reply.send(Err(unsupported("files", "the file browser"))); + return; + } + let items = vec![entity(Kind::File(file.clone()))]; + let to = remote(file.channel_id, &file.password, join(&file.path, &file.name)); + let request = self.wait(Waiting::Done(items), reply, ANSWER_TIME); + if file.from_path.is_empty() { + // A directory. + self.send_inner(LinkCmd::CreateDirectory { request, dir: to }); + } else { + // A rename or a move: `from_path` is the whole old path. + let from = remote(file.from_channel_id, &file.from_password, file.from_path); + self.send_inner(LinkCmd::RenameFile { request, from, to }); + } + } + + fn put_mail(&mut self, mail: v1::Mail, paths: &[v1::FieldPath], reply: Reply) { + if !self.cfg.mail { + let _ = reply.send(Err(unsupported("mailbox", "offline messages"))); + return; + } + let read = path_of("voelin.v1.Mail", "read"); + let id = u32::try_from(mail.id).unwrap_or(u32::MAX); + let items = vec![entity(Kind::Mail(mail.clone()))]; + if paths.iter().any(|p| Some(p.numbers.as_slice()) == read.as_deref()) { + let request = self.wait(Waiting::Done(items), reply, ANSWER_TIME); + self.send_inner(LinkCmd::OfflineFlag { request, id, read: mail.read }); + } else { + let request = self.wait(Waiting::Done(items), reply, ANSWER_TIME); + self.send_inner(LinkCmd::OfflineAdd { + request, + to_uid: mail.to_uid, + subject: mail.subject, + text: mail.text, + }); + } + } + + fn delete(&mut self, delete: v1::Delete, reply: Reply) { + let mut keys = delete.keys.into_iter().filter_map(|e| e.kind); + match keys.next() { + Some(Kind::Mail(mail)) if self.cfg.mail => { + let id = u32::try_from(mail.id).unwrap_or(u32::MAX); + let request = + self.wait(Waiting::Deleted { left: 1, failed: None }, reply, ANSWER_TIME); + self.send_inner(LinkCmd::OfflineDelete { request, id }); + } + Some(Kind::Mail(_)) => { + let _ = reply.send(Err(unsupported("mailbox", "offline messages"))); + } + Some(Kind::File(first)) if self.cfg.files => { + // One deletion per channel (and password) the files are in. + let mut groups: Vec<(u64, String, Vec)> = Vec::new(); + let rest = keys.filter_map(|key| match key { + Kind::File(file) => Some(file), + _ => None, + }); + for file in std::iter::once(first).chain(rest) { + let path = join(&file.path, &file.name); + let group = groups + .iter_mut() + .find(|(c, p, _)| *c == file.channel_id && *p == file.password); + match group { + Some((_, _, paths)) => paths.push(path), + None => groups.push((file.channel_id, file.password, vec![path])), + } + } + // Every group's `RequestDone` counts for this one request. + let request = self.wait( + Waiting::Deleted { left: groups.len(), failed: None }, + reply, + ANSWER_TIME, + ); + for (channel, password, paths) in groups { + let password = (!password.is_empty()).then_some(password); + self.send_inner(LinkCmd::DeleteFiles { + request: Some(request), + channel, + password, + paths, + }); + } + } + Some(Kind::File(_)) => { + let _ = reply.send(Err(unsupported("files", "the file browser"))); + } + _ => { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "this kind cannot be deleted on this connection", + ))); + } + } + } + + fn signal(&mut self, signal: v1::Signal) -> Result { + match signal.body { + Some(SignalBody::Poke(poke)) => { + let target = signal.to.unwrap_or_default(); + let client = u16::try_from(target.participant_id) + .map_err(|_| rejected(ErrorCode::NotFound, "no such participant"))?; + self.send_inner(LinkCmd::Poke { client, message: poke.message }); + Ok(ack(self.rev)) + } + // Typing indicators have nobody to go to on a TeamSpeak server. + Some(SignalBody::Typing(_)) => Ok(ack(self.rev)), + _ => Err(rejected( + ErrorCode::Unsupported, + "this signal is not offered by this connection", + )), + } + } + + /// A move into a channel (`JoinVoice`). The first of a connection is the + /// seat the link gave us at connect: answered, nothing moved. + fn join(&mut self, join: v1::JoinVoice, reply: Reply) { + if join.server_id != SERVER_ID { + let _ = reply.send(Err(rejected(ErrorCode::NotFound, "no such server"))); + return; + } + let first = !std::mem::replace(&mut self.seated, true); + if first || self.own_channel == Some(join.channel_id) { + let _ = reply.send(Ok(self.own_voice())); + return; + } + let password = (!join.password.is_empty()).then_some(join.password); + self.wait(Waiting::Move { channel: join.channel_id }, reply, MOVE_TIME); + self.send_inner(LinkCmd::Move(join.channel_id, password)); + } + + // ---- files ------------------------------------------------------------ + + fn read( + &mut self, + request: v1::FileRead, + reply: oneshot::Sender>, + ) { + let Some(v1::file_read::Target::Path(path)) = request.target else { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "attachments are not offered by this connection", + ))); + return; + }; + if !self.cfg.files { + let _ = reply.send(Err(unsupported("files", "the file browser"))); + return; + } + let (tx, rx) = oneshot::channel(); + let file = remote(path.channel_id, &path.password, path.path.clone()); + self.send_inner(LinkCmd::OpenRead { file, offset: request.offset, reply: tx }); + let (dir, name) = split_path(&path.path); + let channel = path.channel_id; + tokio::spawn(async move { + let opened = match tokio::time::timeout(ANSWER_TIME, rx).await { + Ok(Ok(Ok(opened))) => Ok(opened), + Ok(Ok(Err(text))) => Err(rejected(ErrorCode::Unavailable, text)), + Ok(Err(_)) => Err(rejected(ErrorCode::Unavailable, "the connection ended")), + Err(_) => Err(SessionError::Timeout), + }; + let answer = opened.map(|(size, body): (u64, BoxRead)| Download { + head: v1::Entities { + items: vec![entity(Kind::File(v1::FileEntry { + channel_id: channel, + path: dir, + name, + size, + ..Default::default() + }))], + ..Default::default() + }, + body, + }); + let _ = reply.send(answer); + }); + } + + fn write( + &mut self, + request: v1::FileWrite, + reply: oneshot::Sender>, + ) { + let Some(v1::file_write::Target::Path(path)) = request.target else { + let _ = reply.send(Err(rejected( + ErrorCode::Unsupported, + "attachments are not offered by this connection", + ))); + return; + }; + if !self.cfg.files { + let _ = reply.send(Err(unsupported("files.upload", "file uploads"))); + return; + } + let (tx, rx) = oneshot::channel(); + let file = remote(path.channel_id, &path.password, path.path.clone()); + let (size, offset) = (request.size, request.offset); + self.send_inner(LinkCmd::OpenWrite { + file, + size, + overwrite: request.overwrite, + resume: offset > 0, + reply: tx, + }); + let (dir, name) = split_path(&path.path); + let channel = path.channel_id; + tokio::spawn(async move { + let opened = match tokio::time::timeout(ANSWER_TIME, rx).await { + Ok(Ok(Ok(opened))) => opened, + Ok(Ok(Err(text))) => { + let _ = reply.send(Err(rejected(ErrorCode::Unavailable, text))); + return; + } + Ok(Err(_)) => { + let _ = + reply.send(Err(rejected(ErrorCode::Unavailable, "the connection ended"))); + return; + } + Err(_) => { + let _ = reply.send(Err(SessionError::Timeout)); + return; + } + }; + let (seek, stream): (u64, BoxDuplex) = opened; + if seek != offset { + let _ = reply.send(Err(rejected( + ErrorCode::Conflict, + format!("the server has {seek} bytes"), + ))); + return; + } + let stored = v1::FileEntry { + channel_id: channel, + path: dir, + name, + size, + modified_ms: now_ms(), + ..Default::default() + }; + let _ = reply.send(Ok(super::upload(stream, stored))); + }); + } +} + +fn reply_to(reply: Option, answer: Result) { + if let Some(reply) = reply { + let _ = reply.send(answer); + } +} + +/// The field path of `name` in the message called `message`, as a write names it. +fn path_of(message: &str, name: &str) -> Option> { + let root = voelin_proto::fields::lookup(message)?; + voelin_proto::fields::resolve(root, name).ok().map(|p| p.numbers) +} + +/// A directory entry as the `FileEntry` entity of its directory. +fn file_entity(channel: u64, dir: &str, entry: FileEntry) -> Entity { + entity(Kind::File(v1::FileEntry { + channel_id: channel, + path: dir.to_owned(), + name: entry.name, + size: entry.size, + modified_ms: entry.modified_s.saturating_mul(1000), + is_dir: entry.is_dir, + ..Default::default() + })) +} + +fn mail_info(info: OfflineMessageInfo) -> Entity { + entity(Kind::Mail(v1::Mail { + id: u64::from(info.id), + from_uid: info.from_uid, + subject: info.subject, + ts_ms: info.ts_s.saturating_mul(1000), + read: info.read, + ..Default::default() + })) +} + +fn mail_full(mail: OfflineMessage) -> Entity { + entity(Kind::Mail(v1::Mail { + id: u64::from(mail.id), + from_uid: mail.from_uid, + subject: mail.subject, + text: mail.text, + ts_ms: mail.ts_s.saturating_mul(1000), + ..Default::default() + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_split_at_the_last_slash_and_join_back() { + assert_eq!(split_path("/docs/a.txt"), ("/docs".into(), "a.txt".into())); + assert_eq!(split_path("/a.txt"), ("/".into(), "a.txt".into())); + assert_eq!(split_path("a.txt"), ("/".into(), "a.txt".into())); + assert_eq!(join("/docs", "a.txt"), "/docs/a.txt"); + assert_eq!(join("/", "a.txt"), "/a.txt"); + assert_eq!(join("", "a.txt"), "a.txt"); + } + + #[test] + fn the_field_paths_of_the_writes_resolve() { + assert_eq!(path_of("voelin.v1.VoiceState", "self_mute"), Some(vec![9])); + assert_eq!(path_of("voelin.v1.VoiceState", "self_deaf"), Some(vec![10])); + assert_eq!(path_of("voelin.v1.User", "avatar.hash"), Some(vec![6, 3])); + assert_eq!(path_of("voelin.v1.Mail", "read"), Some(vec![9])); + } +} diff --git a/crates/voelin-core/src/ts_session/entities.rs b/crates/voelin-core/src/ts_session/entities.rs new file mode 100644 index 0000000..91e0d5e --- /dev/null +++ b/crates/voelin-core/src/ts_session/entities.rs @@ -0,0 +1,495 @@ +//! The TeamSpeak connection's presence as v1 entities (protocol section +//! 11.1, "Ids and entities"): the client's older model on one side, the +//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and +//! `VoiceState` on the other. +//! +//! [`build`] is the translation the TeamSpeak `Session` makes of every +//! snapshot its link reports; the engine's projection (`link/project.rs`) +//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule +//! both keep: projecting what was built gives back the snapshot (up to the +//! normalisations of section 5.4). What v1 has no field for rides in +//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`]. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use serde_json::json; +use voelin_model::replica::Key; +use voelin_model::{ + BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, + HostMessageMode, Presence, ServerDetails, +}; +use voelin_proto::v1::{self, Entity, entity::Kind}; + +use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID}; + +/// Entities by key, as a scope holds them. +pub(crate) type Layer = BTreeMap; + +/// The entities one snapshot stands for, by scope. +#[derive(Debug, Default)] +pub(crate) struct Built { + /// SERVER (1): the server, its channels and its roles. + pub server: Layer, + /// LIVE (1): who is online and where. + pub live: Layer, + /// The own user, for HOME, when the snapshot holds our client. + pub own_user: Option, + /// Clients by unique id: their user id and participant id. + pub by_uid: HashMap, +} + +/// The `Foreign` of something v1 has no field for. +pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign { + v1::Foreign { + system: FOREIGN_SYSTEM.into(), + kind: kind.into(), + json: serde_json::to_vec(json).unwrap_or_default().into(), + } +} + +fn entity(kind: Kind) -> Entity { + Entity { kind: Some(kind) } +} + +/// A picture known by its id (an icon CRC). +fn icon(id: u32) -> Option { + (id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() }) +} + +fn banner_mode(mode: BannerMode) -> v1::BannerMode { + match mode { + BannerMode::NoAdjust => v1::BannerMode::NoAdjust, + BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect, + BannerMode::KeepAspect => v1::BannerMode::KeepAspect, + } +} + +fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode { + match mode { + HostMessageMode::None => v1::HostMessageMode::None, + HostMessageMode::Log => v1::HostMessageMode::Log, + HostMessageMode::Modal => v1::HostMessageMode::Modal, + HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit, + } +} + +/// The `Server` entity of a connection. +pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server { + let gfx = + |url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() }); + let banner = (!details.banner_url.is_empty() + || !details.banner_gfx_url.is_empty() + || details.banner_gfx_interval_s != 0 + || details.banner_mode != BannerMode::NoAdjust) + .then(|| v1::Banner { + image: gfx(&details.banner_gfx_url), + link: details.banner_url.clone(), + reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX), + mode: banner_mode(details.banner_mode) as i32, + }); + let host_button = (!details.host_button_tooltip.is_empty() + || !details.host_button_url.is_empty() + || !details.host_button_gfx_url.is_empty()) + .then(|| v1::HostButton { + tooltip: details.host_button_tooltip.clone(), + url: details.host_button_url.clone(), + icon: gfx(&details.host_button_gfx_url), + }); + v1::Server { + id: SERVER_ID, + name: name.to_owned(), + icon: icon(details.icon), + banner, + host_button, + welcome: details.welcome_message.clone(), + host_message: details.host_message.clone(), + host_message_mode: host_message_mode(details.host_message_mode) as i32, + default_channel_id: default_channel, + default_role_id: details.default_server_group.unwrap_or(0), + default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role), + priority_dim_db: details.priority_speaker_dimm_db, + max_members: u32::from(details.max_clients), + uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(), + foreign: Some(foreign( + "server", + &json!({ "platform": details.platform, "version": details.version }), + )), + ..Default::default() + } +} + +/// The server group or channel group `info` as a role. +fn role(info: &GroupInfo, channel: bool) -> v1::Role { + v1::Role { + id: if channel { ids::channel_role(info.id) } else { info.id }, + server_id: SERVER_ID, + name: info.name.clone(), + icon: icon(info.icon), + position: info.sort_id.saturating_neg(), + scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32, + name_mode: match info.naming_mode { + GroupNamingMode::None => v1::NameMode::None, + GroupNamingMode::Before => v1::NameMode::Before, + GroupNamingMode::After => v1::NameMode::After, + } as i32, + kind: match info.group_type { + GroupType::Template => v1::RoleKind::Template, + GroupType::Regular => v1::RoleKind::Regular, + GroupType::Query => v1::RoleKind::Query, + } as i32, + ..Default::default() + } +} + +/// The sibling chain of each parent as positions: `order` names the sibling +/// above, so the chain is followed from 0; siblings that no chain reaches +/// (a snapshot with broken orders) follow by id. +fn positions(channels: &BTreeMap) -> HashMap { + let mut by_parent: BTreeMap> = BTreeMap::new(); + for channel in channels.values() { + by_parent.entry(channel.parent).or_default().push(channel); + } + let mut positions = HashMap::new(); + for siblings in by_parent.values() { + let mut placed: HashSet = HashSet::new(); + let mut next = 0; + let mut above = 0; + loop { + // The sibling whose `order` is the one placed last (lowest id first, + // so that two claiming the same place do not depend on map order). + let Some(channel) = siblings + .iter() + .filter(|c| c.order == above && !placed.contains(&c.id)) + .min_by_key(|c| c.id) + else { + break; + }; + positions.insert(channel.id, next * 1024); + placed.insert(channel.id); + above = channel.id; + next += 1; + } + for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) { + positions.insert(channel.id, next * 1024); + next += 1; + } + } + positions +} + +fn channel(info: &ChannelInfo, position: i64) -> v1::Channel { + let mut needed = HashMap::new(); + if info.needed_talk_power != 0 { + needed.insert(v1::Power::Talk as u32, info.needed_talk_power); + } + if info.needed_subscribe_power != 0 { + needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power); + } + let banner = + (info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| { + v1::Banner { + image: info + .banner_gfx_url + .as_ref() + .map(|url| v1::Image { url: url.clone(), ..Default::default() }), + mode: banner_mode(info.banner_mode) as i32, + ..Default::default() + } + }); + v1::Channel { + id: info.id, + server_id: SERVER_ID, + parent_id: info.parent, + kind: v1::ChannelKind::Voice as i32, + name: info.name.clone(), + topic: info.topic.clone().unwrap_or_default(), + position, + has_password: info.has_password, + // A limit of 0 cannot be said with `max_members` (0 is unlimited). + max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)), + needed, + icon: icon(info.icon), + banner, + is_default: info.is_default, + foreign: (info.max_clients == Some(0)) + .then(|| foreign("channel", &json!({ "max_clients": 0 }))), + ..Default::default() + } +} + +/// The user a client is. `Foreign` carries a unique id that is no base64. +fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User { + let uid = client.uid.as_deref().filter(|u| !u.is_empty()); + let bytes = uid.and_then(ids::uid_bytes); + let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image { + hash: client.avatar.clone().unwrap_or_default(), + url: client.myts_avatar.clone().unwrap_or_default(), + ..Default::default() + }); + v1::User { + id, + uid: bytes.clone().unwrap_or_default().into(), + uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32, + name: client.nickname.clone(), + avatar, + badges: client.badges.clone(), + country: client.country.clone().unwrap_or_default(), + foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))), + ..Default::default() + } +} + +/// A user who is on no snapshot (the sender of a message or a poke): its +/// unique id and name only. `None` for a unique id with no content. +pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User { + user( + &ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() }, + ids::synthetic_user(uid), + ts6, + ) +} + +/// Everything the snapshot `presence` says, as entities of the scopes of +/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids). +pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option) -> Built { + let mut built = Built::default(); + let name = + if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name }; + let default_channel = + presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id); + let put = |layer: &mut Layer, kind: Kind| { + let entity = entity(kind); + if let Some(key) = Key::of(&entity) { + layer.insert(key, entity); + } + }; + put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel))); + put( + &mut built.server, + Kind::Channel(v1::Channel { + id: SERVER_CHAT, + server_id: SERVER_ID, + kind: v1::ChannelKind::ServerChat as i32, + name: "Server chat".into(), + ..Default::default() + }), + ); + let positions = positions(&presence.channels); + for info in presence.channels.values() { + let position = positions.get(&info.id).copied().unwrap_or_default(); + put(&mut built.server, Kind::Channel(channel(info, position))); + } + for info in presence.server_groups.values() { + put(&mut built.server, Kind::Role(role(info, false))); + } + for info in presence.channel_groups.values() { + put(&mut built.server, Kind::Role(role(info, true))); + } + let mut used: HashSet = HashSet::new(); + for client in presence.clients.values() { + // The same identity twice on a server has one database id: the lower + // client id keeps it, the other is a user of its own. + let uid = client.uid.as_deref().filter(|u| !u.is_empty()); + let mut id = client.database_id.unwrap_or_else(|| { + ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned)) + }); + if !used.insert(id) { + id = ids::synthetic_user(&format!("client:{}", client.id)); + used.insert(id); + } + let participant = u32::from(client.id); + if let Some(uid) = uid { + built.by_uid.entry(uid.to_owned()).or_insert((id, participant)); + } + let user = user(client, id, ts6); + if Some(client.id) == own_client { + built.own_user = Some(user.clone()); + } + put(&mut built.live, Kind::User(user)); + put( + &mut built.live, + Kind::Member(v1::Member { + server_id: SERVER_ID, + user_id: id, + roles: client.server_groups.clone(), + channel_roles: client + .channel_group + .map(|group| (client.channel, ids::channel_role(group))) + .into_iter() + .collect(), + description: client.description.clone().unwrap_or_default(), + foreign: (client.icon != 0) + .then(|| foreign("client", &json!({ "icon": client.icon }))), + ..Default::default() + }), + ); + put( + &mut built.live, + Kind::Presence(v1::Presence { + user_id: id, + status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online } + as i32, + text: client.away.clone().unwrap_or_default(), + ..Default::default() + }), + ); + put( + &mut built.live, + Kind::Voice(v1::VoiceState { + server_id: SERVER_ID, + participant_id: participant, + user_id: id, + channel_id: client.channel, + slot: slot(client.id), + nick: client.nickname.clone(), + kind: if client.is_query { + v1::ParticipantKind::Query + } else { + v1::ParticipantKind::User + } as i32, + self_mute: client.input_muted, + self_deaf: client.output_muted, + priority_speaker: client.priority_speaker, + channel_commander: client.channel_commander, + talker: client.talker, + talk_power: client.talk_power, + recording: client.recording, + streaming: client.streaming.unwrap_or(false), + ..Default::default() + }), + ); + } + built +} + +/// The unique id of a user as the client's older model writes it: base64 for +/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a +/// ServerQuery client's login name). `None` for a user without one. +pub(crate) fn user_uid(user: &v1::User) -> Option { + let kept = user + .foreign + .as_ref() + .filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user") + .and_then(|f| serde_json::from_slice::(&f.json).ok()) + .and_then(|json| json.get("uid")?.as_str().map(str::to_owned)); + kept.or_else(|| voelin_model::replica::convert::uid_text(user)) +} + +/// The media slot of a client: its id plus one (slot 0 is not a media source). +pub(crate) fn slot(client: u16) -> u32 { + u32::from(client) + 1 +} + +/// The key of an entity, as a `Change` deletes it: the key fields only. +pub(crate) fn key_only(entity: &Entity) -> Entity { + let kind = match entity.kind.as_ref() { + Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }), + Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }), + Some(Kind::Role(r)) => { + Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() }) + } + Some(Kind::Member(m)) => Kind::Member(v1::Member { + server_id: m.server_id, + user_id: m.user_id, + ..Default::default() + }), + Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }), + Some(Kind::Presence(p)) => { + Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() }) + } + Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState { + server_id: v.server_id, + participant_id: v.participant_id, + ..Default::default() + }), + Some(Kind::Message(m)) => { + Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() }) + } + Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }), + _ => return entity.clone(), + }; + Entity { kind: Some(kind) } +} + +/// What changed from `old` to `new`: the entities to put (new or different) +/// and the keys to delete. +pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec, Vec) { + let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity)); + let del = old.iter().filter(|(key, _)| !new.contains_key(*key)); + (put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo { + ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() } + } + + #[test] + fn the_order_chain_becomes_positions() { + // 3 first, then 1, then 2 under the same parent; 5 alone under 3. + let channels: BTreeMap<_, _> = [ + channel_info(1, 0, 3), + channel_info(2, 0, 1), + channel_info(3, 0, 0), + channel_info(5, 3, 0), + ] + .into_iter() + .map(|c| (c.id, c)) + .collect(); + let positions = positions(&channels); + assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]); + assert_eq!(positions[&5], 0); + } + + #[test] + fn siblings_a_chain_does_not_reach_follow_by_id() { + // Both claim the first place, and 4 follows nobody. + let channels: BTreeMap<_, _> = + [channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)] + .into_iter() + .map(|c| (c.id, c)) + .collect(); + let positions = positions(&channels); + assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048)); + } + + #[test] + fn the_same_identity_twice_keeps_both_clients() { + let client = |id, db| ClientInfo { + id, + uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()), + nickname: format!("n{id}"), + database_id: Some(db), + ..Default::default() + }; + let mut presence = Presence::default(); + for c in [client(3, 77), client(4, 77)] { + presence.clients.insert(c.id, c); + } + let built = build(&presence, false, None); + let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count(); + let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count(); + assert_eq!((voices, users), (2, 2)); + } + + #[test] + fn a_change_deletes_by_key_and_puts_what_differs() { + let mut presence = Presence::default(); + presence.channels.insert(1, channel_info(1, 0, 0)); + let before = build(&presence, false, None); + presence.channels.insert(2, channel_info(2, 0, 1)); + presence.channels.get_mut(&1).unwrap().name = "renamed".into(); + let after = build(&presence, false, None); + let (put, del) = diff(&before.server, &after.server); + assert_eq!(put.len(), 2, "the renamed channel and the new one"); + assert!(del.is_empty()); + let (put, del) = diff(&after.server, &before.server); + assert_eq!(put.len(), 1, "channel 1 is back to its old name"); + assert_eq!(del.len(), 1); + let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") }; + assert_eq!((gone.id, gone.name.as_str()), (2, "")); + } +} diff --git a/crates/voelin-core/src/ts_session/ids.rs b/crates/voelin-core/src/ts_session/ids.rs new file mode 100644 index 0000000..fd67627 --- /dev/null +++ b/crates/voelin-core/src/ts_session/ids.rs @@ -0,0 +1,115 @@ +//! Ids and unique ids as the TeamSpeak gateway writes them (protocol +//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few +//! synthetic ones with bit 63 set. +//! +//! Both sides of the seam use these rules: the TeamSpeak `Session` +//! ([`super::LinkSession`]) writes entities with them, and the engine's +//! projection (`link/project.rs`) undoes the few that the client's older +//! model has no room for. + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; + +/// The only server of a TeamSpeak connection (its virtual server). +pub(crate) const SERVER_ID: u64 = 1; + +/// Marks the ids the gateway makes up: the server chat, direct-message +/// channels and users it knows by their unique id only. +pub(crate) const SYNTHETIC: u64 = 1 << 63; + +/// The channel of the server chat, in the SERVER scope. +pub(crate) const SERVER_CHAT: u64 = SYNTHETIC; + +/// Set on the id of a channel group, so that a role id does not mean a server +/// group and a channel group at once. +pub(crate) const CHANNEL_ROLE: u64 = 1 << 62; + +/// The `Foreign.system` of what the protocol has no field for. +pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak"; + +/// The role id of a channel group. +pub(crate) fn channel_role(group: u64) -> u64 { + group | CHANNEL_ROLE +} + +/// The channel group a role id stands for (the reverse of [`channel_role`]). +pub(crate) fn channel_group(role: u64) -> u64 { + role & !CHANNEL_ROLE +} + +/// FNV-1a, 64 bits. +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for byte in bytes { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +/// A synthetic id for something known by a name only: bit 63 set and the +/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never +/// [`SERVER_CHAT`]). +fn synthetic(name: &str) -> u64 { + let low = fnv1a(name.as_bytes()) & !SYNTHETIC; + SYNTHETIC | low.max(1) +} + +/// The direct-message channel with the client of this unique id. +pub(crate) fn dm_channel(uid: &str) -> u64 { + synthetic(uid) +} + +/// The user id of a client that has no database id (or that the snapshot +/// does not hold): by unique id, else by whatever names it. +pub(crate) fn synthetic_user(uid: &str) -> u64 { + synthetic(uid) +} + +/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak +/// writes): decoding and encoding again gives the same text. A ServerQuery +/// client's login name, or anything else, is not, and goes into +/// [`Foreign`](voelin_proto::v1::Foreign) instead. +pub(crate) fn uid_bytes(uid: &str) -> Option> { + let bytes = STANDARD.decode(uid).ok()?; + (STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_groups_keep_their_number_below_the_flag() { + assert_eq!(channel_role(8), 8 | (1 << 62)); + assert_eq!(channel_group(channel_role(8)), 8); + assert_eq!(channel_group(channel_role(0)), 0); + } + + #[test] + fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() { + for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] { + let id = dm_channel(name); + assert_ne!(id & SYNTHETIC, 0, "{name}"); + assert_ne!(id, SERVER_CHAT, "{name}"); + } + assert_eq!(dm_channel("alice="), dm_channel("alice=")); + assert_ne!(dm_channel("alice="), dm_channel("bob=")); + } + + #[test] + fn only_canonical_base64_is_a_unique_id() { + // A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256). + assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20)); + assert_eq!( + uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()), + Some(32) + ); + // A ServerQuery login name, a fixture's name, the empty string. + for not in ["serveradmin", "alice=", "me=", "", "Af4"] { + assert_eq!(uid_bytes(not), None, "{not:?}"); + } + // Non-canonical trailing bits decode but do not round trip. + assert_eq!(uid_bytes("Af5="), None); + } +} diff --git a/crates/voelin-core/src/ts_session/media.rs b/crates/voelin-core/src/ts_session/media.rs new file mode 100644 index 0000000..5b4ced4 --- /dev/null +++ b/crates/voelin-core/src/ts_session/media.rs @@ -0,0 +1,245 @@ +//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section +//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our +//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded +//! (protocol section 1.2): the Opus payload is the same bytes both ways. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use bytes::BytesMut; +use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket}; +use voelin_proto::link::{FlowId, MediaPacket, voice_sub}; +use voelin_proto::media::opus::{self, Toc}; +use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS}; +use voelin_proto::media::{RtpHeader, RtpView}; + +use super::entities::slot; + +/// Silence this long between two packets of a talker starts a new talk spurt +/// (the marker bit is set on the first packet of it). +const SPURT_GAP: Duration = Duration::from_millis(250); + +/// What is kept of the last packet of a talker. +struct Talker { + timestamp: u32, + sequence: u16, + at: Instant, + /// The 48 kHz ticks the last packet spans. + ticks: u32, + /// The last packet ended the spurt. + ended: bool, +} + +/// Wraps what a TeamSpeak connection receives into RTP. +#[derive(Default)] +pub(super) struct Downlink { + talkers: HashMap, +} + +impl Downlink { + /// `packet` as the RTP packet of its talker's slot. The sequence number is + /// TeamSpeak's packet id (both 16 bits); the timestamp advances by each + /// packet's duration (its Opus table-of-contents byte) on the packet id's + /// counter, so it never goes back when the id wraps, and by wall-clock time + /// across silences, so a silence is not compressed. The marker is set on + /// the first packet after an end or a gap, and an end is an empty payload. + pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option { + let id = packet.talker.0; + let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL }; + let flow = FlowId::new(slot(id), sub); + let end = packet.is_end(); + let (timestamp, marker) = match self.talkers.get(&id) { + None => (0, !end), + Some(last) => { + let gap = now.saturating_duration_since(last.at); + if last.ended || gap > SPURT_GAP { + // A new spurt: the time that passed since the last packet. + let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32; + (last.timestamp.wrapping_add(last.ticks.max(wall)), !end) + } else { + let ahead = packet.seq.wrapping_sub(last.sequence); + if ahead == 0 || ahead >= 0x8000 { + // A duplicate or a late packet: where it belongs, and the + // state keeps what the latest packet said. + let back = u32::from(last.sequence.wrapping_sub(packet.seq)); + let at = last.timestamp.wrapping_sub(back * last.ticks); + return self.finish(flow, packet, at, false); + } + (last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false) + } + } + }; + let ticks = + if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) }; + self.talkers + .insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end }); + self.finish(flow, packet, timestamp, marker) + } + + fn finish( + &self, + flow: FlowId, + packet: &VoicePacket, + timestamp: u32, + marker: bool, + ) -> Option { + let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp); + header.marker = marker; + // An end is an empty payload, also where the server sent one byte. + let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] }; + let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len()); + header.write(flow, &mut out).ok()?; + out.extend_from_slice(payload); + Some(MediaPacket { flow, rtp: out.freeze() }) + } + + /// Forget a talker (it left the server). + pub(super) fn forget(&mut self, client: u16) { + self.talkers.remove(&client); + } +} + +/// The voice a media packet of our own slot carries, for TeamSpeak: its +/// payload, and `Music` when the Opus packet is stereo. `None` for a packet +/// that is no RTP. +pub(super) fn uplink(packet: &MediaPacket) -> Option { + let view = RtpView::parse(&packet.rtp).ok()?; + let payload = view.payload(); + let codec = match Toc::parse(payload) { + Ok(toc) if toc.stereo() => VoiceCodec::Music, + _ => VoiceCodec::Voice, + }; + Some(EncodedVoice { codec, payload: payload.to_vec() }) +} + +/// An RTP packet of voice, for tests of both sides. +#[cfg(test)] +pub(super) fn rtp_packet( + flow: FlowId, + sequence: u16, + timestamp: u32, + marker: bool, + payload: &[u8], +) -> bytes::Bytes { + let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp); + header.marker = marker; + let mut out = BytesMut::new(); + header.write(flow, &mut out).unwrap(); + out.extend_from_slice(payload); + out.freeze() +} + +#[cfg(test)] +mod tests { + use bytes::Bytes; + use voelin_audio::TalkerId; + + use super::*; + + fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket { + VoicePacket { + talker: TalkerId(talker), + seq, + codec: VoiceCodec::Voice, + whisper, + payload: payload.to_vec(), + } + } + + /// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19 + /// is 20 ms), mono, one frame. + const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02]; + + fn view(packet: &MediaPacket) -> RtpView<'_> { + RtpView::parse(&packet.rtp).unwrap() + } + + #[test] + fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() { + let mut down = Downlink::default(); + let t0 = Instant::now(); + let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap(); + let v = view(&first); + assert!(v.marker()); + assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0))); + assert_eq!((v.sequence(), v.timestamp()), (65_534, 0)); + // The id wraps; the timestamp keeps counting. + let t1 = t0 + Duration::from_millis(20); + let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap(); + let third = + down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap(); + assert!(!view(&second).marker() && !view(&third).marker()); + assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS); + assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS)); + } + + #[test] + fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() { + let mut down = Downlink::default(); + let t0 = Instant::now(); + down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap(); + let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap(); + assert!(view(&end).payload().is_empty() && !view(&end).marker()); + // TeamSpeak's single byte after a talk is an end too. + let mut down = Downlink::default(); + down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap(); + let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap(); + assert!(view(&end).payload().is_empty()); + let next = + down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap(); + assert!(view(&next).marker()); + } + + #[test] + fn a_silence_is_not_compressed() { + let mut down = Downlink::default(); + let t0 = Instant::now(); + let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap(); + let again = + down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap(); + assert!(view(&again).marker(), "a gap starts a spurt"); + // Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock. + assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000); + } + + #[test] + fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() { + let mut down = Downlink::default(); + let now = Instant::now(); + let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap(); + assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1)); + let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap(); + assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0)); + } + + #[test] + fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() { + let mut down = Downlink::default(); + let t0 = Instant::now(); + down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap(); + down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap(); + let late = + down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap(); + assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs"); + let next = + down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap(); + assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS); + } + + #[test] + fn our_voice_loses_its_header_and_stereo_is_music() { + let flow = FlowId::new(8, 0); + let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) }; + let voice = uplink(&mono).unwrap(); + assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..])); + // The same TOC with the stereo bit. + let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2]; + let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) }; + assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music); + // The end of a spurt: an empty payload. + let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) }; + assert!(uplink(&end).unwrap().is_end()); + // Not RTP. + assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none()); + } +} diff --git a/crates/voelin-core/src/ts_session/mod.rs b/crates/voelin-core/src/ts_session/mod.rs new file mode 100644 index 0000000..e5c6212 --- /dev/null +++ b/crates/voelin-core/src/ts_session/mod.rs @@ -0,0 +1,769 @@ +//! A TeamSpeak connection as a `voelin_proto::link::Session` +//! (`docs/session-seam.md`, "the TeamSpeak side"). +//! +//! [`LinkSession`] is a `Session` over any [`ServerLink`](crate::link::ServerLink): +//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older, +//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With +//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link +//! inside it is what the link tests of the engine run through. [`TsConnector`] +//! is the `Connector` that makes them for `ts3server://` and `teamspeak://` +//! addresses. +//! +//! This module and the files it is made of are TeamSpeak's: they keep the +//! TeamSpeak types (`tsclientlib`'s identity and client version) in +//! [`connect_params`] and [`TsConnector`], and everything else is v1 and the +//! client's own model. In the second half of the decoupling plan they move, +//! with `TsLink`, to the TeamSpeak gateway (`voelin-gateway-ts` of +//! VoelinGateWay). + +mod driver; +pub(crate) mod entities; +pub(crate) mod ids; +mod media; + +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use bytes::Bytes; +use tokio::io::{AsyncReadExt, AsyncWrite}; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use voelin_model::{Link, ServerDetails}; +use voelin_proto::link::{ + BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features, + IssuerTrust, LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, MediaSink, Placement, + Sent, Session, SessionError, Upload, placement, voice_sub, +}; +use voelin_proto::v1::{self, response::Result as Answer}; + +use self::driver::{Cmd, Config, Driver, Parts, rejected}; +use crate::link::{ + Backends, BoxDuplex, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected, + LocalConnector, LocalCtx, ServerLink, StreamPort, +}; +use crate::{BackendInfo, TsLink}; + +/// The `Credential::Foreign` kind of a stored TeamSpeak identity. +const IDENTITY_KIND: &str = "teamspeak"; +/// The link parameter that carries the client version to impersonate: the +/// JSON of `tsclientlib::Version`, in unpadded URL-safe base64. +const VERSION_PARAM: &str = "client_version"; +/// How long the link may take to report its first snapshot after it said it +/// is connected; the snapshot gives the `Welcome` its own user. +const FIRST_SNAPSHOT: Duration = Duration::from_millis(250); + +static SESSIONS: AtomicU64 = AtomicU64::new(1); + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() +} + +// ---- what the engine hands a connector ------------------------------------ + +/// The connect parameters of a TeamSpeak connection, from the options the +/// session was asked to connect with (`docs/session-seam.md` section 4.2). +/// +/// The address is the `ts3server://` link of the bookmark (the channel and +/// its password ride in it, and so does the client version to claim, until +/// v1 has fields for them), the server password is `Hello.password` and the +/// privilege key `Hello.invite_code`. The identity goes as +/// `Credential::Foreign`; no account is used yet. +pub(crate) fn connect_params( + options: &ConnectOptions, + media: Arc, + backends: &Backends, +) -> ConnectParams { + let credential = Credential::Foreign { + kind: IDENTITY_KIND, + blob: options + .identity + .as_ref() + .and_then(|identity| serde_json::to_vec(identity).ok()) + .map(Bytes::from) + .unwrap_or_default(), + }; + let hello = v1::Hello { + version: 1, + client: Some(v1::ClientInfo { + name: "Voelin".into(), + version: voelin_platform::crash::app_version().to_owned(), + platform: std::env::consts::OS.into(), + kind: v1::ClientKind::User as i32, + }), + nickname: options.nickname.clone(), + password: options.server_password.clone().unwrap_or_default(), + invite_code: options.token.clone().unwrap_or_default(), + ..Default::default() + }; + ConnectParams { + address: address_link(options), + credential, + linked: Vec::new(), + account: backends.account(), + issuer_trust: IssuerTrust::Unknown, + hello, + host_pin: None, + trust: backends.trust(), + media, + push_capacity: 1024, + timeout: Duration::from_secs(35), + } +} + +/// The `ts3server://` link of the options' address, with the channel to join +/// and the client version to claim. +fn address_link(options: &ConnectOptions) -> String { + let mut link = match Link::parse(&options.address) { + Some(Link::Server(link)) => link, + // Not a TeamSpeak link, or none: a bookmark's `host[:port]`. + _ if !options.address.contains("://") => voelin_model::ServerLink::new(&options.address), + // Some other scheme: as given, for the connector of that scheme. + _ => return options.address.clone(), + }; + link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel); + link.channel_password = + options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password); + let mut url = link.to_url(); + if let Some(version) = options.client_version.as_ref().and_then(|v| serde_json::to_vec(v).ok()) + { + url.push(if url.contains('?') { '&' } else { '?' }); + url.push_str(VERSION_PARAM); + url.push('='); + url.push_str(&URL_SAFE_NO_PAD.encode(version)); + } + url +} + +/// The options a TeamSpeak link is connected with: the reverse of +/// [`connect_params`]. +fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result { + let link = match Link::parse(¶ms.address) { + Some(Link::Server(link)) => link, + _ => { + return Err(SessionError::Protocol(format!( + "not a TeamSpeak server address: {}", + params.address + ))); + } + }; + let identity = match ¶ms.credential { + Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None, + Credential::Foreign { kind: IDENTITY_KIND, blob } => { + Some(serde_json::from_slice(blob).map_err(|e| { + SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}")) + })?) + } + _ => { + return Err(SessionError::Protocol( + "a TeamSpeak server needs a TeamSpeak identity".into(), + )); + } + }; + let client_version = params + .address + .split_once('?') + .and_then(|(_, query)| { + query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}="))) + }) + .and_then(|text| URL_SAFE_NO_PAD.decode(text).ok()) + .and_then(|json| serde_json::from_slice(&json).ok()); + let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned()); + Ok(ConnectOptions { + address: link.address(), + nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(), + identity, + client_version, + server_password: nonempty(¶ms.hello.password).or(link.password.clone()), + channel: link.channel.clone(), + channel_password: link.channel_password.clone(), + token: nonempty(¶ms.hello.invite_code).or(link.token.clone()), + audio: ctx.audio, + stream_peer: ctx.stream_peer.clone(), + }) +} + +// ---- backend and features --------------------------------------------------- + +/// The server software as v1 names it (table 4.7): `teamspeak` with the +/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is. +pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo { + let (product, flavor) = match backend.product.as_str() { + "TeamSpeak 3" => ("teamspeak", "ts3"), + "TeamSpeak 6" => ("teamspeak", "ts6"), + // A TeamSpeak server the engine does not recognise: the version it + // sent, no flavor. + "" => ("teamspeak", ""), + other => (other, ""), + }; + v1::BackendInfo { + product: product.into(), + version: backend.version.clone(), + flavor: flavor.into(), + } +} + +/// The features a TeamSpeak connection offers, from what its link can do +/// (`docs/session-seam.md` section 4.7). +pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> { + let mut features = + vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"]; + if capabilities.file_transfer { + features.extend(["files", "files.upload"]); + } + if capabilities.offline_messages { + features.push("mailbox"); + } + if capabilities.streams { + features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]); + } + features +} + +// ---- the session ------------------------------------------------------------ + +/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam. +pub(crate) struct LinkSession { + welcome: v1::Welcome, + features: Features, + cmds: mpsc::UnboundedSender, + closed: watch::Receiver>, + own_slot: u32, +} + +fn closed_reason(closed: &watch::Receiver>) -> CloseReason { + closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into())) +} + +impl Session for LinkSession { + fn welcome(&self) -> &v1::Welcome { + &self.welcome + } + + fn features(&self) -> Features { + self.features.clone() + } + + fn request(&self, op: v1::request::Op) -> BoxFuture> { + let closed = self.closed.clone(); + match placement(&op) { + Placement::Invalid => { + return Box::pin(async { + Err(SessionError::Protocol("a Hello is part of connecting".into())) + }); + } + Placement::OwnStream + if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) => + { + return Box::pin(async { + Err(SessionError::Protocol("files go through read_file and write_file".into())) + }); + } + _ => {} + } + // Queued now, in the order of the calls, not when the future is polled. + let (reply, answer) = oneshot::channel(); + if self.cmds.send(Cmd::Request { op, reply }).is_err() { + return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) }); + } + Box::pin(async move { + match answer.await { + Ok(answer) => answer, + Err(_) => Err(SessionError::Closed(closed_reason(&closed))), + } + }) + } + + fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> { + if placement(&op) == Placement::Invalid { + return Err(SessionError::Protocol("a Hello is part of connecting".into())); + } + self.cmds + .send(Cmd::Notify(op)) + .map_err(|_| SessionError::Closed(closed_reason(&self.closed))) + } + + fn read_file(&self, request: v1::FileRead) -> BoxFuture> { + let closed = self.closed.clone(); + let (reply, answer) = oneshot::channel(); + if self.cmds.send(Cmd::Read { request, reply }).is_err() { + return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) }); + } + Box::pin(async move { + match answer.await { + Ok(answer) => answer, + Err(_) => Err(SessionError::Closed(closed_reason(&closed))), + } + }) + } + + fn write_file(&self, request: v1::FileWrite) -> BoxFuture> { + let closed = self.closed.clone(); + let (reply, answer) = oneshot::channel(); + if self.cmds.send(Cmd::Write { request, reply }).is_err() { + return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) }); + } + Box::pin(async move { + match answer.await { + Ok(answer) => answer, + Err(_) => Err(SessionError::Closed(closed_reason(&closed))), + } + }) + } + + fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result { + let flow = packet.flow; + if self.closed.borrow().is_some() { + return Err(MediaError::Closed); + } + if packet.rtp.len() > MAX_RTP { + return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP }); + } + // Only our voice to the channel: TeamSpeak whispers and priority voice, + // like video, are not offered here. + if class != MediaClass::Voice + || flow.slot() != self.own_slot + || flow.sub() != voice_sub::CHANNEL + { + return Err(MediaError::NotOwned(flow)); + } + let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?; + self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?; + Ok(Sent::Queued) + } + + fn stats(&self) -> LinkStats { + LinkStats { max_rtp: MAX_RTP, ..Default::default() } + } + + fn close(&self, code: v1::CloseCode, reason: &str) { + let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() }); + } + + fn closed(&self) -> BoxFuture { + let mut closed = self.closed.clone(); + Box::pin(async move { + let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone()); + reason.unwrap_or_else(|| closed_reason(&closed)) + }) + } +} + +/// The write half of an upload: ending it tells the other half of the +/// upload that the file is all there. +struct UploadBody { + inner: tokio::io::WriteHalf, + ended: Option>, +} + +impl AsyncWrite for UploadBody { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let done = Pin::new(&mut self.inner).poll_shutdown(cx); + if matches!(done, Poll::Ready(Ok(()))) + && let Some(ended) = self.ended.take() + { + let _ = ended.send(()); + } + done + } +} + +/// An upload over the transfer connection `stream`: the body writes to it, +/// and `done` resolves once the body is shut down and the server has closed +/// the connection (or 30 s passed), with the file as `stored`. +fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload { + let (mut read, write) = tokio::io::split(stream); + let (ended, shut) = oneshot::channel(); + let done: BoxFuture> = Box::pin(async move { + if shut.await.is_err() { + return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped")); + } + // The server closes the connection once it has everything. + let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await; + Ok(v1::Entities { + items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }], + ..Default::default() + }) + }); + Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done } +} + +// ---- the connector ---------------------------------------------------------- + +/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s. +#[derive(Clone)] +pub(crate) struct LinkConnector { + link: Arc, + schemes: &'static [&'static str], + /// Serves every scheme (the engine's tests give a link of their own). + any: bool, +} + +impl LinkConnector { + /// A connector for `schemes`. + pub(crate) fn new(link: Arc, schemes: &'static [&'static str]) -> Self { + Self { link, schemes, any: false } + } + + /// A connector for addresses of every scheme. + pub(crate) fn any(link: Arc) -> Self { + Self { link, schemes: &[], any: true } + } +} + +impl Connector for LinkConnector { + fn schemes(&self) -> &'static [&'static str] { + self.schemes + } + + fn connect(&self, params: ConnectParams) -> BoxFuture> { + let connect = connect_link(self.link.clone(), params, LocalCtx::standalone()); + Box::pin(async move { Ok(connect.await?.connected) }) + } +} + +impl LocalConnector for LinkConnector { + fn accepts(&self, scheme: &str) -> bool { + self.any || self.schemes.contains(&scheme) + } + + fn connect_local( + &self, + params: ConnectParams, + ctx: LocalCtx, + ) -> BoxFuture> { + Box::pin(connect_link(self.link.clone(), params, ctx)) + } +} + +/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`) +/// with `tsclientlib`: [`LinkSession`]s over [`TsLink`]. +#[derive(Clone)] +pub(crate) struct TsConnector(LinkConnector); + +impl TsConnector { + pub(crate) fn new() -> Self { + Self(LinkConnector::new(Arc::new(TsLink), &["ts3server", "teamspeak"])) + } +} + +impl Connector for TsConnector { + fn schemes(&self) -> &'static [&'static str] { + self.0.schemes() + } + + fn connect(&self, params: ConnectParams) -> BoxFuture> { + self.0.connect(params) + } +} + +impl LocalConnector for TsConnector { + fn connect_local( + &self, + params: ConnectParams, + ctx: LocalCtx, + ) -> BoxFuture> { + self.0.connect_local(params, ctx) + } +} + +/// What the link told when it connected. +struct Joined { + name: String, + backend: BackendInfo, + capabilities: voelin_model::Capabilities, + own_client: u16, + server_uid: String, + own_uid: Option, +} + +fn ended_error(reason: Option) -> SessionError { + SessionError::Closed(match reason { + Some(reason) => CloseReason::Network(reason), + None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() }, + }) +} + +/// Wait for the link to say it is connected (or that it failed). +async fn wait_connected( + events: &mut mpsc::UnboundedReceiver, +) -> Result { + loop { + match events.recv().await { + Some(LinkEvent::Connected { + name, + backend, + capabilities, + own_client, + server_uid, + own_uid, + }) => { + return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid }); + } + Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)), + Some(_) => {} + None => return Err(ended_error(Some("the connection ended".into()))), + } + } +} + +/// Open a [`LinkSession`] over `link` to the address in `params`. +async fn connect_link( + link: Arc, + params: ConnectParams, + ctx: LocalCtx, +) -> Result { + let options = inner_options(¶ms, &ctx)?; + let nickname = options.nickname.clone(); + let (inner_tx, inner_rx) = mpsc::unbounded_channel(); + let (events_tx, mut events) = mpsc::unbounded_channel(); + // The link answers requests on a bus of its own: this session reads the + // answers, and passes on the rest to the engine's. + let (bus_tx, bus) = broadcast::channel(4096); + let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() }; + link.spawn(options, inner_ctx, inner_rx, events_tx); + + let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await { + Ok(joined) => joined?, + Err(_) => { + let _ = inner_tx.send(LinkCmd::Disconnect); + return Err(SessionError::Timeout); + } + }; + // The link reports its first snapshot right after it says it is connected; + // the session needs it to know the own user. + let mut early: Vec = Vec::new(); + let _ = tokio::time::timeout(FIRST_SNAPSHOT, async { + while let Some(event) = events.recv().await { + let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_)); + early.push(event); + if stop { + break; + } + } + }) + .await; + if let Some(LinkEvent::Disconnected(reason)) = early.last() { + return Err(ended_error(reason.clone())); + } + let own_database_id = early.iter().find_map(|event| match event { + LinkEvent::Presence(presence) => { + presence.clients.get(&joined.own_client).and_then(|c| c.database_id) + } + _ => None, + }); + + let ts6 = joined.backend.product == "TeamSpeak 6"; + let own_user = + own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0); + let features = features_of(&joined.capabilities); + let welcome = v1::Welcome { + user_id: own_user, + session_id: SESSIONS.fetch_add(1, Ordering::Relaxed), + uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(), + host: Some(v1::HostInfo { + host_key: Bytes::new(), + name: joined.name.clone(), + product: joined.backend.product.clone(), + version: joined.backend.version.clone(), + backend: Some(backend_to_v1(&joined.backend)), + icon: None, + }), + features: features.iter().map(|f| (*f).to_owned()).collect(), + limits: Some(v1::Limits { + max_message_chars: 1024, + max_page: 100, + max_subscriptions: 4, + max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS, + max_live_subscriptions: 8, + ..Default::default() + }), + time_ms: now_ms(), + ..Default::default() + }; + + let (cmds_tx, cmds_rx) = mpsc::unbounded_channel(); + let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16)); + let (closed_tx, closed_rx) = watch::channel(None); + let (port, streams) = if joined.capabilities.streams { + let (events_tx, events_rx) = mpsc::unbounded_channel(); + let cmds = cmds_tx.clone(); + let send = move |cmd| { + let _ = cmds.send(Cmd::Stream(cmd)); + }; + (Some(events_tx), Some(StreamPort::new(send, events_rx))) + } else { + (None, None) + }; + let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() }; + let driver = Driver::new(Parts { + cfg: Config { + ts6, + own_client: joined.own_client, + nickname, + own_uid: joined.own_uid.clone(), + files: joined.capabilities.file_transfer, + mail: joined.capabilities.offline_messages, + }, + inner: inner_tx, + events, + early, + bus, + engine_bus: ctx.link.events.clone(), + pushes: pushes_tx, + media: params.media.clone(), + port, + closed: closed_tx, + server: entities::server(&details, &joined.name, 0), + epoch: u64::try_from(now_ms()).unwrap_or(1).max(1), + }); + let session = LinkSession { + welcome, + features: Features::new(features), + cmds: cmds_tx, + closed: closed_rx, + own_slot: entities::slot(joined.own_client), + }; + tokio::spawn(driver.run(cmds_rx)); + Ok(LocalConnected { + connected: Connected { + session: Arc::new(session), + pushes: pushes_rx, + // A TeamSpeak server has no host key to pin. + host_uid: [0; 32], + }, + streams, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn params(options: &ConnectOptions) -> ConnectParams { + let (media, _rx) = voelin_proto::test_util::media_channel(); + connect_params(options, media, &Backends::empty()) + } + + fn back(options: &ConnectOptions) -> ConnectOptions { + inner_options(¶ms(options), &LocalCtx::standalone()).unwrap() + } + + #[test] + fn the_options_of_a_bookmark_come_back_as_they_went() { + let mut options = ConnectOptions::new("ts.example.com:9988", "nick"); + let same = back(&options); + assert_eq!( + (same.address.as_str(), same.nickname.as_str()), + ("ts.example.com:9988", "nick") + ); + assert!(same.identity.is_none() && same.client_version.is_none()); + assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none()); + + // Everything a connection can be told: the server password and the + // privilege key go in the hello, the channel and its password in the + // link, the identity as a credential. + options.server_password = Some("s3cret pass&word".into()); + options.channel = Some("Games/Raid Night".into()); + options.channel_password = Some("p w+%".into()); + options.token = Some("tokenvalue".into()); + options.identity = Some(tsclientlib::Identity::create()); + options.client_version = Some(crate::versions::native_version().unwrap()); + options.audio = false; + let sent = params(&options); + assert_eq!(sent.hello.password, "s3cret pass&word"); + assert_eq!(sent.hello.invite_code, "tokenvalue"); + assert_eq!(sent.hello.nickname, "nick"); + assert!( + sent.address.starts_with("ts3server://ts.example.com?port=9988"), + "{}", + sent.address + ); + assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue")); + let got = back(&options); + assert_eq!(got.address, "ts.example.com:9988"); + assert_eq!(got.server_password, options.server_password); + assert_eq!(got.channel.as_deref(), Some("Games/Raid Night")); + assert_eq!(got.channel_password, options.channel_password); + assert_eq!(got.token.as_deref(), Some("tokenvalue")); + assert_eq!(got.client_version, options.client_version); + // The identity is the same key and counters. + let (a, b) = (options.identity.as_ref().unwrap(), got.identity.as_ref().unwrap()); + assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap()); + } + + #[test] + fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() { + let mut options = ConnectOptions::new("[::1]:9987", "nick"); + options.channel = Some("/12".into()); + let got = back(&options); + assert_eq!(got.address, "[::1]:9987"); + assert_eq!(got.channel.as_deref(), Some("/12")); + + // A bookmark that is a link keeps its own parameters. + let options = + ConnectOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick"); + let got = back(&options); + assert_eq!( + (got.address.as_str(), got.channel.as_deref()), + ("ts.example.com:1", Some("Lobby")) + ); + // Another scheme is left as it is for the connector of that scheme. + let options = ConnectOptions::new("voelin://host/i/code", "nick"); + assert_eq!(params(&options).address, "voelin://host/i/code"); + } + + #[test] + fn what_is_no_teamspeak_identity_is_refused() { + let mut sent = params(&ConnectOptions::new("ts.example.com", "nick")); + sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner)); + let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err(); + assert!(matches!(error, SessionError::Protocol(_))); + let mut sent = params(&ConnectOptions::new("ts.example.com", "nick")); + sent.credential = + Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") }; + assert!(inner_options(&sent, &LocalCtx::standalone()).is_err()); + let mut sent = params(&ConnectOptions::new("ts.example.com", "nick")); + sent.credential = + Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") }; + assert!(inner_options(&sent, &LocalCtx::standalone()).is_err()); + // A host that wants trust is refused: TeamSpeak has no host key. + let backends = Backends::empty(); + let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity { + address: "x".into(), + uid: [0; 32], + previous: None, + }); + assert!(!futures::executor::block_on(confirm)); + } + + #[test] + fn the_params_carry_what_the_session_needs_and_no_account_yet() { + let sent = params(&ConnectOptions::new("ts.example.com", "nick")); + assert!(sent.account.is_none()); + assert_eq!(sent.issuer_trust, IssuerTrust::Unknown); + assert!(sent.linked.is_empty() && sent.host_pin.is_none()); + assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35))); + let client = sent.hello.client.unwrap(); + assert_eq!(client.name, "Voelin"); + assert_eq!(sent.hello.version, 1); + } +} diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index 729e20c..180df63 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -20,7 +20,7 @@ use std::time::Duration; use base64::Engine as _; use futures::prelude::*; -use tokio::sync::{mpsc, watch}; +use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::AbortHandle; use tokio::time::{Instant, timeout}; use tracing::{debug, info, warn}; @@ -37,9 +37,9 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavo use voelin_stream::{ClientState, Request, StreamNotification}; use crate::book::presence_from_book; -use crate::cache; +use crate::cache::{self, IMAGE_NEGOTIATION, image_download_time}; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; -use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote}; +use crate::link::{BoxDuplex, BoxRead, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; use crate::settings::FILES_PROGRESS_MS; use crate::stream::{StreamCmd, StreamHandle, StreamInput}; @@ -172,43 +172,58 @@ enum Job { size: u64, report: Report, }, + /// The caller wants the connection itself ([`LinkCmd::OpenRead`]). + OpenRead(oneshot::Sender>), + /// The caller wants the connection itself ([`LinkCmd::OpenWrite`]). + OpenWrite(oneshot::Sender>), } impl Job { - fn report(&self) -> &Report { + /// The job could not be done: tell whoever waits. + fn fail(self, text: String) { match self { - Job::Download { report, .. } | Job::Upload { report, .. } => report, + Job::Download { report, .. } | Job::Upload { report, .. } => { + report(TransferState::Failed(text)); + } + Job::OpenRead(reply) => { + let _ = reply.send(Err(text)); + } + Job::OpenWrite(reply) => { + let _ = reply.send(Err(text)); + } + } + } + + /// The user cancelled the transfer before the server opened it. + fn cancel(self) { + if let Job::Download { report, .. } | Job::Upload { report, .. } = self { + report(TransferState::Cancelled); } } fn transfer(&self) -> Option { match self { Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer, + Job::OpenRead(_) | Job::OpenWrite(_) => None, } } } -/// How long a picture of `size` bytes may take to arrive: a minute, plus -/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow -/// links while a stalled transfer still ends. -fn image_download_time(size: u64) -> Duration { - Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE) -} - -/// How long the server may take to start an image transfer (a busy server -/// answers the requests of a large channel tree in turn). -const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30); - /// Bound background image handshakes without imposing a deadline on user transfers. fn expire_image_jobs(jobs: &mut HashMap, now: Instant) { - jobs.retain(|_, job| { - if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) { - job.report()(TransferState::Failed("image transfer negotiation timed out".into())); - false - } else { - true + let expired: Vec = jobs + .iter() + .filter(|(_, job)| { + matches!(job, Job::Download { transfer: None, started, .. } + if now.duration_since(*started) >= IMAGE_NEGOTIATION) + }) + .map(|(handle, _)| *handle) + .collect(); + for handle in expired { + if let Some(job) = jobs.remove(&handle) { + job.fail("image transfer negotiation timed out".into()); } - }); + } } /// A user's transfer, for cancelling. @@ -468,7 +483,7 @@ async fn run_inner( drop(voice.streams.take()); // Transfers the server never opened fail; running ones go on. for (_, job) in voice.jobs.drain() { - job.report()(TransferState::Failed("disconnected".into())); + job.fail("disconnected".into()); } let disconnect = shutdown_connection(voice.con).await; result?; @@ -606,6 +621,13 @@ impl Voice { } } StreamItem::FileDownload(handle, download) => { + if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_))) { + // The caller wants the connection itself. + if let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle) { + let _ = reply.send(Ok((download.size, Box::pin(download.stream)))); + } + return Ok(()); + } if let Some(Job::Download { transfer, offset, sink, report, .. }) = self.jobs.remove(&handle) { @@ -639,6 +661,13 @@ impl Voice { } } StreamItem::FileUpload(handle, upload) => { + if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_))) { + // The caller wants the connection itself. + if let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle) { + let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream)))); + } + return Ok(()); + } if let Some(Job::Upload { transfer, from, size, report }) = self.jobs.remove(&handle) { @@ -658,7 +687,7 @@ impl Voice { if let Some(id) = job.transfer() { self.transfers.remove(&id); } - job.report()(TransferState::Failed(transfer_error(&error))); + job.fail(transfer_error(&error)); } } StreamItem::DisconnectedTemporarily(reason) => { @@ -1120,10 +1149,35 @@ impl Voice { self.transfers.insert(id, Slot::Waiting(handle)); } } + LinkCmd::OpenRead { file, offset, reply } => { + let seek = (offset > 0).then_some(offset); + let password = file.password.as_deref().filter(|p| !p.is_empty()); + let channel = tsclientlib::ChannelId(file.channel); + match self.con.download_file(channel, &file.path, password, seek) { + Ok(handle) => { + self.jobs.insert(handle, Job::OpenRead(reply)); + } + Err(e) => { + let _ = reply.send(Err(e.to_string())); + } + } + } + LinkCmd::OpenWrite { file, size, overwrite, resume, reply } => { + let password = file.password.as_deref().filter(|p| !p.is_empty()); + let channel = tsclientlib::ChannelId(file.channel); + match self.con.upload_file(channel, &file.path, password, size, overwrite, resume) { + Ok(handle) => { + self.jobs.insert(handle, Job::OpenWrite(reply)); + } + Err(e) => { + let _ = reply.send(Err(e.to_string())); + } + } + } LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) { Some(Slot::Waiting(handle)) => { if let Some(job) = self.jobs.remove(&handle) { - job.report()(TransferState::Cancelled); + job.cancel(); } } Some(Slot::Running { task, part, report }) if !task.is_finished() => { diff --git a/crates/voelin-core/tests/link_fake.rs b/crates/voelin-core/tests/link_fake.rs index 101f5af..ed9b394 100644 --- a/crates/voelin-core/tests/link_fake.rs +++ b/crates/voelin-core/tests/link_fake.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::{broadcast, mpsc}; +use voelin_audio::{TalkerId, VoiceCodec, VoicePacket}; use voelin_core::history::MessageSource; use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; use voelin_core::settings::Settings; @@ -19,6 +20,7 @@ use voelin_core::{ }; use voelin_model::{ Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, + ServerDetails, }; /// A connection the session asked the link for. @@ -167,28 +169,53 @@ fn connected(streams: bool) -> LinkEvent { } } +/// A client as a TeamSpeak link reports one: with its database id, and not +/// talking (who talks comes from the media, which the session derives). fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo { ClientInfo { id, uid: Some(format!("{nickname}=")), nickname: nickname.into(), channel, + talking: Some(false), + database_id: Some(1_000 + u64::from(id)), ..Default::default() } } -/// Two channels, three clients; we are in the second channel. +/// Two channels, three clients; we are in the second channel. The shape is +/// what a TeamSpeak link reports: sibling channels form an order chain, the +/// server is named and has its unique id. fn presence() -> Presence { - let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() }; + let channel = + |id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() }; let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() }; - presence.channels.insert(LOBBY, channel(LOBBY, "Lobby")); - presence.channels.insert(GAMES, channel(GAMES, "Games")); - for c in [client(ME, "tester", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] { + presence.server = ServerDetails { + name: "Fake Server".into(), + uid: Some(SERVER_UID.into()), + version: backend().version, + ..Default::default() + }; + presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0)); + presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY)); + let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) }; + for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] { presence.clients.insert(c.id, c); } presence } +/// One packet of voice from `talker`: what the session derives talking from. +fn voice_of(talker: u16) -> LinkEvent { + LinkEvent::Audio(VoicePacket { + talker: TalkerId(talker), + seq: 1, + codec: VoiceCodec::Voice, + whisper: false, + payload: vec![1, 2, 3], + }) +} + fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage { ChatMessage { target: ChatTarget::Channel(GAMES), @@ -246,7 +273,8 @@ async fn presence_follows_the_link_until_it_disconnects() { assert_eq!(state.presence_source, Some(Source::Voice)); conn.play([ - LinkEvent::Talking { client: 8, talking: true }, + // Alice talks: a packet of her voice (the session derives who talks). + voice_of(8), LinkEvent::Poke { from: 8, from_uid: Some("alice=".into()), @@ -333,8 +361,9 @@ async fn commands_reach_the_link() { password: None, path: "/docs/".into(), }); - let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") }; - assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/")); + let LinkCmd::ListFiles { dir, .. } = conn.cmd().await else { panic!("a file list") }; + // The request id is the session's own: the link gets one of its making. + assert_eq!((dir.channel, dir.path.as_str()), (GAMES, "/docs/")); // No streams in the capabilities: the session refuses them itself. let setup = || StreamSetup { name: "screen".into(), ..Default::default() }; @@ -548,6 +577,8 @@ async fn a_replaced_connection_is_ignored() { ]); let mut fresh = presence(); fresh.clients.remove(&9); + // A link that says we are in the lobby shows us in the lobby. + fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY; new.play([ connected(false), LinkEvent::Presence(Box::new(fresh.clone())), @@ -565,6 +596,10 @@ async fn a_replaced_connection_is_ignored() { assert_eq!(*shown, fresh); let state = h.state(|s| s.own_channel == Some(LOBBY)).await; assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count"); - new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]); + // Channel chat reaches the channel we are in (the lobby, now). + new.play([LinkEvent::Chat(ChatMessage { + target: ChatTarget::Channel(LOBBY), + ..message("alice", "hello", now_ms()) + })]); assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed"); }