diff --git a/Cargo.lock b/Cargo.lock index bf6d35f..73c9f0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9518,10 +9518,12 @@ dependencies = [ "tsproto-types", "voelin-audio", "voelin-gateway-proto", + "voelin-identity", "voelin-media", "voelin-model", "voelin-observer", "voelin-platform", + "voelin-proto", "voelin-query", "voelin-store", "voelin-stream", @@ -9576,7 +9578,7 @@ dependencies = [ [[package]] name = "voelin-identity" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" dependencies = [ "aws-lc-rs", "base64 0.23.1", @@ -9635,9 +9637,11 @@ dependencies = [ [[package]] name = "voelin-model" version = "0.1.0" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" dependencies = [ + "prost", "serde", - "serde_json", + "voelin-proto", ] [[package]] @@ -9672,7 +9676,7 @@ dependencies = [ [[package]] name = "voelin-proto" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" dependencies = [ "bytes", "prost", diff --git a/Cargo.toml b/Cargo.toml index 359f1bb..10350af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,6 @@ members = [ "crates/voelin-gateway", "crates/voelin-gateway-proto", "crates/voelin-media", - "crates/voelin-model", "crates/voelin-observer", "crates/voelin-platform", "crates/voelin-query", @@ -37,7 +36,6 @@ default-members = [ "crates/voelin-core", "crates/voelin-gateway", "crates/voelin-gateway-proto", - "crates/voelin-model", "crates/voelin-observer", "crates/voelin-platform", "crates/voelin-query", @@ -59,9 +57,14 @@ publish = false # The protocol repository is private (VoelinProtocol). This is the SSH URL its # docs/development.md names, so that a per-developer .cargo/config.toml [patch] # can point it at a sibling checkout (docs/building.md, "Working with a sibling -# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release -# that has the account-bound KeyStore (its Phase 2 task 28). -voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "64808ccbb1e3aa10213392724f2f436bc25fd36f" } +# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release: +# the three crates below are at one revision (main c8e0e5a: the account-bound +# KeyStore of Phase 2 task 28, the account types of the session seam). +voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages. +voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +# The UI-facing domain model and the client's replica of v1 entities. +voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } [workspace.lints.rust] # deny, not forbid: generated code (Slint) needs a local allow. diff --git a/README.md b/README.md index 7a24eeb..96986e6 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch - `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes; see [UPSTREAM.md](crates/proto/UPSTREAM.md)) -- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities +- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities - `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices - `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets - `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive) diff --git a/crates/voelin-android/Cargo.toml b/crates/voelin-android/Cargo.toml index 9b267aa..b04b51c 100644 --- a/crates/voelin-android/Cargo.toml +++ b/crates/voelin-android/Cargo.toml @@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", " tracing = "0.1.44" voelin-core = { path = "../voelin-core" } # Channels and people for the voice notification. -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } [target.'cfg(target_os = "android")'.dependencies] anyhow = "1.0.104" diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index ab77a67..c5e18ab 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). @@ -50,11 +52,17 @@ toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } +# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store +# keeps it, or a Voelin key). +voelin-identity = { workspace = true } voelin-media = { path = "../voelin-media", default-features = false } -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } voelin-observer = { path = "../voelin-observer" } # Paths only (the cache directory). voelin-platform = { path = "../voelin-platform", default-features = false } +# The backend-neutral session seam the engine consumes (`voelin_proto::link`) +# and the v1 messages it speaks. +voelin-proto = { workspace = true } voelin-query = { path = "../voelin-query" } voelin-store = { path = "../voelin-store" } voelin-stream = { path = "../voelin-stream" } @@ -65,13 +73,15 @@ 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 } # `process`: the browser interop test drives Chromium through Node.js. tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] } +# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance +# suite). +voelin-proto = { workspace = true, features = ["test-util"] } [lints] workspace = true diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index 4410be4..7ec055c 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -4,21 +4,21 @@ //! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a //! map access, and the same image seen on several servers or under //! several clients is one file. Pictures from the web (banners, -//! [`crate::web`]) are named by the MD5 hash of their address. Keys are +//! `web`) are named by the MD5 hash of their address. Keys are //! relative paths (`avatars/`, `icons/`, `pictures/`). //! //! The cache is bounded by `cache.max_mb` (read on every insert; 0: no //! limit): the least recently used files go first. Use times survive //! restarts as the files' modification times. //! -//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to +//! Downloads are deduplicated: `Cache::fetch` tells the first asker to //! download (into a temporary path), later askers wait for the same -//! download ([`Cache::finish`] answers them all). +//! download (`Cache::finish` answers them all). //! //! A picture from the web keeps its host's validators (`ETag`, //! `Last-Modified`) next to it, in `validators/pictures/`: asked for -//! again, it is downloaded only if it changed ([`Cache::validators`], -//! [`Arrived::Unchanged`]). +//! again, it is downloaded only if it changed (`Cache::validators`, +//! `Arrived::Unchanged`). use std::collections::{BTreeMap, HashMap}; use std::fmt; @@ -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 { @@ -489,6 +500,15 @@ mod tests { use super::*; + #[test] + fn large_pictures_get_time_to_arrive() { + let secs = std::time::Duration::from_secs; + assert_eq!(image_download_time(0), secs(60)); + assert_eq!(image_download_time(100 << 10), secs(72)); + // The largest picture, at the slowest rate allowed. + assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384)); + } + fn temp_dir(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!( "voelin-cache-{tag}-{}-{:?}", diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs index 493ff74..d0e416d 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,34 @@ async fn receive( } } -/// Send `file` from `offset` (`size` bytes in total). Reports `Started`, -/// `Progress` and the final state. -pub(crate) async fn upload( - mut stream: TcpStream, +/// 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 +309,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 +428,7 @@ fn percent_decode(text: &str) -> Option { mod tests { use std::sync::Mutex; - use tokio::net::TcpListener; + use tokio::net::{TcpListener, TcpStream}; use super::*; @@ -562,7 +569,8 @@ mod tests { }); let (report, states) = recorder(); let stream = TcpStream::connect(addr).await.unwrap(); - upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await; + let (_, write) = tokio::io::split(stream); + upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await; assert_eq!(server.await.unwrap(), b"456789"); assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. }))); assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7"); diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index f534544..a056017 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -61,6 +61,7 @@ use voelin_gateway_proto::{ HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry, StreamSpec, TopicInfo, UserRef, }; +use voelin_identity::IdentityBlob; use voelin_model::{ChannelId, ChatTarget, Presence}; use voelin_store::WriteOutcome; @@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent { Disconnected(Option), } +/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to +/// with it. +fn login_identity(blob: &IdentityBlob) -> Result { + crate::ts::identity::from_blob(blob).map_err(|e| e.to_string()) +} + /// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a -/// TeamSpeak identity. +/// TeamSpeak identity (a blob of kind `teamspeak`, see +/// [`crate::ts::identity::to_blob`]; one that is none is refused as +/// [`ErrorCode::AuthFailed`], the way the gateway would). pub async fn connect( url: &str, - identity: &tsclientlib::Identity, + identity: &IdentityBlob, ) -> Result<(GatewayClient, mpsc::UnboundedReceiver), ClientError> { - connect_watched(url, identity, &Progress::default()).await + let identity = login_identity(identity) + .map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?; + connect_watched(url, &identity, &Progress::default()).await } /// [`connect`], telling `progress` each step (for the log). @@ -114,10 +125,19 @@ async fn connect_watched( /// logs in. pub(crate) async fn run( mut urls: Vec, - identity: tsclientlib::Identity, + identity: IdentityBlob, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { + // An identity that cannot be read will not be tomorrow: like a refused login. + let identity = match login_identity(&identity) { + Ok(identity) => identity, + Err(reason) => { + debug!(%reason, "gateway: the identity cannot be read"); + let _ = events.send(GatewayEvent::Disconnected(Some(reason))); + return; + } + }; // A gateway that is away (down, restarting, a network change, a proxy // in front of it that fails) or cannot log us in yet (it does not know // the identity before voice connected once, its server is restarting) @@ -274,20 +294,24 @@ pub(crate) struct Observed { } impl Observed { - pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self { - Self { - urls: urls.to_vec(), - key: identity.key().to_pub().to_ts(), - counter: identity.counter(), - nudged: None, + pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self { + let (key, counter) = Self::of(identity); + Self { urls: urls.to_vec(), key, counter, nudged: None } + } + + /// The public key and the counter of an identity: an identity that cannot be + /// read has neither (and so is the same as any other that cannot). + fn of(identity: &IdentityBlob) -> (String, u64) { + match login_identity(identity) { + Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()), + Err(_) => (String::new(), 0), } } /// Whether this is what is observed with. - pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool { - self.urls == urls - && self.counter == identity.counter() - && self.key == identity.key().to_pub().to_ts() + pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool { + let (key, counter) = Self::of(identity); + self.urls == urls && self.counter == counter && self.key == key } /// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice @@ -1182,15 +1206,16 @@ mod tests { #[test] fn the_same_observation_is_nudged_at_most_every_5_s() { + let blob = crate::ts::identity::to_blob; let identity = tsclientlib::Identity::create(); let urls = vec!["ws://gw.example.test:7788/v1".to_owned()]; - let mut observed = Observed::new(&urls, &identity); - assert!(observed.same(&urls, &identity)); - assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity)); - assert!(!observed.same(&urls, &tsclientlib::Identity::create())); + let mut observed = Observed::new(&urls, &blob(&identity)); + assert!(observed.same(&urls, &blob(&identity))); + assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity))); + assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create()))); // Its security level raised: logged in with the new counter. let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1); - assert!(!observed.same(&urls, &raised)); + assert!(!observed.same(&urls, &blob(&raised))); let now = Instant::now(); assert!(observed.nudge_at(now)); assert!(!observed.nudge_at(now + Duration::from_secs(4))); diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 8cda54b..496e5a5 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -3,8 +3,10 @@ //! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s. //! Each server the user works with is a session with up to three sources: //! -//! - **voice**: a normal client connection (visible, can talk), made by a -//! [`link::ServerLink`] ([`TsLink`] for TeamSpeak servers; see [`link`]) +//! - **voice**: a normal client connection (visible, can talk): a +//! `voelin_proto::link::Session` that the connector of the server's address +//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see +//! [`link`]) //! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat) //! - **query**: the user's own ServerQuery credentials (same, without a gateway) //! @@ -17,9 +19,9 @@ //! [`Engine::subscribe_frames`] for the frames of watched streams. The audio //! of watched streams plays through the session's speakers by itself //! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video -//! are in [`media`] (feature `media`), and the Stream Studio (scenes of +//! are in `media` (feature `media`), and the Stream Studio (scenes of //! sources composited into one stream, recording, a replay buffer, WHIP) in -//! [`studio`]. +//! `studio`. //! //! Settings are a [`settings::Settings`] service: typed keys, runtime //! values stored in the client database ahead of command line, config file @@ -46,14 +48,12 @@ //! volume) are engine-wide ([`contacts`]). mod audio; -mod book; pub mod cache; pub mod contacts; pub mod discover; pub mod files; pub mod gateway; pub mod history; -pub mod identity; pub mod link; #[cfg(feature = "media")] pub mod media; @@ -66,16 +66,14 @@ pub mod stream; mod stream_types; #[cfg(feature = "media")] pub mod studio; -mod ts_link; -pub mod versions; -mod voice; +pub mod ts; mod web; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc, watch}; +use tokio::sync::{broadcast, mpsc}; pub use voelin_audio::settings::TransmitMode; pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings}; use voelin_model::{ @@ -91,15 +89,14 @@ 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::ConnectOptions; -pub use link::ConnectOptions as VoiceOptions; -pub use link::ServerLink; +pub use link::{Backends, VoiceOptions}; pub use offline::{OfflineMessage, OfflineMessageInfo}; +pub use query::{QueryLogin, QueryTransport}; pub use route::{ChatRoute, Dedup, route_chat}; use settings::{SettingChange, Settings, SharedSettings}; use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; -pub use ts_link::TsLink; +pub use voelin_identity::IdentityBlob; /// Banners are downloaded and shown by the same rule. pub use web::is_svg; /// Pictures from the web go through the desktop's proxy (set at startup). @@ -114,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100; /// What the UI asks for. #[derive(Clone, Debug)] pub enum Command { - /// Main account proof for every current and future voice connection. - SetMytsIdentity(Option>), - /// What voice servers are shown of the main account (its avatar and - /// badges with their certificates, its User Tag; TeamSpeak 6): sent to - /// every connection that presents the account's myTS ID, once connected - /// and when it changes; cleared on a sign-out. - SetMytsData(Option>), ConnectVoice { session: SessionId, options: Box, @@ -136,12 +126,15 @@ pub enum Command { ObserveGateway { session: SessionId, urls: Vec, - identity: Box, + /// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]). + /// One that is none, or cannot be read, ends the observation with + /// its reason. + identity: Box, }, /// Invisible presence and relay chat with own ServerQuery credentials. ObserveQuery { session: SessionId, - connect: Box, + connect: Box, }, StopObserving { session: SessionId, @@ -276,7 +269,7 @@ pub enum Command { }, /// The video of a watched stream arrives, but none of it decodes: watch /// it in another codec the streamer offered, if there is one (a new - /// connection without this one). [`media::Viewer`] sends it. + /// connection without this one). `media::Viewer` sends it. StreamUndecodable { session: SessionId, stream_id: String, @@ -792,19 +785,18 @@ 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`]). - pub fn start_with_link( - settings: Settings, - history: History, - link: Arc, - ) -> Self { + /// 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::new(link::SessionLink::new(backends)); let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. @@ -900,14 +892,12 @@ async fn run( events: broadcast::Sender, frames: broadcast::Sender, engine: Shared, - link: Arc, + link: Arc, ) { let Shared { settings: shared, history, cache, contacts } = engine.clone(); // Before any command: a contact set meanwhile would be lost. contacts.load().await; let mut sessions: HashMap = HashMap::new(); - let (myts_identity, _) = watch::channel(None); - let (myts_data, _) = watch::channel(None); let mut current = shared.current(); // Pruning: at start, then hourly (and when the setting changes). let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); @@ -952,29 +942,6 @@ async fn run( }, }; let id = match command { - Command::SetMytsIdentity(identity) => { - // Still no account is no change: every notification restarts - // handshakes and sends `updatemytsid` on every connection. Any - // account is (each connection's proof is signed anew). - myts_identity.send_if_modified(|current| { - if current.is_none() && identity.is_none() { - return false; - } - *current = identity; - true - }); - continue; - } - Command::SetMytsData(data) => { - myts_data.send_if_modified(|current| { - if *current == data { - return false; - } - *current = data; - true - }); - continue; - } Command::SetAudioSettings(new) => { settings = (*new).clone(); for s in sessions.values() { @@ -1051,8 +1018,6 @@ async fn run( settings.clone(), engine.clone(), link.clone(), - myts_identity.subscribe(), - myts_data.subscribe(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -1131,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId { | Command::DeleteOfflineMessage { session, .. } | Command::SetOfflineMessageRead { session, .. } | Command::CloseSession { session } => *session, - Command::SetMytsIdentity(_) - | Command::SetMytsData(_) - | Command::SetAudioSettings(_) + Command::SetAudioSettings(_) | Command::SetSrtpProfiles(_) | Command::TestMicrophone { .. } | Command::SetSetting { .. } diff --git a/crates/voelin-core/src/link.rs b/crates/voelin-core/src/link.rs deleted file mode 100644 index 52369ad..0000000 --- a/crates/voelin-core/src/link.rs +++ /dev/null @@ -1,330 +0,0 @@ -//! The seam between a session and the server it talks to as a client. -//! -//! A session merges up to three sources (voice, gateway, query). The *voice* -//! source is the connection that is visible on the server, can talk and -//! carries chat, files, pokes, offline messages and streams. Everything the -//! session needs from it goes through [`ServerLink`]: the session hands the -//! link the connection's options and a [`LinkCtx`], and talks to it with two -//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the -//! backend shows: the session merges, deduplicates, stores and routes what a -//! link reports, whichever server software is behind it. -//! -//! # Contract for a link -//! -//! - [`ServerLink::spawn`] returns at once; the connection runs on its own -//! task and reports through `events`. Connecting is not an event: the -//! session shows `Connecting` from the moment it spawned the link, until -//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed). -//! - The first thing a connected link reports is [`LinkEvent::Connected`] -//! (name, backend, what it can do, our client id, the server's unique id), -//! then [`LinkEvent::Presence`] whenever anything in the server's tree or -//! client list changed (a full snapshot each time) and -//! [`LinkEvent::OwnChannel`] when we moved. -//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for, -//! reports that the connection ended, whichever way it did; a link sends it -//! once, and nothing from the connection itself follows it. A link that -//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves. -//! It is not promised to be the last event of the link: the stream task of -//! a connection with streams is a task of its own, which winds down after -//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and -//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its -//! streams, may follow `Disconnected` (`TsLink` ends the stream task as the -//! connection's loop ends, which usually, not always, puts them before it). -//! The session does not depend on the order: it ends our own stream and -//! the audio of watched streams itself when it hears `Disconnected`, and -//! ignores what a link says after that, like the events of a replaced one. -//! - Streams (screen sharing) are the link's business from the capabilities -//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the -//! stream task, takes [`LinkCmd::Stream`] and reports through the event -//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the -//! session first (file lists, transfers, offline messages, stream state). -//! What the session must place itself comes as events: our own stream's -//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio -//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread, -//! and [`LinkEvent::StreamAudioEnded`] when a stream's audio is over). -//! When the session replaces a connection it gives the old link -//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear -//! of their end before the link stops reading commands). -//! - What the session must see first (chat, pokes, who is talking, audio) -//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file -//! list, a request's `Done`) go straight to the event bus with -//! [`LinkCtx::emit`]. -//! - Events of a link the session replaced are ignored (each link has a -//! generation), so a link need not stop emitting at once. -//! -//! # Implementations -//! -//! [`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. -//! -//! # 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: -//! -//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and -//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account -//! proof in [`LinkCtx`] (`myts_identity` of `tsproto`, `myts_data` of -//! `tsclientlib`). -//! - Client ids are TeamSpeak's `u16`: `own_client` of -//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of -//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a -//! [`ChatMessage`], and the viewer and streamer ids of the stream API. -//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client -//! ids, `u64` channel and group ids, server and channel groups, talk -//! power, icons, badges and the myTeamSpeak avatar. -//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream -//! 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`]). - -use std::path::PathBuf; -use std::sync::Arc; - -use tokio::sync::{broadcast, mpsc, watch}; -use voelin_audio::{EncodedVoice, VoicePacket}; -use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence}; -use voelin_stream::PeerConfig; - -use crate::files::{Report, RequestId, Sink, TransferId}; -use crate::settings::SharedSettings; -use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame}; -use crate::{BackendInfo, Event, SessionId}; - -/// Starts the voice connection of a session. -/// -/// One link serves every session of an engine; [`spawn`](Self::spawn) starts -/// one connection. -pub trait ServerLink: Send + Sync + 'static { - /// Connect to the server `options` names and run the connection on its - /// own task: take commands from `cmds`, report through `events`, and end - /// the connection with [`LinkEvent::Disconnected`]. Does not block. - fn spawn( - &self, - options: ConnectOptions, - ctx: LinkCtx, - cmds: mpsc::UnboundedReceiver, - events: mpsc::UnboundedSender, - ); -} - -/// What a connection needs to know: the server, who to be, where to join. -/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.) -#[derive(Clone, Debug)] -pub struct ConnectOptions { - pub address: String, - pub nickname: String, - /// The identity to connect with (TeamSpeak's, for now). - pub identity: Option, - /// Signed compatibility version; `None` selects the native platform's tuple. - pub client_version: Option, - pub server_password: Option, - /// Channel path to join, e.g. `Lobby/Sub`, or `/`. - pub channel: Option, - /// The password of `channel`. - pub channel_password: Option, - /// A privilege key to use when connecting. - pub token: Option, - /// Open the audio devices (capture and playback). - pub audio: bool, - /// Network settings for stream peer connections (TeamSpeak 6). - pub stream_peer: PeerConfig, -} - -impl ConnectOptions { - pub fn new(address: impl Into, nickname: impl Into) -> Self { - Self { - address: address.into(), - nickname: nickname.into(), - identity: None, - client_version: None, - server_password: None, - channel: None, - channel_password: None, - token: None, - audio: false, - stream_peer: PeerConfig::default(), - } - } -} - -/// What the engine gives a link besides the options: where the connection -/// answers the requests the session need not see, and what it shares with -/// the session's other parts. -#[derive(Clone)] -pub struct LinkCtx { - pub(crate) session: SessionId, - pub(crate) events: broadcast::Sender, - /// The frames of watched streams (kept off the event bus). - pub(crate) frames: broadcast::Sender, - pub(crate) settings: SharedSettings, - /// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]). - pub(crate) myts_identity: watch::Receiver>>, - /// What the server is shown of the account ([`crate::Command::SetMytsData`]). - pub(crate) myts_data: watch::Receiver>>, -} - -impl LinkCtx { - /// The session this connection belongs to. - pub fn session(&self) -> SessionId { - self.session - } - - /// Tell the engine's event bus something (a request's answer, a - /// transfer's progress). - pub fn emit(&self, event: Event) { - let _ = self.events.send(event); - } - - pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) { - self.emit(Event::RequestDone { session: self.session, request, result }); - } -} - -/// A file on the server: channel, its password, path. -#[derive(Clone, Debug)] -pub struct Remote { - pub channel: ChannelId, - pub password: Option, - pub path: String, -} - -/// What the session asks of a connection. -pub enum LinkCmd { - SendChat(ChatTarget, String), - Move(ChannelId, Option), - SetInputMuted(bool), - SetOutputMuted(bool), - /// An encoded voice frame from the audio thread. - Audio(EncodedVoice), - /// A stream command; the link answers on the event bus. Only sent while - /// the connection's capabilities include streams. - Stream(StreamCmd), - Poke { - client: u16, - message: String, - }, - ListFiles { - request: RequestId, - dir: Remote, - }, - /// Download `file`; `transfer` if the user can cancel it. - Download { - transfer: Option, - file: Remote, - sink: Sink, - report: Report, - }, - Upload { - transfer: Option, - file: Remote, - from: PathBuf, - overwrite: bool, - resume: bool, - report: Report, - }, - CancelTransfer(TransferId), - DeleteFiles { - /// `None`: best effort, nobody waits for the answer. - request: Option, - channel: ChannelId, - password: Option, - paths: Vec, - }, - RenameFile { - request: RequestId, - from: Remote, - to: Remote, - }, - CreateDirectory { - request: RequestId, - dir: Remote, - }, - /// Announce our avatar's hash (empty: no avatar). - SetAvatarHash { - request: Option, - hash: String, - }, - OfflineList { - request: RequestId, - }, - OfflineGet { - request: RequestId, - id: u32, - }, - OfflineAdd { - request: RequestId, - to_uid: String, - subject: String, - text: String, - }, - OfflineDelete { - request: RequestId, - id: u32, - }, - OfflineFlag { - request: RequestId, - id: u32, - read: bool, - }, - Disconnect, -} - -/// What a connection tells the session. -pub enum LinkEvent { - Connected { - name: String, - /// The server software, and what it can do (the connection knows - /// both from the server's version). - backend: BackendInfo, - capabilities: Capabilities, - own_client: u16, - /// The server's unique id. - server_uid: String, - /// Our unique id as the server knows it. - own_uid: Option, - }, - /// The server's channels and clients as they are now. - Presence(Box), - OwnChannel(ChannelId), - Chat(ChatMessage), - Poke { - from: u16, - from_uid: Option, - from_name: String, - message: String, - }, - /// Incoming voice for the audio thread. - Audio(VoicePacket), - /// Who is talking (on, and off again when it stopped). - Talking { - client: u16, - talking: bool, - }, - /// Our own stream's life, for the gateway directory. - OwnStream(OwnStreamEvent), - /// An Opus frame (48 kHz) of a watched stream, for the audio thread - /// ([`ConnectOptions::audio`]); `time` is its RTP time on the 48 kHz - /// clock. - StreamAudio { - stream: String, - time: u64, - data: Arc<[u8]>, - }, - /// A watched stream ended: its audio leaves the mixer. - StreamAudioEnded(String), - /// A command failed (the connection stays). - Error(String), - /// The connection ended; the reason if it was not asked for. Sent once; - /// the stream task's closing reports may still follow (see the module - /// documentation). - Disconnected(Option), -} diff --git a/crates/voelin-core/src/link/backends.rs b/crates/voelin-core/src/link/backends.rs new file mode 100644 index 0000000..afabc1d --- /dev/null +++ b/crates/voelin-core/src/link/backends.rs @@ -0,0 +1,261 @@ +//! 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; +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}; +use crate::ts::TsConnector; + +/// 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. + 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, +} + +impl LocalCtx { + pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self { + Self { link, audio, stream_peer } + } + + /// 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 link = LinkCtx { + session: 0, + events, + frames, + settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()), + }; + Self { link, audio: false, stream_peer: PeerConfig::default() } + } +} + +/// 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_teamspeak(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); + } + + /// Register the TeamSpeak connector for the schemes it names + /// (`ts3server`, `teamspeak`, and addresses without a scheme). + /// [`Backends::default`] registers one of its own; register yours to keep a + /// clone of it, whose [`TsConnector::set_myts_identity`] and + /// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every + /// connection it makes. + pub fn register_teamspeak(&mut self, connector: TsConnector) { + self.register_local(Arc::new(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); + } + // Not `Connectors::connect`, which names the whole address when none serves it: + // the text is shown, and a TeamSpeak link carries a channel password. + let Some(connector) = self.connectors.for_address(¶ms.address) else { + let shown = without_query(¶ms.address).to_owned(); + return Box::pin(async move { + Err(SessionError::Protocol(format!("no connector for {shown}"))) + }); + }; + let connect = connector.connect(params); + Box::pin(async move { + let connected = connect.await?; + Ok(LocalConnected { connected, streams: None }) + }) + } +} + +/// An address as it may be shown or logged: without its query and fragment, +/// where a link keeps a channel password or a host pin. +pub(crate) fn without_query(address: &str) -> &str { + address.split(['?', '#']).next().unwrap_or_default() +} + +/// 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"); + } + + #[test] + fn an_address_is_shown_without_its_secrets() { + assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h"); + assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code"); + assert_eq!(without_query("host:9987"), "host:9987"); + } +} diff --git a/crates/voelin-core/src/link/connect.rs b/crates/voelin-core/src/link/connect.rs new file mode 100644 index 0000000..c8c862a --- /dev/null +++ b/crates/voelin-core/src/link/connect.rs @@ -0,0 +1,261 @@ +//! What a session hands the connector of an address: the `ConnectParams` of +//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2). +//! +//! The options are the engine's own, and a connector reads them back: the +//! address is the link of the bookmark (a `ts3server://` link for a +//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname, +//! the server password and the privilege key are in the hello, the identity +//! is the credential. What v1 has no field for yet (the channel to join and +//! its password, the client version a TeamSpeak server is shown) rides in +//! the address, as parameters of the link. + +use std::sync::Arc; +use std::time::Duration; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use bytes::Bytes; +use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK}; +use voelin_model::Link; +use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError}; +use voelin_proto::v1; + +use super::{Backends, VoiceOptions, without_query}; + +/// The link parameter that carries the client version to impersonate: the +/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64. +/// The connector for TeamSpeak resolves it; other connectors never read it. +pub(crate) const VERSION_PARAM: &str = "client_version"; + +/// The connect parameters of a connection, from the options the session was +/// asked to connect with. +/// +/// The address is the 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 the credential of its kind; no +/// account is used yet. +/// +/// An address a link cannot carry is refused here ([`bookmark`]), and so is +/// an identity that is of no kind a connector can use. +pub(crate) fn connect_params( + options: &VoiceOptions, + media: Arc, + backends: &Backends, +) -> Result { + 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() + }; + Ok(ConnectParams { + address: address_link(options)?, + credential: credential(options.identity.as_ref())?, + 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 credential of an identity (`docs/session-seam.md` section 7). A +/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as +/// an empty one, for which the TeamSpeak connector makes an identity up (the +/// protocol's convention for "generate one", follow-up P11); a Voelin key +/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is, +/// it would be that same empty blob and be taken for the request to make one +/// up, which only the absence of an identity may be. +fn credential(identity: Option<&IdentityBlob>) -> Result { + let Some(blob) = identity else { + return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() }); + }; + if blob.is_teamspeak() { + if blob.json.trim().is_empty() { + return Err(SessionError::Protocol( + "the TeamSpeak identity cannot be read: it is empty".into(), + )); + } + let json = Bytes::copy_from_slice(blob.json.as_bytes()); + Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json }) + } else if blob.is_voelin() { + let key = blob.voelin_key().map_err(|e| { + SessionError::Protocol(format!("the Voelin identity cannot be read: {e}")) + })?; + Ok(Credential::Voelin(Arc::new(key))) + } else { + Err(SessionError::Protocol(format!( + "an identity of kind {:?} cannot be used to connect", + blob.kind + ))) + } +} + +/// The `ts3server://` link of the options' address, with the channel to join +/// and the client version to claim. +fn address_link(options: &VoiceOptions) -> Result { + 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("://") => bookmark(&options.address)?, + // Some other scheme: as given, for the connector of that scheme. + _ => return Ok(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(spec) = &options.client_version { + url.push(if url.contains('?') { '&' } else { '?' }); + url.push_str(VERSION_PARAM); + url.push('='); + url.push_str(&URL_SAFE_NO_PAD.encode(spec)); + } + Ok(url) +} + +/// The link to a bookmark's `host[:port]`. +/// +/// A link cannot say everything an address can: it drops a port that is no +/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins +/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a +/// `%` (so that a `?` in the host would hide the channel behind the next +/// one). The TeamSpeak library refuses such an address when it resolves it; +/// so does this, in words, instead of connecting to something else. +fn bookmark(address: &str) -> Result { + let address = address.trim(); + // Without the query: a link keeps secrets in it. + let shown = without_query(address); + let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}")); + if address.is_empty() + || address + .chars() + .any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control()) + { + return Err(not_an_address()); + } + // The text after the port's colon: `[v6]:port`, or `host:port` with the one + // colon (more colons are an IPv6 address without a port). + let port = if let Some(rest) = address.strip_prefix('[') { + let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?; + (!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after)) + } else { + address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port) + }; + if let Some(port) = port + && !port.parse::().is_ok_and(|port| port != 0) + { + return Err(SessionError::Protocol(format!( + "the port in {shown} is not a number from 1 to 65535" + ))); + } + Ok(voelin_model::ServerLink::new(address)) +} + +#[cfg(test)] +mod tests { + use super::*; + use voelin_identity::IdentityKey; + + fn params(options: &VoiceOptions) -> Result { + let (media, _rx) = voelin_proto::test_util::media_channel(); + connect_params(options, media, &Backends::empty()) + } + + /// The identity of the options is the credential of its kind: a TeamSpeak + /// identity as the JSON the key store keeps, none as the empty blob a + /// connector makes an identity up for, a Voelin key as its signer. + #[test] + fn an_identity_is_the_credential_of_its_kind() { + let mut options = VoiceOptions::new("ts.example.com", "nick"); + let none = params(&options).unwrap(); + assert!(matches!( + &none.credential, + Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty() + )); + + options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#)); + let sent = params(&options).unwrap(); + assert!(matches!( + &sent.credential, + Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"# + )); + + let key = IdentityKey::generate().unwrap(); + options.identity = Some(IdentityBlob::voelin(&key).unwrap()); + let Credential::Voelin(signer) = params(&options).unwrap().credential else { + panic!("a Voelin credential") + }; + assert_eq!(signer.public_key(), key.public_key()); + assert_eq!(signer.sign(b"hello"), key.sign(b"hello")); + + // A Voelin blob whose key cannot be read, and a kind that connects to + // nothing: refused in words, without the JSON. + options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2")); + let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") }; + assert!( + text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2") + ); + options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2")); + let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") }; + assert_eq!(text, "an identity of kind \"account\" cannot be used to connect"); + } + + /// A TeamSpeak identity with no JSON is no identity. The empty blob is + /// what asks the TeamSpeak connector to make one up (`identity: None`), so + /// it is refused here instead of being sent as that request. + #[test] + fn a_teamspeak_identity_without_json_is_refused() { + let mut options = VoiceOptions::new("ts.example.com", "nick"); + for json in ["", " \n\t"] { + options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json)); + let Err(SessionError::Protocol(text)) = params(&options) else { + panic!("a refusal for {json:?}") + }; + assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty"); + } + // No identity at all is the request to make one up, as before. + options.identity = None; + assert!(matches!( + params(&options).unwrap().credential, + Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty() + )); + } + + /// The client version spec rides the link as it was typed, whatever it + /// holds, and only for an address that is a TeamSpeak bookmark or link. + #[test] + fn the_client_version_spec_rides_the_link_unchanged() { + let spec = |address: &str, spec: &str| { + let mut options = VoiceOptions::new(address, "nick"); + options.client_version = Some(spec.into()); + params(&options).unwrap().address + }; + let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#"); + let (_, query) = address.split_once('?').unwrap(); + let text = query + .split('&') + .find_map(|pair| pair.strip_prefix("client_version=")) + .expect("the parameter"); + let decoded = URL_SAFE_NO_PAD.decode(text).unwrap(); + assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#"); + // Another scheme is left as it is: its connector has no use for a TeamSpeak + // client's version. + assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code"); + // No spec, no parameter. + let options = VoiceOptions::new("ts.example.com", "nick"); + assert!(!params(&options).unwrap().address.contains(VERSION_PARAM)); + } +} diff --git a/crates/voelin-core/src/link/fake_link_tests.rs b/crates/voelin-core/src/link/fake_link_tests.rs new file mode 100644 index 0000000..aa99b79 --- /dev/null +++ b/crates/voelin-core/src/link/fake_link_tests.rs @@ -0,0 +1,363 @@ +//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each +//! connection the test asks for to the test, which plays the server by +//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session +//! gives. These are the tests that need the inner link itself: +//! +//! - the stream commands, which travel on the in-process port of the link +//! and which a `voelin_proto::link::Session` has no part in until the +//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2); +//! - the order in which a reconnect shuts the streams and the old connection +//! down, which is the order of the one queue `LinkSession` keeps; +//! - a link that keeps talking after the engine replaced its connection, +//! which a closed `FakeSession` cannot do on purpose. +//! +//! (They were integration tests while the inner link was public; it is the +//! TeamSpeak module's now, and so are these.) +//! +//! Presence, chat, the dedup of a message that comes twice, history, transfers +//! and the rest of what the engine does with a session are tested on the +//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here +//! needs a TeamSpeak server or a TeamSpeak type. + +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tokio::sync::{broadcast, mpsc}; + +use super::{Backends, LinkCmd, LinkCtx, LinkEvent}; +use crate::settings::Settings; +use crate::stream::{StreamCmd, StreamSetup}; +use crate::ts::ts_session::LinkConnector; +use crate::ts::{ConnectOptions, ServerLink}; +use crate::{ + BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState, +}; +use voelin_model::{ + Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, + ServerDetails, +}; + +/// A connection the session asked the link for. +struct Conn { + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +} + +impl Conn { + /// Play `script`, the server's side, in order. + fn play(&self, script: impl IntoIterator) { + for event in script { + self.events.send(event).expect("the session listens"); + } + } + + /// The next command the session gave. + async fn cmd(&mut self) -> LinkCmd { + tokio::time::timeout(Duration::from_secs(10), self.cmds.recv()) + .await + .expect("a command in time") + .expect("the session keeps the connection") + } +} + +/// Hands every connection to the test. +struct FakeLink { + conns: mpsc::UnboundedSender, +} + +impl FakeLink { + fn new() -> (Self, mpsc::UnboundedReceiver) { + let (conns, rx) = mpsc::unbounded_channel(); + (Self { conns }, rx) + } +} + +impl ServerLink for FakeLink { + fn spawn( + &self, + _options: ConnectOptions, + _ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + let _ = self.conns.send(Conn { cmds, events }); + } +} + +const SESSION: SessionId = 1; +const SERVER_UID: &str = "fake-server="; +const ME: u16 = 7; +const ME_UID: &str = "me="; +const LOBBY: ChannelId = 1; +const GAMES: ChannelId = 2; + +struct Harness { + engine: Engine, + events: broadcast::Receiver, + conns: mpsc::UnboundedReceiver, +} + +impl Harness { + fn start() -> Self { + let (link, conns) = FakeLink::new(); + let mut backends = Backends::empty(); + backends.register_local(Arc::new(LinkConnector::any(Arc::new(link)))); + let engine = + Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends); + let events = engine.subscribe(); + Self { engine, events, conns } + } + + /// Ask for a voice connection and take it from the link. + async fn connect(&mut self) -> Conn { + let options = VoiceOptions::new("fake.test:9987", "tester"); + self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + tokio::time::timeout(Duration::from_secs(10), self.conns.recv()) + .await + .expect("the session spawns the link") + .expect("the link lives") + } + + /// The next event `f` picks, skipping the others. + async fn next(&mut self, mut f: impl FnMut(Event) -> Option) -> T { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some(t) = f(self.events.recv().await.expect("engine events")) { + return t; + } + } + }) + .await + .expect("event in time") + } + + /// The next state of the session that `ok` accepts. + async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState { + self.next(|e| match e { + Event::State { state, .. } if ok(&state) => Some(state), + _ => None, + }) + .await + } + + /// The next live chat message. + async fn chat(&mut self) -> ChatMessage { + self.next(|e| match e { + Event::Chat { message, .. } => Some(message), + _ => None, + }) + .await + } +} + +fn now_ms() -> i64 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64 +} + +fn capabilities(streams: bool) -> Capabilities { + Capabilities { streams, file_transfer: true, ..Default::default() } +} + +fn backend() -> BackendInfo { + BackendInfo { product: "Fake".into(), version: "1.2".into() } +} + +fn connected(streams: bool) -> LinkEvent { + LinkEvent::Connected { + name: "Fake Server".into(), + backend: backend(), + capabilities: capabilities(streams), + own_client: ME, + server_uid: SERVER_UID.into(), + own_uid: Some(ME_UID.into()), + } +} + +/// 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. 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, order| ChannelInfo { id, name: name.into(), order, ..Default::default() }; + let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() }; + 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 +} + +fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(GAMES), + author_name: author.into(), + author_uid: Some(format!("{author}=")), + author_id: None, + text: text.into(), + ts_ms, + via_relay: false, + blocked: false, + } +} + +/// Stream commands reach a link that has streams in its capabilities, and +/// end with the connection; a link without them is spared. (The rest of what +/// the user asks for is checked on the fake host in `session_fake.rs`.) +#[tokio::test(flavor = "multi_thread")] +async fn stream_commands_reach_a_link_with_streams() { + let mut h = Harness::start(); + let mut conn = h.connect().await; + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + // No streams in the capabilities: the session refuses them itself. + let engine = h.engine.clone(); + let setup = || StreamSetup { name: "screen".into(), ..Default::default() }; + engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); + let error = h + .next(|e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await; + assert!(error.contains("streams"), "{error}"); + assert!(conn.cmds.try_recv().is_err(), "nothing reached the link"); + + // A link with streams: stream commands go to it, and end with the connection. + let mut with_streams = { + let link_engine = h.engine.clone(); + link_engine.send(Command::ConnectVoice { + session: SESSION, + options: Box::new(VoiceOptions::new("fake.test:9987", "tester")), + }); + h.conns.recv().await.expect("the second connection") + }; + // The replaced connection is told to go. + assert!(matches!(conn.cmd().await, LinkCmd::Disconnect)); + with_streams.play([connected(true)]); + h.next(|e| match e { + Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()), + _ => None, + }) + .await; + // A connection with streams is given the (empty) stream directory first. + let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else { + panic!("the stream directory") + }; + assert!(directory.is_empty()); + engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); + let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else { + panic!("a stream start") + }; + assert_eq!((setup.name.as_str(), auto_accept), ("screen", true)); + engine.send(Command::StopStream { session: SESSION }); + assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop))); + engine.send(Command::DisconnectVoice { session: SESSION }); + assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect)); +} + +/// A reconnect ends the streams of the connection it replaces through that +/// connection, before the connection itself: the old link is given +/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its +/// connection on `Disconnect` (the TeamSpeak one stops reading commands +/// there) relies on this order for the streams to hear of their end. +#[tokio::test(flavor = "multi_thread")] +async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() { + let mut h = Harness::start(); + let mut old = h.connect().await; + old.play([ + connected(true), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else { + panic!("the stream directory") + }; + assert!(directory.is_empty()); + + // Connecting again replaces the connection. + let _new = h.connect().await; + let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else { + panic!("the streams end first") + }; + assert_eq!(reason, "voice reconnecting"); + assert!(matches!(old.cmd().await, LinkCmd::Disconnect)); +} + +/// Events of a connection the session replaced do not reach it. +#[tokio::test(flavor = "multi_thread")] +async fn a_replaced_connection_is_ignored() { + let mut h = Harness::start(); + let mut old = h.connect().await; + old.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + let new = h.connect().await; + assert!(matches!(old.cmd().await, LinkCmd::Disconnect)); + // The old connection winds down, and says more than it should. + let mut stale = presence(); + stale.clients.insert(10, client(10, "ghost", LOBBY)); + old.play([ + LinkEvent::Presence(Box::new(stale)), + LinkEvent::Chat(message("ghost", "boo", now_ms())), + LinkEvent::Disconnected(None), + ]); + 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())), + LinkEvent::OwnChannel(LOBBY), + ]); + // Only the new connection's presence is shown (nobody else has 2 clients). + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => { + Some(presence) + } + _ => None, + }) + .await; + 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"); + // 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"); +} diff --git a/crates/voelin-core/src/link/fake_tests.rs b/crates/voelin-core/src/link/fake_tests.rs new file mode 100644 index 0000000..f428d5c --- /dev/null +++ b/crates/voelin-core/src/link/fake_tests.rs @@ -0,0 +1,322 @@ +//! The engine's side of the seam against the protocol repository's fake host +//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a +//! `SessionLink` that talks to a `FakeSession`, and the link conformance +//! suite run against the session the engine's registry hands over. +//! +//! The tests that need only the engine's public API are in +//! `tests/session_fake.rs`; these need what is private to the crate: the +//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`, +//! the registry's `connect` and the context of a connector called outside an +//! engine. + +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::mpsc; +use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket}; +use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub}; +use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS}; +use voelin_proto::media::{RtpHeader, RtpView}; +use voelin_proto::test_util::conformance::{self, Fixture, Verdict}; +use voelin_proto::test_util::{ + FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually, +}; +use voelin_proto::v1::{self, entity::Kind}; + +use super::*; + +const WAIT: Duration = Duration::from_secs(10); +/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`). +const MONO: [u8; 3] = [0xf8, 0xff, 0xfe]; +const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe]; +const ALICE: u32 = 50; +const ALICE_SLOT: u32 = 90; +const BOB: u32 = 51; +const BOB_SLOT: u32 = 91; + +fn put(connector: &FakeConnector, kind: Kind) { + connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it"); +} + +/// A host with one server, a lobby, and alice and bob talking in it. +fn host() -> FakeConnector { + let connector = FakeConnector::new(); + put( + &connector, + Kind::Server(v1::Server { + id: 1, + name: "Fake Host".into(), + uid: "fake-host".into(), + default_channel_id: 10, + ..Default::default() + }), + ); + put( + &connector, + Kind::Channel(v1::Channel { + id: 10, + server_id: 1, + kind: v1::ChannelKind::Voice as i32, + name: "Lobby".into(), + ..Default::default() + }), + ); + for (user, participant, slot, name) in + [(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")] + { + put( + &connector, + Kind::User(v1::User { + id: user, + uid: vec![user as u8; 32].into(), + uid_kind: v1::IdKind::Voelin as i32, + name: name.into(), + ..Default::default() + }), + ); + put( + &connector, + Kind::Voice(v1::VoiceState { + server_id: 1, + participant_id: participant, + user_id: user, + channel_id: 10, + slot, + nick: name.into(), + ..Default::default() + }), + ); + } + connector +} + +/// A `SessionLink` over a fake host, driven the way `session.rs` drives it. +struct HostRig { + handle: FakeHandle, + cmds: mpsc::UnboundedSender, + events: mpsc::UnboundedReceiver, + /// Our participant and voice slot, as the host gave them. + own_client: u16, + own_slot: u32, + /// The clients the link told started talking, in order. + talking: Vec, +} + +/// The next event `f` picks from `events`, skipping the others. +async fn event_of( + events: &mut mpsc::UnboundedReceiver, + mut f: impl FnMut(LinkEvent) -> Option, +) -> T { + tokio::time::timeout(WAIT, async { + loop { + if let Some(t) = f(events.recv().await.expect("the link lives")) { + return t; + } + } + }) + .await + .expect("an event in time") +} + +impl HostRig { + async fn connect() -> Self { + let connector = host(); + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + let link = SessionLink::new(backends); + let (cmds, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + let ctx = LocalCtx::standalone().link; + link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx); + let own_client = event_of(&mut events, |e| match e { + LinkEvent::Connected { own_client, .. } => Some(own_client), + _ => None, + }) + .await; + event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await; + let own_slot = connector + .host() + .entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 }) + .into_iter() + .find_map(|e| match e.kind? { + Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot), + _ => None, + }) + .expect("the host seated us in voice"); + let handle = connector.last_session().expect("the connector made a session"); + Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() } + } + + /// The next voice packet the audio thread would get; who started to talk on + /// the way is kept in `talking`. + async fn audio(&mut self) -> VoicePacket { + let talking = &mut self.talking; + event_of(&mut self.events, |e| match e { + LinkEvent::Talking { client, talking: true } => { + talking.push(client); + None + } + LinkEvent::Audio(packet) => Some(packet), + _ => None, + }) + .await + } + + fn give(&self, cmd: LinkCmd) { + self.cmds.send(cmd).expect("the link listens"); + } +} + +/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it. +fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket { + let flow = FlowId::new(slot, sub); + let mut out = bytes::BytesMut::new(); + RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960) + .write(flow, &mut out) + .expect("a header"); + out.extend_from_slice(payload); + MediaPacket { flow, rtp: out.freeze() } +} + +fn voice(payload: &[u8]) -> EncodedVoice { + EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() } +} + +/// Our voice leaves as RTP on the slot the host gave us: the sequence counts +/// every packet, the timestamp advances by the duration of the previous one, +/// the marker is on the first packet of a spurt, the end of a spurt is an +/// empty payload sent once, and the SSRC is the flow (protocol section 6). +#[tokio::test(flavor = "multi_thread")] +async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() { + let rig = HostRig::connect().await; + // The fake host loops accepted media back; this test looks at what left. + rig.handle.set_loopback(false); + for n in 1..=3 { + rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n]))); + } + rig.give(LinkCmd::Audio(voice(&[]))); + rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9]))); + let handle = rig.handle.clone(); + eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await; + + let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL); + let sent = rig.handle.sent_media(); + let seen: Vec<_> = sent + .iter() + .map(|(class, packet)| { + let view = RtpView::parse(&packet.rtp).expect("RTP"); + assert_eq!(*class, MediaClass::Voice); + assert_eq!(packet.flow, flow); + assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0)); + (view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec()) + }) + .collect(); + let ticks = OPUS_20_MS_TICKS; + assert_eq!( + seen, + [ + (0, true, 0, vec![0xf8, 0xff, 0xfe, 1]), + (1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]), + (2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]), + // The end of the spurt: no payload, no marker, once. + (3, false, 3 * ticks, vec![]), + // The next spurt marks its first packet again. + (4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]), + ] + ); +} + +/// The RTP of other slots becomes the packets of the audio thread: the talker +/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo +/// Opus frame is music, an empty payload ends the spurt; what is no voice of a +/// slot the host told about is dropped. +#[tokio::test(flavor = "multi_thread")] +async fn the_voice_of_other_slots_reaches_the_audio_thread() { + let mut rig = HostRig::connect().await; + let handle = rig.handle.clone(); + + // A slot nobody has, a probe and feedback: nothing. Then alice, mono. + handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO)); + handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) }); + handle.inject_media(MediaPacket { + flow: FlowId::FEEDBACK, + rtp: bytes::Bytes::from_static(&[1, 2]), + }); + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO)); + let packet = rig.audio().await; + assert_eq!( + (packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()), + (ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice()) + ); + + // Bob whispers (sub-flow 1) in stereo: music, a whisper. + handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO)); + let packet = rig.audio().await; + assert_eq!( + (packet.talker.0, packet.seq, packet.codec, packet.whisper), + (BOB as u16, 6, VoiceCodec::Music, true) + ); + + // Alice stops: an empty payload. + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[])); + let packet = rig.audio().await; + assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0)); + + // Who talks comes from the same packets: alice started, then bob, once each + // (the slot nobody has started nobody). + assert_eq!(rig.talking, [ALICE as u16, BOB as u16]); +} + +/// A host whose session loops our own voice back (the fake one does, so that +/// the conformance suite can see media move) does not make the engine play us +/// our own voice or show us as talking: the engine never plays itself. +#[tokio::test(flavor = "multi_thread")] +async fn our_own_voice_coming_back_is_not_played_back() { + let mut rig = HostRig::connect().await; + // The fake host loops accepted media back into the sink (the default). + rig.give(LinkCmd::Audio(voice(&MONO))); + let handle = rig.handle.clone(); + eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await; + // A packet of alice behind it: when this one is out, ours has been through. + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO)); + let own = rig.own_client; + let mut heard = Vec::new(); + while heard.last().is_none_or(|talker| *talker != ALICE as u16) { + heard.push(rig.audio().await.talker.0); + } + assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}"); +} + +/// The link conformance suite of the protocol repository against the session +/// the engine's registry hands over: the registry adds nothing to a plain +/// connector's session (`Backends::connect` returns it untouched), so the 17 +/// cases pass as they do in the protocol repository, none skipped. +#[tokio::test(flavor = "multi_thread")] +async fn the_conformance_suite_passes_on_a_session_of_the_registry() { + async fn through_the_registry() -> Fixture { + let connector = FakeConnector::new(); + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + let (params, media) = connect_params("fake://conformance"); + let local = backends + .connect(params, LocalCtx::standalone()) + .await + .unwrap_or_else(|e| panic!("the registry connects: {e}")); + assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer"); + assert!(local.streams.is_none(), "a plain connector has no stream port"); + let backend = connector.last_session().expect("the connector made a session"); + // The session is the connector's own, so a request id means the same to both. + Fixture { + shared_request_ids: true, + ..Fixture::new(local.connected.session, local.connected.pushes, media, backend) + } + } + let report = conformance::run(&through_the_registry).await; + assert_eq!(report.cases.len(), conformance::CASES.len()); + assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases"); + assert!( + report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed), + "{:?}", + report.cases + ); +} diff --git a/crates/voelin-core/src/link/media.rs b/crates/voelin-core/src/link/media.rs new file mode 100644 index 0000000..f0eccba --- /dev/null +++ b/crates/voelin-core/src/link/media.rs @@ -0,0 +1,310 @@ +//! 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, HashSet}; +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. +/// +/// A host can also say that someone talks whose voice it does not carry as +/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such): +/// that is a hint, which holds until the host says it is over. +#[derive(Default)] +pub(crate) struct TalkTracker { + last: HashMap, + hinted: HashSet, +} + +impl TalkTracker { + /// A packet of `client` arrived; whether this starts its talking. + pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool { + let was = self.is_talking(client); + self.last.insert(client, now); + !was + } + + /// The host says `client` talks or has stopped; whether this changes + /// whether it is talking. + pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool { + let was = self.is_talking(client); + if talking { + self.hinted.insert(client); + } else { + self.hinted.remove(&client); + } + was != self.is_talking(client) + } + + /// Forget the hints about clients `present` does not hold any more: a + /// client that left cannot say it stopped. + pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) { + self.hinted.retain(|client| present(*client)); + } + + /// 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.retain(|client| !self.hinted.contains(client)); + silent + } + + pub(crate) fn is_talking(&self, client: u16) -> bool { + self.last.contains_key(&client) || self.hinted.contains(&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))); + } + + #[test] + fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() { + let mut talk = TalkTracker::default(); + let t0 = Instant::now(); + // A talker whose voice is no media: on, and no silence ends it. + assert!(talk.hint(8, true)); + assert!(!talk.hint(8, true), "already talking"); + assert!(talk.is_talking(8)); + assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty()); + assert!(talk.hint(8, false)); + assert!(!talk.is_talking(8)); + // A talker with media that the host also names: the media ends it, when + // the host has said it is over (in either order). + assert!(talk.heard(9, t0)); + assert!(!talk.hint(9, true), "heard already"); + assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so"); + assert!(talk.is_talking(9)); + assert!(talk.hint(9, false)); + assert!(!talk.is_talking(9)); + assert!(talk.heard(10, t0)); + assert!(!talk.hint(10, false), "the media goes on"); + assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]); + // A hint about somebody who is gone is forgotten. + assert!(talk.hint(11, true)); + talk.retain_hints(|client| client != 11); + assert!(!talk.is_talking(11)); + } +} diff --git a/crates/voelin-core/src/link/mod.rs b/crates/voelin-core/src/link/mod.rs new file mode 100644 index 0000000..0010497 --- /dev/null +++ b/crates/voelin-core/src/link/mod.rs @@ -0,0 +1,322 @@ +//! The engine's seam to the server its voice source talks to. +//! +//! A session merges up to three sources (voice, gateway, query). The *voice* +//! source is the connection that is visible on the server, can talk and +//! carries chat, files, pokes, offline messages and streams. The engine holds +//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the +//! protocol repository, and knows nothing else of the server software behind +//! it: which backend makes the `Session` is the scheme of the address, and +//! [`Backends`] is the registry of connectors by scheme +//! ([`Backends::default`] has the TeamSpeak one, +//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be +//! another). [`VoiceOptions`] says what to connect to and as whom. +//! +//! Inside the crate `session.rs` merges and routes, and an adapter below it +//! turns what it asks into `Session` calls and what the `Session` pushes into +//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`); +//! `docs/session-seam.md` describes the mapping row by row. + +mod backends; +mod connect; +#[cfg(test)] +mod fake_link_tests; +#[cfg(test)] +mod fake_tests; +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, without_query, +}; +pub(crate) use connect::{VERSION_PARAM, connect_params}; +pub(crate) use session_link::SessionLink; + +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; + +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::sync::{broadcast, oneshot}; +use voelin_audio::{EncodedVoice, VoicePacket}; +use voelin_identity::IdentityBlob; +use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence}; +use voelin_stream::PeerConfig; + +use crate::files::{Report, RequestId, Sink, TransferId}; +use crate::settings::SharedSettings; +use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame}; +use crate::{BackendInfo, Event, SessionId}; + +/// What a voice connection needs to know: the server, who to be, where to +/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)). +/// +/// Nothing in it belongs to one kind of server: what a connector needs of it +/// that is its own (a TeamSpeak identity, the client version to claim) is in +/// the `identity` blob and the `client_version` spec, which the connector of +/// the address reads. +#[derive(Clone, Debug)] +pub struct VoiceOptions { + /// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a + /// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`) + /// that picks the connector ([`Backends`]). + pub address: String, + pub nickname: String, + /// The identity to connect with: a TeamSpeak identity + /// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key + /// for a Voelin host. None lets the connector make one up (a TeamSpeak + /// connection generates an identity, which a server then knows as a new + /// client). + pub identity: Option, + /// The client version a TeamSpeak server is shown, as a spec for + /// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or + /// `@`); `None` is the native platform's. A spec that is + /// none ends the connect with the reason. Other backends ignore it. + pub client_version: Option, + pub server_password: Option, + /// Channel path to join, e.g. `Lobby/Sub`, or `/`. + pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, + /// Open the audio devices (capture and playback). + pub audio: bool, + /// Network settings for stream peer connections (TeamSpeak 6). + pub stream_peer: PeerConfig, +} + +impl VoiceOptions { + /// Options for `address` and `nickname`; everything else is left to the + /// connector. + pub fn new(address: impl Into, nickname: impl Into) -> Self { + Self { + address: address.into(), + nickname: nickname.into(), + identity: None, + client_version: None, + server_password: None, + channel: None, + channel_password: None, + token: None, + audio: false, + stream_peer: PeerConfig::default(), + } + } +} + +/// What the engine gives a link besides the options: where the connection +/// answers the requests the session need not see, and what it shares with +/// the session's other parts. +#[derive(Clone)] +pub(crate) struct LinkCtx { + pub(crate) session: SessionId, + pub(crate) events: broadcast::Sender, + /// The frames of watched streams (kept off the event bus). + pub(crate) frames: broadcast::Sender, + pub(crate) settings: SharedSettings, +} + +impl LinkCtx { + /// The session this connection belongs to. + pub(crate) fn session(&self) -> SessionId { + self.session + } + + /// Tell the engine's event bus something (a request's answer, a + /// transfer's progress). + pub(crate) fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) { + self.emit(Event::RequestDone { session: self.session, request, result }); + } +} + +/// A file on the server: channel, its password, path. +#[derive(Clone, Debug)] +pub(crate) struct Remote { + pub channel: ChannelId, + pub password: Option, + pub path: String, +} + +/// A boxed stream of bytes to read: the body of a file the server sends. +pub(crate) type BoxRead = Pin>; + +/// A connection that can be read and written: a file transfer connection. +pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {} + +impl Duplex for T {} + +/// A boxed [`Duplex`]. +pub(crate) type BoxDuplex = Pin>; + +/// What the session asks of a connection. +pub(crate) enum LinkCmd { + SendChat(ChatTarget, String), + Move(ChannelId, Option), + SetInputMuted(bool), + SetOutputMuted(bool), + /// An encoded voice frame from the audio thread. + Audio(EncodedVoice), + /// A stream command; the link answers on the event bus. Only sent while + /// the connection's capabilities include streams. + Stream(StreamCmd), + Poke { + client: u16, + message: String, + }, + ListFiles { + request: RequestId, + dir: Remote, + }, + /// Download `file`; `transfer` if the user can cancel it. + Download { + transfer: Option, + file: Remote, + sink: Sink, + report: Report, + }, + Upload { + transfer: Option, + file: Remote, + from: PathBuf, + overwrite: bool, + resume: bool, + 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, + channel: ChannelId, + password: Option, + paths: Vec, + }, + RenameFile { + request: RequestId, + from: Remote, + to: Remote, + }, + CreateDirectory { + request: RequestId, + dir: Remote, + }, + /// Announce our avatar's hash (empty: no avatar). + SetAvatarHash { + request: Option, + hash: String, + }, + OfflineList { + request: RequestId, + }, + OfflineGet { + request: RequestId, + id: u32, + }, + OfflineAdd { + request: RequestId, + to_uid: String, + subject: String, + text: String, + }, + OfflineDelete { + request: RequestId, + id: u32, + }, + OfflineFlag { + request: RequestId, + id: u32, + read: bool, + }, + Disconnect, +} + +/// What a connection tells the session. +pub(crate) enum LinkEvent { + Connected { + name: String, + /// The server software, and what it can do (the connection knows + /// both from the server's version). + backend: BackendInfo, + capabilities: Capabilities, + /// Our client id when the link connected. TeamSpeak's own reconnect gives + /// a new one, which is not announced; the engine follows it in the + /// snapshots by our unique id. + own_client: u16, + /// The server's unique id. + server_uid: String, + /// Our unique id as the server knows it. + own_uid: Option, + }, + /// The server's channels and clients as they are now. + Presence(Box), + /// The channel we are in, after every [`LinkEvent::Presence`]. The engine + /// derives it itself, from our own voice state in the snapshots of the + /// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes + /// us another client. What an in-process link such as `TsLink` says here only + /// tells the TeamSpeak `Session` made of it that a move has arrived. + OwnChannel(ChannelId), + Chat(ChatMessage), + Poke { + from: u16, + from_uid: Option, + from_name: String, + message: String, + }, + /// Incoming voice for the audio thread. + Audio(VoicePacket), + /// Who is talking (on, and off again when it stopped). The engine derives + /// it from the media of its `Session` (protocol section 6.4). What an + /// in-process link such as `TsLink` says here reaches the engine as a + /// speaking hint next to the media: that is what shows the talkers whose + /// packets the link does not forward as Opus (Speex, CELT). + Talking { + client: u16, + talking: bool, + }, + /// Our own stream's life, for the gateway directory. + OwnStream(OwnStreamEvent), + /// An Opus frame (48 kHz) of a watched stream, for the audio thread + /// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz + /// clock. + StreamAudio { + stream: String, + time: u64, + data: Arc<[u8]>, + }, + /// A watched stream ended: its audio leaves the mixer. + StreamAudioEnded(String), + /// A command failed (the connection stays). + Error(String), + /// The connection ended; the reason if it was not asked for. Sent once; + /// the stream task's closing reports may still follow (see the module + /// documentation). + Disconnected(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..60d28f3 --- /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::ts_session::entities::user_uid; +use crate::ts::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..c1ecb59 --- /dev/null +++ b/crates/voelin-core/src/link/session_link.rs @@ -0,0 +1,2004 @@ +//! [`SessionLink`]: what `session.rs` talks to as the voice source, over a +//! `voelin_proto::link::Session` (`docs/session-seam.md` sections 3 and 4). +//! +//! `session.rs` hands a link its [`VoiceOptions`] 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. +//! +//! # The vocabulary of the session +//! +//! - [`SessionLink::spawn`] returns at once; the connection runs on its own +//! task and reports through `events`. Connecting is not an event: the +//! session shows `Connecting` from the moment it spawned the link, until +//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed). +//! - The first thing a connected link reports is [`LinkEvent::Connected`] +//! (name, backend, what it can do, our client id, the server's unique id), +//! then [`LinkEvent::Presence`] whenever anything in the server's tree or +//! client list changed (a full snapshot each time) and +//! [`LinkEvent::OwnChannel`] when we moved. +//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for, +//! reports that the connection ended, whichever way it did; a link sends it +//! once, and nothing from the connection itself follows it. A link that +//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves. +//! It is not promised to be the last event of the link: the stream task of +//! a connection with streams is a task of its own, which winds down after +//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and +//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its +//! streams, may follow `Disconnected`. The session does not depend on the +//! order: it ends our own stream and the audio of watched streams itself +//! when it hears `Disconnected`, and ignores what a link says after that, +//! like the events of a replaced one. +//! - Streams (screen sharing) are the link's business from the capabilities +//! on: when `Capabilities::streams` is set in `Connected`, the connection +//! has a stream task, takes [`LinkCmd::Stream`] and reports through the +//! event bus ([`LinkCtx::emit`]) like the other answers that need not pass +//! the session first (file lists, transfers, offline messages, stream +//! state). What the session must place itself comes as events: our own +//! stream's life ([`LinkEvent::OwnStream`], for the gateway directory) and +//! the audio of watched streams ([`LinkEvent::StreamAudio`], for the audio +//! thread, and [`LinkEvent::StreamAudioEnded`] when a stream's audio is +//! over). When the session replaces a connection it gives the old link +//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear of +//! their end before the link stops reading commands). +//! - What the session must see first (chat, pokes, who is talking, audio) +//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file +//! list, a request's `Done`) go straight to the event bus with +//! [`LinkCtx::emit`]. +//! - Events of a link the session replaced are ignored (each link has a +//! generation), so a link need not stop emitting at once. +//! +//! # What is still TeamSpeak's +//! +//! The vocabulary, and the engine above it, is not backend-neutral yet: +//! +//! - Client ids are TeamSpeak's `u16`: `own_client` of +//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of +//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a +//! [`ChatMessage`](voelin_model::ChatMessage), and the viewer and streamer +//! ids of the stream API. +//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client +//! ids, `u64` channel and group ids, server and channel groups, talk +//! power, icons, badges and the myTeamSpeak avatar. +//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream +//! protocol: `PeerConfig` in [`VoiceOptions::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`]). TeamSpeak 6 streams are peer +//! to peer, so their commands and events pass the `Session` through a local +//! port ([`StreamPort`]) for now. + +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, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalCtx, Remote, StreamEvent, + StreamPort, VoiceOptions, connect_params, +}; +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); +/// How long a session whose push channel ended may take to say that it has. +const END_TIME: Duration = Duration::from_secs(1); +/// Most CHAT scopes the engine subscribes when the host does not say +/// (`Limits.max_chat_subscriptions` of 0 is the v1.0 default, 16). +const DEFAULT_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) } + } + + /// Connect to the server `options` names and run the connection on its own + /// task: take commands from `cmds`, report through `events`, and end the + /// connection with [`LinkEvent::Disconnected`]. Does not block. One + /// SessionLink serves every session of an engine. + pub(crate) fn spawn( + &self, + options: VoiceOptions, + 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: VoiceOptions, + 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: &VoiceOptions, + 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 = match connect_params(options, sink, backends) { + Ok(params) => params, + Err(e) => return connect_failure(&e), + }; + 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; + } + }; + match sequence { + Ok(()) => {} + Err(None) => { + // The push channel ended, so the session did, and its end says why. (A + // refusal with no words leaves it open: it is closed then.) + if let Ok(reason) = tokio::time::timeout(END_TIME, session.closed()).await { + return close_text(&reason); + } + session.close(v1::CloseCode::Normal, ""); + let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; + return None; + } + Err(Some(reason)) => { + session.close(v1::CloseCode::Normal, ""); + let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; + return Some(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)>, + /// CHAT scopes whose sync ended: their messages are in the replica now. + synced: Vec, + 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.synced.extend(other.synced); + 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, + /// What the host offers this user (`Session::features`, as `HostUpdate`s change it). + host_features: Features, + /// What it offers on this server: the host's set narrowed by `Server.features`. + features: Features, + welcome: v1::Welcome, + server: u64, + /// The participant and media slot we are, and the user (see `follow_seat`). + participant: u32, + slot: u32, + user: u64, + /// Most CHAT scopes the host lets us hold (`Limits.max_chat_subscriptions`). + max_chat: usize, + 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 host_features = session.features(); + let max_chat = welcome + .limits + .as_ref() + .map(|limits| limits.max_chat_subscriptions) + .filter(|max| *max != 0) + .map_or(DEFAULT_CHAT_SCOPES, |max| usize::try_from(max).unwrap_or(usize::MAX)); + let user = welcome.user_id; + Self { + session, + pushes, + media, + streams, + ctx, + events, + internal_tx, + internal, + replica: Replica::new(SCHEMA_GENERATION), + features: host_features.clone(), + host_features, + welcome, + server: 0, + participant: 0, + slot: 0, + user, + max_chat, + 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); + } + + /// What the host says it is: its backend, else the product and version of + /// the host itself. + fn backend(&self) -> v1::BackendInfo { + let Some(host) = self.welcome.host.as_ref() else { return Default::default() }; + host.backend.clone().unwrap_or_else(|| v1::BackendInfo { + product: host.product.clone(), + version: host.version.clone(), + flavor: String::new(), + }) + } + + /// 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: &VoiceOptions) -> 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.user = self + .replica + .voice_state(self.server, self.participant) + .map(|v| v.user_id) + .filter(|id| *id != 0) + .unwrap_or(self.welcome.user_id); + self.replica.set_own_user(self.user); + + let backend = self.backend(); + let own_uid = + self.replica.user(self.own_user()).and_then(crate::ts::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: &VoiceOptions) -> 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. + fn own_user(&self) -> u64 { + self.user + } + + /// Whether the host is a TeamSpeak server (`Welcome.host.backend`). + fn teamspeak(&self) -> bool { + self.backend().product == "teamspeak" + } + + /// Follow our seat to the participant that is us now. A participant is us + /// for the life of a session, except behind a TeamSpeak server: the + /// connection reconnects by itself, without a word, as another client with + /// the same user (`docs/session-seam.md` 4.4). The seat stays while it is + /// ours; when it is gone, or does not carry our user while another + /// participant does (a ghost of the old connection), the other is our seat. + /// A seat whose user id changed by itself (the snapshot that tells our + /// database id came after the seat) is still ours, and so is the new id. + fn follow_seat(&mut self) { + let seat = self.replica.voice_state(self.server, self.participant); + if self.user == 0 || seat.is_some_and(|v| v.user_id == self.user) || !self.teamspeak() { + return; + } + let seat_user = seat.map(|v| v.user_id).filter(|id| *id != 0); + let other = self + .replica + .voice_states(self.server) + .find(|v| v.user_id == self.user) + .map(|v| (v.participant_id, v.slot)); + match (other, seat_user) { + (Some((participant, slot)), _) => { + debug!(from = self.participant, to = participant, "we are another participant now"); + self.participant = participant; + self.slot = slot; + } + (None, Some(user)) => self.user = user, + // Gone, and nobody takes its place yet. + (None, None) => {} + } + } + + /// 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); + if let Some(ScopeId::Chat(channel)) = + end.scope.as_ref().and_then(ScopeId::from_proto) + { + batch.synced.push(channel); + } + } + Some(Body::Signal(signal)) => batch.signals.push(signal.clone()), + Some(Body::HostUpdate(update)) => { + self.host_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); + // The host's features changed, or the server's list that narrows them may + // have (the SERVER scope holds the `Server` entity). + let server_scope = match &push.body { + Some(Body::Change(c)) => c.scope.as_ref(), + Some(Body::SyncEnd(e)) => e.scope.as_ref(), + _ => None, + } + .and_then(ScopeId::from_proto) + .is_some_and(|scope| scope == ScopeId::Server(self.server)); + if server_scope || matches!(push.body, Some(Body::HostUpdate(_))) { + self.narrow_features(); + } + batch + } + + /// The features of this server: what the host offers, narrowed by + /// `Server.features` (an empty list keeps them all, `docs/session-seam.md` + /// 4.7). + fn narrow_features(&mut self) { + let listed = self.replica.server(self.server).map(|s| s.features.as_slice()); + self.features = self.host_features.narrowed(listed.unwrap_or_default()); + } + + 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, mut messages, synced, signals, closed } = batch; + if view || home { + self.follow_seat(); + 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(); + } + // The messages of a full sync are staged until its end: a `Change` of it + // cannot be read yet, and this is where they can. + for channel in synced { + messages.extend(self.replica.messages(channel).map(|m| (channel, m.id))); + } + for (channel, id) in messages { + // Reported once, and only once it can be read: a message the replica + // does not hold yet stays unreported until it does. + if self.seen.contains(&(channel, id)) { + continue; + } + if let Some(message) = project::chat_message(&self.replica, channel, id) { + self.seen.insert((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(); + // A client that left cannot say it stopped talking. + let slots = &self.slots; + self.talk.retain_hints(|client| slots.values().any(|present| *present == client)); + 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_by(|a, b| b.cmp(a)); + wanted.extend(dms); + // More than the host lets us hold: the server chat and our channel first, + // then the private conversations, the newest first (the ids of a host grow). + wanted.truncate(self.max_chat); + 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::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)); + } + } + // A talker whose voice the host does not carry as media (TeamSpeak's Speex + // and CELT talkers): the host's word that it talks, until it says it is over. + Some(Signal::Speaking(speaking)) => { + let Ok(client) = u16::try_from(speaking.participant_id) else { return }; + if self.talk.hint(client, speaking.on) { + self.send(LinkEvent::Talking { client, talking: speaking.on }); + } + } + // 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 }; + // Our own voice, if the session loops it back (the fake host of the + // protocol repository does, so that a test sees media move): the engine + // neither plays us to ourselves nor shows us as talking. + if incoming.slot == self.slot { + 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::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::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::ts_session::features_of(&caps)); + let host = crate::ts::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())); + } + + // ---- the replica behind the events --------------------------------------- + + /// A connection over the protocol repository's fake host, driven by hand: + /// the test applies the pushes batch by batch and reads the events. + async fn conn() -> (Conn, mpsc::UnboundedReceiver) { + use voelin_proto::link::Connector; + let connector = voelin_proto::test_util::FakeConnector::new(); + let (params, _media) = voelin_proto::test_util::connect_params("fake://host"); + let connected = connector.connect(params).await.unwrap(); + let (_media_tx, media) = mpsc::unbounded_channel(); + let (events_tx, events) = mpsc::unbounded_channel(); + let ctx = LocalCtx::standalone().link; + (Conn::new(connected.session, connected.pushes, media, None, ctx, events_tx), events) + } + + fn push(body: Body) -> v1::Push { + v1::Push { body: Some(body) } + } + + fn message(channel: u64, id: u64) -> Entity { + Entity { + kind: Some(Kind::Message(v1::Message { + id, + channel_id: channel, + author_name: "alice".into(), + text: format!("m{id}"), + ts_ms: 1_700_000_000_000, + ..Default::default() + })), + } + } + + fn sync_begin(scope: ScopeId) -> v1::Push { + push(Body::SyncBegin(v1::SyncBegin { + scope: Some(scope.to_proto()), + mode: v1::SyncMode::Full as i32, + epoch: 1, + })) + } + + fn sync_change(scope: ScopeId, put: Vec) -> v1::Push { + push(Body::Change(v1::Change { + scope: Some(scope.to_proto()), + rev: 5, + put, + del: Vec::new(), + })) + } + + fn sync_end(scope: ScopeId) -> v1::Push { + push(Body::SyncEnd(v1::SyncEnd { + scope: Some(scope.to_proto()), + cursor: Some(v1::Cursor { epoch: 1, rev: 5 }), + gap: false, + })) + } + + fn texts(events: &mut mpsc::UnboundedReceiver) -> Vec { + let mut texts = Vec::new(); + while let Ok(event) = events.try_recv() { + if let LinkEvent::Chat(message) = event { + texts.push(message.text); + } + } + texts + } + + /// A full sync stages its messages until `SyncEnd`: a message of its + /// `Change` cannot be read when the `Change` is applied, and the batch that + /// carries `SyncEnd` may be another one. + #[tokio::test] + async fn the_messages_of_a_chat_sync_are_reported_when_the_sync_ends() { + let (mut conn, mut events) = conn().await; + let scope = ScopeId::Chat(7); + conn.replica.subscribe(scope); + + // One batch: the start of the sync and its messages. + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(7, 10), message(7, 11)]))); + conn.after(batch).await; + assert!(texts(&mut events).is_empty(), "staged: nothing can be read yet"); + + // The next batch: its end. Both messages are reported now, in order. + let batch = conn.apply(&sync_end(scope)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m10", "m11"]); + + // And once: the same window again (a re-subscription) adds a message. + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(7, 10), message(7, 12)]))); + batch.merge(conn.apply(&sync_end(scope))); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m12"]); + + // A live message is reported once, however often it comes. + let live = push(Body::Change(v1::Change { + scope: Some(scope.to_proto()), + rev: 6, + put: vec![message(7, 13)], + del: Vec::new(), + })); + let mut batch = conn.apply(&live); + batch.merge(conn.apply(&live)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m13"]); + } + + /// A message that comes before its scope is subscribed is not lost: it is + /// reported with the sync that holds it. + #[tokio::test] + async fn a_message_that_comes_before_its_scope_is_reported_with_the_sync() { + let (mut conn, mut events) = conn().await; + let scope = ScopeId::Chat(8); + // Nothing subscribed: the replica holds none of it. + let batch = conn.apply(&sync_change(scope, vec![message(8, 20)])); + conn.after(batch).await; + assert!(texts(&mut events).is_empty()); + + conn.replica.subscribe(scope); + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(8, 20), message(8, 21)]))); + conn.after(batch).await; + let batch = conn.apply(&sync_end(scope)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m20", "m21"]); + } +} diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs new file mode 100644 index 0000000..90f8c77 --- /dev/null +++ b/crates/voelin-core/src/link/tests.rs @@ -0,0 +1,2283 @@ +//! 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::ts_session::LinkConnector; +use crate::ts::{ConnectOptions, ServerLink}; +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 { + connected_to(capabilities, BackendInfo { product: "Fake".into(), version: "1.2".into() }) +} + +fn connected_to(capabilities: Capabilities, backend: BackendInfo) -> LinkEvent { + LinkEvent::Connected { + name: "Test Server".into(), + backend, + 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 { + Rig::connect(connected(capabilities)).await + } + + /// A connection to a TeamSpeak 3 server (its session follows our client across + /// the reconnects of the link). + async fn teamspeak(capabilities: Capabilities) -> Rig { + let backend = BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() }; + Rig::connect(connected_to(capabilities, backend)).await + } + + async fn connect(connected: LinkEvent) -> 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(VoiceOptions::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).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(VoiceOptions::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(VoiceOptions::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(); + // No limit anything reaches: a private conversation with every client fits. + assert!(limits.max_chat_subscriptions >= 1 << 16, "{limits:?}"); + assert!(limits.max_subscriptions > limits.max_chat_subscriptions, "{limits:?}"); + + // 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") +} + +/// A session that is no TeamSpeak one: the engine consumes it as it does +/// the TeamSpeak side's, through the registry (the fake host of the protocol +/// repository stands for a Voelin host). +#[tokio::test(flavor = "multi_thread")] +async fn the_engine_consumes_any_session_a_connector_makes() { + use v1::entity::Kind; + use voelin_proto::test_util::FakeConnector; + + let connector = FakeConnector::new(); + let host = connector.host(); + let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap(); + put(Kind::Server(v1::Server { + id: 1, + name: "Fake Host".into(), + uid: "fake-host".into(), + default_channel_id: 10, + ..Default::default() + })); + let channel = |id, name: &str, position| v1::Channel { + id, + server_id: 1, + kind: v1::ChannelKind::Voice as i32, + name: name.into(), + position, + ..Default::default() + }; + put(Kind::Channel(channel(10, "Lobby", 0))); + put(Kind::Channel(channel(11, "Games", 1024))); + put(Kind::User(v1::User { + id: 2, + uid: vec![2; 32].into(), + uid_kind: v1::IdKind::Voelin as i32, + name: "alice".into(), + ..Default::default() + })); + put(Kind::Voice(v1::VoiceState { + server_id: 1, + participant_id: 50, + user_id: 2, + channel_id: 11, + slot: 90, + nick: "alice".into(), + ..Default::default() + })); + + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + 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(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx); + + async fn event( + events: &mut mpsc::UnboundedReceiver, + mut f: impl FnMut(LinkEvent) -> Option, + ) -> T { + within("an event", async { + loop { + if let Some(t) = f(events.recv().await?) { + return Some(t); + } + } + }) + .await + } + let (name, backend, own_client, server_uid) = event(&mut events, |e| match e { + LinkEvent::Connected { name, backend, own_client, server_uid, .. } => { + Some((name, backend, own_client, server_uid)) + } + _ => None, + }) + .await; + assert_eq!((name.as_str(), server_uid.as_str()), ("Fake Host", "fake-host")); + assert_eq!(backend.product, "voelin-fake"); + // The host seated us: its participant id is the client id of the older model. + assert_ne!(own_client, 0); + let presence = event(&mut events, |e| match e { + LinkEvent::Presence(p) => Some(*p), + _ => None, + }) + .await; + assert_eq!(presence.server.name, "Fake Host"); + assert_eq!(presence.channels.len(), 2); + assert_eq!(presence.channels[&11].order, 10, "the order follows the positions"); + let alice = &presence.clients[&50]; + assert_eq!((alice.nickname.as_str(), alice.channel), ("alice", 11)); + assert!(alice.uid.as_deref().is_some_and(|uid| uid.len() == 52), "a Voelin uid is base32"); + + // A move is a JoinVoice; the host's voice state tells where we are. + cmd_tx.send(LinkCmd::Move(11, None)).unwrap(); + event(&mut events, |e| match e { + LinkEvent::OwnChannel(11) => Some(()), + _ => None, + }) + .await; + // Chat in the channel we are in: the host's copy comes back as ours. + cmd_tx.send(LinkCmd::SendChat(ChatTarget::Channel(11), "hello host".into())).unwrap(); + let chat = event(&mut events, |e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + assert_eq!((chat.text.as_str(), chat.target), ("hello host", ChatTarget::Channel(11))); + + // The session closes with us. + cmd_tx.send(LinkCmd::Disconnect).unwrap(); + let reason = event(&mut events, |e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, None); + assert_eq!(connector.connects().len(), 1); +} + +/// What the second adapter costs per voice packet (the last row of the risk +/// table in `docs/session-seam.md`): every packet is framed as RTP and taken +/// apart again on its way, in each direction. A generous bound in a debug +/// build; the figures are printed. +#[tokio::test(flavor = "multi_thread")] +async fn a_voice_packet_costs_microseconds_through_both_adapters() { + const PACKETS: usize = 5_000; + let mut rig = Rig::new(everything()).await; + let started = std::time::Instant::now(); + for _ in 0..PACKETS { + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + } + for _ in 0..PACKETS { + assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); + } + let uplink = started.elapsed() / PACKETS as u32; + + let started = std::time::Instant::now(); + for seq in 0..PACKETS { + rig.play(LinkEvent::Audio(VoicePacket { + talker: TalkerId(8), + seq: seq as u16, + codec: VoiceCodec::Voice, + whisper: false, + payload: OPUS_20_MS.to_vec(), + })); + } + let mut heard = 0; + while heard < PACKETS { + rig.event(|e| matches!(e, LinkEvent::Audio(_)).then_some(())).await; + heard += 1; + } + let downlink = started.elapsed() / PACKETS as u32; + eprintln!("voice through both adapters: {uplink:?} per packet up, {downlink:?} down"); + assert!(uplink < Duration::from_micros(500), "{uplink:?}"); + assert!(downlink < Duration::from_micros(500), "{downlink:?}"); +} + +/// What the stream task reports before the engine has announced the +/// connection waits for it (`ts/ts_session/driver.rs`, `Held`): the engine acts +/// on a list of streams as soon as it sees one, and has to know it has voice +/// by then, as it did when the stream task was not behind a session. +#[tokio::test] +async fn the_stream_tasks_reports_wait_for_the_engine_to_announce_the_connection() { + let mut rig = Rig::new(everything()).await; + let listed = || Event::StreamsChanged { session: 0, streams: Vec::new() }; + rig.inner.ctx.events.send(listed()).unwrap(); + rig.inner.ctx.events.send(Event::Error { session: 0, message: "second".into() }).unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + !on_the_bus(&mut rig), + "the list was passed on before the engine's first stream command" + ); + + // The engine's first stream command comes after it announced the + // connection; the reports follow it, in their order. + rig.give(LinkCmd::Stream(StreamCmd::Directory(Vec::new()))); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Directory(_)))); + rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; + rig.bus(|e| matches!(e, Event::Error { message, .. } if message == "second").then_some(())) + .await; + + // Afterwards they go straight through. + rig.inner.ctx.events.send(listed()).unwrap(); + rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; +} + +/// Nobody announces the connection to a session used without an engine: its +/// stream reports are held for a while only. +#[tokio::test] +async fn the_stream_tasks_reports_are_not_held_for_ever() { + let mut rig = Rig::new(everything()).await; + rig.inner.ctx.events.send(Event::StreamsChanged { session: 0, streams: Vec::new() }).unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!on_the_bus(&mut rig), "the list was not held at all"); + rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; +} + +/// A link without streams has no stream task to hold back: what it puts on +/// the bus goes straight through. +#[tokio::test] +async fn a_link_without_streams_is_not_held_back() { + let mut rig = Rig::new(Capabilities::default()).await; + rig.inner.ctx.events.send(Event::Error { session: 0, message: "now".into() }).unwrap(); + tokio::time::timeout( + Duration::from_millis(250), + rig.bus(|e| matches!(e, Event::Error { message, .. } if message == "now").then_some(())), + ) + .await + .expect("the report went through at once"); +} + +/// Whether a list of streams is on the engine's bus now. +fn on_the_bus(rig: &mut Rig) -> bool { + let mut found = false; + while let Ok(event) = rig.bus.try_recv() { + found |= matches!(event, Event::StreamsChanged { .. }); + } + found +} + +// ---- the connection across TeamSpeak's own reconnect ------------------------------ + +/// Our identity again, as the client TeamSpeak's reconnect makes: the same +/// unique id and database id, a client id of its own. +fn reconnected(id: u16, channel: u64) -> ClientInfo { + ClientInfo { id, ..client(ME, "me", channel) } +} + +async fn own_channel(rig: &mut Rig) -> u64 { + rig.event(|e| match e { + LinkEvent::OwnChannel(channel) => Some(channel), + _ => None, + }) + .await +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_engine_follows_a_reconnect_that_makes_us_another_client() { + let mut rig = Rig::teamspeak(everything()).await; + // The connection comes back as client 21, in the lobby: 7 is gone. + let mut next = presence(); + next.clients.remove(&ME); + next.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(next))); + assert_eq!(own_channel(&mut rig).await, LOBBY); + + // The chat of the channel we are in now reaches us. + rig.play(LinkEvent::Chat(ChatMessage { + target: ChatTarget::Channel(LOBBY), + author_name: "bob".into(), + author_uid: Some("bob=".into()), + author_id: Some(9), + text: "welcome back".into(), + ts_ms: 1_700_000_000_000, + via_relay: false, + blocked: false, + })); + let chat = rig + .event(|e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + assert_eq!((chat.text.as_str(), chat.target), ("welcome back", ChatTarget::Channel(LOBBY))); + + // What we say goes to the channel we are in now, not to the old one. + rig.give(LinkCmd::SendChat(ChatTarget::Channel(LOBBY), "thanks".into())); + let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Channel(LOBBY), "thanks")); + rig.give(LinkCmd::SendChat(ChatTarget::Channel(GAMES), "stale".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert!(error.starts_with("message: "), "{error}"); + // Our voice leaves on the slot of the client we are now, and the flags too. + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); + rig.give(LinkCmd::SetInputMuted(true)); + assert!(matches!(rig.inner_cmd().await, LinkCmd::SetInputMuted(true))); + rig.quiet(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn we_stay_the_client_we_were_while_it_is_there() { + let mut rig = Rig::teamspeak(everything()).await; + // A ghost of the old connection lingers: both clients carry our unique id. + // We stay client 7 (in the games channel), as another client of the same + // identity may be a second connection of ours. + let mut ghost = presence(); + ghost.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(ghost))); + assert_eq!(own_channel(&mut rig).await, GAMES); + + // The ghost goes: we are the one that is left. + let mut gone = presence(); + gone.clients.remove(&ME); + gone.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(gone))); + assert_eq!(own_channel(&mut rig).await, LOBBY); + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); +} + +// ---- chat scopes, private conversations ------------------------------------------- + +#[tokio::test(flavor = "multi_thread")] +async fn private_messages_from_more_than_16_peers_all_arrive() { + const PEERS: usize = 24; + let mut rig = Rig::new(everything()).await; + for peer in 0..PEERS { + let uid = format!("peer{peer}="); + rig.play(LinkEvent::Chat(ChatMessage { + target: ChatTarget::Private(uid.clone()), + author_name: format!("peer{peer}"), + author_uid: Some(uid), + author_id: None, + text: format!("hello {peer}"), + ts_ms: 1_700_000_000_000 + peer as i64, + via_relay: false, + blocked: false, + })); + } + let mut got = Vec::new(); + while got.len() < PEERS { + let chat = rig + .event(|e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + got.push((chat.text, chat.target)); + } + got.sort_by(|a, b| a.0.cmp(&b.0)); + let mut want: Vec<_> = (0..PEERS) + .map(|peer| (format!("hello {peer}"), ChatTarget::Private(format!("peer{peer}=")))) + .collect(); + want.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(got, want); +} + +// ---- who is talking ------------------------------------------------------------------ + +#[tokio::test(flavor = "multi_thread")] +async fn a_talker_the_link_hears_but_does_not_forward_is_shown_as_talking() { + let mut rig = Rig::new(everything()).await; + // A Speex or CELT talker: the link says it talks, and sends no Opus. + rig.play(LinkEvent::Talking { client: 8, talking: true }); + let on = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(on, (8, true)); + // And it holds for as long as the link says, silence or not. + tokio::time::sleep(Duration::from_millis(700)).await; + rig.play(LinkEvent::Talking { client: 8, talking: false }); + let off = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(off, (8, false)); +} + +// ---- notify ---------------------------------------------------------------------------- + +#[tokio::test(flavor = "multi_thread")] +async fn a_notify_needs_the_control_stream_and_is_run_as_the_request_it_is() { + use v1::request::Op; + let (session, _pushes, mut inner) = open(everything()).await; + // A List and the file transfers have a stream and an answer of their own; + // a Hello is part of connecting. + for op in [ + Op::List(v1::List { kind: v1::EntityKind::File as i32, ..Default::default() }), + Op::FileRead(Default::default()), + Op::FileWrite(Default::default()), + Op::Hello(Default::default()), + ] { + let error = session.notify(op).unwrap_err(); + assert!(matches!(error, SessionError::Protocol(_)), "{error:?}"); + } + // An op of the control stream is acted on, answer or not: a poke is a poke. + session + .notify(Op::Signal(v1::Signal { + to: Some(v1::SignalTarget { server_id: 1, participant_id: 8, ..Default::default() }), + body: Some(v1::signal::Body::Poke(v1::Poke { message: "wake up".into() })), + ..Default::default() + })) + .unwrap(); + let LinkCmd::Poke { client, message } = within("a poke", inner.cmds.recv()).await else { + panic!("a poke") + }; + assert_eq!((client, message.as_str()), (8, "wake up")); + // And a closed session refuses it. + session.close(v1::CloseCode::Normal, ""); + let _ = within("the disconnect", inner.cmds.recv()).await; + inner.events.send(LinkEvent::Disconnected(None)).unwrap(); + let _ = session.closed().await; + let error = session.notify(Op::LeaveVoice(v1::LeaveVoice { server_id: 1 })).unwrap_err(); + assert!(matches!(error, SessionError::Closed(_)), "{error:?}"); +} + +// ---- how a connect ends ------------------------------------------------------------------ + +/// A connector of the protocol repository's fake host whose sessions answer +/// every `Subscribe` and push nothing: the test pushes the syncs itself. +struct Silent(voelin_proto::test_util::FakeConnector); + +impl Connector for Silent { + fn schemes(&self) -> &'static [&'static str] { + self.0.schemes() + } + + fn connect( + &self, + params: voelin_proto::link::ConnectParams, + ) -> voelin_proto::link::BoxFuture> { + let connecting = self.0.connect(params); + let fake = self.0.clone(); + Box::pin(async move { + let connected = connecting.await?; + if let Some(handle) = fake.last_session() { + handle.script( + voelin_proto::test_util::Script::answer( + "subscribe", + v1::response::Result::Ack(Default::default()), + ) + .times(3), + ); + } + Ok(connected) + }) + } +} + +/// A session that ends while the connect waits for the syncs says why it +/// ended: the engine shows the host's words, not a silent disconnect. +#[tokio::test(flavor = "multi_thread")] +async fn a_session_that_ends_during_the_connect_syncs_says_why() { + use voelin_model::replica::ScopeId; + use voelin_proto::v1::push::Body; + let fake = voelin_proto::test_util::FakeConnector::new(); + fake.host() + .put(v1::Entity { + kind: Some(v1::entity::Kind::Server(v1::Server { + id: 1, + name: "Fake Host".into(), + uid: "fake-host".into(), + ..Default::default() + })), + }) + .unwrap(); + let mut backends = Backends::empty(); + backends.register(Arc::new(Silent(fake.clone()))); + 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(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx); + + // The three subscriptions are answered; two syncs end, the LIVE one never does. + let handle = loop { + if let Some(handle) = fake.last_session() { + break handle; + } + tokio::time::sleep(Duration::from_millis(2)).await; + }; + voelin_proto::test_util::eventually(WAIT, "the three subscriptions", || { + let requests = handle.requests(); + let subscribed = requests + .iter() + .filter(|logged| matches!(&logged.request.op, Some(v1::request::Op::Subscribe(_)))) + .count(); + subscribed == 3 + }) + .await; + for scope in [ScopeId::Home, ScopeId::Server(1)] { + let proto = Some(scope.to_proto()); + let begin = v1::SyncBegin { scope: proto, mode: v1::SyncMode::Full as i32, epoch: 1 }; + let end = + v1::SyncEnd { scope: proto, cursor: Some(v1::Cursor { epoch: 1, rev: 1 }), gap: false }; + handle.push(v1::Push { body: Some(Body::SyncBegin(begin)) }).unwrap(); + handle.push(v1::Push { body: Some(Body::SyncEnd(end)) }).unwrap(); + } + // The host ends the session, with a reason. + handle.kill(CloseReason::Network("kicked: spam".into())); + let reason = within("the end", async { + loop { + if let LinkEvent::Disconnected(reason) = events.recv().await? { + return Some(reason); + } + } + }) + .await; + assert_eq!(reason.as_deref(), Some("kicked: spam")); +} + +/// A link no connector serves: the text shows where, never the channel +/// password that rides in the link. +#[tokio::test(flavor = "multi_thread")] +async fn the_text_of_an_address_nobody_serves_keeps_the_channel_password_out() { + 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()); + let mut options = VoiceOptions::new("ts.example.com:9987", "tester"); + options.channel = Some("Raid".into()); + options.channel_password = Some("hunter2".into()); + link.spawn(options, ctx, cmd_rx, event_tx); + let event = within("the end", events.recv()).await; + let LinkEvent::Disconnected(Some(why)) = event else { panic!("a disconnect with a reason") }; + assert!(why.starts_with("no connector for ts3server://ts.example.com"), "{why}"); + assert!(!why.contains("hunter2") && !why.contains('?'), "{why}"); +} + +// ---- a consumer that lags ------------------------------------------------------------------- + +/// A session whose consumer does not read pushes does not stall the +/// connection: the voice goes on, and once the consumer reads again it gets +/// the scopes it missed in full (`ConnectParams.push_capacity`). +#[tokio::test(flavor = "multi_thread")] +async fn a_consumer_that_lags_loses_the_queue_and_gets_the_scope_again() { + use voelin_model::replica::{Replica, ScopeId}; + let (conns, mut seen) = mpsc::unbounded_channel(); + let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); + let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987"); + params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; + // The smallest queue there is: 16 pushes. + params.push_capacity = 1; + let connecting = tokio::spawn(connector.connect(params)); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(connected(everything())).unwrap(); + inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); + let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; + let (session, mut pushes) = (connected.session, connected.pushes); + + let server = ScopeId::Server(1); + session.request(subscribe(server)).await.unwrap(); + // Far more changes than the queue holds, and nobody reads. + const NAMES: usize = 40; + for i in 0..NAMES { + let mut next = presence(); + next.channels.get_mut(&LOBBY).unwrap().name = format!("name{i}"); + inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); + } + // The connection still takes voice from the link while the queue is full. + inner + .events + .send(LinkEvent::Audio(VoicePacket { + talker: TalkerId(8), + seq: 1, + codec: VoiceCodec::Voice, + whisper: false, + payload: OPUS_20_MS.to_vec(), + })) + .unwrap(); + let packet = within("the voice", media.recv()).await; + assert_eq!(packet.flow.slot(), 9, "alice's slot"); + + // The consumer reads at last: what it gets ends with the last state. + let mut replica = Replica::default(); + replica.subscribe(server); + let last = format!("name{}", NAMES - 1); + within("the last state", async { + loop { + let push = pushes.recv().await?; + replica.apply_push(&push); + if replica.channel(LOBBY).is_some_and(|channel| channel.name == last) { + return Some(()); + } + } + }) + .await; +} + +/// A scope that needs more frames than the channel holds is sent in bigger +/// chunks, not never: the smallest channel is 16 pushes, of 256 entities. +#[tokio::test(flavor = "multi_thread")] +async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() { + use voelin_model::replica::{Replica, ScopeId}; + const CHANNELS: u64 = 5_000; + 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.push_capacity = 1; + let connecting = tokio::spawn(connector.connect(params)); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(connected(everything())).unwrap(); + let mut big = presence(); + for id in 100..100 + CHANNELS { + let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() }; + big.channels.insert(id, channel); + } + inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap(); + let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; + let (session, mut pushes) = (connected.session, connected.pushes); + + let server = ScopeId::Server(1); + session.request(subscribe(server)).await.unwrap(); + let mut replica = Replica::default(); + replica.subscribe(server); + within("the whole scope", async { + loop { + let push = pushes.recv().await?; + replica.apply_push(&push); + if matches!(push.body, Some(v1::push::Body::SyncEnd(_))) { + return Some(()); + } + } + }) + .await; + // Two of the fixture's channels, and the ones added. + assert_eq!(replica.channels(1).count() as u64, 2 + CHANNELS + 1, "with the server chat"); +} + +// ---- moves in flight, transfers, nameless pokes, narrowed features -------------- + +fn join(channel: u64) -> v1::request::Op { + request(v1::request::Op::JoinVoice(v1::JoinVoice { + server_id: 1, + channel_id: channel, + ..Default::default() + })) +} + +/// The channel of the voice state an answer carries. +fn voice_channel(answer: v1::response::Result) -> u64 { + let v1::response::Result::Entities(entities) = answer else { panic!("a voice state") }; + let Some(v1::entity::Kind::Voice(voice)) = &entities.items[0].kind else { + panic!("a voice state") + }; + voice.channel_id +} + +/// The link reports a snapshot that has us in `channel`. +fn moved_to(inner: &Inner, channel: u64) { + let mut next = presence(); + next.clients.get_mut(&ME).unwrap().channel = channel; + inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); +} + +/// A move made while another is on its way is a move: the channel the +/// snapshots show is where we were, not where the first move leaves us. A +/// move into the channel we are in, with none on its way, is answered at once. +#[tokio::test(flavor = "multi_thread")] +async fn a_move_made_while_another_is_on_its_way_reaches_the_link() { + let (session, _pushes, mut inner) = open(everything()).await; + // The seat, then a move into the channel we are in: nothing to ask the link. + assert_eq!(voice_channel(session.request(join(GAMES)).await.unwrap()), GAMES); + let same = within("the answer", async { session.request(join(GAMES)).await.ok() }).await; + assert_eq!(voice_channel(same), GAMES); + assert!(inner.cmds.try_recv().is_err(), "a move into the channel we are in went to the link"); + + // The link is slow to answer the first move ... + let first = session.request(join(LOBBY)); + let LinkCmd::Move(channel, _) = within("a move", inner.cmds.recv()).await else { + panic!("a move") + }; + assert_eq!(channel, LOBBY); + // ... and the user changes their mind: back into the channel the snapshots + // still show. The link is asked, or the user stays in the lobby. + let second = session.request(join(GAMES)); + let LinkCmd::Move(channel, _) = within("the move back", inner.cmds.recv()).await else { + panic!("the move back") + }; + assert_eq!(channel, GAMES); + moved_to(&inner, LOBBY); + let first = within("the first move", async { first.await.ok() }).await; + assert_eq!(voice_channel(first), LOBBY); + moved_to(&inner, GAMES); + let second = within("the move back", async { second.await.ok() }).await; + assert_eq!(voice_channel(second), GAMES); + + // Nothing is on its way any more. + let same = within("the answer", async { session.request(join(GAMES)).await.ok() }).await; + assert_eq!(voice_channel(same), GAMES); + assert!(inner.cmds.try_recv().is_err()); +} + +/// A move back into the channel we never left, after a refused move: the link +/// says nothing to a move into the channel it is in, and the refusal of the +/// first move answers the second. +#[tokio::test(flavor = "multi_thread")] +async fn a_move_back_after_a_refused_move_is_answered_though_the_link_says_nothing() { + let (session, _pushes, mut inner) = open(everything()).await; + session.request(join(GAMES)).await.unwrap(); + let refused = session.request(join(LOBBY)); + let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; + let back = session.request(join(GAMES)); + let LinkCmd::Move(..) = within("the move back", inner.cmds.recv()).await else { + panic!("the move back") + }; + inner.ctx.emit(Event::JoinFailed { session: 0, channel: LOBBY, reason: JoinFailure::Password }); + let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; + assert_eq!(error.code(), Some(v1::ErrorCode::Password)); + // Answered now, not after the ten seconds of a move that gets no answer. + let back = tokio::time::timeout(Duration::from_secs(2), back).await; + assert_eq!(voice_channel(back.expect("answered at once").unwrap()), GAMES); +} + +fn file_path(path: &str) -> v1::FilePath { + v1::FilePath { channel_id: GAMES, path: path.into(), password: String::new() } +} + +/// A transfer waits for the server as long as its caller does: the engine +/// puts the deadline on a picture's negotiation and none on a file the user +/// asked for. A caller that gives up takes the link's job with it. +#[tokio::test(start_paused = true)] +async fn a_transfer_waits_for_the_server_for_as_long_as_the_caller_does() { + let (session, _pushes, mut inner) = open(everything()).await; + let long = Duration::from_secs(120); + + let read = tokio::spawn(session.read_file(v1::FileRead { + target: Some(v1::file_read::Target::Path(file_path("/a.txt"))), + offset: 0, + length: 0, + })); + let LinkCmd::OpenRead { reply, .. } = within("a read", inner.cmds.recv()).await else { + panic!("a connection to read") + }; + tokio::time::sleep(long).await; + assert!(!read.is_finished(), "a read gave up on its own"); + let _ = reply.send(Ok((5, Box::pin(std::io::Cursor::new(b"hello".to_vec()))))); + let Ok(Ok(download)) = read.await else { panic!("the read opened") }; + let sizes: Vec = download + .head + .items + .iter() + .filter_map(|e| match &e.kind { + Some(v1::entity::Kind::File(file)) => Some(file.size), + _ => None, + }) + .collect(); + assert_eq!(sizes, [5]); + + let write = tokio::spawn(session.write_file(v1::FileWrite { + target: Some(v1::file_write::Target::Path(file_path("/b.txt"))), + size: 3, + offset: 0, + overwrite: true, + ..Default::default() + })); + let LinkCmd::OpenWrite { reply, .. } = within("a write", inner.cmds.recv()).await else { + panic!("a connection to write") + }; + tokio::time::sleep(long).await; + assert!(!write.is_finished(), "a write gave up on its own"); + let (_server, client) = tokio::io::duplex(64); + let _ = reply.send(Ok((0, Box::pin(client)))); + assert!(matches!(write.await, Ok(Ok(_))), "the write opened"); + + // The caller gives up: the link's job is told. + let read = session.read_file(v1::FileRead { + target: Some(v1::file_read::Target::Path(file_path("/c.txt"))), + offset: 0, + length: 0, + }); + let LinkCmd::OpenRead { reply, .. } = within("a read", inner.cmds.recv()).await else { + panic!("a connection to read") + }; + drop(read); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(reply.is_closed(), "the link's job outlived its caller"); +} + +/// A sender with no unique id who is not on the snapshot is named all the +/// same: the name the link gave goes into LIVE as a user of its own. +#[tokio::test(flavor = "multi_thread")] +async fn a_poke_from_a_sender_with_no_unique_id_outside_the_snapshot_is_named() { + let mut rig = Rig::new(everything()).await; + let poke = |name: &str| LinkEvent::Poke { + from: 77, + from_uid: None, + from_name: name.into(), + message: "boo".into(), + }; + async fn named(rig: &mut Rig) -> (Option, String) { + rig.event(|e| match e { + LinkEvent::Poke { from: 77, from_uid, from_name, .. } => Some((from_uid, from_name)), + _ => None, + }) + .await + } + rig.play(poke("ghost")); + assert_eq!(named(&mut rig).await, (None, "ghost".to_owned())); + // The link gives the client id to whoever connects next: the name follows. + rig.play(poke("ghost two")); + assert_eq!(named(&mut rig).await, (None, "ghost two".to_owned())); +} + +async fn event_of( + events: &mut mpsc::UnboundedReceiver, + mut f: impl FnMut(LinkEvent) -> Option, +) -> T { + within("an event", async { + loop { + if let Some(t) = f(events.recv().await?) { + return Some(t); + } + } + }) + .await +} + +/// `Server.features` narrows what the host offers (protocol 1.3, +/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed. +#[tokio::test(flavor = "multi_thread")] +async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() { + use v1::entity::Kind; + use voelin_proto::test_util::{FakeConnector, eventually}; + + let connector = FakeConnector::new(); + let host = connector.host(); + let put_server = |features: &[&str]| { + let server = v1::Server { + id: 1, + name: "Narrow Host".into(), + uid: "narrow-host".into(), + default_channel_id: 10, + features: features.iter().map(|f| (*f).to_owned()).collect(), + ..Default::default() + }; + host.put(v1::Entity { kind: Some(Kind::Server(server)) }).unwrap(); + }; + put_server(&["voice", "chat"]); + let lobby = v1::Channel { + id: 10, + server_id: 1, + kind: v1::ChannelKind::Voice as i32, + name: "Lobby".into(), + ..Default::default() + }; + host.put(v1::Entity { kind: Some(Kind::Channel(lobby)) }).unwrap(); + + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + let link = SessionLink::new(backends); + let ctx = LocalCtx::standalone().link; + let mut bus = ctx.events.subscribe(); + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx); + + // The host offers files, the server does not. + let capabilities = event_of(&mut events, |e| match e { + LinkEvent::Connected { capabilities, .. } => Some(capabilities), + _ => None, + }) + .await; + assert!(!capabilities.file_transfer, "the server's list leaves files out"); + let handle = connector.last_session().expect("a session"); + let file_lists = || { + let requests = handle.requests(); + requests + .iter() + .filter(|logged| match &logged.request.op { + Some(v1::request::Op::List(list)) => list.kind == v1::EntityKind::File as i32, + _ => false, + }) + .count() + }; + let ask = |request| { + let dir = remote(10, None, "/"); + cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap(); + }; + let refusal = "not offered by this server: files"; + let refused = + |event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal); + + // Refused here: nothing reaches the host. + ask(1); + loop { + let event = within("the refusal", async { bus.recv().await.ok() }).await; + if refused(&event) { + break; + } + } + assert_eq!(file_lists(), 0); + + // The server lifts its list (an empty one keeps all the host's): files work. + put_server(&[]); + let mut request = 1; + eventually(WAIT, "a file list to reach the host", || { + request += 1; + ask(request); + file_lists() > 0 + }) + .await; + + // The host narrows what it offers this user. A refusal counts only for a + // request made after the update: the earlier ones were answered by the host's + // wider set (or, before the server lifted its list, refused for that). + let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None }; + handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap(); + let after = request; + within("the narrower set to apply", async { + loop { + request += 1; + ask(request); + tokio::time::sleep(Duration::from_millis(20)).await; + while let Ok(event) = bus.try_recv() { + if matches!(&event, Event::FileList { request, .. } if *request > after) + && refused(&event) + { + return Some(()); + } + } + } + }) + .await; +} + +/// A port that is no port is refused in words, not dropped: the connection +/// would go to another port than the one the bookmark names. +#[tokio::test(flavor = "multi_thread")] +async fn a_bookmark_with_a_port_that_is_no_port_does_not_connect() { + let mut backends = Backends::empty(); + let (conns, mut seen) = mpsc::unbounded_channel(); + 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(VoiceOptions::new("ts.example.com:99999", "tester"), ctx, cmd_rx, event_tx); + let reason = event_of(&mut events, |e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + let reason = reason.expect("a reason"); + assert!(reason.contains("65535") && reason.contains("ts.example.com:99999"), "{reason}"); + assert!(seen.try_recv().is_err(), "a link was asked to connect anyway"); +} diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index b6c3655..6d77331 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -2680,7 +2680,7 @@ pub struct DecodeStats { pub bytes: u64, /// Pictures decoded per second and video received in bit/s, over the /// time since the previous [`VideoPipeline::stats`] (at least - /// [`RATE_WINDOW`]; the watch screen asks once a second). + /// `RATE_WINDOW`; the watch screen asks once a second). pub fps: u32, pub bitrate: u64, } diff --git a/crates/voelin-core/src/query.rs b/crates/voelin-core/src/query.rs index b048bfb..183f943 100644 --- a/crates/voelin-core/src/query.rs +++ b/crates/voelin-core/src/query.rs @@ -1,11 +1,94 @@ //! The query source: own ServerQuery credentials, in-process observer and relays. +use std::fmt; + use tokio::sync::{broadcast, mpsc}; use voelin_model::{ChatMessage, ChatTarget, Presence}; use voelin_observer::{ Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool, }; +/// How a ServerQuery connection talks to the server. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QueryTransport { + /// The raw text protocol (TeamSpeak 3; port 10011). + Raw, + /// SSH. + Ssh, + /// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret). + Http, +} + +/// The user's own ServerQuery credentials for a server +/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the +/// engine logs in with to observe a server invisibly and to relay its +/// channels' chat. The connection's own tuning (flood protection, timeouts) +/// is the engine's. +#[derive(Clone, PartialEq, Eq)] +pub struct QueryLogin { + /// The protocol of the query interface at `address`. + pub transport: QueryTransport, + /// `host:port` of the query interface. + pub address: String, + /// The login name (raw and SSH; ignored for HTTP). + pub user: String, + /// The password (raw and SSH) or API key (HTTP, optional for guest access). + pub secret: Option, + /// Select the virtual server by its voice port... + pub server_port: Option, + /// ...or by id (the first server when neither is given). + pub server_id: Option, + /// This machine's address is on the server's query allowlist, which the + /// server's flood protection skips: the engine then sends its commands + /// without the limit it keeps for a server that has not said so (a command + /// the server refuses as a flood slows the connection down all the same). + /// The application usually cannot know, and says `false`; the development + /// servers of the tests allowlist their clients. + pub allowlisted: bool, +} + +impl fmt::Debug for QueryLogin { + // The secret is kept out of logs. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("QueryLogin") + .field("transport", &self.transport) + .field("address", &self.address) + .field("user", &self.user) + .field("secret", &self.secret.as_ref().map(|_| "[secret]")) + .field("server_port", &self.server_port) + .field("server_id", &self.server_id) + .field("allowlisted", &self.allowlisted) + .finish() + } +} + +impl QueryLogin { + /// The connection the observer and the relays open. + fn connect(&self) -> voelin_query::Connect { + voelin_query::Connect { + transport: match self.transport { + QueryTransport::Raw => voelin_query::Transport::Raw, + QueryTransport::Ssh => voelin_query::Transport::Ssh, + QueryTransport::Http => voelin_query::Transport::Http, + }, + addr: self.address.clone(), + user: self.user.clone(), + secret: self.secret.clone(), + server_port: self.server_port, + server_id: self.server_id, + line: voelin_query::LineOptions { + // Off the client-side limit only where the server skips it. + rate_limit: if self.allowlisted { + None + } else { + voelin_query::LineOptions::default().rate_limit + }, + ..Default::default() + }, + } + } +} + pub(crate) enum QueryCmd { OpenChat(ChatTarget), CloseChat(ChatTarget), @@ -21,10 +104,11 @@ pub(crate) enum QueryEvent { } pub(crate) async fn run( - connect: voelin_query::Connect, + login: QueryLogin, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { + let connect = login.connect(); let observer = Observer::spawn(ObserverConfig::new(connect.clone())); let relays = RelayPool::new(RelayConfig::new(connect)); let mut observed = observer.subscribe(); @@ -88,3 +172,59 @@ pub(crate) async fn run( relays.close_all().await; let _ = events.send(QueryEvent::Disconnected); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_login_is_the_connection_the_query_crate_opens() { + let login = QueryLogin { + transport: QueryTransport::Ssh, + address: "ts.example.com:10022".into(), + user: "serveradmin".into(), + secret: Some("hunter2".into()), + server_port: Some(9987), + server_id: Some(3), + allowlisted: false, + }; + let connect = login.connect(); + assert_eq!(connect.transport, voelin_query::Transport::Ssh); + assert_eq!( + (connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()), + ("ts.example.com:10022", "serveradmin", Some("hunter2")) + ); + assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3))); + for (ours, theirs) in [ + (QueryTransport::Raw, voelin_query::Transport::Raw), + (QueryTransport::Http, voelin_query::Transport::Http), + ] { + let connect = QueryLogin { transport: ours, ..login.clone() }.connect(); + assert_eq!(connect.transport, theirs); + } + // The line options are the query crate's defaults, as the UI always + // gave them, unless the server allowlists the client. + let line = voelin_query::LineOptions::default(); + assert!(line.rate_limit.is_some()); + assert_eq!(connect.line.rate_limit, line.rate_limit); + assert_eq!(connect.line.timeout, line.timeout); + let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect(); + assert_eq!(allowlisted.line.rate_limit, None); + assert_eq!(allowlisted.line.timeout, line.timeout); + } + + #[test] + fn the_secret_stays_out_of_the_debug_text() { + let login = QueryLogin { + transport: QueryTransport::Raw, + address: "h:1".into(), + user: "u".into(), + secret: Some("hunter2".into()), + server_port: None, + server_id: None, + allowlisted: false, + }; + let text = format!("{login:?}"); + assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}"); + } +} diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 5658df9..26c86be 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -29,7 +29,7 @@ use crate::gateway::{ Push, ReactionPush, }; use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory}; -use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, ServerLink}; +use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; use crate::settings::{ @@ -78,31 +78,16 @@ pub(crate) struct SessionHandle { } impl SessionHandle { - #[allow(clippy::too_many_arguments)] // what the engine hands each session pub fn spawn( id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, shared: Shared, - link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, + link: Arc, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn( - Session::new( - id, - events, - frames, - audio_settings, - shared, - link, - myts_identity, - myts_data, - ) - .run(rx), - ); + tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx)); Self { tx } } @@ -298,9 +283,7 @@ struct OwnStream { struct Session { /// Starts the voice connections. - link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, + link: Arc, id: SessionId, events: broadcast::Sender, state: SessionState, @@ -386,24 +369,19 @@ struct Session { } impl Session { - #[allow(clippy::too_many_arguments)] // what the engine hands each session fn new( id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, shared: Shared, - link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, + link: Arc, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); let Shared { settings, history, cache, contacts } = shared; let contacts_rx = Some(contacts.watch()); Self { link, - myts_identity, - myts_data, cache, contacts, contacts_rx, @@ -546,8 +524,6 @@ impl Session { events: self.events.clone(), frames: self.frames.clone(), settings: self.settings.clone(), - myts_identity: self.myts_identity.clone(), - myts_data: self.myts_data.clone(), }; self.link.spawn(options, ctx, cmd_rx, ev_tx); self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); @@ -600,7 +576,10 @@ impl Session { // source, the history is kept under the query address. if self.state.server_uid.is_none() { let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default(); - self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query); + self.learn_server_uid( + format!("query:{}{port}", connect.address), + Source::Query, + ); self.open_histories(); } let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); @@ -873,9 +852,7 @@ impl Session { self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read }); } // Engine-wide. - Command::SetMytsIdentity(_) - | Command::SetMytsData(_) - | Command::CloseSession { .. } + Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } | Command::ResetSetting { .. } @@ -2276,19 +2253,13 @@ mod banner_tests { cache: SharedCache::new(Cache::new(dir)), contacts: Contacts::new(events.clone(), history), }; - // No myTeamSpeak account; its source stays open, as the engine's does - // (a closed one ends voice connections). - let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); - let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); let session = Session::new( 1, events, frames, AudioSettings::default(), shared, - Arc::new(crate::TsLink), - myts_identity, - myts_data, + Arc::new(SessionLink::new(crate::Backends::empty())), ); (session, receiver) } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index f7390d4..c89a46c 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key = Key::new( ); /// Import identities from the official TeamSpeak clients when the app -/// starts ([`crate::identity::import_new`]; their files are only read). +/// starts ([`crate::ts::identity::import_new`]; their files are only read). pub static IDENTITY_IMPORT: Key = Key::new( "identity.import_from_teamspeak", Kind::Bool, diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 7ba77a7..585631e 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -171,7 +171,7 @@ impl PartialEq for StreamSink { } } -/// What the session asks of the streams of a connection ([`crate::link::LinkCmd::Stream`]). +/// What the session asks of the streams of a connection (`LinkCmd::Stream`). #[derive(Debug)] pub enum StreamCmd { Start { diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/ts/book.rs similarity index 55% rename from crates/voelin-core/src/book.rs rename to crates/voelin-core/src/ts/book.rs index 98cc7f7..8450843 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/ts/book.rs @@ -331,4 +331,301 @@ 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::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 parents = vec![0u64]; + for id in 1..=(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); + 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/identity.rs b/crates/voelin-core/src/ts/identity.rs similarity index 92% rename from crates/voelin-core/src/identity.rs rename to crates/voelin-core/src/ts/identity.rs index 7b3864d..83cbdc5 100644 --- a/crates/voelin-core/src/identity.rs +++ b/crates/voelin-core/src/ts/identity.rs @@ -32,6 +32,7 @@ use std::{fs, str}; use rusqlite::{Connection, OpenFlags, OptionalExtension}; use tsclientlib::Identity; use voelin_gateway_proto::UniqueIds; +use voelin_identity::IdentityBlob; use voelin_store::{IdentityOrigin, Store}; /// Name given to an identity whose source kept none. @@ -55,6 +56,9 @@ pub enum IdentityError { NoIdentity { path: String }, #[error("client database: {0}")] Store(String), + /// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]). + #[error("{0}")] + Blob(String), } impl IdentityError { @@ -230,6 +234,43 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result IdentityBlob { + // An identity is a key and two counters: writing it cannot fail. (A blob with + // no JSON is refused when it is used, in words.) + let json = serde_json::to_string(identity).unwrap_or_default(); + IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json) +} + +/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]). +pub fn from_blob(blob: &IdentityBlob) -> Result { + if !blob.is_teamspeak() { + return Err(IdentityError::Blob(format!( + "the identity is of kind {:?}, not a TeamSpeak one", + blob.kind + ))); + } + serde_json::from_str(&blob.json).map_err(|e| { + // Where the JSON is wrong, not what it says: it holds a private key. + let what = match e.classify() { + serde_json::error::Category::Syntax => "malformed", + serde_json::error::Category::Eof => "cut short", + serde_json::error::Category::Data => "not an identity", + serde_json::error::Category::Io => "unreadable", + }; + IdentityError::Blob(format!( + "the TeamSpeak identity cannot be read: {what} at line {}, column {}", + e.line(), + e.column() + )) + }) +} + /// The TeamSpeak 3 `.ini` export of an identity, which the official client /// and every other tool reads. pub fn export(nickname: &str, identity: &Identity) -> String { @@ -548,6 +589,32 @@ mod tests { Identity::create() } + /// The blob of an identity is how the key store keeps it, and reads back as + /// the same identity; what is no TeamSpeak identity is refused without + /// quoting its JSON. + #[test] + fn an_identity_goes_through_its_blob() { + let identity = synthetic(); + let blob = to_blob(&identity); + assert!(blob.is_teamspeak()); + assert_eq!(blob.uid, identity.key().to_pub().get_uid()); + assert_eq!(blob.level, identity.level()); + assert_eq!(blob.json, serde_json::to_string(&identity).unwrap()); + let back = from_blob(&blob).unwrap(); + assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap()); + + // Another kind. + let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone()); + let error = from_blob(&other).unwrap_err().to_string(); + assert!(error.contains("\"voelin\""), "{error}"); + // Not an identity: the text says where, and nothing of what it holds. + for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] { + let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string(); + assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}"); + assert!(!error.contains("hunter2"), "{error}"); + } + } + #[test] fn improve_level_keeps_the_key() { let identity = synthetic(); diff --git a/crates/voelin-core/src/ts/mod.rs b/crates/voelin-core/src/ts/mod.rs new file mode 100644 index 0000000..e232001 --- /dev/null +++ b/crates/voelin-core/src/ts/mod.rs @@ -0,0 +1,30 @@ +//! The TeamSpeak implementation of the session seam. +//! +//! Everything of the engine that is TeamSpeak's lives here, so that it can +//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of +//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9): +//! +//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib` +//! (chat, voice, files, pokes, offline messages, the stream task's +//! requests) with `book.rs`, its presence from the library's book; +//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection +//! ([`TsConnector`] is the `Connector` the engine registers for +//! `ts3server://` and `teamspeak://`); +//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know +//! about itself: the signed compatibility versions it can claim, and the +//! identities (reading, importing from the official clients, the security +//! level). +//! +//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are +//! named in the public items of this module and nowhere else of the crate's +//! API. + +mod book; +pub mod identity; +mod ts_link; +pub(crate) mod ts_session; +pub mod versions; +mod voice; + +pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink}; +pub use ts_session::TsConnector; diff --git a/crates/voelin-core/src/ts/ts_link.rs b/crates/voelin-core/src/ts/ts_link.rs new file mode 100644 index 0000000..e768e1a --- /dev/null +++ b/crates/voelin-core/src/ts/ts_link.rs @@ -0,0 +1,256 @@ +//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that +//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with. +//! +//! The engine does not know this vocabulary: it talks to a +//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session` +//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link +//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3 +//! or 6 client with `tsclientlib` and +//! runs the connection ([`super::voice`]) with everything that rides on it: +//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the +//! stream task. Which product the server is (and what it can do) is decided +//! there, from the version it sends, and reported in +//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected). +//! +//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`, +//! `identity.rs`) is TeamSpeak's and leaves this crate together with it: +//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts` +//! of VoelinGateWay. + +use std::sync::Arc; + +use tokio::sync::{mpsc, watch}; +use voelin_stream::PeerConfig; + +use super::voice; +use crate::link::{LinkCmd, LinkCtx, LinkEvent}; + +/// Starts the connection of a link: the contract of `crate::link` for the +/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does +/// with them, and the module documentation of `link/session_link.rs` states +/// it. +/// +/// One link serves every session of an engine; [`spawn`](Self::spawn) starts +/// one connection. +pub(crate) trait ServerLink: Send + Sync + 'static { + /// Connect to the server `options` names and run the connection on its + /// own task: take commands from `cmds`, report through `events`, and end + /// the connection with [`LinkEvent::Disconnected`]. Does not block. + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ); +} + +/// What a TeamSpeak connection needs to know: the server, who to be, where +/// to join. The reverse of what the engine's `ConnectParams` carry +/// (`ts_session::inner_options`). +#[derive(Clone, Debug)] +pub(crate) struct ConnectOptions { + pub address: String, + pub nickname: String, + /// The identity to connect with; none generates one. + pub identity: Option, + /// Signed compatibility version; `None` selects the native platform's tuple. + pub client_version: Option, + pub server_password: Option, + /// Channel path to join, e.g. `Lobby/Sub`, or `/`. + pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, + /// Open the audio devices (capture and playback). + pub audio: bool, + /// Network settings for stream peer connections. + pub stream_peer: PeerConfig, +} + +impl ConnectOptions { + /// Options for `address` and `nickname`, the rest as a test leaves it. + #[cfg(test)] + pub(crate) fn new(address: impl Into, nickname: impl Into) -> Self { + Self { + address: address.into(), + nickname: nickname.into(), + identity: None, + client_version: None, + server_password: None, + channel: None, + channel_password: None, + token: None, + audio: false, + stream_peer: PeerConfig::default(), + } + } +} + +/// The main myTeamSpeak account of an application, as its connections show +/// it to the servers: the proof of the myTS ID, and what servers are shown +/// of it (its avatar and badges with their certificates, its User Tag). +/// +/// The senders live here, one pair for every connection of a [`TsLink`]; each +/// connection watches the pair through [`Watches`], presents the account it +/// finds when it connects, and follows the changes. +pub(crate) struct Account { + identity: watch::Sender>>, + data: watch::Sender>>, +} + +impl Default for Account { + /// No account is signed in. + fn default() -> Self { + Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) } + } +} + +impl Account { + /// The account proof for every current and future connection. Still no + /// account is no change: every notification restarts the handshakes and + /// sends `updatemytsid` on every connection. Any account is (each + /// connection's proof is signed anew). + pub(crate) fn set_identity(&self, identity: Option>) { + self.identity.send_if_modified(|current| { + if current.is_none() && identity.is_none() { + return false; + } + *current = identity; + true + }); + } + + /// What the servers are shown of the account: sent to every connection + /// that presents the account's myTS ID, once connected and when it + /// changes; cleared on a sign-out. The same data is no change. + pub(crate) fn set_data(&self, data: Option>) { + self.data.send_if_modified(|current| { + if *current == data { + return false; + } + *current = data; + true + }); + } + + /// What one connection watches. It keeps the senders alive for as long as + /// it runs: a connection ends with "account source closed" when its + /// watches have lost them, so the account outlives the connector that + /// made the connection. + pub(crate) fn watches(self: &Arc) -> Watches { + Watches { + identity: self.identity.subscribe(), + data: self.data.subscribe(), + _keep: Some(self.clone()), + } + } +} + +/// The account a connection presents and follows ([`Account::watches`]). +pub(crate) struct Watches { + pub(super) identity: watch::Receiver>>, + pub(super) data: watch::Receiver>>, + _keep: Option>, +} + +impl Watches { + /// Watches of senders that someone else keeps (a test's). + #[cfg(test)] + pub(super) fn of( + identity: watch::Receiver>>, + data: watch::Receiver>>, + ) -> Self { + Self { identity, data, _keep: None } + } +} + +/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector). +#[derive(Clone, Default)] +pub(crate) struct TsLink { + account: Arc, +} + +impl TsLink { + /// A link that presents no account until it is given one. + pub(crate) fn new() -> Self { + Self::default() + } + + /// The account the link's connections present. + pub(crate) fn account(&self) -> &Arc { + &self.account + } +} + +impl ServerLink for TsLink { + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A myTS ID's proof (the standard Ed25519 base point as the public key). + fn identity() -> Arc { + let mut private = [0; 32]; + private[0] = 1; + let mut public = [0x66; 32]; + public[0] = 0x58; + Arc::new( + tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(), + ) + } + + /// An account sets what it holds only when it changes: every notification + /// of a watch restarts the handshake of a connection. + #[test] + fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() { + let account = Arc::new(Account::default()); + let mut watches = account.watches(); + // No account, still none: nothing. + account.set_identity(None); + account.set_data(None); + assert!(!watches.identity.has_changed().unwrap()); + assert!(!watches.data.has_changed().unwrap()); + + let proof = identity(); + account.set_identity(Some(proof.clone())); + assert!(watches.identity.borrow_and_update().is_some()); + // An account again is a change (each connection signs its proof anew), the + // same data is none. + account.set_identity(Some(proof)); + assert!(watches.identity.has_changed().unwrap()); + watches.identity.borrow_and_update(); + let data = Arc::new(tsclientlib::MytsData::default()); + account.set_data(Some(data.clone())); + assert!(watches.data.has_changed().unwrap()); + watches.data.borrow_and_update(); + account.set_data(Some(Arc::new(tsclientlib::MytsData::default()))); + assert!(!watches.data.has_changed().unwrap(), "equal data is no change"); + // A sign-out is a change. + account.set_identity(None); + assert!(watches.identity.has_changed().unwrap()); + assert!(watches.identity.borrow_and_update().is_none()); + } + + /// A connection outlives the connector that made it (a session handed out + /// by a connector that was dropped): its watches keep their senders. + #[test] + fn a_connection_keeps_the_account_open_when_its_link_is_gone() { + let link = TsLink::new(); + let watches = link.account().watches(); + drop(link); + assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender"); + assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender"); + } +} diff --git a/crates/voelin-core/src/ts/ts_session/driver.rs b/crates/voelin-core/src/ts/ts_session/driver.rs new file mode 100644 index 0000000..1f342a7 --- /dev/null +++ b/crates/voelin-core/src/ts/ts_session/driver.rs @@ -0,0 +1,1677 @@ +//! 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::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use tracing::{debug, warn}; +use voelin_audio::EncodedVoice; +use voelin_model::replica::{Key, ScopeId}; +use voelin_model::{ChatMessage, ChatTarget, ClientInfo, 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`). The engine +/// subscribes the server chat, the channel it is in and one per private +/// conversation of the connection, so this is no limit anything reaches: far +/// more than there are clients (a client id is 16 bits). +pub(super) const MAX_CHAT_SUBSCRIPTIONS: u32 = 1 << 16; +/// How long what the stream task reports waits for the engine to have +/// announced the connection (see [`Held`]). +#[cfg(not(test))] +const ANNOUNCE_WAIT: Duration = Duration::from_secs(3); +/// (Short in tests, which wait for it.) +#[cfg(test)] +const ANNOUNCE_WAIT: Duration = Duration::from_millis(400); +/// 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, + /// The client id the link named when it connected. We are another client + /// after TeamSpeak's own reconnect: see [`Driver::follow_own_client`]. + 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 media slot of our client, for the session's `send_media` to check + /// (it follows [`Driver::follow_own_client`]). + pub own_slot: Arc, + /// 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, +} + +/// What the stream task puts on the engine's bus before the engine has +/// announced the connection. +/// +/// The stream task starts with the link and lists the streams it finds as +/// soon as the server tells it; the engine learns of the connection only +/// after the connect sequence of the session (a few requests through this +/// task), and a list that arrives first would be acted on before the engine +/// knows it has voice. A link that was not behind a session delivered the two +/// in the other order, so the reports wait: the engine's first stream command +/// (sent when it handles the connection, after it has announced it) releases +/// them, or the time they may wait ([`ANNOUNCE_WAIT`]) does. +struct Held { + events: Vec, + until: 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, + /// The stream task's reports, until the engine has announced the connection. + held: Option, + 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, + /// The client we are in the snapshots (see [`Driver::follow_own_client`]). + own_client: u16, + own_slot: Arc, + /// Subscribed scopes whose pushes were dropped because the consumer lags + /// (the push channel was full): each is sent again in full as soon as + /// the channel has room for it (`ConnectParams.push_capacity`). + lagged: HashSet, + + 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, + own_slot, + server, + epoch, + } = parts; + let own_client = cfg.own_client; + 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); + } + // Only a link with streams has a stream task to hold back. + let held = port + .is_some() + .then(|| Held { events: Vec::new(), until: Instant::now() + ANNOUNCE_WAIT }); + let mut driver = Self { + cfg, + inner, + events, + early, + bus, + bus_open: true, + engine_bus, + held, + pushes, + media, + port, + closed, + closing: None, + gone: false, + own_client, + own_slot, + lagged: HashSet::new(), + 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); + } + loop { + tokio::select! { + biased; + cmd = cmds.recv(), if commands_open => match cmd { + Some(cmd) => self.command(cmd), + 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), + 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); + } + + /// Put a push on the channel if it has room, without waiting: this task + /// also carries the voice media and the commands, and a consumer that + /// lags must not stall them. `false` when the push was not put (the + /// channel is full, or nobody listens any more, which ends the task). + fn try_push(&mut self, push: v1::Push) -> bool { + match self.pushes.try_send(push) { + Ok(()) => true, + Err(TrySendError::Full(_)) => false, + Err(TrySendError::Closed(_)) => { + self.gone = true; + false + } + } + } + + /// A push that belongs to no scope (a signal): there is nothing to send + /// again later, so it is dropped when the channel is full. + fn push_signal(&mut self, signal: v1::Signal) { + let push = v1::Push { body: Some(Body::Signal(signal)) }; + if !self.try_push(push) && !self.gone { + debug!("a signal was dropped: the session lags"); + } + } + + /// The frames of a sync (or of a change), all or none: a scope is never + /// left half sent. When the channel has no room for all of them the scope + /// is marked as lagged and sent again, whole, once there is room + /// ([`Driver::retry_lagged`]). + fn push_scope(&mut self, scope: ScopeId, frames: Vec) { + if self.gone { + return; + } + if self.pushes.capacity() < frames.len() { + self.lagged.insert(scope); + return; + } + for frame in frames { + if !self.try_push(frame) { + // Cannot happen: this task is the only sender and the room + // was counted. If it does, the scope is sent again. + self.lagged.insert(scope); + return; + } + } + self.lagged.remove(&scope); + } + + /// Send again, in full, the scopes whose pushes were dropped, as far as + /// the channel has room for each (protocol section 5.7: an in-process + /// host without a log re-syncs from its state). + fn retry_lagged(&mut self) { + if self.lagged.is_empty() { + return; + } + self.lagged.retain(|scope| self.subs.contains(scope)); + let mut scopes: Vec = self.lagged.iter().copied().collect(); + scopes.sort_unstable(); + for scope in scopes { + let frames = self.sync_frames(scope, None, 0); + if self.pushes.capacity() < frames.len() { + // Later scopes wait for this one. + return; + } + debug!(?scope, frames = frames.len(), "the session lagged: the scope is sent again"); + self.push_scope(scope, frames); + } + } + + 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_signal(signal); + } + + // ---- commands --------------------------------------------------------- + + fn command(&mut self, cmd: Cmd) { + match cmd { + Cmd::Request { op, reply } => self.request(op, reply), + 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) => { + // The engine handled the connection before it sent this. + self.announced(); + 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); + } + + fn request(&mut self, op: Op, reply: Reply) { + let answer = match op { + Op::Subscribe(subscribe) => self.subscribe(subscribe), + Op::Unsubscribe(unsubscribe) => { + if let Some(scope) = unsubscribe.scope.as_ref().and_then(ScopeId::from_proto) { + self.subs.remove(&scope); + self.lagged.remove(&scope); + } + Ok(ack(self.rev)) + } + Op::List(list) => return self.list(list, reply), + Op::Put(put) => return self.put(put, reply), + 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 (request id 0). Our own mute flags are what the engine + /// sends this way; any other op of the control stream is run as the + /// request it is, and its answer, or its refusal, is told to nobody. + fn notify(&mut self, op: Op) { + match op { + Op::Put(put) if is_voice_flags(&put) => self.voice_flags(put), + op => { + let (reply, _) = oneshot::channel(); + self.request(op, reply); + } + } + } + + /// Our own mute and deafen flags go to the link. + fn voice_flags(&mut self, put: v1::Put) { + 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 ----------------------------------------- + + 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); + let frames = self.sync_frames(scope, subscribe.since.as_ref(), subscribe.limit); + // Sent now if the channel has room for the whole sync, else as soon as it has. + self.push_scope(scope, frames); + 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(), + } + } + + /// The frames of a scope's sync: its whole state, or (CHAT, with a cursor + /// of this connection) the messages after the cursor. + fn sync_frames(&self, scope: ScopeId, since: Option<&v1::Cursor>, limit: u32) -> Vec { + 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(); + // A sync has to fit the channel when it is empty, or it could never be sent: + // a scope bigger than the channel has bigger chunks. + let room = self.pushes.max_capacity().saturating_sub(2).max(1); + let chunk = SYNC_CHUNK.max(items.len().div_ceil(room)); + let frame = |body| v1::Push { body: Some(body) }; + let mut frames = Vec::with_capacity(items.len().div_ceil(chunk) + 2); + frames.push(frame(Body::SyncBegin(v1::SyncBegin { + scope: Some(proto), + mode: mode as i32, + epoch: self.epoch, + }))); + for part in items.chunks(chunk) { + frames.push(frame(Body::Change(v1::Change { + scope: Some(proto), + rev: self.rev, + put: part.to_vec(), + del: Vec::new(), + }))); + } + frames.push(frame(Body::SyncEnd(v1::SyncEnd { + scope: Some(proto), + cursor: Some(v1::Cursor { epoch: self.epoch, rev: self.rev }), + gap: false, + }))); + frames + } + + /// A change of a scope, pushed to its subscribers (the rev counts either + /// way). A scope that lags gets nothing now: its state is up to date + /// here, and the sync that follows carries the change. + fn commit(&mut self, scope: ScopeId, put: Vec, del: Vec) { + if put.is_empty() && del.is_empty() { + return; + } + self.rev += 1; + self.retry_lagged(); + if self.subs.contains(&scope) && !self.lagged.contains(&scope) { + let change = v1::Change { scope: Some(scope.to_proto()), rev: self.rev, put, del }; + self.push_scope(scope, vec![v1::Push { body: Some(Body::Change(change)) }]); + } + } + + // ---- what the link reports ------------------------------------------- + + fn event(&mut self, event: LinkEvent) { + match event { + LinkEvent::Connected { .. } => {} + LinkEvent::Presence(presence) => self.presence(*presence), + LinkEvent::OwnChannel(channel) => { + self.own_channel = Some(channel); + self.settle_moves(); + } + LinkEvent::Chat(message) => self.chat(message), + LinkEvent::Poke { from, from_uid, from_name, message } => { + let (user, _) = self.sender(from_uid.as_deref(), &from_name, Some(from)); + 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.own_client), + ..Default::default() + }), + body: Some(SignalBody::Poke(v1::Poke { message })), + }; + self.push_signal(signal); + } + 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), but + // the link hears talkers whose packets it does not forward as Opus + // (Speex, CELT): for those its word is all there is, and it goes to + // the engine as a speaking signal, a hint next to the media. + LinkEvent::Talking { client, talking } => { + self.push_signal(v1::Signal { + from_participant: u32::from(client), + body: Some(SignalBody::Speaking(v1::Speaking { + server_id: SERVER_ID, + participant_id: u32::from(client), + on: talking, + whisper: false, + })), + ..Default::default() + }); + } + 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), + LinkEvent::Disconnected(_) => {} + } + } + + fn stream_event(&mut self, event: StreamEvent) { + if let Some(port) = &self.port { + let _ = port.send(event); + } + } + + /// Which client of the snapshots we are. The link names our client id once, + /// when it connects, and TeamSpeak's own reconnect (inside the link) gives a + /// new one with the same unique id and no word about it. So we stay the + /// client we were for as long as it is there, and when it is gone we are a + /// client of our unique id (the newest, when there are several: a ghost of + /// the old connection may linger). A link that names no unique id leaves us + /// the client of the connect. + fn follow_own_client(&mut self, presence: &Presence) { + let uid = self.cfg.own_uid.as_deref().filter(|uid| !uid.is_empty()); + let ours = |client: &ClientInfo| match uid { + Some(uid) => client.uid.as_deref() == Some(uid), + None => client.id == self.own_client, + }; + if presence.clients.get(&self.own_client).is_some_and(ours) { + return; + } + let Some(next) = presence.clients.values().filter(|c| ours(c)).map(|c| c.id).max() else { + return; + }; + debug!(from = self.own_client, to = next, "we are another client now"); + self.own_client = next; + self.own_slot.store(entities::slot(next), Ordering::Relaxed); + } + + /// A snapshot of the server: the entities of the scopes that changed. + fn presence(&mut self, presence: Presence) { + self.follow_own_client(&presence); + let Built { server, live, own_user, by_uid } = + entities::build(&presence, self.cfg.ts6, Some(self.own_client)); + // Clients that left take their talk state with them. + for id in self.by_client.keys().filter(|id| !presence.clients.contains_key(id)) { + self.downlink.forget(*id); + } + 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.own_client) { + self.own_channel = Some(own.channel); + } + if own_user.is_some() { + self.own_user = own_user; + } + + let (put, del) = entities::diff(&self.server, &server); + self.server = server; + self.commit(ScopeId::Server(SERVER_ID), put, del); + + 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); + + self.refresh_home(); + 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(), + } + } + + 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); + } + + /// 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). + 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), participant), + None if client.is_some() => (self.extra_client(participant, name), participant), + None => (0, participant), + } + } + + /// A user for a sender with no unique id who is not on the snapshot, + /// made from its client id and put into LIVE with the name the link + /// gave, so that whoever reads the poke or the message can name it. The + /// link hands a client id to whoever connects next: the name follows the + /// sender. + fn extra_client(&mut self, client: u32, name: &str) -> u64 { + let id = ids::synthetic_user(&format!("client:{client}")); + if name.is_empty() { + return id; + } + let user = entities::client_user(id, name, self.cfg.ts6); + if self.extras.get(&id) != Some(&user) { + self.extras.insert(id, user.clone()); + let entity = entity(Kind::User(user)); + if let Some(key) = Key::of(&entity) { + self.live.insert(key, entity.clone()); + self.commit(ScopeId::Live(SERVER_ID), vec![entity], Vec::new()); + } + } + id + } + + /// A user for a unique id the snapshot does not hold, put into LIVE. + 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()); + } + } + id + } + + /// A message of the book: kept per channel, and pushed to the channel's + /// subscribers. + 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); + 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); + } + 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); + } + + /// Remember a message and push it to its channel's subscribers. + 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(); + } + let scope = ScopeId::Chat(channel); + self.retry_lagged(); + if self.subs.contains(&scope) && !self.lagged.contains(&scope) { + let change = v1::Change { + scope: Some(scope.to_proto()), + rev, + put: vec![entity(Kind::Message(message))], + del: Vec::new(), + }; + self.push_scope(scope, vec![v1::Push { body: Some(Body::Change(change)) }]); + } + } + + /// 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). + 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), + }; + self.dms.insert(channel, (uid.to_owned(), peer)); + self.refresh_home(); + } + + // ---- answers from the link ------------------------------------------- + + /// The engine has announced the connection: pass on what the stream task + /// reported meanwhile, in its order. + fn announced(&mut self) { + if let Some(held) = self.held.take() { + for event in held.events { + let _ = self.engine_bus.send(event); + } + } + } + + 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)); + // A move that followed this one into the channel we never + // left gets no answer from the link (it swallows "already + // in that channel"): the snapshots' channel answers it. + self.settle_moves(); + } + } + // What the stream task says (its own bus events) goes to the engine. + other => match &mut self.held { + Some(held) => held.events.push(other), + None => { + 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.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.own_client), + user_id: self.own_user_id(), + channel_id: self.own_channel.unwrap_or(0), + slot: entities::slot(self.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(); + // Nobody announced the connection (a session used without an engine): + // the reports are not held for ever. + if self.held.as_ref().is_some_and(|held| held.until <= now) { + self.announced(); + } + // A consumer that lagged may have room again. + self.retry_lagged(); + 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", + ))); + } + } + } + + 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); + let _ = reply.send(answer); + } + Kind::Voice(voice) => { + // Our own flags, as a request that wants its answer. + self.voice_flags(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.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). + 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(); + 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. A move into + /// the channel the snapshots show is answered at once, unless another + /// move is on its way: the snapshot is where we were, not where that move + /// leaves us, so this request goes to the link like any other (the link + /// answers a move into the channel it is in with nothing, which is what + /// [`Driver::settle_moves`] makes up for). + 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); + let moving = self.pending.values().any(|p| matches!(p.waiting, Waiting::Move { .. })); + if first || (!moving && 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, + mut 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 { + // No deadline of ours: how long a transfer may take to start is the + // caller's to say (the engine gives a picture's negotiation 30 s, a + // file the user asked for as long as the server needs). A caller + // that has given up drops `reply`, and the job goes with `rx`. + let opened = tokio::select! { + () = reply.closed() => return, + opened = rx => match opened { + Ok(Ok(opened)) => Ok(opened), + Ok(Err(text)) => Err(rejected(ErrorCode::Unavailable, text)), + Err(_) => Err(rejected(ErrorCode::Unavailable, "the connection ended")), + }, + }; + 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, + mut 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 { + // No deadline of ours, as in `read`. + let opened = tokio::select! { + () = reply.closed() => return, + opened = rx => opened, + }; + let opened = match opened { + Ok(Ok(opened)) => opened, + Ok(Err(text)) => { + let _ = reply.send(Err(rejected(ErrorCode::Unavailable, text))); + return; + } + Err(_) => { + let _ = + reply.send(Err(rejected(ErrorCode::Unavailable, "the connection ended"))); + 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))); + }); + } +} + +/// Whether a `Put` is made of writes to the voice state only (the flags of a +/// fire-and-forget). +fn is_voice_flags(put: &v1::Put) -> bool { + !put.writes.is_empty() + && put + .writes + .iter() + .all(|write| matches!(write.entity, Some(Entity { kind: Some(Kind::Voice(_)) }))) +} + +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/ts_session/entities.rs b/crates/voelin-core/src/ts/ts_session/entities.rs new file mode 100644 index 0000000..512a665 --- /dev/null +++ b/crates/voelin-core/src/ts/ts_session/entities.rs @@ -0,0 +1,537 @@ +//! 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; + // 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). + while let Some(channel) = siblings + .iter() + .filter(|c| c.order == above && !placed.contains(&c.id)) + .min_by_key(|c| c.id) + { + 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, + ) +} + +/// A user who is on no snapshot and has no unique id (the sender of a poke +/// or a message that the link names by its client id only): `id` and name. +pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User { + user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, 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))); + } + // The own client first, then by client id. + let mut clients: Vec<&ClientInfo> = presence.clients.values().collect(); + clients.sort_by_key(|client| (Some(client.id) != own_client, client.id)); + let mut used: HashSet = HashSet::new(); + for client in clients { + // The same identity twice on a server has one database id: the own + // client keeps it (it must stay the user we are, also while a ghost of + // our old connection lingers), else the lower client id; 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)); + } + + /// The own client is the user whose database id the identity has, also when a + /// ghost of the old connection (the lower client id) lingers. + #[test] + fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() { + let client = |id| ClientInfo { + id, + uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()), + nickname: format!("n{id}"), + database_id: Some(77), + ..Default::default() + }; + let mut presence = Presence::default(); + for c in [client(3), client(4)] { + presence.clients.insert(c.id, c); + } + let user_of = |built: &Built, client: u32| { + let key = Key::Voice { server_id: SERVER_ID, participant_id: client }; + let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else { + panic!("no voice state") + }; + voice.user_id + }; + // Nobody is us: the lower client id keeps it. + let built = build(&presence, false, None); + assert_eq!(user_of(&built, 3), 77); + assert_ne!(user_of(&built, 4), 77); + // The later client is us: it keeps it, and the ghost has the made-up id. + let built = build(&presence, false, Some(4)); + assert_eq!(user_of(&built, 4), 77); + assert_ne!(user_of(&built, 3), 77); + assert_eq!(built.own_user.map(|u| u.id), Some(77)); + assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4)); + } + + #[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/ts_session/ids.rs b/crates/voelin-core/src/ts/ts_session/ids.rs new file mode 100644 index 0000000..fd67627 --- /dev/null +++ b/crates/voelin-core/src/ts/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/ts_session/live_tests.rs b/crates/voelin-core/src/ts/ts_session/live_tests.rs new file mode 100644 index 0000000..87966e7 --- /dev/null +++ b/crates/voelin-core/src/ts/ts_session/live_tests.rs @@ -0,0 +1,862 @@ +//! The TeamSpeak `Session` against the development servers +//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16). +//! Runs only with `VOELIN_LIVE=1`: +//! +//! ```text +//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1 +//! ``` +//! +//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6: +//! +//! - the link conformance suite of the protocol repository, the cases that +//! apply to a TeamSpeak session, with the verdict of every case asserted +//! and the reason of every case that cannot pass or cannot run in +//! [`EXPECTED`]; +//! - what the suite cannot reach, as a session of its own does it: a message +//! in the own channel answered, then pushed to the other session and back to +//! ours, the refusals of a move, a poke between two sessions, voice RTP from +//! one session's slot to the other's media sink, and a channel file written +//! and read back from an offset. +//! +//! The sessions are made by [`TsConnector`] through the plain `Connector` +//! interface, as a client of the seam outside an engine would make them. +//! +//! The servers ban an address that connects as often as these tests do +//! (`ConnectFailedBanned` after three or four connections) unless their +//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it +//! prepares its admin identity; this module raises them itself, once per server +//! and run, through the ServerQuery admin login that `refused_moves` uses +//! ([`raise_flood_limits`]), so that the command above works on a freshly +//! started stack. It needs that login (the development servers of +//! `dev/docker-compose.yml` have it) and does not lower the limits again. + +use std::collections::BTreeMap; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::mpsc; +use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub}; +use voelin_proto::media::payload::PT_OPUS; +use voelin_proto::media::{RtpHeader, RtpView}; +use voelin_proto::test_util::conformance::{self, Fixture, Verdict}; +use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel}; +use voelin_proto::v1::request::Op; +use voelin_proto::v1::{self, entity::Kind}; + +use super::*; +use crate::link::{Backends, VoiceOptions, connect_params}; + +fn live() -> bool { + std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1") +} + +/// How long a test waits for the server. +const WAIT: Duration = Duration::from_secs(20); + +async fn within(what: &str, future: impl Future) -> T { + match tokio::time::timeout(WAIT, future).await { + Ok(value) => value, + Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"), + } +} + +/// A development server: where to connect, and how to ask it as the admin. +#[derive(Clone, Copy)] +struct Dev { + name: &'static str, + voice: &'static str, + ssh: bool, + query: &'static str, +} + +const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" }; +const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" }; + +impl Dev { + fn query(&self) -> voelin_query::Connect { + voelin_query::Connect { + transport: if self.ssh { + voelin_query::Transport::Ssh + } else { + voelin_query::Transport::Raw + }, + addr: self.query.into(), + user: "serveradmin".into(), + secret: Some("voelin-dev-admin".into()), + server_port: Some(9987), + server_id: None, + line: voelin_query::LineOptions { rate_limit: None, ..Default::default() }, + } + } + + /// A nickname no other client of this run has. + fn nick(&self, role: &str) -> String { + static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = COUNT.fetch_add(1, Ordering::Relaxed); + format!("{role}-{}-{n}", std::process::id() % 10_000) + } +} + +/// Raise the anti-flood limits of a development server, once per run, and +/// lift the bans an earlier run left behind. The tests connect many times in +/// a few seconds from one address, which a server with its default limits +/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two +/// values in `admin_args`. Done through the ServerQuery login of the admin, +/// which the tests that create channels and keys use as well. +async fn raise_flood_limits(dev: &Dev) { + use tokio::sync::OnceCell; + use voelin_query::{Command as Query, QueryClient}; + static TS3_READY: OnceCell<()> = OnceCell::const_new(); + static TS6_READY: OnceCell<()> = OnceCell::const_new(); + let ready = if dev.ssh { &TS6_READY } else { &TS3_READY }; + ready + .get_or_init(|| async { + let (admin, _) = within("the query login", QueryClient::connect(&dev.query())) + .await + .unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name)); + for key in [ + "virtualserver_antiflood_points_needed_ip_block", + "virtualserver_antiflood_points_needed_command_block", + ] { + let edit = Query::new("serveredit").arg(key, 100_000); + within("the anti-flood limits", admin.send(&edit)) + .await + .unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name)); + } + // A ban of an earlier run outlives the change of the limit. + within("the ban list", admin.send(&Query::new("bandelall"))) + .await + .unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name)); + }) + .await; +} + +/// A TeamSpeak session as a client of the seam sees it: made by the +/// connector, with its push channel and media sink. +async fn session( + dev: &Dev, + options: &VoiceOptions, +) -> (Arc, mpsc::Receiver, MediaReceiver) { + raise_flood_limits(dev).await; + let (sink, media) = media_channel(); + let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters"); + let connected = + within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params)) + .await + .unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name)); + (connected.session, connected.pushes, media) +} + +/// A client of the TeamSpeak session that has done what an engine does after +/// it connects (`docs/session-seam.md` 4.2, without the replica): the server +/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice. +struct Client { + session: Arc, + pushes: mpsc::Receiver, + media: MediaReceiver, + server: u64, + default_channel: u64, + /// Our seat in voice (participant, slot, channel). + seat: v1::VoiceState, + /// The voice states of the server, as the pushes told them. + voices: BTreeMap, +} + +fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope { + v1::Scope { kind: kind as i32, id } +} + +impl Client { + async fn connect(dev: &Dev, nick: &str) -> Self { + Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await + } + + async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self { + let (session, pushes, media) = session(dev, &options).await; + let mut client = Self { + session, + pushes, + media, + server: 0, + default_channel: 0, + seat: v1::VoiceState::default(), + voices: BTreeMap::new(), + }; + let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() }); + let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else { + panic!("the server list is not entities") + }; + let server = servers + .items + .iter() + .find_map(|e| match &e.kind { + Some(Kind::Server(server)) => Some(server.clone()), + _ => None, + }) + .expect("the host lists its server"); + client.server = server.id; + client.default_channel = server.default_channel_id; + for scope in [ + scope(v1::ScopeKind::Home, 0), + scope(v1::ScopeKind::Server, server.id), + scope(v1::ScopeKind::Live, server.id), + ] { + client.subscribe(scope).await; + } + client.seat = client.join(client.default_channel, "").await.expect("a seat in voice"); + client.settle().await; + client + } + + /// A request, answered within [`WAIT`]. + async fn ask(&self, op: Op) -> Result { + within("an answer", self.session.request(op)).await + } + + /// Subscribe `scope` and take its sync off the push channel. + async fn subscribe(&mut self, scope: v1::Scope) { + let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() }); + self.ask(op).await.expect("a subscription"); + self.until("the end of the sync", |push| match &push.body { + Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()), + _ => None, + }) + .await; + } + + /// `JoinVoice`: our seat, or why not. + async fn join(&self, channel: u64, password: &str) -> Result { + let join = v1::JoinVoice { + server_id: self.server, + channel_id: channel, + password: password.into(), + ..Default::default() + }; + match self.ask(Op::JoinVoice(join)).await? { + Answer::Entities(entities) => entities + .items + .into_iter() + .find_map(|e| match e.kind { + Some(Kind::Voice(voice)) => Some(voice), + _ => None, + }) + .ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())), + other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))), + } + } + + /// Keep track of what a push says about the server and its voice states. + fn absorb(&mut self, push: &v1::Push) { + let Some(v1::push::Body::Change(change)) = &push.body else { return }; + for entity in &change.put { + match &entity.kind { + Some(Kind::Voice(voice)) => { + self.voices.insert(voice.participant_id, voice.clone()); + } + Some(Kind::Server(server)) if server.default_channel_id != 0 => { + self.default_channel = server.default_channel_id; + } + _ => {} + } + } + for entity in &change.del { + if let Some(Kind::Voice(voice)) = &entity.kind { + self.voices.remove(&voice.participant_id); + } + } + } + + /// The next push `f` picks, skipping (and keeping track of) the others. + async fn until(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option) -> T { + within(what, async { + loop { + let push = self.pushes.recv().await.expect("the session lives"); + self.absorb(&push); + if let Some(t) = f(&push) { + return t; + } + } + }) + .await + } + + /// Wait until the host shows our seat in LIVE: the first snapshot of the + /// TeamSpeak link may come after the session was handed out, so the syncs + /// can be empty and the voice states follow as changes. The seat then + /// names the channel we are in. + async fn settle(&mut self) { + let participant = self.seat.participant_id; + within("our voice state to appear", async { + while !self.voices.contains_key(&participant) { + let push = self.pushes.recv().await.expect("the session lives"); + self.absorb(&push); + } + }) + .await; + self.seat = self.voices[&participant].clone(); + } + + /// The next message `Change` of the CHAT scope of `channel` with `text`. + async fn message(&mut self, channel: u64, text: &str) -> v1::Message { + let chat = Some(scope(v1::ScopeKind::Chat, channel)); + self.until(&format!("the message {text:?}"), |push| match &push.body { + Some(v1::push::Body::Change(change)) if change.scope == chat => { + change.put.iter().find_map(|e| match &e.kind { + Some(Kind::Message(message)) if message.text == text => Some(message.clone()), + _ => None, + }) + } + _ => None, + }) + .await + } + + async fn close(self) { + self.session.close(v1::CloseCode::Normal, ""); + within("the session to close", self.session.closed()).await; + } +} + +// ---- the conformance suite ---------------------------------------------------- + +/// What a case is expected to do against a TeamSpeak session, and why. +enum Expect { + /// Every assertion of the case holds. + Passes, + /// The session lacks the feature the case needs (`Verdict::Skipped`). + Skipped(&'static str), + /// The case does not apply: it cannot run, or cannot pass, for this reason + /// (`cases_that_do_not_apply_fail` runs them and watches them fail). + NotRun(&'static str), +} +use Expect::{NotRun, Passes, Skipped}; + +/// Every case of the suite of the protocol repository at `c8e0e5a`, in its +/// order, with what a TeamSpeak session does with it. A case the suite gains +/// fails `the_suite_is_known` until it is listed here. +/// +/// The suite is written for a backend that is a `FakeHost`. A case that needs +/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases +/// that hold, kill or read it, or push into it, cannot run against a session of +/// a TeamSpeak server; the others write to places a TeamSpeak server does not +/// have (the suite's channels, a server with another id, `ScheduledEvent`, +/// `Emoji`, attachments). Each reason is what the case did when it was run. +const EXPECTED: [(&str, Expect); 17] = [ + ("welcome_matches_features", Passes), + ( + "subscribe_syncs_the_scope", + NotRun("writes to channel 4001: rejected (NotFound) no such channel"), + ), + ( + "subscribe_resumes_from_a_cursor", + NotRun("writes to channel 4002: rejected (NotFound) no such channel"), + ), + ( + "put_answers_entities_and_pushes_the_change_with_the_same_rev", + NotRun("writes to channel 4003: rejected (NotFound) no such channel"), + ), + ( + "delete_answers_an_ack_and_pushes_the_removal", + NotRun( + "writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \ + where the case needs only `chat`, not `chat.delete` (P8)", + ), + ), + ( + "a_key_names_an_entity_without_its_server", + NotRun( + "rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \ + which TeamSpeak lacks, though it needs no feature (P8)", + ), + ), + ("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")), + ("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")), + ("list_pages_history", Skipped("chat.history")), + ( + "cancel_before_apply_is_cancelled", + NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""), + ), + ("idempotency_keys_apply_a_put_once", Skipped("idempotency")), + ( + "notifications_are_fire_and_forget", + NotRun("reads the request log of the unrelated fake host: the notification never arrives"), + ), + ( + "renew_account_follows_the_feature", + NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"), + ), + ( + "media_loops_back", + NotRun( + "a TeamSpeak server does not return a client's own voice: the packet never loops back", + ), + ), + ( + "files_round_trip", + NotRun( + "writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \ + TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)", + ), + ), + ("close_ends_the_session", Passes), + ( + "the_backend_can_end_the_session", + NotRun( + "kills the unrelated fake session, so closed() of this one never resolves; and a \ + kick is Network(text), not Remote{KICKED}, until H1", + ), + ), +]; + +/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the +/// backend behind the session; a TeamSpeak server has none, so it gets the one +/// of an unrelated fake host, which the cases that are run never touch. +async fn fixture(dev: Dev) -> Fixture { + let (session, pushes, media) = + session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await; + let unrelated = FakeConnector::new(); + let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated"); + unrelated.connect(params).await.expect("a fake session"); + let backend = unrelated.last_session().expect("a fake session"); + Fixture::new(session, pushes, media, backend) +} + +fn the_suite_is_known() { + let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect(); + let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect(); + assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED"); +} + +/// The cases that apply run and pass, the ones that need a feature the session +/// lacks are skipped, and the rest are not run (their reason is in +/// [`EXPECTED`]). +async fn conformance_subset(dev: Dev) { + the_suite_is_known(); + let harness = move || fixture(dev); + let (mut passed, mut skipped) = (0, 0); + for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) { + match expect { + Passes => { + let verdict = conformance::run_case(&harness, case).await; + assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name); + passed += 1; + } + Skipped(feature) => { + let verdict = conformance::run_case(&harness, case).await; + assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name); + skipped += 1; + } + NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name), + } + } + assert_eq!((passed, skipped), (2, 4)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_conformance_subset() { + if live() { + conformance_subset(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_conformance_subset() { + if live() { + conformance_subset(TS6).await; + } +} + +// ---- what the suite cannot reach ---------------------------------------------- + +/// A message in the own channel is answered with the message as written, and +/// pushed to the CHAT scope of every session in the channel: to the other one +/// as a `Change`, and back to ours (the ids agree only with the native +/// session of H1: the answer has a local id, the echo the one of the +/// `Change`). +async fn chat_in_the_own_channel(dev: Dev) { + let mut a = Client::connect(&dev, &dev.nick("chat-a")).await; + let mut b = Client::connect(&dev, &dev.nick("chat-b")).await; + assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel"); + let channel = a.seat.channel_id; + a.subscribe(scope(v1::ScopeKind::Chat, channel)).await; + b.subscribe(scope(v1::ScopeKind::Chat, channel)).await; + + let text = format!("live-chat-{}", std::process::id()); + let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() }; + let write = v1::Write { + entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }), + paths: Vec::new(), + }; + let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() }); + let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else { + panic!("a message is answered with entities") + }; + let written = match &answer.items[..] { + [v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(), + other => panic!("one message expected, got {other:?}"), + }; + assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str())); + + let heard = b.message(channel, &text).await; + assert_ne!(heard.id, 0); + assert_eq!(heard.channel_id, channel); + // And ours, back from the server: the same words, once. + let echo = a.message(channel, &text).await; + assert_ne!(echo.id, 0); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_chat_in_the_own_channel() { + if live() { + chat_in_the_own_channel(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_chat_in_the_own_channel() { + if live() { + chat_in_the_own_channel(TS6).await; + } +} + +/// A move into a channel with a password or without room is refused with the +/// code the seam names: `PASSWORD` and `FULL`. +async fn refused_moves(dev: Dev) { + use voelin_query::{Command as Query, QueryClient}; + let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login"); + let tag = std::process::id() % 10_000; + let create = |name: &str| { + Query::new("channelcreate") + .arg("channel_name", format!("{name}-{tag}")) + .arg("channel_flag_semi_permanent", 1) + }; + let locked = + admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0] + .parse::("cid") + .unwrap(); + let full = create("seam-full") + .arg("channel_maxclients", 0) + .arg("channel_flag_maxclients_unlimited", 0); + let full = admin.send(&full).await.unwrap()[0].parse::("cid").unwrap(); + // A key for the Normal group, which has to keep to passwords and limits. + let token = group_token(&admin, "Normal").await; + + let check = { + let token = token.clone(); + tokio::spawn(async move { + let mut options = VoiceOptions::new(dev.voice, dev.nick("moves")); + options.token = Some(token); + let client = Client::connect_with(&dev, options).await; + let code = |result: Result| match result { + Err(SessionError::Rejected(error)) => error.code(), + other => panic!("expected a refusal, got {other:?}"), + }; + assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password); + assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password); + let seat = client.join(locked, "secret").await.expect("the right password"); + assert_eq!(seat.channel_id, locked); + assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full); + client.close().await; + }) + }; + let result = check.await; + // Clean up before reporting a failure; the key is gone once used. + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + for cid in [locked, full] { + admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap(); + } + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_refused_moves() { + if live() { + refused_moves(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_refused_moves() { + if live() { + refused_moves(TS6).await; + } +} + +/// A poke is a `Signal` to a participant: the other session gets it, with +/// the participant and the words of the sender. +async fn poke_between_sessions(dev: Dev) { + let a = Client::connect(&dev, &dev.nick("poke-a")).await; + let mut b = Client::connect(&dev, &dev.nick("poke-b")).await; + let text = format!("live-poke-{}", std::process::id()); + let target = v1::SignalTarget { + server_id: a.server, + participant_id: b.seat.participant_id, + ..Default::default() + }; + let signal = v1::Signal { + to: Some(target), + body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })), + ..Default::default() + }; + a.ask(Op::Signal(signal)).await.expect("the poke is accepted"); + let from = b + .until("the poke", |push| match &push.body { + Some(v1::push::Body::Signal(signal)) => match &signal.body { + Some(v1::signal::Body::Poke(poke)) if poke.message == text => { + Some(signal.from_participant) + } + _ => None, + }, + _ => None, + }) + .await; + assert_eq!(from, a.seat.participant_id); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_poke_between_sessions() { + if live() { + poke_between_sessions(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_poke_between_sessions() { + if live() { + poke_between_sessions(TS6).await; + } +} + +/// One frame of Opus (20 ms, mono, fullband). +const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe]; + +fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket { + let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960); + header.marker = marker; + let mut out = bytes::BytesMut::new(); + header.write(flow, &mut out).expect("a header"); + out.extend_from_slice(payload); + MediaPacket { flow, rtp: out.freeze() } +} + +/// Voice sent on our slot arrives on the sender's slot at the other session's +/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so +/// it only has to count up), the marker on the first, and an empty payload at +/// the end. +async fn voice_between_sessions(dev: Dev) { + let a = Client::connect(&dev, &dev.nick("voice-a")).await; + let mut b = Client::connect(&dev, &dev.nick("voice-b")).await; + assert_eq!(a.seat.channel_id, b.seat.channel_id); + let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL); + for n in 0..5u8 { + let frame = [0xf8, 0xff, 0xfe, n]; + let packet = rtp(flow, u16::from(n), n == 0, &frame); + a.session.send_media(MediaClass::Voice, packet).expect("our own slot"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end"); + + let mut heard = Vec::new(); + while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await { + let view = RtpView::parse(&packet.rtp).expect("RTP"); + heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec())); + if view.payload().is_empty() { + break; + } + } + assert!(heard.len() >= 2, "{heard:?}"); + assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}"); + let (_, _, first_marker, first_payload) = &heard[0]; + assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}"); + assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}"); + let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end"); + assert!( + end_payload.is_empty() && !*end_marker, + "the spurt ends with an empty payload: {heard:?}" + ); + assert_eq!(*end_flow, flow); + let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect(); + assert!( + sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)), + "the sequence counts up by one: {sequences:?}" + ); + // Voice on a slot that is not ours is refused before it reaches the server. + let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL); + assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err()); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_voice_between_sessions() { + if live() { + voice_between_sessions(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_voice_between_sessions() { + if live() { + voice_between_sessions(TS6).await; + } +} + +/// A channel file written with `write_file` and read back from an offset with +/// `read_file`: the head names the file and its size, the body starts where +/// the offset says. +async fn channel_file_from_an_offset(dev: Dev) { + use voelin_query::{Command as Query, QueryClient}; + // Guests may not upload: a key for the Server Admin group. + let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login"); + let token = group_token(&admin, "Server Admin").await; + let check = tokio::spawn({ + let token = token.clone(); + async move { channel_file_with_a_key(dev, token).await } + }); + let result = check.await; + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +/// A one-time key for the server group `name` (a template group, type 1). +async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String { + use voelin_query::Command as Query; + let groups = admin.send(&Query::new("servergrouplist")).await.unwrap(); + let group = groups + .iter() + .find(|g| g.get("name") == Some(name) && g.get("type") == Some("1")) + .and_then(|g| g.parse::("sgid")) + .unwrap_or_else(|| panic!("a {name} server group")); + let key = + Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0); + admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned() +} + +async fn channel_file_with_a_key(dev: Dev, token: String) { + let mut options = VoiceOptions::new(dev.voice, dev.nick("files")); + options.token = Some(token); + let a = Client::connect_with(&dev, options).await; + let channel = a.seat.channel_id; + let name = format!("seam-{}.bin", std::process::id()); + let path = format!("/{name}"); + let data: Vec = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect(); + let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() }; + + let write = v1::FileWrite { + target: Some(v1::file_write::Target::Path(target.clone())), + size: data.len() as u64, + offset: 0, + overwrite: true, + sha256: Default::default(), + }; + let mut upload = + within("the upload to open", a.session.write_file(write)).await.expect("an upload"); + upload.body.write_all(&data).await.expect("the body"); + upload.body.shutdown().await.expect("the end of the body"); + let stored = within("the server to keep it", upload.done).await.expect("the file is stored"); + assert!( + stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)), + "{stored:?}" + ); + + let read = v1::FileRead { + target: Some(v1::file_read::Target::Path(target.clone())), + offset: 1_000, + length: 0, + }; + let mut download = + within("the download to open", a.session.read_file(read)).await.expect("a download"); + let size = download.head.items.iter().find_map(|e| match &e.kind { + Some(Kind::File(file)) => Some(file.size), + _ => None, + }); + assert_eq!(size, Some(3_000), "{:?}", download.head); + let mut body = Vec::new(); + within("the body", download.body.read_to_end(&mut body)).await.expect("the body"); + assert_eq!(body, data[1_000..], "the body starts at the offset"); + + // Clean up what we put on the server. + let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() }; + let delete = Op::Delete(v1::Delete { + keys: vec![v1::Entity { kind: Some(Kind::File(key)) }], + ..Default::default() + }); + let _ = a.ask(delete).await; + a.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_channel_file_from_an_offset() { + if live() { + channel_file_from_an_offset(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_channel_file_from_an_offset() { + if live() { + channel_file_from_an_offset(TS6).await; + } +} + +// ---- the cases that do not apply ---------------------------------------------- + +/// The cases of [`EXPECTED`] that do not apply fail against a session of a +/// TeamSpeak server, each with a panic of its own (its first line is printed): +/// the reasons of the table are what they did when they were run. A case that +/// passes one day (with the native session of H1) is to be moved to `Passes`. +/// +/// Ignored by default: the cases that wait for a backend that is not there +/// take their three seconds each. +async fn cases_that_do_not_apply_fail(dev: Dev) { + // A case the suite gained is not in `EXPECTED`, and the zip below would leave + // it out without a word. + the_suite_is_known(); + for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) { + let NotRun(reason) = expect else { continue }; + let harness = move || async move { + let mut fixture = fixture(dev).await; + fixture.step = Duration::from_secs(3); + fixture + }; + match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await { + Err(error) if error.is_panic() => { + let payload = error.into_panic(); + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + let first = message.lines().next().unwrap_or_default(); + eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name); + } + other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name), + } + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"] +async fn ts3_cases_that_do_not_apply_fail() { + if live() { + cases_that_do_not_apply_fail(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"] +async fn ts6_cases_that_do_not_apply_fail() { + if live() { + cases_that_do_not_apply_fail(TS6).await; + } +} diff --git a/crates/voelin-core/src/ts/ts_session/media.rs b/crates/voelin-core/src/ts/ts_session/media.rs new file mode 100644 index 0000000..5b4ced4 --- /dev/null +++ b/crates/voelin-core/src/ts/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/ts_session/mod.rs b/crates/voelin-core/src/ts/ts_session/mod.rs new file mode 100644 index 0000000..b586d00 --- /dev/null +++ b/crates/voelin-core/src/ts/ts_session/mod.rs @@ -0,0 +1,855 @@ +//! A TeamSpeak connection as a `voelin_proto::link::Session` +//! (`docs/session-seam.md`, "the TeamSpeak side"). +//! +//! [`LinkSession`] is a `Session` over any [`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 +//! [`inner_options`], the reverse of what the engine's `connect_params` wrote, +//! 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; +#[cfg(test)] +mod live_tests; +mod media; + +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, 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, + LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, 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 super::{ConnectOptions, ServerLink, TsLink, versions}; +use crate::BackendInfo; +use crate::link::{ + BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort, + VERSION_PARAM, +}; + +/// The `Credential::Foreign` kind of a stored TeamSpeak identity. +const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK; +/// 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 options a TeamSpeak link is connected with: the reverse of +/// `link::connect_params`. A client version spec that [`versions::resolve`] +/// refuses fails the connect, in words. +fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result { + let link = match Link::parse(¶ms.address) { + Some(Link::Server(link)) => link, + _ => { + // Without the query: a channel password rides in it. + let shown = crate::link::without_query(¶ms.address); + return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}"))); + } + }; + 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 spec = params + .address + .split_once('?') + .and_then(|(_, query)| { + query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}="))) + }) + .map(|text| { + URL_SAFE_NO_PAD + .decode(text) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .ok_or_else(|| SessionError::Protocol("the client version cannot be read".into())) + }) + .transpose()?; + let client_version = match spec { + None => None, + Some(spec) => versions::resolve(&spec).map_err(|e| { + SessionError::Protocol(format!("invalid client compatibility version: {e}")) + })?, + }; + 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>, + /// The media slot of our client; the driver changes it when we are another + /// client after TeamSpeak's own reconnect. + own_slot: Arc, +} + +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> { + // Only an op of the control stream can go without an answer: a Hello is + // part of connecting, and a List and the file transfers have streams + // (and answers) of their own. + match placement(&op) { + Placement::Control => {} + Placement::Invalid => { + return Err(SessionError::Protocol("a Hello is part of connecting".into())); + } + Placement::OwnStream => { + return Err(SessionError::Protocol( + "a List and the file transfers have a stream and an answer of their own, \ + they cannot be sent without one" + .into(), + )); + } + } + // The task may be on its way out and not have dropped its queue yet. + if self.closed.borrow().is_some() { + return Err(SessionError::Closed(closed_reason(&self.closed))); + } + 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.load(Ordering::Relaxed) + || 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. + #[cfg(test)] + 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`: a `LinkSession` over a `TsLink` for every connection. +/// +/// Clones share one account: the main myTeamSpeak account that every +/// connection of the connector presents ([`TsConnector::set_myts_identity`], +/// [`TsConnector::set_myts_data`]), also those made before it was set. +/// Register a connector in the engine's registry with +/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and +/// keep a clone to set the account. +#[derive(Clone)] +pub struct TsConnector { + connector: LinkConnector, + link: Arc, +} + +impl Default for TsConnector { + fn default() -> Self { + Self::new() + } +} + +impl TsConnector { + /// A connector that presents no account until it is given one. + pub fn new() -> Self { + let link = Arc::new(TsLink::new()); + Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link } + } + + /// The main account's proof for every current and future connection of + /// this connector (and its clones): a myTS ID signed with the account's + /// key. Connections that are up show the server the new proof, and those + /// that connect later present it from the start; `None` is a sign-out. + pub fn set_myts_identity(&self, identity: Option>) { + self.link.account().set_identity(identity); + } + + /// What servers are shown of the main account: its avatar and badges with + /// their certificates, its User Tag (TeamSpeak 6). It is sent to every + /// connection that presents the account's myTS ID, once connected and when + /// it changes; cleared on a sign-out (`None`). + pub fn set_myts_data(&self, data: Option>) { + self.link.account().set_data(data); + } +} + +impl Connector for TsConnector { + fn schemes(&self) -> &'static [&'static str] { + self.connector.schemes() + } + + fn connect(&self, params: ConnectParams) -> BoxFuture> { + self.connector.connect(params) + } +} + +impl LocalConnector for TsConnector { + fn connect_local( + &self, + params: ConnectParams, + ctx: LocalCtx, + ) -> BoxFuture> { + self.connector.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, + // HOME, SERVER and LIVE, and the chats. + max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3, + 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 own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client))); + 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, + own_slot: own_slot.clone(), + 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, + }; + 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::*; + use crate::link::{Backends, VoiceOptions, connect_params}; + use voelin_proto::link::IssuerTrust; + + fn params(options: &VoiceOptions) -> ConnectParams { + let (media, _rx) = voelin_proto::test_util::media_channel(); + connect_params(options, media, &Backends::empty()).unwrap() + } + + fn back(options: &VoiceOptions) -> ConnectOptions { + inner_options(¶ms(options), &LocalCtx::standalone()).unwrap() + } + + #[test] + fn the_options_of_a_bookmark_come_back_as_they_went() { + let mut options = VoiceOptions::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()); + let identity = tsclientlib::Identity::create(); + options.identity = Some(crate::ts::identity::to_blob(&identity)); + // A spec the user can give; the connector resolves it. + options.client_version = Some("generic".into()); + 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, versions::resolve("generic").unwrap()); + assert!(got.client_version.is_some()); + // The identity is the same key and counters. + let b = got.identity.as_ref().unwrap(); + assert_eq!(serde_json::to_value(&identity).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 = VoiceOptions::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 = VoiceOptions::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 = VoiceOptions::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(&VoiceOptions::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(&VoiceOptions::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(&VoiceOptions::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(&VoiceOptions::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); + } + + /// Why `connect_params` refused an address, if it did. + fn refused(address: &str) -> Option { + let (media, _rx) = voelin_proto::test_util::media_channel(); + match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) { + Ok(_) => None, + Err(SessionError::Protocol(text)) => Some(text), + Err(other) => panic!("{address}: {other}"), + } + } + + #[test] + fn a_bookmark_the_link_would_change_is_refused() { + // A port that is no port, in any shape: the link would drop it and the + // connection would go to the default port. + for address in [ + "ts.example.com:99999", + "ts.example.com:65536", + "ts.example.com:0", + "ts.example.com:abc", + "ts.example.com:", + "[::1]:70000", + "[::1]:", + "[::1]x", + ] { + let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted")); + assert!(text.contains("65535") && text.contains(address), "{text}"); + } + // A host the link would cut or decode: a `?` hides the channel behind the + // next one, a `/` or `#` ends the host, a `%` is decoded. + for address in [ + "", + " ", + "ts.example.com?x", + "ts.example.com#x", + "ts.example.com/x", + "a b", + "h%41", + "[::1", + ] { + let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted")); + assert!(text.starts_with("not a server address"), "{text}"); + } + // The text names no query: a link keeps secrets in it. + let text = refused("ts.example.com?password=hunter2").unwrap(); + assert!(!text.contains("hunter2"), "{text}"); + } + + #[test] + fn the_bookmarks_a_server_has_come_back_with_their_channel() { + for (address, host) in [ + ("ts.example.com", "ts.example.com"), + ("ts.example.com:9987", "ts.example.com:9987"), + (" ts.example.com:1 ", "ts.example.com:1"), + ("127.0.0.1:65535", "127.0.0.1:65535"), + ("[::1]:9987", "[::1]:9987"), + // The brackets of a v6 address without a port are the link's to drop; + // the TeamSpeak library reads both forms. + ("[::1]", "::1"), + ("::1", "::1"), + ("2001:db8::1", "2001:db8::1"), + ] { + let mut options = VoiceOptions::new(address, "nick"); + options.channel = Some("Games/Raid".into()); + let got = back(&options); + assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid"))); + } + } + + /// The normalisations of the round trip, listed in `docs/session-seam.md` + /// (13): an empty option is none, and an empty nickname stays empty. + #[test] + fn empty_options_come_back_as_none() { + let mut options = VoiceOptions::new("ts.example.com", ""); + options.server_password = Some(String::new()); + options.channel = Some(String::new()); + options.channel_password = Some(String::new()); + options.token = Some(String::new()); + let got = back(&options); + assert!(got.nickname.is_empty()); + assert!( + got.server_password.is_none() + && got.channel.is_none() + && got.channel_password.is_none() + && got.token.is_none() + ); + } +} diff --git a/crates/voelin-core/src/versions.rs b/crates/voelin-core/src/ts/versions.rs similarity index 98% rename from crates/voelin-core/src/versions.rs rename to crates/voelin-core/src/ts/versions.rs index 76c11b0..98f2be4 100644 --- a/crates/voelin-core/src/versions.rs +++ b/crates/voelin-core/src/ts/versions.rs @@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail}; use base64::prelude::*; use tsclientlib::Version; -const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv"); +const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv"); /// The signed generic version of every platform, tsclientlib's default. const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]"; diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/ts/voice.rs similarity index 86% rename from crates/voelin-core/src/voice.rs rename to crates/voelin-core/src/ts/voice.rs index 729e20c..24fcd9d 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/ts/voice.rs @@ -1,5 +1,5 @@ -//! The TeamSpeak link: a normal client connection ([`crate::TsLink`] runs -//! [`run`]). +//! The TeamSpeak connection: a normal client connection +//! ([`TsLink`](super::ts_link::TsLink) runs [`run`]). //! //! Besides presence, chat, voice and stream signalling it carries what only //! a client connection can do: pokes, file transfer (channel files, @@ -14,14 +14,12 @@ //! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]). use std::collections::{BTreeMap, HashMap}; -use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use base64::Engine as _; use futures::prelude::*; -use tokio::sync::{mpsc, watch}; -use tokio::task::AbortHandle; +use tokio::sync::{mpsc, oneshot, watch}; use tokio::time::{Instant, timeout}; use tracing::{debug, info, warn}; use tsclientlib::events::Event as BookEvent; @@ -36,12 +34,11 @@ use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket}; use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavor}; use voelin_stream::{ClientState, Request, StreamNotification}; -use crate::book::presence_from_book; -use crate::cache; -use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; -use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote}; +use super::book::presence_from_book; +use super::ts_link::{ConnectOptions, Watches}; +use crate::files::{self, FileEntry, RequestId, TransferState}; +use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkCtx, LinkEvent, Remote}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; -use crate::settings::FILES_PROGRESS_MS; use crate::stream::{StreamCmd, StreamHandle, StreamInput}; use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX}; @@ -157,74 +154,39 @@ enum Pending { Quiet, } -/// A transfer the server has not opened yet. +/// A transfer connection the server has not opened yet: the caller wants the +/// connection itself, and does the copying (the engine's `SessionLink` +/// does, with its progress, its limits and its cancel). enum Job { - Download { - transfer: Option, - offset: u64, - sink: Sink, - report: Report, - started: Instant, - }, - Upload { - transfer: Option, - from: PathBuf, - size: u64, - report: Report, - }, + /// [`LinkCmd::OpenRead`]. + OpenRead(oneshot::Sender>), + /// [`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::OpenRead(reply) => { + let _ = reply.send(Err(text)); + } + Job::OpenWrite(reply) => { + let _ = reply.send(Err(text)); + } } } - - fn transfer(&self) -> Option { - match self { - Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer, - } - } -} - -/// 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 - } - }); -} - -/// A user's transfer, for cancelling. -enum Slot { - Waiting(FiletransferHandle), - Running { task: AbortHandle, part: Option, report: Report }, } /// Run a voice connection until it ends or is told to disconnect. pub(crate) async fn run( options: ConnectOptions, ctx: LinkCtx, + account: Watches, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - let reason = match run_inner(&options, ctx, &mut commands, &events).await { + let reason = match run_inner(&options, ctx, account, &mut commands, &events).await { Ok(()) => None, Err(e) => Some(e.to_string()), }; @@ -254,13 +216,14 @@ impl Drop for ConnectionStreams { struct Voice { con: Connection, link: LinkCtx, + /// The account this connection presents (and keeps open). + account: Watches, events: mpsc::UnboundedSender, server_uid: String, /// Who is talking: last voice packet per client. talking: HashMap, pending: HashMap, jobs: HashMap, - transfers: HashMap, /// `updatemytsdata` is to be sent once connected again: a reconnect /// (tsclientlib's own) leaves the server without it. myts_data_due: bool, @@ -276,17 +239,18 @@ struct Voice { async fn run_inner( options: &ConnectOptions, link: LinkCtx, + account: Watches, commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { let version = match &options.client_version { Some(version) => version.clone(), - None => crate::versions::native_version()?, + None => super::versions::native_version()?, }; let mut builder = Connection::build(options.address.clone()) .name(options.nickname.clone()) .version(version) - .metadata(crate::versions::client_metadata()); + .metadata(super::versions::client_metadata()); if let Some(identity) = &options.identity { builder = builder.identity(identity.clone()); } @@ -302,8 +266,8 @@ async fn run_inner( if let Some(token) = &options.token { builder = builder.default_token(token.clone()); } - let mut identity = link.myts_identity.clone(); - let mut data = link.myts_data.clone(); + let mut identity = account.identity.clone(); + let mut data = account.data.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. let mut con = timeout(Duration::from_secs(30), async { @@ -385,12 +349,12 @@ async fn run_inner( let mut voice = Voice { con, link, + account, events: events.clone(), server_uid, talking: HashMap::new(), pending: HashMap::new(), jobs: HashMap::new(), - transfers: HashMap::new(), myts_data_due: false, myts_shown: tsclientlib::MytsData::default(), streams, @@ -468,7 +432,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?; @@ -552,7 +516,6 @@ impl Voice { } fn tick(&mut self) { - expire_image_jobs(&mut self.jobs, Instant::now()); let events = &self.events; self.talking.retain(|client, last| { let active = last.elapsed() < Duration::from_millis(400); @@ -563,10 +526,6 @@ impl Voice { }); } - fn progress_every(&self) -> Duration { - Duration::from_millis(self.link.settings.current().get(&FILES_PROGRESS_MS).into()) - } - fn item(&mut self, item: StreamItem) -> anyhow::Result<()> { match item { StreamItem::BookEvents(book_events) => { @@ -605,60 +564,25 @@ impl Voice { } } } + // The server opened a transfer connection: the caller that asked for it + // gets the connection itself. StreamItem::FileDownload(handle, download) => { - if let Some(Job::Download { transfer, offset, sink, report, .. }) = - self.jobs.remove(&handle) + if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_))) + && let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle) { - // Pictures (avatars, icons, banners): bounded like the - // banners on the web, the user's own files are not. - if transfer.is_none() && download.size > cache::MAX_PICTURE_BYTES { - let limit = cache::MAX_PICTURE_BYTES >> 20; - report(TransferState::Failed(format!("larger than {limit} MiB"))); - return Ok(()); - } - let part = sink.part().map(ToOwned::to_owned); - let progress = self.progress_every(); - let task_report = report.clone(); - let deadline = image_download_time(download.size); - let task = tokio::spawn(async move { - let receive = files::download( - download.stream, - download.size, - offset, - sink, - progress, - task_report.clone(), - ); - if transfer.is_some() { - receive.await; - } else if timeout(deadline, receive).await.is_err() { - task_report(TransferState::Failed("image download timed out".into())); - } - }); - self.running(transfer, task.abort_handle(), part, report); + let _ = reply.send(Ok((download.size, Box::pin(download.stream)))); } } StreamItem::FileUpload(handle, upload) => { - if let Some(Job::Upload { transfer, from, size, report }) = - self.jobs.remove(&handle) + if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_))) + && let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle) { - let task = tokio::spawn(files::upload( - upload.stream, - from, - size, - upload.seek_position, - self.progress_every(), - report.clone(), - )); - self.running(transfer, task.abort_handle(), None, report); + let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream)))); } } StreamItem::FiletransferFailed(handle, error) => { if let Some(job) = self.jobs.remove(&handle) { - 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) => { @@ -672,22 +596,6 @@ impl Voice { Ok(()) } - fn running( - &mut self, - transfer: Option, - task: AbortHandle, - part: Option, - report: Report, - ) { - self.transfers.retain(|_, slot| match slot { - Slot::Running { task, .. } => !task.is_finished(), - Slot::Waiting(_) => true, - }); - if let Some(id) = transfer { - self.transfers.insert(id, Slot::Running { task, part, report }); - } - } - /// A chat message or poke from the book. fn message(&self, target: &MessageTarget, invoker: &tsclientlib::Invoker, text: &str) { let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string()); @@ -868,8 +776,8 @@ impl Voice { /// gave, when it is for the myTS ID this connection presents; nothing /// without one (signed out). fn myts_wanted(&self) -> tsclientlib::MytsData { - let identity = self.link.myts_identity.borrow(); - let data = self.link.myts_data.borrow(); + let identity = self.account.identity.borrow(); + let data = self.account.data.borrow(); match (identity.as_deref(), data.as_deref()) { (Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(), _ => tsclientlib::MytsData::default(), @@ -1069,72 +977,40 @@ impl Voice { Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() }; self.send(cmd, pending)?; } - LinkCmd::Download { transfer, file, sink, report } => { - let offset = sink.offset(); + 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); - let handle = match self.con.download_file(channel, &file.path, password, seek) { - Ok(handle) => handle, + match self.con.download_file(channel, &file.path, password, seek) { + Ok(handle) => { + self.jobs.insert(handle, Job::OpenRead(reply)); + } Err(e) => { - report(TransferState::Failed(e.to_string())); - return Ok(()); + let _ = reply.send(Err(e.to_string())); } - }; - report(TransferState::Requested); - self.jobs.insert( - handle, - Job::Download { transfer, offset, sink, report, started: Instant::now() }, - ); - if let Some(id) = transfer { - self.transfers.insert(id, Slot::Waiting(handle)); } } - LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => { - let size = match std::fs::metadata(&from) { - Ok(m) if m.is_file() => m.len(), - Ok(_) => { - report(TransferState::Failed(format!("{} is not a file", from.display()))); - return Ok(()); - } - Err(e) => { - report(TransferState::Failed(format!("{}: {e}", from.display()))); - return Ok(()); - } - }; + LinkCmd::OpenWrite { file, size, overwrite, resume, reply } => { let password = file.password.as_deref().filter(|p| !p.is_empty()); let channel = tsclientlib::ChannelId(file.channel); - let handle = match self - .con - .upload_file(channel, &file.path, password, size, overwrite, resume) - { - Ok(handle) => handle, + match self.con.upload_file(channel, &file.path, password, size, overwrite, resume) { + Ok(handle) => { + self.jobs.insert(handle, Job::OpenWrite(reply)); + } Err(e) => { - report(TransferState::Failed(e.to_string())); - return Ok(()); + let _ = reply.send(Err(e.to_string())); } - }; - report(TransferState::Requested); - self.jobs.insert(handle, Job::Upload { transfer, from, size, report }); - if let Some(id) = transfer { - self.transfers.insert(id, Slot::Waiting(handle)); } } - LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) { - Some(Slot::Waiting(handle)) => { - if let Some(job) = self.jobs.remove(&handle) { - job.report()(TransferState::Cancelled); - } - } - Some(Slot::Running { task, part, report }) if !task.is_finished() => { - task.abort(); - if let Some(part) = part { - let _ = std::fs::remove_file(part); - } - report(TransferState::Cancelled); - } - _ => debug!(id, "cancel: no such transfer (finished?)"), - }, + // SessionLink copies the bytes itself, over the connections OpenRead and + // OpenWrite open (`docs/session-seam.md` section 8): this link is never + // given a transfer to run. One that is given anyway fails (its report + // is the answer), and the connection, which other things ride on, goes + // on; there is nothing to cancel. + LinkCmd::Download { report, .. } | LinkCmd::Upload { report, .. } => { + report(TransferState::Failed("this link does not run transfers itself".into())); + } + LinkCmd::CancelTransfer(id) => debug!(transfer = id, "no transfer runs on this link"), LinkCmd::DeleteFiles { request, channel, password, paths } => { let cpw = encode_password(password.as_deref()); let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart { @@ -1499,52 +1375,6 @@ mod poke_tests { } } -#[cfg(test)] -mod image_download_tests { - use super::*; - use std::sync::{Arc, Mutex}; - - #[test] - fn stalled_image_handshake_expires_but_user_transfer_does_not() { - let started = Instant::now(); - let reports = Arc::new(Mutex::new(Vec::new())); - let sink = reports.clone(); - let report: Report = Arc::new(move |state| sink.lock().unwrap().push(state)); - let mut jobs = HashMap::new(); - for (id, transfer) in [(1, None), (2, Some(77))] { - jobs.insert( - FiletransferHandle(id), - Job::Download { - transfer, - offset: 0, - sink: Sink::Memory, - report: report.clone(), - started, - }, - ); - } - expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1)); - assert_eq!(jobs.len(), 2); - assert!(reports.lock().unwrap().is_empty()); - expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION); - assert_eq!(jobs.len(), 1); - assert!(jobs.contains_key(&FiletransferHandle(2))); - assert!( - matches!(&reports.lock().unwrap()[..], [TransferState::Failed(error)] if error.contains("timed out")) - ); - expire_image_jobs(&mut jobs, started + Duration::from_secs(60)); - assert_eq!(reports.lock().unwrap().len(), 1); - } - - #[test] - fn large_pictures_get_time_to_arrive() { - assert_eq!(image_download_time(0), Duration::from_secs(60)); - assert_eq!(image_download_time(100 << 10), Duration::from_secs(72)); - // The largest picture, at the slowest rate allowed. - assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384)); - } -} - #[cfg(test)] mod account_tests { use super::*; @@ -1678,18 +1508,20 @@ mod account_tests { events, frames: broadcast::channel(1).0, settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), - myts_identity: watch::channel(Some(Arc::new(identity))).1, - myts_data: watch::channel(Some(Arc::new(data))).1, }; + let account = Watches::of( + watch::channel(Some(Arc::new(identity))).1, + watch::channel(Some(Arc::new(data))).1, + ); Voice { con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(), link, + account, events: mpsc::unbounded_channel().0, server_uid: String::new(), talking: HashMap::new(), pending: HashMap::new(), jobs: HashMap::new(), - transfers: HashMap::new(), myts_data_due: false, myts_shown: tsclientlib::MytsData::default(), streams: None, @@ -1731,7 +1563,7 @@ mod account_tests { let other = unconnected(&server, account_data(&[2; 33])); assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default()); let mut signed_out = unconnected(&server, account_data(&[1; 33])); - signed_out.link.myts_identity = watch::channel(None).1; + signed_out.account.identity = watch::channel(None).1; assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default()); for voice in [voice, other, signed_out] { timeout(Duration::from_millis(100), shutdown_connection(voice.con)) @@ -1741,6 +1573,46 @@ mod account_tests { } } + /// `SessionLink` copies the bytes of a transfer itself. A transfer command + /// that reaches this link anyway fails that transfer with its report, and + /// not the connection, which every other request of the session rides on. + #[tokio::test] + async fn a_transfer_command_fails_the_transfer_and_not_the_connection() { + let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let mut voice = unconnected(&server, account_data(&[1; 33])); + let states = Arc::new(std::sync::Mutex::new(Vec::new())); + let report: crate::files::Report = { + let states = states.clone(); + Arc::new(move |state| states.lock().unwrap().push(state)) + }; + let file = || Remote { channel: 1, password: None, path: "/a".into() }; + let kept = "the connection goes on"; + voice + .command(LinkCmd::Download { + transfer: Some(1), + file: file(), + sink: crate::files::Sink::Memory, + report: report.clone(), + }) + .expect(kept); + voice + .command(LinkCmd::Upload { + transfer: None, + file: file(), + from: "a".into(), + overwrite: false, + resume: false, + report, + }) + .expect(kept); + // Nothing runs, so there is nothing to cancel and nobody to tell. + voice.command(LinkCmd::CancelTransfer(1)).expect(kept); + let failed = TransferState::Failed("this link does not run transfers itself".into()); + assert_eq!(*states.lock().unwrap(), [failed.clone(), failed]); + assert!(voice.jobs.is_empty() && voice.pending.is_empty()); + timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap(); + } + #[tokio::test] async fn shutdown_never_polls_a_connecting_connection() { let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); @@ -1766,14 +1638,14 @@ mod account_tests { events, frames: broadcast::channel(1).0, settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), - myts_identity: identity, - myts_data: watch::channel(None).1, }; + let watches = Watches::of(identity, watch::channel(None).1); let (_commands, commands) = mpsc::unbounded_channel(); let (events, mut received) = mpsc::unbounded_channel(); let task = tokio::spawn(run( ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"), link, + watches, commands, events, )); diff --git a/crates/voelin-core/src/ts_link.rs b/crates/voelin-core/src/ts_link.rs deleted file mode 100644 index d122cd2..0000000 --- a/crates/voelin-core/src/ts_link.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`]. -//! -//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and -//! runs the connection ([`crate::voice`]) with everything that rides on it: -//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the -//! stream task. Which product the server is (and what it can do) is decided -//! there, from the version it sends, and reported in -//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected). -//! -//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`, -//! `identity.rs`) is TeamSpeak's and leaves this crate together with it: -//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts` -//! of VoelinGateWay. - -use tokio::sync::mpsc; - -use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; -use crate::voice; - -/// Connects to TeamSpeak 3 and 6 servers. The engine's default link. -#[derive(Clone, Copy, Debug, Default)] -pub struct TsLink; - -impl ServerLink for TsLink { - fn spawn( - &self, - options: ConnectOptions, - ctx: LinkCtx, - cmds: mpsc::UnboundedReceiver, - events: mpsc::UnboundedSender, - ) { - tokio::spawn(voice::run(options, ctx, cmds, events)); - } -} diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs index d5f6443..65e37ac 100644 --- a/crates/voelin-core/tests/gateway.rs +++ b/crates/voelin-core/tests/gateway.rs @@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response}; use voelin_core::gateway::{GatewayRequest, GatewayUpdate}; use voelin_core::history::MessageSource; use voelin_core::settings::Settings; +use voelin_core::ts::identity::to_blob; use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState}; use voelin_gateway_proto::{ ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg, @@ -448,7 +449,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) { engine.send(Command::ObserveGateway { session, urls: vec![gw.url.clone()], - identity: Box::new(identity), + identity: Box::new(to_blob(&identity)), }); } @@ -742,7 +743,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() { engine.send(Command::ObserveGateway { session: 3, urls: vec![format!("ws://127.0.0.1:{port}/v1")], - identity: Box::new(tsclientlib::Identity::create()), + identity: Box::new(to_blob(&tsclientlib::Identity::create())), }); // The first attempts fail (the next ones about 1 s, then 2 s later): // still connecting, and the user is told nothing. @@ -819,7 +820,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() { engine.send(Command::ObserveGateway { session: 4, urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()], - identity: Box::new(tsclientlib::Identity::create()), + identity: Box::new(to_blob(&tsclientlib::Identity::create())), }); // Within one round: sooner than the shortest wait after a failed round // (1 s, less 30 %). @@ -904,7 +905,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() { engine.send(Command::ObserveGateway { session, urls: vec![gw.url.clone()], - identity: Box::new(tsclientlib::Identity::create()), + identity: Box::new(to_blob(&tsclientlib::Identity::create())), }); // After the first wait: about 1 s. quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session)) @@ -932,6 +933,45 @@ async fn a_refused_login_ends_observing() { assert_eq!(gw.logins(), 1); } +/// An identity that cannot be read will not be better tomorrow: like a refused +/// login, observing ends, and the gateway is not even asked. +#[tokio::test(flavor = "multi_thread")] +async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() { + let gw = FakeGateway::start().await; + let engine = Engine::start(); + let mut rx = engine.subscribe(); + let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity"); + engine.send(Command::ObserveGateway { + session: 10, + urls: vec![gw.url.clone()], + identity: Box::new(not_an_identity), + }); + wait(&mut rx, "connecting", |e| match e { + Event::State { session: 10, state } if state.observe == ObserveState::Connecting => { + Some(()) + } + _ => None, + }) + .await; + wait(&mut rx, "observing off", |e| match e { + Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()), + _ => None, + }) + .await; + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(gw.logins(), 0); + // The public entry refuses it the same way. + let error = voelin_core::gateway::connect( + &gw.url, + &voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"), + ) + .await + .err() + .expect("a refusal"); + assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}"); + assert_eq!(gw.logins(), 0); +} + /// Selecting the server again while its gateway is still connecting does /// not start it over, and ends the wait for the next attempt. #[tokio::test(flavor = "multi_thread")] @@ -944,7 +984,7 @@ async fn asking_again_while_connecting_tries_at_once() { let ask = || Command::ObserveGateway { session: 9, urls: vec![gw.url.clone()], - identity: Box::new(identity.clone()), + identity: Box::new(to_blob(&identity)), }; engine.send(ask()); // Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s. diff --git a/crates/voelin-core/tests/link_fake.rs b/crates/voelin-core/tests/link_fake.rs deleted file mode 100644 index 101f5af..0000000 --- a/crates/voelin-core/tests/link_fake.rs +++ /dev/null @@ -1,570 +0,0 @@ -//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each -//! connection the test asks for to the test, which plays the server by -//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session -//! gives. Presence, chat, the dedup of a message that comes twice, history -//! and the end of a connection are the session's own behaviour; nothing here -//! needs a TeamSpeak server or a TeamSpeak type. - -use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use tokio::sync::{broadcast, mpsc}; -use voelin_core::history::MessageSource; -use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; -use voelin_core::settings::Settings; -use voelin_core::stream::{StreamCmd, StreamSetup}; -use voelin_core::{ - BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId, - SessionState, Source, VoiceOptions, VoiceState, -}; -use voelin_model::{ - Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, -}; - -/// A connection the session asked the link for. -struct Conn { - options: ConnectOptions, - session: SessionId, - cmds: mpsc::UnboundedReceiver, - events: mpsc::UnboundedSender, -} - -impl Conn { - /// Play `script`, the server's side, in order. - fn play(&self, script: impl IntoIterator) { - for event in script { - self.events.send(event).expect("the session listens"); - } - } - - /// The next command the session gave. - async fn cmd(&mut self) -> LinkCmd { - tokio::time::timeout(Duration::from_secs(10), self.cmds.recv()) - .await - .expect("a command in time") - .expect("the session keeps the connection") - } -} - -/// Hands every connection to the test. -struct FakeLink { - conns: mpsc::UnboundedSender, -} - -impl FakeLink { - fn new() -> (Self, mpsc::UnboundedReceiver) { - let (conns, rx) = mpsc::unbounded_channel(); - (Self { conns }, rx) - } -} - -impl ServerLink for FakeLink { - fn spawn( - &self, - options: ConnectOptions, - ctx: LinkCtx, - cmds: mpsc::UnboundedReceiver, - events: mpsc::UnboundedSender, - ) { - let conn = Conn { options, session: ctx.session(), cmds, events }; - let _ = self.conns.send(conn); - } -} - -const SESSION: SessionId = 1; -const SERVER_UID: &str = "fake-server="; -const ME: u16 = 7; -const ME_UID: &str = "me="; -const LOBBY: ChannelId = 1; -const GAMES: ChannelId = 2; - -struct Harness { - engine: Engine, - events: broadcast::Receiver, - conns: mpsc::UnboundedReceiver, -} - -impl Harness { - fn start() -> Self { - let (link, conns) = FakeLink::new(); - let engine = - Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link)); - let events = engine.subscribe(); - Self { engine, events, conns } - } - - /// Ask for a voice connection and take it from the link. - async fn connect(&mut self) -> Conn { - let options = VoiceOptions::new("fake.test:9987", "tester"); - self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); - tokio::time::timeout(Duration::from_secs(10), self.conns.recv()) - .await - .expect("the session spawns the link") - .expect("the link lives") - } - - /// The next event `f` picks, skipping the others. - async fn next(&mut self, mut f: impl FnMut(Event) -> Option) -> T { - tokio::time::timeout(Duration::from_secs(10), async { - loop { - if let Some(t) = f(self.events.recv().await.expect("engine events")) { - return t; - } - } - }) - .await - .expect("event in time") - } - - /// The next state of the session that `ok` accepts. - async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState { - self.next(|e| match e { - Event::State { state, .. } if ok(&state) => Some(state), - _ => None, - }) - .await - } - - /// The next live chat message. - async fn chat(&mut self) -> ChatMessage { - self.next(|e| match e { - Event::Chat { message, .. } => Some(message), - _ => None, - }) - .await - } - - /// The messages stored for `target`, oldest first. - async fn stored(&self, target: ChatTarget) -> Vec { - self.engine - .history() - .page(SERVER_UID, &target, Default::default(), false) - .await - .expect("the history") - } -} - -fn now_ms() -> i64 { - SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64 -} - -fn capabilities(streams: bool) -> Capabilities { - Capabilities { streams, file_transfer: true, ..Default::default() } -} - -fn backend() -> BackendInfo { - BackendInfo { product: "Fake".into(), version: "1.2".into() } -} - -fn connected(streams: bool) -> LinkEvent { - LinkEvent::Connected { - name: "Fake Server".into(), - backend: backend(), - capabilities: capabilities(streams), - own_client: ME, - server_uid: SERVER_UID.into(), - own_uid: Some(ME_UID.into()), - } -} - -fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo { - ClientInfo { - id, - uid: Some(format!("{nickname}=")), - nickname: nickname.into(), - channel, - ..Default::default() - } -} - -/// Two channels, three clients; we are in the second channel. -fn presence() -> Presence { - let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..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.clients.insert(c.id, c); - } - presence -} - -fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage { - ChatMessage { - target: ChatTarget::Channel(GAMES), - author_name: author.into(), - author_uid: Some(format!("{author}=")), - author_id: None, - text: text.into(), - ts_ms, - via_relay: false, - blocked: false, - } -} - -/// Connecting, the server's presence, moving, talking, a failing command -/// and the end of the connection, as the session reports them. -#[tokio::test(flavor = "multi_thread")] -async fn presence_follows_the_link_until_it_disconnects() { - let mut h = Harness::start(); - let conn = h.connect().await; - // What the link was given. - assert_eq!( - (conn.options.address.as_str(), conn.options.nickname.as_str()), - ("fake.test:9987", "tester") - ); - assert_eq!(conn.session, SESSION); - h.state(|s| s.voice == VoiceState::Connecting).await; - - conn.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - // In the order the session tells them: the server, its presence, our channel. - let (name, info, caps) = h - .next(|e| match e { - Event::ServerInfo { name, backend, capabilities, .. } => { - Some((name, backend, capabilities)) - } - _ => None, - }) - .await; - assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2")); - assert_eq!(caps, capabilities(false)); - let shown = h - .next(|e| match e { - Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence), - _ => None, - }) - .await; - assert_eq!(*shown, presence()); - let state = h.state(|s| s.own_channel == Some(GAMES)).await; - assert_eq!(state.voice, VoiceState::Connected); - assert_eq!(state.own_client, Some(ME)); - assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID)); - assert_eq!(state.presence_source, Some(Source::Voice)); - - conn.play([ - LinkEvent::Talking { client: 8, talking: true }, - LinkEvent::Poke { - from: 8, - from_uid: Some("alice=".into()), - from_name: "alice".into(), - message: "wake up".into(), - }, - LinkEvent::Error("move refused".into()), - ]); - h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await; - let poke = h - .next(|e| match e { - Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)), - _ => None, - }) - .await; - assert_eq!(poke, ("alice".into(), "wake up".into(), false)); - let error = h - .next(|e| match e { - Event::Error { message, .. } => Some(message), - _ => None, - }) - .await; - assert_eq!(error, "move refused"); - - // The link ends the connection: the session forgets what it showed. - conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]); - let state = h.state(|s| s.voice == VoiceState::Disconnected).await; - assert_eq!((state.own_channel, state.own_client), (None, None)); - let error = h - .next(|e| match e { - Event::Error { message, .. } => Some(message), - _ => None, - }) - .await; - assert_eq!(error, "voice: server shut down"); - let state = h.state(|s| s.presence_source.is_none()).await; - assert_eq!(state.voice, VoiceState::Disconnected); - let shown = h - .next(|e| match e { - Event::Presence { presence, .. } => Some(presence), - _ => None, - }) - .await; - assert!(shown.clients.is_empty() && shown.channels.is_empty()); -} - -/// What the user asks for reaches the link; streams only where the link's -/// capabilities say it has them. -#[tokio::test(flavor = "multi_thread")] -async fn commands_reach_the_link() { - let mut h = Harness::start(); - let mut conn = h.connect().await; - conn.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - - let engine = h.engine.clone(); - engine.send(Command::SendChat { - session: SESSION, - target: ChatTarget::Channel(GAMES), - text: "hello".into(), - }); - let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") }; - assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello")); - engine.send(Command::MoveToChannel { - session: SESSION, - channel: LOBBY, - password: Some("pw".into()), - }); - let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") }; - assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); - engine.send(Command::SetInputMuted { session: SESSION, muted: true }); - assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true))); - assert!(h.state(|s| s.input_muted).await.input_muted); - engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() }); - assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. })); - engine.send(Command::ListFiles { - session: SESSION, - request: 5, - channel: GAMES, - 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/")); - - // No streams in the capabilities: the session refuses them itself. - let setup = || StreamSetup { name: "screen".into(), ..Default::default() }; - engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); - let error = h - .next(|e| match e { - Event::Error { message, .. } => Some(message), - _ => None, - }) - .await; - assert!(error.contains("streams"), "{error}"); - assert!(conn.cmds.try_recv().is_err(), "nothing reached the link"); - - // A link with streams: stream commands go to it, and end with the connection. - let mut with_streams = { - let link_engine = h.engine.clone(); - link_engine.send(Command::ConnectVoice { - session: SESSION, - options: Box::new(VoiceOptions::new("fake.test:9987", "tester")), - }); - h.conns.recv().await.expect("the second connection") - }; - // The replaced connection is told to go. - assert!(matches!(conn.cmd().await, LinkCmd::Disconnect)); - with_streams.play([connected(true)]); - h.next(|e| match e { - Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()), - _ => None, - }) - .await; - // A connection with streams is given the (empty) stream directory first. - let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else { - panic!("the stream directory") - }; - assert!(directory.is_empty()); - engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); - let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else { - panic!("a stream start") - }; - assert_eq!((setup.name.as_str(), auto_accept), ("screen", true)); - engine.send(Command::StopStream { session: SESSION }); - assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop))); - engine.send(Command::DisconnectVoice { session: SESSION }); - assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect)); -} - -/// A reconnect ends the streams of the connection it replaces through that -/// connection, before the connection itself: the old link is given -/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its -/// connection on `Disconnect` (the TeamSpeak one stops reading commands -/// there) relies on this order for the streams to hear of their end. -#[tokio::test(flavor = "multi_thread")] -async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() { - let mut h = Harness::start(); - let mut old = h.connect().await; - old.play([ - connected(true), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else { - panic!("the stream directory") - }; - assert!(directory.is_empty()); - - // Connecting again replaces the connection. - let _new = h.connect().await; - let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else { - panic!("the streams end first") - }; - assert_eq!(reason, "voice reconnecting"); - assert!(matches!(old.cmd().await, LinkCmd::Disconnect)); -} - -/// A message we send is stored at once; the server's copy of it merges -/// into the same row, and is shown (once). -#[tokio::test(flavor = "multi_thread")] -async fn a_sent_message_and_its_echo_are_one_message() { - let mut h = Harness::start(); - let mut conn = h.connect().await; - conn.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - - h.engine.send(Command::SendChat { - session: SESSION, - target: ChatTarget::Channel(GAMES), - text: "hello".into(), - }); - assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..))); - // The server sends it back to everyone in the channel, to us too. - let mut echo = message("tester", "hello", now_ms()); - echo.author_uid = Some(ME_UID.into()); - echo.author_id = Some(ME); - conn.play([LinkEvent::Chat(echo.clone())]); - let shown = h.chat().await; - assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello")); - - // A marker: what comes next is the next message, not a second "hello". - conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]); - assert_eq!(h.chat().await.text, "marker"); - let rows = h.stored(ChatTarget::Channel(GAMES)).await; - let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); - assert_eq!(texts, ["hello", "marker"]); - assert_eq!(rows[0].source, MessageSource::Local); -} - -/// A message that comes twice (the server's and a relay's copy, with the -/// relay's `[nick] ` prefix) is shown once. -#[tokio::test(flavor = "multi_thread")] -async fn a_message_that_comes_twice_is_shown_once() { - let mut h = Harness::start(); - let conn = h.connect().await; - h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); - conn.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - - let t = now_ms(); - let mut relayed = message("alice", "[alice] gg everyone", t + 300); - relayed.via_relay = true; - conn.play([ - LinkEvent::Chat(message("alice", "gg everyone", t)), - LinkEvent::Chat(relayed), - // The same words much later are another message. - LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)), - LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)), - ]); - let shown: Vec<_> = { - let mut shown = Vec::new(); - while shown.len() < 3 { - shown.push(h.chat().await); - } - shown - }; - let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect(); - assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]); -} - -/// Stored messages come back when a chat opens, also after the connection -/// is gone; the server's id keys them. -#[tokio::test(flavor = "multi_thread")] -async fn history_is_kept_across_the_connection() { - let mut h = Harness::start(); - let conn = h.connect().await; - conn.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - let t = now_ms(); - conn.play([ - LinkEvent::Chat(message("alice", "first", t)), - LinkEvent::Chat(message("bob", "second", t + 1_000)), - // A private message to us is stored under its peer, not the channel. - LinkEvent::Chat(ChatMessage { - target: ChatTarget::Private("alice=".into()), - ..message("alice", "psst", t + 2_000) - }), - ]); - for _ in 0..3 { - h.chat().await; - } - conn.play([LinkEvent::Disconnected(None)]); - h.state(|s| s.voice == VoiceState::Disconnected).await; - - h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); - // The stored page (the live batches of the messages came before). - let messages = h - .next(|e| match e { - Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages), - _ => None, - }) - .await; - let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect(); - assert_eq!(texts, ["first", "second"]); - let private = h.stored(ChatTarget::Private("alice=".into())).await; - assert_eq!(private.len(), 1); - assert_eq!(private[0].message.text, "psst"); -} - -/// Events of a connection the session replaced do not reach it. -#[tokio::test(flavor = "multi_thread")] -async fn a_replaced_connection_is_ignored() { - let mut h = Harness::start(); - let mut old = h.connect().await; - old.play([ - connected(false), - LinkEvent::Presence(Box::new(presence())), - LinkEvent::OwnChannel(GAMES), - ]); - h.state(|s| s.own_channel == Some(GAMES)).await; - - let new = h.connect().await; - assert!(matches!(old.cmd().await, LinkCmd::Disconnect)); - // The old connection winds down, and says more than it should. - let mut stale = presence(); - stale.clients.insert(10, client(10, "ghost", LOBBY)); - old.play([ - LinkEvent::Presence(Box::new(stale)), - LinkEvent::Chat(message("ghost", "boo", now_ms())), - LinkEvent::Disconnected(None), - ]); - let mut fresh = presence(); - fresh.clients.remove(&9); - new.play([ - connected(false), - LinkEvent::Presence(Box::new(fresh.clone())), - LinkEvent::OwnChannel(LOBBY), - ]); - // Only the new connection's presence is shown (nobody else has 2 clients). - let shown = h - .next(|e| match e { - Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => { - Some(presence) - } - _ => None, - }) - .await; - 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()))]); - assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed"); -} diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index 498b734..105aa04 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -5,7 +5,10 @@ use std::time::Duration; use tokio::sync::broadcast::Receiver; use tokio::time::{Instant, timeout_at}; -use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState}; +use voelin_core::{ + Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions, + VoiceState, +}; use voelin_model::ChatTarget; fn live() -> bool { @@ -45,7 +48,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) { .await; // Session 2: invisible, through own query credentials. - engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) }); + engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) }); let (mut observing, mut sees_voice_client) = (false, false); wait_for(&mut events, "query presence with the voice client", |e| { match e { @@ -93,6 +96,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) { tokio::time::sleep(Duration::from_millis(500)).await; } +/// The credentials of a query connection, as the engine takes them. +fn login(connect: &voelin_query::Connect) -> QueryLogin { + QueryLogin { + transport: match connect.transport { + voelin_query::Transport::Raw => QueryTransport::Raw, + voelin_query::Transport::Ssh => QueryTransport::Ssh, + voelin_query::Transport::Http => QueryTransport::Http, + }, + address: connect.addr.clone(), + user: connect.user.clone(), + secret: connect.secret.clone(), + server_port: connect.server_port, + server_id: connect.server_id, + // The development servers allowlist their clients. + allowlisted: connect.line.rate_limit.is_none(), + } +} + fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect { voelin_query::Connect { transport, diff --git a/crates/voelin-core/tests/session_backends.rs b/crates/voelin-core/tests/session_backends.rs new file mode 100644 index 0000000..a6a46da --- /dev/null +++ b/crates/voelin-core/tests/session_backends.rs @@ -0,0 +1,124 @@ +//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code +//! made: `Engine::start_with_backends` takes the connector registry, and the +//! scheme of a session's address picks the connector. The fake host of the +//! protocol repository stands for a Voelin host here (the fuller tests of the +//! seam on the fake host come with the next slice of +//! `docs/session-seam.md`). + +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::broadcast; +use voelin_core::settings::Settings; +use voelin_core::{ + Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState, +}; +use voelin_proto::test_util::FakeConnector; +use voelin_proto::v1::{self, entity::Kind}; + +const SESSION: u64 = 1; + +async fn next( + events: &mut broadcast::Receiver, + mut f: impl FnMut(Event) -> Option, +) -> T { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some(t) = f(events.recv().await.expect("engine events")) { + return t; + } + } + }) + .await + .expect("an event in time") +} + +fn host_with_two_channels(connector: &FakeConnector) { + let host = connector.host(); + let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap(); + put(Kind::Server(v1::Server { + id: 1, + name: "Fake Host".into(), + uid: "fake-host".into(), + default_channel_id: 10, + ..Default::default() + })); + for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] { + put(Kind::Channel(v1::Channel { + id, + server_id: 1, + kind: v1::ChannelKind::Voice as i32, + name: name.into(), + position, + ..Default::default() + })); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_session_of_a_registered_connector_is_the_engines_voice_source() { + let connector = FakeConnector::new(); + host_with_two_channels(&connector); + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends); + let mut events = engine.subscribe(); + + engine.send(Command::ConnectVoice { + session: SESSION, + options: Box::new(VoiceOptions::new("fake://host", "tester")), + }); + let (name, backend) = next(&mut events, |e| match e { + Event::ServerInfo { name, backend, .. } => Some((name, backend)), + _ => None, + }) + .await; + assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake")); + let presence = next(&mut events, |e| match e { + Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence), + _ => None, + }) + .await; + let channels: Vec<_> = + presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect(); + assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]); + // The host was asked once, with the nickname and the TeamSpeak-shaped + // credential the engine makes of its options for now. + let connects = connector.connects(); + assert_eq!(connects.len(), 1); + assert_eq!(connects[0].address, "fake://host"); + assert_eq!(connects[0].hello.nickname, "tester"); + + // A move is a request to the host; the host's voice state is where we are. + engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None }); + let state: SessionState = next(&mut events, |e| match e { + Event::State { state, .. } if state.own_channel == Some(11) => Some(state), + _ => None, + }) + .await; + assert_eq!(state.voice, VoiceState::Connected); + + engine.send(Command::DisconnectVoice { session: SESSION }); + next(&mut events, |e| match e { + Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()), + _ => None, + }) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_address_no_connector_serves_fails_with_the_registry_s_words() { + let engine = + Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty()); + let mut events = engine.subscribe(); + engine.send(Command::ConnectVoice { + session: SESSION, + options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")), + }); + let error = next(&mut events, |e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await; + assert_eq!(error, "voice: no connector for voelin://host/i/code"); +} diff --git a/crates/voelin-core/tests/session_fake.rs b/crates/voelin-core/tests/session_fake.rs new file mode 100644 index 0000000..e7fe65c --- /dev/null +++ b/crates/voelin-core/tests/session_fake.rs @@ -0,0 +1,1504 @@ +//! The engine on the protocol repository's fake host: `Engine::start_with_backends` +//! with a `FakeConnector` (scheme `fake`) registered, so a session of the +//! engine is a `voelin_proto::link::Session` that no TeamSpeak code made +//! (`docs/session-seam.md` section 9.2). +//! +//! The host is a `FakeHost` filled through `FakeHost::put` (it stores what a +//! client cannot set, such as the author of a message); `FakeHandle` plays the +//! backend of one session: pushes, media, scripted answers, held requests and +//! kills, and the log of every request the host received. Presence, chat, the +//! dedup of a message that comes twice, history, transfers, offline messages, +//! the features of a host, a reconnect and the media of a session are the +//! engine's own behaviour; nothing here needs a TeamSpeak server or a +//! TeamSpeak type. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use bytes::BytesMut; +use tokio::io::AsyncWriteExt; +use tokio::sync::broadcast; +use voelin_core::history::MessageSource; +use voelin_core::settings::Settings; +use voelin_core::{ + Backends, Command, DownloadTo, Engine, Event, History, HistoryMessage, HistorySource, + IdentityBlob, JoinFailure, SessionId, SessionState, Source, TransferState, VoiceOptions, + VoiceState, +}; +use voelin_model::{ChatMessage, ChatTarget, Presence}; +use voelin_proto::link::{CloseReason, Connector, FlowId, MediaPacket, SessionError, voice_sub}; +use voelin_proto::media::RtpHeader; +use voelin_proto::media::payload::PT_OPUS; +use voelin_proto::test_util::{ + DEFAULT_FEATURES, FakeConnector, FakeHandle, FakeHost, Logged, Script, connect_params, + eventually, +}; +use voelin_proto::v1::{self, entity::Kind, push, request::Op, response}; + +const SESSION: SessionId = 1; +const SERVER: u64 = 1; +const LOBBY: u64 = 10; +const GAMES: u64 = 11; +const SERVER_CHAT: u64 = 20; +/// The host's name for the server: `Server.uid` (a Voelin host has no `ts:`). +const SERVER_UID: &str = "fake-host"; +/// The user and the participant the fake host gives the first session. +const ME_USER: u64 = 1; +const ME: u32 = 1; +const ALICE_USER: u64 = 2; +const ALICE: u32 = 50; +const ALICE_SLOT: u32 = 90; +const BOB_USER: u64 = 3; +const BOB: u32 = 51; +const BOB_SLOT: u32 = 91; +/// How long a test waits for the engine or the host. +const WAIT: Duration = Duration::from_secs(20); + +fn now_ms() -> i64 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64 +} + +fn entity(kind: Kind) -> v1::Entity { + v1::Entity { kind: Some(kind) } +} + +fn user(id: u64, name: &str) -> Kind { + Kind::User(v1::User { + id, + uid: vec![id as u8; 32].into(), + uid_kind: v1::IdKind::Voelin as i32, + name: name.into(), + ..Default::default() + }) +} + +fn voice(participant: u32, user_id: u64, nick: &str, channel: u64, slot: u32) -> Kind { + Kind::Voice(v1::VoiceState { + server_id: SERVER, + participant_id: participant, + user_id, + channel_id: channel, + slot, + nick: nick.into(), + ..Default::default() + }) +} + +fn channel(id: u64, name: &str, position: i64, kind: v1::ChannelKind) -> Kind { + Kind::Channel(v1::Channel { + id, + server_id: SERVER, + kind: kind as i32, + name: name.into(), + position, + ..Default::default() + }) +} + +/// A message of `author` (a user the host knows), as the host stores it. +fn message(channel: u64, author: (u64, u32, &str), text: &str, ts_ms: i64) -> Kind { + Kind::Message(v1::Message { + channel_id: channel, + author_id: author.0, + author_participant: author.1, + author_name: author.2.into(), + text: text.into(), + ts_ms, + ..Default::default() + }) +} + +const ALICE_AUTHOR: (u64, u32, &str) = (ALICE_USER, ALICE, "alice"); +const BOB_AUTHOR: (u64, u32, &str) = (BOB_USER, BOB, "bob"); + +/// A host with a server, a lobby and a games channel, a server chat, us (user +/// 1, seated by `JoinVoice` where the server's default channel is: games), +/// alice in games and bob in the lobby. +fn connector() -> FakeConnector { + let connector = FakeConnector::new(); + let host = connector.host(); + let mut welcome = host.welcome(); + let info = welcome.host.as_mut().expect("the fake host names itself"); + info.backend = Some(v1::BackendInfo { + product: "Fake".into(), + version: "1.2".into(), + ..Default::default() + }); + host.set_welcome(welcome); + let put = |kind: Kind| host.put(entity(kind)).expect("the fake host stores it"); + put(Kind::Server(v1::Server { + id: SERVER, + name: "Fake Host".into(), + uid: SERVER_UID.into(), + default_channel_id: GAMES, + ..Default::default() + })); + put(channel(LOBBY, "Lobby", 0, v1::ChannelKind::Voice)); + put(channel(GAMES, "Games", 1024, v1::ChannelKind::Voice)); + put(channel(SERVER_CHAT, "Server chat", 0, v1::ChannelKind::ServerChat)); + put(user(ME_USER, "tester")); + put(user(ALICE_USER, "alice")); + put(user(BOB_USER, "bob")); + put(voice(ALICE, ALICE_USER, "alice", GAMES, ALICE_SLOT)); + put(voice(BOB, BOB_USER, "bob", LOBBY, BOB_SLOT)); + connector +} + +/// The engine, the connector it uses and the events it reports. +struct Harness { + engine: Engine, + events: broadcast::Receiver, + connector: FakeConnector, + /// The latest state and presence the test has seen go by. + state: SessionState, + presence: Arc, +} + +impl Harness { + fn start() -> Self { + Self::on(connector()) + } + + fn on(connector: FakeConnector) -> Self { + let mut backends = Backends::empty(); + backends.register(Arc::new(connector.clone())); + let engine = + Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends); + let events = engine.subscribe(); + Self { + engine, + events, + connector, + state: SessionState::default(), + presence: Arc::new(Presence::default()), + } + } + + /// The unique id the engine shows for the participant `client`. + fn uid_of(&self, client: u32) -> String { + let shown = self.presence.clients.get(&(client as u16)); + shown.and_then(|c| c.uid.clone()).expect("the client is on the last presence") + } + + fn host(&self) -> FakeHost { + self.connector.host() + } + + /// Ask for a voice connection to the fake host. + fn ask_connect(&self) { + let options = VoiceOptions::new("fake://host", "tester"); + self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + } + + /// Connect, and wait until the engine shows us in a channel. Returns the + /// host's handle on the session that was made. + async fn connect(&mut self) -> FakeHandle { + self.ask_connect(); + self.state(|s| s.voice == VoiceState::Connected && s.own_channel.is_some()).await; + self.connector.last_session().expect("the connector made a session") + } + + /// The next event `f` picks, skipping the others. + async fn next(&mut self, mut f: impl FnMut(Event) -> Option) -> T { + tokio::time::timeout(WAIT, async { + loop { + let event = self.events.recv().await.expect("engine events"); + match &event { + Event::State { state, .. } => self.state = state.clone(), + Event::Presence { presence, .. } => self.presence = presence.clone(), + _ => {} + } + if let Some(t) = f(event) { + return t; + } + } + }) + .await + .expect("event in time") + } + + /// The next state of the session that `ok` accepts. + async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState { + self.next(|e| match e { + Event::State { state, .. } if ok(&state) => Some(state), + _ => None, + }) + .await + } + + /// The next live chat message. + async fn chat(&mut self) -> ChatMessage { + self.next(|e| match e { + Event::Chat { message, .. } => Some(message), + _ => None, + }) + .await + } + + /// The next error the engine reports. + async fn error(&mut self) -> String { + self.next(|e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await + } + + /// The messages stored for `target`, oldest first. + async fn stored(&self, target: ChatTarget) -> Vec { + self.engine + .history() + .page(SERVER_UID, &target, Default::default(), false) + .await + .expect("the history") + } + + /// Wait until the engine has applied everything the host pushed before + /// now: a notice is told after the pushes before it. + async fn synced(&mut self, handle: &FakeHandle) { + notice(handle, "sync marker"); + assert_eq!(self.error().await, "sync marker"); + } +} + +/// The host tells the session an error notice. +fn notice(handle: &FakeHandle, text: &str) { + let notice = v1::Notice { + level: v1::NoticeLevel::Error as i32, + text: text.into(), + ..Default::default() + }; + signal(handle, 0, 0, v1::signal::Body::Notice(notice)); +} + +fn signal(handle: &FakeHandle, from_user: u64, from_participant: u32, body: v1::signal::Body) { + let signal = v1::Signal { from_user, from_participant, body: Some(body), ..Default::default() }; + handle + .push(v1::Push { body: Some(push::Body::Signal(signal)) }) + .expect("the push channel has room"); +} + +fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope { + v1::Scope { kind: kind as i32, id } +} + +/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it. +fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket { + let flow = FlowId::new(slot, sub); + let mut out = BytesMut::new(); + RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960) + .write(flow, &mut out) + .expect("a header"); + out.extend_from_slice(payload); + MediaPacket { flow, rtp: out.freeze() } +} + +/// An Opus frame (20 ms, mono, fullband). +const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe]; + +/// The requests the host received after the first `skip` of its log. +fn requests_after(handle: &FakeHandle, skip: usize) -> Vec { + handle.requests().into_iter().skip(skip).collect() +} + +/// Wait until a request after the first `skip` matches `f`; return it. +async fn request_after( + handle: &FakeHandle, + skip: usize, + what: &str, + f: impl Fn(&Op) -> bool, +) -> Logged { + eventually(WAIT, what, || { + requests_after(handle, skip).iter().any(|l| l.request.op.as_ref().is_some_and(&f)) + }) + .await; + requests_after(handle, skip) + .into_iter() + .find(|l| l.request.op.as_ref().is_some_and(&f)) + .expect("the request that was seen") +} + +/// The one message a `Put` writes. +fn written_message(op: &Op) -> Option<&v1::Message> { + let Op::Put(put) = op else { return None }; + match put.writes.first()?.entity.as_ref()?.kind.as_ref()? { + Kind::Message(message) => Some(message), + _ => None, + } +} + +fn list_of(kind: v1::EntityKind) -> impl Fn(&Op) -> bool { + move |op| matches!(op, Op::List(list) if list.kind == kind as i32) +} + +fn entities(items: Vec) -> response::Result { + response::Result::Entities(v1::Entities { + items: items.into_iter().map(entity).collect(), + ..Default::default() + }) +} + +/// Connecting, the host's presence, talking, a poke, a notice and the end of +/// the session, as the engine reports them. +#[tokio::test(flavor = "multi_thread")] +async fn presence_follows_the_host_until_it_ends() { + let mut h = Harness::start(); + h.ask_connect(); + h.state(|s| s.voice == VoiceState::Connecting).await; + + // In the order the engine tells them: the server, its presence, our channel. + let (name, info, caps) = h + .next(|e| match e { + Event::ServerInfo { name, backend, capabilities, .. } => { + Some((name, backend, capabilities)) + } + _ => None, + }) + .await; + assert_eq!((name.as_str(), info.label().as_str()), ("Fake Host", "Fake 1.2")); + // `files` is offered, `mailbox` is not, and no session has streams yet. + assert!(caps.file_transfer && !caps.offline_messages && !caps.streams, "{caps:?}"); + // The server's details come with its first presence; its unique id is the + // host's name for it. + let details = h + .next(|e| match e { + Event::ServerDetails { details, .. } => Some(details), + _ => None, + }) + .await; + assert_eq!(details.uid.as_deref(), Some(SERVER_UID)); + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } if presence.clients.len() == 3 => Some(presence), + _ => None, + }) + .await; + assert_eq!(shown.server_name, "Fake Host"); + let channels: Vec<_> = + shown.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect(); + // The server chat is no channel of the tree; siblings form an order chain. + assert_eq!(channels, [(LOBBY, "Lobby", 0), (GAMES, "Games", LOBBY)]); + let clients: Vec<_> = + shown.clients.values().map(|c| (c.id, c.nickname.as_str(), c.channel)).collect(); + let (me, alice, bob) = (ME as u16, ALICE as u16, BOB as u16); + assert_eq!(clients, [(me, "tester", GAMES), (alice, "alice", GAMES), (bob, "bob", LOBBY)]); + // A Voelin user's unique id is shown as the base32 of its 32 bytes (here the + // user's id, 32 times: `user`). + assert_eq!(h.uid_of(ME), "aeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaq"); + assert_eq!(h.uid_of(ALICE), "aibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaiba"); + assert_eq!(h.uid_of(BOB), "ambqgaydambqgaydambqgaydambqgaydambqgaydambqgaydambq"); + let state = h.state(|s| s.own_channel == Some(GAMES)).await; + assert_eq!(state.voice, VoiceState::Connected); + assert_eq!(state.own_client, Some(me)); + assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID)); + assert_eq!(state.presence_source, Some(Source::Voice)); + let handle = h.connector.last_session().expect("a session"); + + // Alice talks: the engine derives it from the media the session delivers. + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &OPUS)); + h.next(|e| { + matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) + }) + .await; + // A poke names its sender from the host's participant and user. + let poke = v1::signal::Body::Poke(v1::Poke { message: "wake up".into() }); + signal(&handle, ALICE_USER, ALICE, poke); + let poke = h + .next(|e| match e { + Event::Poke { from, from_uid, from_name, message, blocked, .. } => { + Some((from, from_uid.is_some(), from_name, message, blocked)) + } + _ => None, + }) + .await; + assert_eq!(poke, (alice, true, "alice".into(), "wake up".into(), false)); + // An error notice of the host is an error of the session. + notice(&handle, "move refused"); + assert_eq!(h.error().await, "move refused"); + + // The host ends the session: the engine forgets what it showed. + handle.kill(CloseReason::Network("server shut down".into())); + let state = h.state(|s| s.voice == VoiceState::Disconnected).await; + assert_eq!((state.own_channel, state.own_client), (None, None)); + assert_eq!(h.error().await, "voice: server shut down"); + let state = h.state(|s| s.presence_source.is_none()).await; + assert_eq!(state.voice, VoiceState::Disconnected); + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } => Some(presence), + _ => None, + }) + .await; + assert!(shown.clients.is_empty() && shown.channels.is_empty()); +} + +/// How a host ends a session is how the user is told: a close code with a +/// reason, an idle timeout, and the user's own wish. +#[tokio::test(flavor = "multi_thread")] +async fn the_way_a_session_ends_is_the_text_the_user_reads() { + let kicked = v1::CloseCode::Kicked as u64; + let cases = [ + (CloseReason::Remote { code: kicked, reason: "bye".into() }, Some("voice: bye")), + (CloseReason::TimedOut, Some("voice: timed out")), + (CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() }, None), + ]; + for (reason, text) in cases { + let mut h = Harness::start(); + let handle = h.connect().await; + handle.kill(reason.clone()); + h.state(|s| s.voice == VoiceState::Disconnected).await; + match text { + Some(text) => assert_eq!(h.error().await, text, "{reason:?}"), + None => { + // Nothing to say: the next thing the engine tells is the empty presence. + h.next(|e| match e { + Event::Error { message, .. } => panic!("an error for {reason:?}: {message}"), + Event::Presence { presence, .. } if presence.clients.is_empty() => Some(()), + _ => None, + }) + .await; + } + } + } + + // The user's own wish closes the session towards the host: `Local(Normal)`. + let mut h = Harness::start(); + let handle = h.connect().await; + h.engine.send(Command::DisconnectVoice { session: SESSION }); + h.state(|s| s.voice == VoiceState::Disconnected).await; + eventually(WAIT, "the host to see the close", || handle.close_reason().is_some()).await; + assert_eq!(handle.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); +} + +/// What the user asks for reaches the host, as the v1 requests of the +/// translation table. +#[tokio::test(flavor = "multi_thread")] +async fn commands_reach_the_host_as_requests() { + let mut h = Harness::start(); + let handle = h.connect().await; + let before = handle.requests().len(); + + h.engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Channel(GAMES), + text: "hello".into(), + }); + let put = + request_after(&handle, before, "the chat message", |op| written_message(op).is_some()) + .await; + let sent = put.request.op.as_ref().and_then(written_message).expect("a message"); + assert_eq!((sent.channel_id, sent.text.as_str()), (GAMES, "hello")); + // The host does not offer `chat.bbcode`. + assert_eq!(sent.format, v1::TextFormat::Markdown as i32); + + h.engine.send(Command::MoveToChannel { + session: SESSION, + channel: LOBBY, + password: Some("pw".into()), + }); + let join = + request_after(&handle, before, "the move", |op| matches!(op, Op::JoinVoice(_))).await; + let Some(Op::JoinVoice(join)) = join.request.op else { unreachable!() }; + assert_eq!((join.server_id, join.channel_id, join.password.as_str()), (SERVER, LOBBY, "pw")); + // The host's voice state is where we are. + h.state(|s| s.own_channel == Some(LOBBY)).await; + + // Our own flags are fire and forget: a notification (id 0) that patches + // one leaf of the voice state. + h.engine.send(Command::SetInputMuted { session: SESSION, muted: true }); + h.engine.send(Command::SetOutputMuted { session: SESSION, muted: true }); + assert!(h.state(|s| s.input_muted && s.output_muted).await.input_muted); + for path in ["self_mute", "self_deaf"] { + // The leaf path of the flag, as the protocol writes it. + let leaf = v1::Write::patch(entity(voice(ME, ME_USER, "", 0, 0)), [path]).unwrap().paths; + let flag = request_after( + &handle, + before, + path, + |op| matches!(op, Op::Put(put) if put.writes.iter().any(|w| w.paths == leaf)), + ) + .await; + assert_eq!(flag.request.id, 0, "{path} is a notification"); + let Some(Op::Put(put)) = flag.request.op else { unreachable!() }; + let Some(Kind::Voice(state)) = put.writes[0].entity.as_ref().and_then(|e| e.kind.clone()) + else { + panic!("a voice state") + }; + assert_eq!((state.server_id, state.participant_id), (SERVER, ME)); + assert_eq!(state.self_mute, path == "self_mute"); + assert_eq!(state.self_deaf, path == "self_deaf"); + } + + h.engine.send(Command::Poke { session: SESSION, client: ALICE as u16, message: "hi".into() }); + let poke = request_after(&handle, before, "the poke", |op| matches!(op, Op::Signal(_))).await; + let Some(Op::Signal(signal)) = poke.request.op else { unreachable!() }; + let to = signal.to.expect("a target"); + assert_eq!((to.server_id, to.participant_id), (SERVER, ALICE)); + assert!(matches!(signal.body, Some(v1::signal::Body::Poke(p)) if p.message == "hi")); + + // The fake refuses the path of a file list; the test scripts the answer. + let file = |name: &str, size: u64, is_dir: bool| { + Kind::File(v1::FileEntry { + channel_id: GAMES, + path: "/docs".into(), + name: name.into(), + size, + modified_ms: 3_000, + is_dir, + ..Default::default() + }) + }; + let listing = entities(vec![file("a.txt", 5, false), file("sub", 0, true)]); + handle.script(Script::answer("list", listing).once()); + h.engine.send(Command::ListFiles { + session: SESSION, + request: 5, + channel: GAMES, + password: None, + path: "/docs/".into(), + }); + let (request, channel, listed) = h + .next(|e| match e { + Event::FileList { request, channel, result, .. } => Some((request, channel, result)), + _ => None, + }) + .await; + assert_eq!((request, channel), (5, GAMES)); + let listed: Vec<_> = listed + .expect("a listing") + .into_iter() + .map(|f| (f.name, f.size, f.modified_s, f.is_dir)) + .collect(); + assert_eq!(listed, [("a.txt".to_owned(), 5, 3, false), ("sub".to_owned(), 0, 3, true)]); + let list = request_after(&handle, before, "the file list", list_of(v1::EntityKind::File)).await; + let Some(Op::List(list)) = list.request.op else { unreachable!() }; + assert_eq!((list.parent, list.path.as_str()), (GAMES, "/docs/")); +} + +/// A host that offers no streams is not asked for one: the engine refuses +/// `StartStream` itself, with an error, before any request leaves. (The other +/// local refusal of a missing feature, the file list, is in +/// `a_host_update_changes_what_the_engine_asks_for`.) +#[tokio::test(flavor = "multi_thread")] +async fn a_host_without_streams_is_not_asked_for_one() { + let mut h = Harness::start(); + let handle = h.connect().await; + let count = handle.requests().len(); + let setup = voelin_core::stream::StreamSetup { name: "screen".into(), ..Default::default() }; + h.engine.send(Command::StartStream { session: SESSION, setup, auto_accept: true }); + let error = h.error().await; + assert!(error.contains("streams"), "{error}"); + assert_eq!(handle.requests().len(), count, "nothing reached the host"); +} + +/// A request the host refuses is told in the host's words, with the label the +/// user knows it by; a refused move says why. +#[tokio::test(flavor = "multi_thread")] +async fn what_the_host_refuses_is_told_in_its_words() { + let mut h = Harness::start(); + let handle = h.connect().await; + + handle.script(Script::error("put", v1::ErrorCode::Forbidden, "you cannot talk here").once()); + h.engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Channel(GAMES), + text: "hi".into(), + }); + assert_eq!(h.error().await, "message: you cannot talk here"); + + handle.script(Script::error("signal", v1::ErrorCode::NotFound, "no such client").once()); + h.engine.send(Command::Poke { session: SESSION, client: ALICE as u16, message: "hi".into() }); + assert_eq!(h.error().await, "poke: no such client"); + + // A private message to somebody who is not on the server is told without a request. + let count = handle.requests().len(); + h.engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Private("nobody=".into()), + text: "psst".into(), + }); + assert!(h.error().await.starts_with("private message: the client is not on the server")); + assert_eq!(handle.requests().len(), count); + + let refusals = [ + (v1::ErrorCode::Password, "wrong password", JoinFailure::Password), + (v1::ErrorCode::Full, "the channel is full", JoinFailure::Full), + (v1::ErrorCode::Forbidden, "not allowed", JoinFailure::Other("not allowed".into())), + ]; + for (code, text, expected) in refusals { + handle.script(Script::error("join_voice", code, text).once()); + h.engine.send(Command::MoveToChannel { session: SESSION, channel: LOBBY, password: None }); + let (channel, reason) = h + .next(|e| match e { + Event::JoinFailed { channel, reason, .. } => Some((channel, reason)), + _ => None, + }) + .await; + assert_eq!((channel, reason), (LOBBY, expected)); + } + // A refused move moved nothing: the host's voice state is where it was, and + // so is the engine's. + h.synced(&handle).await; + assert_eq!(h.state.own_channel, Some(GAMES)); + let seat = h.host().entities(&scope(v1::ScopeKind::Live, SERVER)).into_iter().find_map(|e| { + match e.kind? { + Kind::Voice(v) if v.participant_id == ME => Some(v.channel_id), + _ => None, + } + }); + assert_eq!(seat, Some(GAMES)); +} + +/// A message we send is stored at once; the host's copy of it merges into +/// the same row, and is shown (once). +#[tokio::test(flavor = "multi_thread")] +async fn a_sent_message_and_its_echo_are_one_message() { + let mut h = Harness::start(); + let handle = h.connect().await; + + h.engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Channel(GAMES), + text: "hello".into(), + }); + // The host stores it and pushes its `Change` to everyone who watches the + // channel, us too. + let shown = h.chat().await; + assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello")); + let stored = handle + .requests() + .iter() + .filter_map(|l| l.request.op.as_ref().and_then(written_message).map(|m| m.text.clone())) + .collect::>(); + assert_eq!(stored, ["hello"]); + + // A marker: what comes next is the next message, not a second "hello". + h.host().put(entity(message(GAMES, ALICE_AUTHOR, "marker", now_ms()))).unwrap(); + assert_eq!(h.chat().await.text, "marker"); + let rows = h.stored(ChatTarget::Channel(GAMES)).await; + let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); + assert_eq!(texts, ["hello", "marker"]); + assert_eq!(rows[0].source, MessageSource::Local); +} + +/// A message that comes twice (the host's and a relay's copy, with the +/// relay's `[nick] ` prefix) is shown once. +#[tokio::test(flavor = "multi_thread")] +async fn a_message_that_comes_twice_is_shown_once() { + let mut h = Harness::start(); + let _handle = h.connect().await; + h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); + + let t = now_ms(); + let host = h.host(); + let relayed = Kind::Message(v1::Message { + flags: v1::MessageFlag::Relayed as u32, + ..match message(GAMES, ALICE_AUTHOR, "[alice] gg everyone", t + 300) { + Kind::Message(m) => m, + _ => unreachable!(), + } + }); + for kind in [ + message(GAMES, ALICE_AUTHOR, "gg everyone", t), + relayed, + // The same words much later are another message. + message(GAMES, ALICE_AUTHOR, "gg everyone", t + 10_000), + message(GAMES, BOB_AUTHOR, "gg everyone", t + 10_100), + ] { + host.put(entity(kind)).unwrap(); + } + let mut shown = Vec::new(); + while shown.len() < 3 { + shown.push(h.chat().await); + } + let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect(); + assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]); + assert!(!shown[0].via_relay); +} + +/// Stored messages come back when a chat opens, also after the session is +/// gone; the host's id of the server keys them, and a private message is +/// stored under its peer. +#[tokio::test(flavor = "multi_thread")] +async fn history_is_kept_across_the_session() { + let mut h = Harness::start(); + let _handle = h.connect().await; + // The direct-message channel is in HOME: the engine subscribes it when it + // appears, and the peer is the other recipient. + let alice_uid = h.uid_of(ALICE); + let host = h.host(); + let dm = host + .put(entity(Kind::Channel(v1::Channel { + server_id: 0, + kind: v1::ChannelKind::Dm as i32, + recipients: vec![ME_USER, ALICE_USER], + ..Default::default() + }))) + .unwrap(); + let Some(Kind::Channel(dm)) = dm.kind else { panic!("a channel") }; + let t = now_ms(); + for kind in [ + message(GAMES, ALICE_AUTHOR, "first", t), + message(GAMES, BOB_AUTHOR, "second", t + 1_000), + // A private message to us is stored under its peer, not the channel. + message(dm.id, ALICE_AUTHOR, "psst", t + 2_000), + ] { + host.put(entity(kind)).unwrap(); + } + let mut texts = Vec::new(); + while texts.len() < 3 { + texts.push(h.chat().await.text); + } + texts.sort(); + assert_eq!(texts, ["first", "psst", "second"]); + h.engine.send(Command::DisconnectVoice { session: SESSION }); + h.state(|s| s.voice == VoiceState::Disconnected).await; + + h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); + // The stored page (the live batches of the messages came before). + let messages = h + .next(|e| match e { + Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages), + _ => None, + }) + .await; + let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect(); + assert_eq!(texts, ["first", "second"]); + let private = h.stored(ChatTarget::Private(alice_uid)).await; + assert_eq!(private.len(), 1); + assert_eq!(private[0].message.text, "psst"); +} + +/// Moving away from a channel and back gives the channel's chat again: the +/// scope is subscribed in full (there is no cursor to keep, `docs/session-seam.md` +/// section 13), and a message is shown once however often its scope is synced. +#[tokio::test(flavor = "multi_thread")] +async fn the_chat_of_a_channel_is_resubscribed_when_we_move_back() { + let mut h = Harness::start(); + let handle = h.connect().await; + let host = h.host(); + let t = now_ms(); + let subscriptions = |handle: &FakeHandle| { + handle + .subscriptions() + .into_iter() + .filter(|s| s.kind == v1::ScopeKind::Chat as i32) + .collect::>() + }; + // The server chat and our channel's chat. + eventually(WAIT, "the chat subscriptions", || subscriptions(&handle).len() == 2).await; + let chats: Vec = subscriptions(&handle).iter().map(|s| s.id).collect(); + assert_eq!(chats, [GAMES, SERVER_CHAT]); + + // Two messages more than `Dedup`'s 4 s apart, so that the copy of "before" + // that the second sync brings is not one `Dedup` would still recognise: it + // is the `seen` set of `SessionLink` that has to drop it. + host.put(entity(message(GAMES, ALICE_AUTHOR, "before", t))).unwrap(); + assert_eq!(h.chat().await.text, "before"); + host.put(entity(message(GAMES, ALICE_AUTHOR, "before too", t + 10_000))).unwrap(); + assert_eq!(h.chat().await.text, "before too"); + + h.engine.send(Command::MoveToChannel { session: SESSION, channel: LOBBY, password: None }); + h.state(|s| s.own_channel == Some(LOBBY)).await; + eventually(WAIT, "the lobby's chat instead of the games'", || { + let chats: Vec = subscriptions(&handle).iter().map(|s| s.id).collect(); + chats == [LOBBY, SERVER_CHAT] + }) + .await; + // Said while we were away: nobody of ours listens to the games chat. + host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); + + h.engine.send(Command::MoveToChannel { session: SESSION, channel: GAMES, password: None }); + h.state(|s| s.own_channel == Some(GAMES)).await; + assert_eq!(h.chat().await.text, "while away", "the missed message, and not 'before' again"); + // Both subscriptions of the games chat were full syncs: no cursor. + let subscribes: Vec<_> = handle + .requests() + .into_iter() + .filter_map(|l| match l.request.op { + Some(Op::Subscribe(s)) if s.scope == Some(scope(v1::ScopeKind::Chat, GAMES)) => Some(s), + _ => None, + }) + .collect(); + assert_eq!(subscribes.len(), 2, "{subscribes:?}"); + assert!(subscribes.iter().all(|s| s.since.is_none()), "{subscribes:?}"); +} + +/// A scope the host closes: a closed chat is nothing to tell; a closed +/// server or live scope is an error and an empty presence. +#[tokio::test(flavor = "multi_thread")] +async fn a_scope_the_host_closes_is_told_only_where_it_matters() { + let mut h = Harness::start(); + let handle = h.connect().await; + let closed = |scope| v1::ScopeClosed { + scope: Some(scope), + code: v1::ErrorCode::Forbidden as i32, + message: "you lost the right to see it".into(), + }; + let push = |closed| v1::Push { body: Some(push::Body::ScopeClosed(closed)) }; + + // A chat scope: unsubscribed, nothing reported. What comes next is the + // notice, not an error of the scope. + handle.push(push(closed(scope(v1::ScopeKind::Chat, GAMES)))).unwrap(); + notice(&handle, "after the chat scope"); + assert_eq!(h.error().await, "after the chat scope"); + + // The live scope: the participants are gone from view. + handle.push(push(closed(scope(v1::ScopeKind::Live, SERVER)))).unwrap(); + assert_eq!(h.error().await, "you lost the right to see it"); + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } if presence.clients.is_empty() => Some(presence), + _ => None, + }) + .await; + assert!(shown.clients.is_empty()); +} + +/// What a host offers can change under a session (`HostUpdate`): the engine +/// refuses a request its host no longer offers, without asking it, and takes +/// it up again when the host offers it again. +#[tokio::test(flavor = "multi_thread")] +async fn a_host_update_changes_what_the_engine_asks_for() { + let mut h = Harness::start(); + let handle = h.connect().await; + let update = |features: Vec| v1::Push { + body: Some(push::Body::HostUpdate(v1::HostUpdate { features, limits: None })), + }; + let without_files: Vec = DEFAULT_FEATURES + .iter() + .filter(|f| !f.starts_with("files")) + .map(|f| (*f).to_owned()) + .collect(); + handle.push(update(without_files)).unwrap(); + h.synced(&handle).await; + + let count = handle.requests().len(); + let list = |request| Command::ListFiles { + session: SESSION, + request, + channel: GAMES, + password: None, + path: "/".into(), + }; + h.engine.send(list(1)); + let result = h + .next(|e| match e { + Event::FileList { request: 1, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(result.unwrap_err(), "not offered by this server: files"); + assert_eq!(handle.requests().len(), count, "refused before it reached the host"); + + let mut all: Vec = DEFAULT_FEATURES.iter().map(|f| (*f).to_owned()).collect(); + all.push("mailbox".into()); + handle.push(update(all)).unwrap(); + h.synced(&handle).await; + handle.script(Script::answer("list", entities(vec![])).once()); + h.engine.send(list(2)); + let result = h + .next(|e| match e { + Event::FileList { request: 2, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(result.unwrap(), []); + // And the offline messages the host now has. + handle.script(Script::answer("list", entities(vec![])).once()); + h.engine.send(Command::ListOfflineMessages { session: SESSION, request: 3 }); + let result = h + .next(|e| match e { + Event::OfflineMessages { request: 3, result, .. } => Some(result), + _ => None, + }) + .await; + assert!(result.unwrap().is_empty()); +} + +fn mail(id: u64, from: &str, subject: &str, text: &str, ts_ms: i64) -> Kind { + Kind::Mail(v1::Mail { + id, + from_uid: from.into(), + subject: subject.into(), + text: text.into(), + ts_ms, + ..Default::default() + }) +} + +/// Offline messages are `Mail`; the fake host stores none, so the answers are +/// scripted, and the requests are what the host received. +#[tokio::test(flavor = "multi_thread")] +async fn offline_messages_are_mail() { + let connector = connector(); + let mut features: Vec = DEFAULT_FEATURES.iter().map(|f| (*f).to_owned()).collect(); + features.push("mailbox".into()); + connector.host().set_features(features); + let mut h = Harness::on(connector); + let handle = h.connect().await; + let before = handle.requests().len(); + + // Without a mailbox the engine would have refused; with one it asks. + handle.script(Script::new("list", |op| { + let Op::List(list) = op else { return Err(SessionError::Protocol("not a list".into())) }; + Ok(match list.ids.as_slice() { + [] => entities(vec![mail(7, "carol=", "hello", "", 1_234_000)]), + _ => entities(vec![mail(7, "carol=", "hello", "the whole text", 1_234_000)]), + }) + })); + h.engine.send(Command::ListOfflineMessages { session: SESSION, request: 1 }); + let listed = h + .next(|e| match e { + Event::OfflineMessages { request: 1, result, .. } => Some(result), + _ => None, + }) + .await + .expect("the list"); + assert_eq!(listed.len(), 1); + let info = &listed[0]; + assert_eq!( + (info.id, info.from_uid.as_str(), info.subject.as_str(), info.ts_s, info.read), + (7, "carol=", "hello", 1_234, false) + ); + + h.engine.send(Command::GetOfflineMessage { session: SESSION, request: 2, id: 7 }); + let got = h + .next(|e| match e { + Event::OfflineMessage { request: 2, result, .. } => Some(result), + _ => None, + }) + .await + .expect("the message"); + assert_eq!((got.id, got.text.as_str(), got.ts_s), (7, "the whole text", 1_234)); + let get = + request_after(&handle, before, "the get", |op| matches!(op, Op::List(l) if l.ids == [7])) + .await; + let Some(Op::List(get)) = get.request.op else { unreachable!() }; + assert_eq!(get.kind, v1::EntityKind::Mail as i32); + + // Write, flag and delete: the requests the host received. + handle.script(Script::answer("put", entities(vec![mail(0, "", "", "", 0)])).times(2)); + handle.script(Script::answer("delete", response::Result::Ack(v1::Ack { rev: 0 })).once()); + h.engine.send(Command::SendOfflineMessage { + session: SESSION, + request: 3, + to_uid: "dave=".into(), + subject: "re".into(), + text: "see you".into(), + }); + h.engine.send(Command::SetOfflineMessageRead { + session: SESSION, + request: 4, + id: 7, + read: true, + }); + h.engine.send(Command::DeleteOfflineMessage { session: SESSION, request: 5, id: 7 }); + let mut done = Vec::new(); + while done.len() < 3 { + let (request, result) = h + .next(|e| match e { + Event::RequestDone { request, result, .. } => Some((request, result)), + _ => None, + }) + .await; + assert_eq!(result, Ok(()), "request {request}"); + done.push(request); + } + done.sort(); + assert_eq!(done, [3, 4, 5]); + let mails: Vec<_> = requests_after(&handle, before) + .into_iter() + .filter_map(|l| match l.request.op { + Some(Op::Put(put)) => put.writes.into_iter().next(), + _ => None, + }) + .filter_map(|w| match w.entity?.kind? { + Kind::Mail(mail) => { + Some((mail.id, mail.to_uid, mail.subject, mail.text, mail.read, w.paths)) + } + _ => None, + }) + .collect(); + // Only the `read` leaf of the flagged mail is written. + let read_leaf = v1::Write::patch(entity(mail(7, "", "", "", 0)), ["read"]).unwrap().paths; + assert_eq!( + mails, + [ + (0, "dave=".into(), "re".into(), "see you".into(), false, vec![]), + (7, String::new(), String::new(), String::new(), true, read_leaf), + ] + ); + let delete = + request_after(&handle, before, "the delete", |op| matches!(op, Op::Delete(_))).await; + let Some(Op::Delete(delete)) = delete.request.op else { unreachable!() }; + assert!(matches!(delete.keys[0].kind, Some(Kind::Mail(ref m)) if m.id == 7)); + + // A host without a mailbox is not asked. + let mut plain = Harness::start(); + let plain_handle = plain.connect().await; + let count = plain_handle.requests().len(); + plain.engine.send(Command::ListOfflineMessages { session: SESSION, request: 9 }); + let result = plain + .next(|e| match e { + Event::OfflineMessages { request: 9, result, .. } => Some(result), + _ => None, + }) + .await; + assert_eq!(result.unwrap_err(), "not offered by this server: mailbox"); + assert_eq!(plain_handle.requests().len(), count); +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("voelin-session-fake-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn pattern(len: usize) -> Vec { + (0..len).map(|i| (i * 7 % 251) as u8).collect() +} + +async fn transfer_done(h: &mut Harness, id: u64) -> TransferState { + h.next(|e| match e { + Event::Transfer { transfer, state, .. } if transfer == id && state.is_final() => { + Some(state) + } + _ => None, + }) + .await +} + +/// A file goes up through `write_file` and comes back through `read_file`, +/// byte for byte; a resumed upload goes on where the host's copy ends. +#[tokio::test(flavor = "multi_thread")] +async fn files_go_through_read_file_and_write_file() { + let mut h = Harness::start(); + let handle = h.connect().await; + let dir = temp_dir("transfers"); + let data = pattern(3_000); + let local = dir.join("up.bin"); + std::fs::write(&local, &data).unwrap(); + let upload = |transfer, path: &str, resume| Command::UploadFile { + session: SESSION, + transfer, + channel: GAMES, + password: None, + path: path.into(), + from: local.clone(), + overwrite: false, + resume, + }; + + h.engine.send(upload(1, "/docs/up.bin", false)); + assert!(matches!(transfer_done(&mut h, 1).await, TransferState::Done { size: 3_000, .. })); + let write = + request_after(&handle, 0, "the file write", |op| matches!(op, Op::FileWrite(_))).await; + let Some(Op::FileWrite(write)) = write.request.op else { unreachable!() }; + assert_eq!((write.size, write.offset, write.overwrite), (3_000, 0, false)); + let Some(v1::file_write::Target::Path(path)) = write.target else { panic!("a path") }; + assert_eq!((path.channel_id, path.path.as_str()), (GAMES, "/docs/up.bin")); + + h.engine.send(Command::DownloadFile { + session: SESSION, + transfer: 2, + channel: GAMES, + password: None, + path: "/docs/up.bin".into(), + to: DownloadTo::Memory, + }); + let TransferState::Done { size, data: Some(bytes), .. } = transfer_done(&mut h, 2).await else { + panic!("a finished download") + }; + assert_eq!((size, &*bytes.0), (3_000, data.as_slice())); + let read = request_after(&handle, 0, "the file read", |op| matches!(op, Op::FileRead(_))).await; + let Some(Op::FileRead(read)) = read.request.op else { unreachable!() }; + assert_eq!(read.offset, 0); + + // A file that is not there fails with the host's words. + h.engine.send(Command::DownloadFile { + session: SESSION, + transfer: 3, + channel: GAMES, + password: None, + path: "/docs/missing.bin".into(), + to: DownloadTo::Memory, + }); + assert_eq!(transfer_done(&mut h, 3).await, TransferState::Failed("no such file".into())); + + // An upload that was interrupted left 1,000 bytes with the host (written + // by another session of it, and dropped before it was shut down). + let other = h.connector.connect(connect_params("fake://other").0).await.expect("a session"); + let mut partial = other + .session + .write_file(v1::FileWrite { + target: Some(v1::file_write::Target::Path(v1::FilePath { + channel_id: GAMES, + path: "/docs/big.bin".into(), + password: String::new(), + })), + size: 3_000, + offset: 0, + overwrite: false, + sha256: Default::default(), + }) + .await + .expect("an upload"); + partial.body.write_all(&data[..1_000]).await.unwrap(); + drop(partial); + // The host's listing of the directory shows the partial size, as a host that + // keeps partial files does (the fake refuses the path of a `List`). + let size_of_copy = Kind::File(v1::FileEntry { + channel_id: GAMES, + path: "/docs".into(), + name: "big.bin".into(), + size: 1_000, + ..Default::default() + }); + handle.script(Script::answer("list", entities(vec![size_of_copy])).once()); + h.engine.send(upload(4, "/docs/big.bin", true)); + assert!(matches!(transfer_done(&mut h, 4).await, TransferState::Done { size: 3_000, .. })); + let writes: Vec<_> = handle + .requests() + .into_iter() + .filter_map(|l| match l.request.op { + Some(Op::FileWrite(w)) => Some((w.offset, w.size)), + _ => None, + }) + .collect(); + assert_eq!(writes, [(0, 3_000), (1_000, 3_000)]); + h.engine.send(Command::DownloadFile { + session: SESSION, + transfer: 5, + channel: GAMES, + password: None, + path: "/docs/big.bin".into(), + to: DownloadTo::Memory, + }); + let TransferState::Done { data: Some(bytes), .. } = transfer_done(&mut h, 5).await else { + panic!("a finished download") + }; + assert_eq!(&*bytes.0, data.as_slice(), "the resumed file is whole"); + let _ = std::fs::remove_dir_all(dir); +} + +/// File operations of the voice session are `Put` and `Delete` of `FileEntry` +/// keys; the answers (scripted: the fake stores no `FileEntry`) end the +/// requests the user made. +#[tokio::test(flavor = "multi_thread")] +async fn file_operations_are_puts_and_deletes_of_file_entries() { + let mut h = Harness::start(); + let handle = h.connect().await; + let before = handle.requests().len(); + handle.script(Script::answer("put", entities(vec![])).times(2)); + handle.script(Script::answer("delete", response::Result::Ack(v1::Ack { rev: 0 })).once()); + + h.engine.send(Command::CreateDirectory { + session: SESSION, + request: 1, + channel: GAMES, + password: Some("pw".into()), + path: "/docs/new".into(), + }); + h.engine.send(Command::RenameFile { + session: SESSION, + request: 2, + channel: GAMES, + password: None, + from: "/docs/a.txt".into(), + to: "/other/b.txt".into(), + to_channel: Some((LOBBY, Some("lobby pw".into()))), + }); + h.engine.send(Command::DeleteFiles { + session: SESSION, + request: 3, + channel: GAMES, + password: None, + paths: vec!["/docs/a.txt".into()], + }); + let mut done = Vec::new(); + while done.len() < 3 { + let (request, result) = h + .next(|e| match e { + Event::RequestDone { request, result, .. } => Some((request, result)), + _ => None, + }) + .await; + assert_eq!(result, Ok(()), "request {request}"); + done.push(request); + } + done.sort(); + assert_eq!(done, [1, 2, 3]); + + let files: Vec = requests_after(&handle, before) + .into_iter() + .flat_map(|l| match l.request.op { + Some(Op::Put(put)) => put.writes.into_iter().filter_map(|w| w.entity).collect(), + Some(Op::Delete(delete)) => delete.keys, + _ => vec![], + }) + .filter_map(|e| match e.kind? { + Kind::File(file) => Some(file), + _ => None, + }) + .collect(); + let key = |f: &v1::FileEntry| { + (f.channel_id, f.path.clone(), f.name.clone(), f.is_dir, f.password.clone()) + }; + let made = files.iter().find(|f| f.is_dir).expect("the new directory"); + assert_eq!(key(made), (GAMES, "/docs".into(), "new".into(), true, "pw".into())); + let moved = files.iter().find(|f| f.from_channel_id != 0).expect("the rename"); + assert_eq!(key(moved), (LOBBY, "/other".into(), "b.txt".into(), false, "lobby pw".into())); + assert_eq!((moved.from_channel_id, moved.from_path.as_str()), (GAMES, "/docs/a.txt")); + let deleted = files.iter().find(|f| !f.is_dir && f.from_channel_id == 0 && f.name == "a.txt"); + assert_eq!( + deleted.map(key), + Some((GAMES, "/docs".into(), "a.txt".into(), false, String::new())) + ); +} + +/// The media a session delivers to the engine's sink: who talks, and when +/// they stop; what comes from a slot nobody has is dropped; a whisper is a +/// talker too. +#[tokio::test(flavor = "multi_thread")] +async fn media_routes_to_the_talker_of_its_slot() { + let mut h = Harness::start(); + let handle = h.connect().await; + let (alice, bob) = (ALICE as u16, BOB as u16); + + // Nobody has this slot: nothing is shown. Bob's whisper is shown (sub-flow 1). + handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &OPUS)); + handle.inject_media(voice_packet(BOB_SLOT, 1, 1, &OPUS)); + let first = h + .next(|e| match e { + Event::Talking { client, talking, .. } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(first, (bob, true), "the unknown slot was not shown"); + + // Alice talks for a moment and stops: 400 ms of silence end the talking. + let started = tokio::time::Instant::now(); + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &OPUS)); + h.next(|e| { + matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) + }) + .await; + h.next(|e| { + matches!(e, Event::Talking { client, talking: false, .. } if client == alice).then_some(()) + }) + .await; + assert!(started.elapsed() >= Duration::from_millis(400), "{:?}", started.elapsed()); + // Feedback and probe flows are no voice. + handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) }); + handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 2, &OPUS)); + h.next(|e| { + matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) + }) + .await; +} + +/// A second `ConnectVoice` replaces the session: the host sees the first one +/// closed, the second finds the state the first left (a message said while we +/// were away comes), and the participant of the second session is another one. +/// +/// What this proves about the replay is narrow: the one message seen before +/// the disconnect is not shown again because `Dedup` still holds it (it is the +/// newest message the engine saw, and `Dedup` keeps the messages up to 4 s +/// older than the last one it was asked about), so the copy the host's sync +/// brings is dropped. A replayed message older than that is shown again, and +/// every replayed message is stored again: the two ignored tests below pin +/// both (F3, `docs/session-seam.md` 16.5). +#[tokio::test(flavor = "multi_thread")] +async fn a_reconnect_finds_the_state_the_first_session_left() { + let mut h = Harness::start(); + let first = h.connect().await; + let host = h.host(); + let t = now_ms(); + host.put(entity(message(GAMES, ALICE_AUTHOR, "before", t))).unwrap(); + assert_eq!(h.chat().await.text, "before"); + + // Away, and a message is said that nobody of ours hears live. + h.engine.send(Command::DisconnectVoice { session: SESSION }); + h.state(|s| s.voice == VoiceState::Disconnected).await; + eventually(WAIT, "the host to see the first session closed", || first.close_reason().is_some()) + .await; + assert_eq!(first.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); + host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); + + let second = h.connect().await; + assert_eq!(h.connector.connects().len(), 2); + assert_eq!(h.connector.sessions().len(), 2); + // The window of the CHAT scope comes again, "before" with it. It is not + // shown only because `Dedup` still holds it, the newest message seen; a + // message older than `Dedup`'s 4 s would be shown (the ignored tests below). + assert_eq!(h.chat().await.text, "while away"); + assert_eq!(h.state.own_client, Some(second.participant_id() as u16)); + assert_ne!(second.participant_id(), first.participant_id()); + // The first session's seat is gone from the host, ours is the only one. + let seats: Vec = host + .entities(&scope(v1::ScopeKind::Live, SERVER)) + .into_iter() + .filter_map(|e| match e.kind? { + Kind::Voice(v) => Some(v.participant_id), + _ => None, + }) + .collect(); + assert!(!seats.contains(&first.participant_id()), "{seats:?}"); + assert!(seats.contains(&second.participant_id()), "{seats:?}"); + // (That the history has each message once, and that a replayed message + // older than `Dedup`'s 4 s is not shown again, are the business of the + // ignored tests below.) +} + +/// Asking to connect while connected replaces the session at once: the host +/// sees the old session closed by us, and the engine follows the new one. +#[tokio::test(flavor = "multi_thread")] +async fn connecting_while_connected_replaces_the_session() { + let mut h = Harness::start(); + let first = h.connect().await; + h.ask_connect(); + let connector = h.connector.clone(); + eventually(WAIT, "the second session", || connector.sessions().len() == 2).await; + let second = connector.last_session().expect("a second session"); + assert_ne!(second.participant_id(), first.participant_id()); + h.state(|s| s.own_client == Some(second.participant_id() as u16)).await; + eventually(WAIT, "the first session to be closed", || first.close_reason().is_some()).await; + assert_eq!(first.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); + assert!(second.close_reason().is_none(), "the new session is open"); +} + +/// What a host that sends the window of a CHAT scope again makes of a +/// reconnect. Two messages more than `Dedup`'s 4 s apart are said and seen, +/// the session ends, a third is said while we are away, and a second session +/// connects. Returns the harness and the texts the engine showed as live chat +/// messages from the second connect until the third had come, and what was +/// still to come when a notice that the host told after them arrived. +/// +/// The window is replayed oldest first (by id), so "while away" is its last +/// message, and whatever precedes it in the result is a replayed message that +/// the engine showed again. +async fn a_reconnect_to_a_host_that_replays() -> (Harness, Vec) { + let mut h = Harness::start(); + let first = h.connect().await; + let host = h.host(); + let t = now_ms(); + host.put(entity(message(GAMES, ALICE_AUTHOR, "first", t))).unwrap(); + host.put(entity(message(GAMES, ALICE_AUTHOR, "second", t + 10_000))).unwrap(); + assert_eq!(h.chat().await.text, "first"); + assert_eq!(h.chat().await.text, "second"); + h.engine.send(Command::DisconnectVoice { session: SESSION }); + h.state(|s| s.voice == VoiceState::Disconnected).await; + eventually(WAIT, "the host to see the first session closed", || first.close_reason().is_some()) + .await; + host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); + + let second = h.connect().await; + let mut shown = Vec::new(); + while shown.last().map(String::as_str) != Some("while away") { + shown.push(h.chat().await.text); + } + // Everything the host's sync had to say is behind us; a notice it tells now + // comes after whatever the engine still reports. + notice(&second, "sync marker"); + loop { + let more = h + .next(|e| match e { + Event::Chat { message, .. } => Some(Some(message.text)), + Event::Error { message, .. } if message == "sync marker" => Some(None), + _ => None, + }) + .await; + match more { + Some(text) => shown.push(text), + None => return (h, shown), + } + } +} + +/// The messages a host sends again when a session reconnects are not shown +/// again: the engine shows "while away" and nothing else. +/// +/// Known limit, found by this test and left for the resume of +/// `docs/session-seam.md` (H8, 16.5): the engine is told every message of a +/// replayed window again (`seen` in `SessionLink` is per connection), and +/// `Dedup` in `session.rs` drops one only while an equal message (target, +/// author, text, a timestamp within 2 s) is still held, and it holds the +/// messages up to 4 s older than the last one it was asked about. "second", +/// the newest message seen before the disconnect, is held and its replay is +/// dropped; "first", 10 s older, is not, and is shown again as a live +/// `Event::Chat` (this test sees `["first", "while away"]`). The one message +/// of `a_reconnect_finds_the_state_the_first_session_left` is inside the +/// window, which is all that test proves. TeamSpeak never replays, so no host +/// the engine reaches today meets this; a `voelin://` host will. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "known limit: a v1 host's replay after a reconnect is shown again (docs/session-seam.md 16.5)"] +async fn a_message_the_host_sends_again_after_a_reconnect_is_not_shown_again() { + let (_h, shown) = a_reconnect_to_a_host_that_replays().await; + assert_eq!(shown, ["while away"]); +} + +/// The messages a host sends again when a session reconnects are one message +/// each in the history. +/// +/// Known limit, found by this test and left for the same resume (H8, 16.5): +/// the engine stores every message it is told, shown or not (`store_live` runs +/// before `Dedup`), and the store merges copies that come from different +/// sources only, so a replay over the same source is a second row, whether +/// `Dedup` hid the copy from the display or not (this test sees `["first", +/// "first", "second", "second", "while away"]`). A `ChatMessage` does not carry +/// the host's message id that would let the store merge them. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "known limit: a v1 host's replay after a reconnect is stored twice (docs/session-seam.md 16.5)"] +async fn a_message_the_host_sends_again_after_a_reconnect_is_stored_once() { + let (h, _) = a_reconnect_to_a_host_that_replays().await; + // The history thread takes its jobs in order: every row the engine was told + // to write before it showed "while away" is written when this page is read. + let rows = h.stored(ChatTarget::Channel(GAMES)).await; + let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); + assert_eq!(texts, ["first", "second", "while away"]); +} + +/// A connect that fails is a disconnect with the reason the connector gave. +#[tokio::test(flavor = "multi_thread")] +async fn a_connect_that_fails_says_why_and_the_next_one_works() { + let connector = connector(); + connector.fail_next(|| SessionError::Protocol("the host is down".into())); + let mut h = Harness::on(connector); + h.ask_connect(); + let state = h.state(|s| s.voice == VoiceState::Disconnected).await; + assert_eq!((state.own_channel, state.own_client), (None, None)); + assert_eq!(h.error().await, "voice: the host is down"); + + // The connector is asked again, and now the host is up. + let handle = h.connect().await; + assert_eq!(h.connector.connects().len(), 2); + assert!(handle.close_reason().is_none()); + let first = &h.connector.connects()[0]; + assert_eq!(first.address, "fake://host"); + assert_eq!(first.hello.nickname, "tester"); +} + +/// A TeamSpeak identity that holds no JSON is refused with its reason before a +/// connector is asked for anything: an empty credential blob would ask a +/// TeamSpeak connector to make an identity up, which only `identity: None` may. +#[tokio::test(flavor = "multi_thread")] +async fn a_teamspeak_identity_without_json_is_refused_and_no_session_is_made() { + let mut h = Harness::start(); + let mut options = VoiceOptions::new("fake://host", "tester"); + options.identity = Some(IdentityBlob::teamspeak("uid=", 8, "")); + h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + let state = h.state(|s| s.voice == VoiceState::Disconnected).await; + assert_eq!((state.own_channel, state.own_client), (None, None)); + assert_eq!(h.error().await, "voice: the TeamSpeak identity cannot be read: it is empty"); + assert!(h.connector.connects().is_empty(), "the connector was asked to connect"); + assert!(h.connector.last_session().is_none(), "a session was made"); + + // Without an identity the connector is asked as usual. + let handle = h.connect().await; + assert!(handle.close_reason().is_none()); + assert_eq!(h.connector.connects().len(), 1); +} diff --git a/crates/voelin-gateway-proto/Cargo.toml b/crates/voelin-gateway-proto/Cargo.toml index 241f55b..4a1cf98 100644 --- a/crates/voelin-gateway-proto/Cargo.toml +++ b/crates/voelin-gateway-proto/Cargo.toml @@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional = # TLS (`wss://`, as gateways run behind a proxy) with the system's # certificates; rustls and its crates are in the tree already (reqwest). tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] } -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } tsproto-types = { path = "../proto/tsproto-types" } [lints] diff --git a/crates/voelin-gateway/Cargo.toml b/crates/voelin-gateway/Cargo.toml index 3492e4b..7245cea 100644 --- a/crates/voelin-gateway/Cargo.toml +++ b/crates/voelin-gateway/Cargo.toml @@ -29,7 +29,7 @@ toml = "1.1.6" tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } voelin-gateway-proto = { path = "../voelin-gateway-proto" } -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } voelin-observer = { path = "../voelin-observer" } voelin-query = { path = "../voelin-query" } diff --git a/crates/voelin-model/Cargo.toml b/crates/voelin-model/Cargo.toml deleted file mode 100644 index d78b175..0000000 --- a/crates/voelin-model/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "voelin-model" -version = "0.1.0" -description = "UI-facing domain model shared by the client engine, gateway and UI (no IO)." -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -publish.workspace = true - -[dependencies] -serde = { version = "1", features = ["derive"] } - -[dev-dependencies] -serde_json = "1" - -[lints] -workspace = true diff --git a/crates/voelin-model/data/badges.csv b/crates/voelin-model/data/badges.csv deleted file mode 100644 index 1ec643c..0000000 --- a/crates/voelin-model/data/badges.csv +++ /dev/null @@ -1,94 +0,0 @@ -uid,name,description,filename,codes -4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years, -f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers, -b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat, -2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha, -05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg, -1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ -cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb, -d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat, -dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill, -afed63f4-82f1-4479-ab02-0ef053f55723,Communities Early Adopter,Thank you for your Support!,communities_early_adopter, -54be472d-3163-4076-9059-7f46128d937e,Communities Purchase,Purchased a TeamSpeak Community,communities_purchase, -f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk, -c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi, -56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP -935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018, -61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022, -b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN -809bdd5a-2601-4152-82ff-a21d23d8fd46,G2 Esports,Aged 20 years being a G2 fan,G2_Esports, -62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014, -50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016, -534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q -4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4 -b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8 -34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017, -24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C -d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD, -c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21, -133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special, -fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22, -e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023, -de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays, -d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020, -1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear, -834d4cc1-cd80-48d6-96c4-23d131d78649,Happy Summer 2023,heat death of the universe,happy_summer_2023, -c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream, -94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase, -288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay, -69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022, -9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft, -7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom, -ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas, -c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020, -0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021, -d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022, -87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl, -0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg, -2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose, -c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018, -8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge, -4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant, -fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014, -d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016, -0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet, -be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist, -5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg, -ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride, -1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg, -f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ -2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg, -641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg, -63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast, -ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship, -7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome, -7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden, -6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered, -e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick, -1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author, -450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze, -94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold, -c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver, -9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge, -64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG, -6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red, -22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper, -205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3, -8d843dfa-c51a-407f-87b3-94cfc8f03e96,TeamSpeak Staff,Official Staff Member,teamspeak_staff, -c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing, -4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT -089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg, -904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine, -4c61af66-22ef-4897-b0bb-25fcef2acf60,Undead Nightmare,I'm the last of my kind,undead_nightmare, -b0a36aea-3e46-4e83-a455-6e92ae1b9d94,Undead Nightmare,I'm the last of my kind,undead_nightmare, -0cd924ed-c5ea-459e-b60a-4f1bc0b65f07,"Up, Up and Away!",Find me on Mount Chiliad,"up,_up_and_away!", -4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge, -92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020, -958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23, -a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21, -c54a9f92-07f7-4214-90f3-eafeea8005da,World Backup Day,Don't be an April Fool. Back up your data!,backupday_2023, -448a6d13-4e08-46a1-aafa-b4ff6d6c2d06,World Bonsai Day,"harmony, balance, patience",bonsai_day, -0f976a27-ddf5-447c-b79c-0644a8e8a297,Year of the Dragon 2024,"Arise, Shenron!",year_of_the_dragon_2024, -8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21, -970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023, -92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger, diff --git a/crates/voelin-model/src/badges.rs b/crates/voelin-model/src/badges.rs deleted file mode 100644 index be1461c..0000000 --- a/crates/voelin-model/src/badges.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! myTeamSpeak badges: what the GUIDs a client shows (`client_badges`) -//! stand for, and where TeamSpeak keeps their pictures. -//! -//! The table is `data/badges.csv`: tsclientlib's list (2023, also in -//! `proto/tsproto-structs/declarations`) and the newer badges of -//! TeamSpeak's own list (`https://badges-content.teamspeak.com/list`, a -//! protobuf) as of October 2026. Badges added since are unknown here. - -use std::collections::HashMap; -use std::sync::LazyLock; - -/// How many badges a client shows at most (TeamSpeak lets one pick three). -pub const SHOWN: usize = 3; - -/// TeamSpeak's server for the badges' pictures. -const CONTENT: &str = "https://badges-content.teamspeak.com"; - -/// One badge of the table. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BadgeInfo { - pub name: String, - pub description: String, - /// Its picture's name on TeamSpeak's server, without `.svg`. - pub filename: String, -} - -/// The table by GUID (lower case), read once. -static BADGES: LazyLock> = LazyLock::new(|| { - // Columns: uid, name, description, filename, codes. - records(include_str!("../data/badges.csv")) - .into_iter() - .skip(1) - .filter_map(|mut fields| { - fields.truncate(4); - let [uid, name, description, filename] = <[String; 4]>::try_from(fields).ok()?; - Some((uid.to_ascii_lowercase(), BadgeInfo { name, description, filename })) - }) - .collect() -}); - -/// What a badge GUID stands for; none for one the table does not know. -pub fn info(guid: &str) -> Option<&'static BadgeInfo> { - BADGES.get(&guid.to_ascii_lowercase()) -} - -/// The address of a badge's picture (an SVG); none for an unknown badge. -pub fn icon_url(guid: &str) -> Option { - let info = info(guid)?; - Some(format!("{CONTENT}/{}/{}.svg", guid.to_ascii_lowercase(), info.filename)) -} - -/// The records of a CSV text (RFC 4180): fields split at commas; a quoted -/// field may hold commas and line breaks, and `""` for a quote. -fn records(text: &str) -> Vec> { - let mut records = Vec::new(); - let mut record = Vec::new(); - let mut field = String::new(); - let mut quoted = false; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { - match c { - '"' if quoted => { - if chars.next_if_eq(&'"').is_some() { - field.push('"'); - } else { - quoted = false; - } - } - '"' if field.is_empty() => quoted = true, - ',' if !quoted => record.push(std::mem::take(&mut field)), - '\r' if !quoted => {} - '\n' if !quoted => { - record.push(std::mem::take(&mut field)); - records.push(std::mem::take(&mut record)); - } - c => field.push(c), - } - } - if !field.is_empty() || !record.is_empty() { - record.push(field); - records.push(record); - } - records -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn known_badges() { - let info = info("4b27be5a-b92a-4b30-8b2d-14b59653f427").unwrap(); - assert_eq!(info.name, "20th Anniversary"); - assert_eq!(info.description, "Celebrating 20 Years of TeamSpeak"); - assert_eq!(info.filename, "20_years"); - // Upper case on the wire finds it too. - assert_eq!(super::info("4B27BE5A-B92A-4B30-8B2D-14B59653F427"), Some(info)); - assert_eq!( - icon_url("4b27be5a-b92a-4b30-8b2d-14b59653f427").as_deref(), - Some( - "https://badges-content.teamspeak.com/4b27be5a-b92a-4b30-8b2d-14b59653f427/20_years.svg" - ) - ); - } - - #[test] - fn quoted_fields_keep_their_commas() { - let fools = info("05114019-6b46-4b13-b5a1-e5179ef69fb5").unwrap(); - assert_eq!(fools.name, "April Fools!"); - assert_eq!( - fools.description, - "Roses are red, gaming is fun, you are carrying too much to be able to run :(" - ); - assert_eq!(fools.filename, "rpg"); - let stay = info("7a627d47-5496-4d68-83b5-2c4eafff9b30").unwrap(); - assert_eq!(stay.name, "Stay Home, Stay Safe"); - assert_eq!(stay.description, "Playing Apart, Staying Connected"); - let up = info("0cd924ed-c5ea-459e-b60a-4f1bc0b65f07").unwrap(); - assert_eq!(up.filename, "up,_up_and_away!"); - } - - #[test] - fn unknown_badges() { - assert_eq!(info("00000000-0000-0000-0000-000000000000"), None); - assert_eq!(info(""), None); - assert_eq!(icon_url("00000000-0000-0000-0000-000000000000"), None); - } - - #[test] - fn every_row_is_read() { - let rows = include_str!("../data/badges.csv").lines().count() - 1; - assert_eq!(BADGES.len(), rows); - assert!(BADGES.values().all(|b| !b.name.is_empty() && !b.filename.is_empty())); - } - - #[test] - fn csv_records() { - assert_eq!( - records("a,\"b, \"\"c\"\"\",\r\n\"multi\nline\",d"), - [vec!["a", "b, \"c\"", ""], vec!["multi\nline", "d"]] - ); - assert!(records("").is_empty()); - } -} diff --git a/crates/voelin-model/src/chat.rs b/crates/voelin-model/src/chat.rs deleted file mode 100644 index 8068b43..0000000 --- a/crates/voelin-model/src/chat.rs +++ /dev/null @@ -1,283 +0,0 @@ -//! Chat messages, from any source. -//! -//! Messages can link files in a channel's file browser: TeamSpeak clients -//! post them as `[URL=ts3file://…]name[/URL]`; [`ChatMessage::file_refs`] -//! finds them as [`FileRef`]s (for file cards) and [`FileRef::to_bbcode`] -//! writes one. - -use serde::{Deserialize, Serialize}; - -use crate::percent; -use crate::presence::{ChannelId, ClientId}; - -fn is_false(b: &bool) -> bool { - !*b -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(tag = "kind", content = "id", rename_all = "snake_case")] -pub enum ChatTarget { - /// Everyone on the server. - Server, - Channel(ChannelId), - /// Private chat, by the other side's unique id when known. - Private(String), -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessage { - pub target: ChatTarget, - pub author_name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub author_uid: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub author_id: Option, - pub text: String, - /// Unix time in milliseconds. - pub ts_ms: i64, - /// Carried by a gateway or query relay rather than our own connection. - #[serde(default)] - pub via_relay: bool, - /// The author is blocked in our contacts (set by the engine when it - /// reports the message; never sent over the wire). - #[serde(default, skip_serializing_if = "is_false")] - pub blocked: bool, -} - -impl ChatMessage { - /// The file links in the text, in order of appearance, each once. - pub fn file_refs(&self) -> Vec { - parse_file_links(&self.text) - } -} - -/// A file in a channel's file browser, as a chat message links it. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct FileRef { - /// The server's unique id (`serverUID`), when the link tells it: a link - /// from another server cannot be downloaded here. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub server_uid: Option, - pub channel: ChannelId, - /// The directory, `/` for the channel's root. - pub path: String, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub size: Option, - #[serde(default, skip_serializing_if = "is_false")] - pub is_dir: bool, - /// Unix seconds of the last change, when the link tells it. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub modified_s: Option, - /// The link as it appeared. - pub url: String, -} - -/// URL schemes of file links (`ts3file`; later clients may use others of -/// the same form). -const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"]; - -impl FileRef { - /// The file's path in the channel: [`Self::path`] joined with [`Self::name`]. - pub fn full_path(&self) -> String { - let dir = self.path.trim_end_matches('/'); - format!("{dir}/{}", self.name) - } - - /// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`). - pub fn parse(url: &str) -> Option { - let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase(); - let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?; - let rest = &url[scheme.len()..]; - let (host, query) = rest.split_once('?').unwrap_or((rest, "")); - let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() }; - let mut channel = None; - for pair in query.split('&') { - let (key, value) = pair.split_once('=').unwrap_or((pair, "")); - let value = percent::decode(value); - match key.to_ascii_lowercase().as_str() { - "serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()), - "channel" | "cid" => channel = value.parse().ok(), - "path" => file.path = if value.is_empty() { "/".into() } else { value }, - "filename" | "name" => file.name = value, - "isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"), - "size" => file.size = value.parse().ok(), - "filedatetime" => file.modified_s = value.parse().ok(), - _ => {} - } - } - if file.name.is_empty() { - file.name = percent::decode(host.trim_end_matches('/')); - } - file.channel = channel?; - (!file.name.is_empty()).then_some(file) - } - - /// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`. - pub fn to_bbcode(&self) -> String { - let mut url = format!("ts3file://{}?", percent::encode(&self.name)); - if let Some(uid) = &self.server_uid { - url.push_str(&format!("serverUID={}&", percent::encode(uid))); - } - url.push_str(&format!( - "channel={}&path={}&filename={}&isDir={}", - self.channel, - percent::encode(&self.path), - percent::encode(&self.name), - u8::from(self.is_dir) - )); - if let Some(size) = self.size { - url.push_str(&format!("&size={size}")); - } - if let Some(t) = self.modified_s { - url.push_str(&format!("&fileDateTime={t}")); - } - format!("[URL={url}]{}[/URL]", self.name) - } -} - -/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown -/// `[name](…)` or bare), in order, each once. -pub fn parse_file_links(text: &str) -> Vec { - let lower = text.to_ascii_lowercase(); - let mut found: Vec = Vec::new(); - let mut at = 0; - while at < text.len() { - let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min(); - let Some(start) = next else { break }; - let end = text[start..] - .find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>')) - .map_or(text.len(), |i| start + i); - if let Some(file) = FileRef::parse(&text[start..end]) - && !found.iter().any(|f| f.url == file.url) - { - found.push(file); - } - at = end.max(start + 1); - } - found -} - -/// Format of messages a relay posts on behalf of a user. -pub fn relay_text(format: &str, nick: &str, text: &str) -> String { - format.replace("{nick}", nick).replace("{text}", text) -} - -/// Split text so each part fits TeamSpeak's message limit (1024 bytes of -/// text), breaking at character boundaries. -pub fn split_message(text: &str, max_bytes: usize) -> Vec { - let mut parts = Vec::new(); - let mut current = String::new(); - for c in text.chars() { - if current.len() + c.len_utf8() > max_bytes { - parts.push(std::mem::take(&mut current)); - } - current.push(c); - } - if !current.is_empty() || parts.is_empty() { - parts.push(current); - } - parts -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn relay_format() { - assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi"); - } - - #[test] - fn splits_on_char_boundaries() { - assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]); - assert_eq!(split_message("", 4), vec![""]); - let parts = split_message("ääää", 3); - assert!(parts.iter().all(|p| p.len() <= 3)); - assert_eq!(parts.concat(), "ääää"); - } - - #[test] - fn parses_ts3_file_links() { - let text = "look: [URL=ts3file://Report%20Q3.pdf?serverUID=l%2FHvD5zXg5r4%2F%2FC6Ht7J9Ts3Wmc%3D&channel=5&path=%2Fdocs&filename=Report%20Q3.pdf&isDir=0&size=12345&fileDateTime=1454598011]Report Q3.pdf[/URL] and [URL]ts3file://a.txt?channel=1&path=%2F&filename=a+b.txt[/URL]"; - let files = parse_file_links(text); - assert_eq!(files.len(), 2); - let f = &files[0]; - assert_eq!(f.server_uid.as_deref(), Some("l/HvD5zXg5r4//C6Ht7J9Ts3Wmc=")); - assert_eq!((f.channel, f.path.as_str(), f.name.as_str()), (5, "/docs", "Report Q3.pdf")); - assert_eq!((f.size, f.modified_s, f.is_dir), (Some(12345), Some(1_454_598_011), false)); - assert_eq!(f.full_path(), "/docs/Report Q3.pdf"); - assert_eq!(files[1].name, "a+b.txt"); - assert_eq!(files[1].full_path(), "/a+b.txt"); - } - - #[test] - fn file_links_in_other_forms() { - // Markdown, bare, a repeated link, a link without a channel. - let text = "[x](ts3file://x?channel=2&filename=x&isDir=true) ts3file://y?channel=3&path=/d/ \ - ts3file://y?channel=3&path=/d/ ts3file://z?filename=z"; - let files = parse_file_links(text); - assert_eq!(files.len(), 2); - assert!(files[0].is_dir); - assert_eq!((files[1].name.as_str(), files[1].full_path().as_str()), ("y", "/d/y")); - let msg = ChatMessage { - target: ChatTarget::Channel(1), - author_name: "a".into(), - author_uid: None, - author_id: None, - text: text.into(), - ts_ms: 0, - via_relay: false, - blocked: false, - }; - assert_eq!(msg.file_refs(), files); - assert!(parse_file_links("no links, ts3file:// alone").is_empty()); - } - - #[test] - fn file_link_round_trip() { - let file = FileRef { - server_uid: Some("uid+/=".into()), - channel: 7, - path: "/a dir".into(), - name: "ä b&c.png".into(), - size: Some(10), - is_dir: false, - modified_s: Some(99), - url: String::new(), - }; - let text = file.to_bbcode(); - let parsed = parse_file_links(&text); - assert_eq!(parsed.len(), 1); - assert_eq!(FileRef { url: String::new(), ..parsed[0].clone() }, file); - assert!(text.ends_with("]ä b&c.png[/URL]")); - } - - #[test] - fn blocked_flag_stays_off_the_wire() { - let msg = ChatMessage { - target: ChatTarget::Server, - author_name: "a".into(), - author_uid: None, - author_id: None, - text: "t".into(), - ts_ms: 1, - via_relay: false, - blocked: false, - }; - let json = serde_json::to_string(&msg).unwrap(); - assert!(!json.contains("blocked")); - let back: ChatMessage = serde_json::from_str(&json).unwrap(); - assert_eq!(back, msg); - } - - #[test] - fn target_json() { - assert_eq!( - serde_json::to_string(&ChatTarget::Channel(5)).unwrap(), - r#"{"kind":"channel","id":5}"# - ); - assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#); - } -} diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs deleted file mode 100644 index cd859fd..0000000 --- a/crates/voelin-model/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Domain model shared by the client engine, the gateway and the UI. -//! -//! Nothing in here does IO; the types describe what a server offers and what -//! the user sees. - -pub mod badges; -mod chat; -mod link; -mod percent; -mod presence; -mod server; -mod tree; - -pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; -pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path}; -pub use presence::{ - ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, - Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, shown_badges, -}; -pub use server::{ - BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, -}; -pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows}; diff --git a/crates/voelin-model/src/link.rs b/crates/voelin-model/src/link.rs deleted file mode 100644 index f2e3b99..0000000 --- a/crates/voelin-model/src/link.rs +++ /dev/null @@ -1,420 +0,0 @@ -//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://` -//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends -//! the browser on to a `teamspeak://` link. - -use crate::percent; -use crate::presence::ChannelId; - -/// What a link opens ([`Link::parse`]). -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Link { - /// A server, and maybe a channel on it. - Server(ServerLink), - /// A TeamSpeak 6 invite code (`tmspk.gg/`, - /// `teamspeak://invite=`): only a TeamSpeak service knows the - /// server it stands for. - Invite(String), -} - -/// A server link: the server, and what to join it with (none of it empty). -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct ServerLink { - /// A host name, an IP address (IPv6 without brackets) or a server - /// nickname. - pub host: String, - pub port: Option, - pub nickname: Option, - /// The server's password. - pub password: Option, - /// The channel to join: its names from the top, separated by `/` (a `/` - /// in a name as `\/`, [`split_channel_path`]), or `/` (`cid=`). - pub channel: Option, - pub channel_password: Option, - /// A privilege key: it puts its user in a server or channel group. - pub token: Option, -} - -const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"]; -const WEB: [&str; 2] = ["https://", "http://"]; -const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"]; - -impl Link { - /// Read a link: `ts3server://?` with the keys `port`, - /// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword` - /// and `token` (`teamspeak://` alike; the scheme and the keys in any - /// case, other keys ignored, a `+` kept as it is), - /// `https://tmspk.gg/s/?` (also `/s=`), and the - /// invite codes `tmspk.gg/` and `teamspeak://invite=`. None - /// for anything else. - pub fn parse(text: &str) -> Option { - let text = text.trim(); - // The same length in bytes: an index of one is one of the other. - let lower = text.to_ascii_lowercase(); - match SCHEMES.iter().find(|s| lower.starts_with(**s)) { - Some(scheme) => parse_server(&text[scheme.len()..]), - None => parse_short(text, &lower), - } - } -} - -impl ServerLink { - /// A link to the server at `address` (`host`, `host:port`, `[v6]`, - /// `[v6]:port` or a bare IPv6 address), joining nothing. - pub fn new(address: &str) -> Self { - let (host, port) = split_address(address.trim()); - ServerLink { host: host.to_owned(), port, ..Default::default() } - } - - /// The server's address as a bookmark keeps it: `host`, `host:port` or - /// `[v6]:port`. - pub fn address(&self) -> String { - match self.port { - Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host), - Some(port) => format!("{}:{port}", self.host), - None => self.host.clone(), - } - } - - /// The link as TeamSpeak clients open it: `ts3server://?port=…`, - /// then what is set of nickname, password, channel (or `cid` for - /// `/`), channel password and privilege key. - pub fn to_url(&self) -> String { - let mut url = match self.port { - Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host), - _ => format!("ts3server://{}", self.host), - }; - let pair = |key: &str, value: &Option| { - let value = value.as_deref().filter(|v| !v.is_empty())?; - Some(format!("{key}={}", percent::encode(value))) - }; - let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| { - match channel_path_id(path) { - Some(id) => format!("cid={id}"), - // A `/` between names, `%2F` in one. - None => { - let names: Vec = - split_channel_path(path).iter().map(|n| percent::encode(n)).collect(); - format!("channel={}", names.join("/")) - } - } - }); - let query: Vec = [ - self.port.map(|port| format!("port={port}")), - pair("nickname", &self.nickname), - pair("password", &self.password), - channel, - pair("channelpassword", &self.channel_password), - pair("token", &self.token), - ] - .into_iter() - .flatten() - .collect(); - if !query.is_empty() { - url.push('?'); - url.push_str(&query.join("&")); - } - url - } -} - -/// A channel path's names from the top: `Gaming/Raid Night` → -/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`. -pub fn split_channel_path(path: &str) -> Vec { - let mut names = Vec::new(); - let mut name = String::new(); - let mut chars = path.chars().peekable(); - while let Some(c) = chars.next() { - match c { - '\\' if chars.peek() == Some(&'/') => { - name.push('/'); - chars.next(); - } - '/' => names.push(std::mem::take(&mut name)), - c => name.push(c), - } - } - names.push(name); - names -} - -/// A channel path from its names from the top, a `/` in a name as `\/`: -/// the reverse of [`split_channel_path`]. -pub fn join_channel_path(names: &[impl AsRef]) -> String { - names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::>().join("/") -} - -/// The channel id of a path `/` (what `cid=` gives). -pub fn channel_path_id(path: &str) -> Option { - let id = path.strip_prefix('/')?; - if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - id.parse().ok() -} - -/// After `ts3server://` or `teamspeak://`: `[:port][/]?`, or -/// `invite=`. -fn parse_server(rest: &str) -> Option { - let (head, query) = rest.split_once('?').unwrap_or((rest, "")); - let authority = head.split('/').next().unwrap_or_default(); - if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) { - let code = percent::decode(&authority[key.len()..]); - return (!code.is_empty()).then_some(Link::Invite(code)); - } - let authority = percent::decode(authority); - let (host, port) = split_address(&authority); - if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) { - return None; - } - let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() }; - let mut cid = None; - for pair in query.split('&') { - let (key, raw) = pair.split_once('=').unwrap_or((pair, "")); - let value = Some(percent::decode(raw)).filter(|v| !v.is_empty()); - match key.to_ascii_lowercase().as_str() { - // One that is no port is ignored. - "port" => link.port = value.as_deref().and_then(parse_port).or(link.port), - "nickname" => link.nickname = value, - "password" => link.password = value, - // A `/` between names, `%2F` in one. - "channel" => { - let names: Vec = raw.split('/').map(percent::decode).collect(); - link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != ""); - } - "cid" => cid = value.and_then(|v| v.parse::().ok()).filter(|c| *c != 0), - "channelpassword" => link.channel_password = value, - "token" => link.token = value, - _ => {} - } - } - // The id names one channel for sure. - if let Some(cid) = cid { - link.channel = Some(format!("/{cid}")); - } - Some(Link::Server(link)) -} - -/// `tmspk.gg/s/?…` (or `/s=`), with or without `https://`, goes where -/// its page sends the browser: `teamspeak://?…`; any other path is an -/// invite code. -fn parse_short(text: &str, lower: &str) -> Option { - let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len()); - let (host, path) = text[start..].split_once('/')?; - if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) { - return None; - } - if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) { - return parse_server(&path[2..]); - } - let code = path.split(['?', '#', '/']).next().unwrap_or_default(); - let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'); - (!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned())) -} - -/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the -/// host (an IPv6 address without its brackets) and the port, if one is -/// given that is one. -fn split_address(address: &str) -> (&str, Option) { - if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) { - return (host, after.strip_prefix(':').and_then(parse_port)); - } - match address.rsplit_once(':') { - // A port follows the only colon; more colons: an IPv6 address. - Some((host, port)) - if !host.contains(':') - && !port.is_empty() - && port.bytes().all(|b| b.is_ascii_digit()) => - { - (host, parse_port(port)) - } - _ => (address, None), - } -} - -fn parse_port(text: &str) -> Option { - text.parse().ok().filter(|p| *p != 0) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn server(text: &str) -> ServerLink { - match Link::parse(text) { - Some(Link::Server(link)) => link, - other => panic!("{text}: {other:?}"), - } - } - - fn host(host: &str, port: Option) -> ServerLink { - ServerLink { host: host.into(), port, ..Default::default() } - } - - #[test] - fn every_parameter() { - let link = server( - "ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine", - ); - assert_eq!( - link, - ServerLink { - host: "ts.example.org".into(), - port: Some(9988), - nickname: Some("Nova X".into()), - password: Some("s3cr?t".into()), - channel: Some("Gaming/Raid Night".into()), - // A `+` stays. - channel_password: Some("raid+1".into()), - token: Some("AbC+d".into()), - } - ); - assert_eq!(link.address(), "ts.example.org:9988"); - assert_eq!( - link.to_url(), - "ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd" - ); - assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link))); - // A channel id names the channel, also next to a path. - assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12")); - assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12")); - assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby")); - assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12"); - // Empty values are none. - assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None)); - } - - #[test] - fn teamspeak_scheme_is_the_same() { - let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova"; - assert_eq!( - Link::parse(&format!("teamspeak://{query}")), - Link::parse(&format!("ts3server://{query}")) - ); - // Any case, of the scheme and the keys; the host as written. - let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID="); - assert_eq!( - link, - ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) } - ); - assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988))); - } - - #[test] - fn short_links() { - for text in [ - "https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby", - "https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby", - "HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby", - "tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby", - "http://tmspk.gg/s/ts.example.org:9988?channel=Lobby", - ] { - assert_eq!( - server(text), - ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) }, - "{text}" - ); - } - let invite = |code: &str| Some(Link::Invite(code.into())); - assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x")); - assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x")); - assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x")); - assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x")); - for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="] - { - assert_eq!(Link::parse(text), None, "{text}"); - } - } - - #[test] - fn ipv6() { - let v6 = host("2001:db8::1", Some(9987)); - assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6); - assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6); - assert_eq!(v6.address(), "[2001:db8::1]:9987"); - assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987"); - // Without a port, with or without brackets. - let bare = host("2001:db8::1", None); - assert_eq!(server("ts3server://2001:db8::1"), bare); - assert_eq!(server("ts3server://[2001:db8::1]"), bare); - assert_eq!(bare.address(), "2001:db8::1"); - assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988))); - } - - #[test] - fn escapes() { - let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen"); - assert_eq!(link.channel.as_deref(), Some("Ärger/Café")); - assert_eq!(link.nickname.as_deref(), Some("Jürgen")); - // `%2F` is a `/` in a name. - let link = server("ts3server://h?channel=AC%2FDC/Live"); - assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live")); - assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]); - assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live"); - assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live"); - assert_eq!(split_channel_path("Lobby"), ["Lobby"]); - assert_eq!(channel_path_id("/12"), Some(12)); - assert_eq!(channel_path_id("12"), None); - assert_eq!(channel_path_id("/1a"), None); - } - - #[test] - fn invalid_ports_are_ignored() { - for text in [ - "ts3server://h?port=abc", - "ts3server://h?port=70000", - "ts3server://h?port=0", - "ts3server://h?port=", - "ts3server://h:70000", - ] { - assert_eq!(server(text), host("h", None), "{text}"); - } - // One in the address stays. - assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988))); - } - - #[test] - fn other_links_are_none() { - for text in [ - "", - "http://example.com", - "https://example.com/s/ts.example.org", - "ts3file://a.png?serverUID=x&channel=1", - "ts3server://", - "ts3server://?port=9987", - "ts3server://a b", - "ts.example.org", - "mailto:a@example.org", - ] { - assert_eq!(Link::parse(text), None, "{text:?}"); - } - } - - #[test] - fn round_trip() { - // The invite links of voelin-ui (`vm::servers::invite_link`). - for (address, names, url) in [ - ( - "ts.example.com:9988", - &["Gaming", "Raid Night"][..], - "ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night", - ), - (" ts.example.com ", &[], "ts3server://ts.example.com"), - ( - "[2001:db8::1]:9987", - &["Chill & Co"], - "ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co", - ), - ("2001:db8::1", &[], "ts3server://2001:db8::1"), - ("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"), - ] { - let mut link = ServerLink::new(address); - link.channel = (!names.is_empty()).then(|| join_channel_path(names)); - assert_eq!(link.to_url(), url); - assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}"); - assert_eq!(link.address(), address.trim()); - if let Some(path) = &link.channel { - assert_eq!(split_channel_path(path), names); - } - } - } -} diff --git a/crates/voelin-model/src/percent.rs b/crates/voelin-model/src/percent.rs deleted file mode 100644 index 9c3e3e1..0000000 --- a/crates/voelin-model/src/percent.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Percent escapes in links: file links ([`crate::FileRef`]) and server -//! links ([`crate::Link`]). - -/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and -/// passwords keep theirs). -pub(crate) fn decode(s: &str) -> String { - let bytes = s.as_bytes(); - let hex = |b: u8| (b as char).to_digit(16); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' - && let (Some(h), Some(l)) = - (bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b))) - { - out.push((h * 16 + l) as u8); - i += 3; - continue; - } - out.push(bytes[i]); - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - -/// Every byte but letters, digits and `-._~` as `%XX`. -pub(crate) fn encode(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for b in s.bytes() { - if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { - out.push(b as char); - } else { - out.push_str(&format!("%{b:02X}")); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn escapes() { - assert_eq!(decode("Raid%20Night"), "Raid Night"); - assert_eq!(decode("%C3%84b"), "Äb"); - assert_eq!(decode("a+b"), "a+b"); - // A broken escape stays as it is. - assert_eq!(decode("100%"), "100%"); - assert_eq!(decode("%zz"), "%zz"); - assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84"); - assert_eq!(decode(&encode("a b+c%")), "a b+c%"); - } -} diff --git a/crates/voelin-model/src/presence.rs b/crates/voelin-model/src/presence.rs deleted file mode 100644 index 1b39e06..0000000 --- a/crates/voelin-model/src/presence.rs +++ /dev/null @@ -1,493 +0,0 @@ -//! Who is where: channels and the clients in them. -//! -//! The same model is fed from a voice connection, a query session or a -//! gateway. Sources send a [`PresenceSnapshot`] followed by -//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`]. -//! -//! A voice connection also knows the server's details (welcome message, -//! host banner, …) and its server and channel groups ([`Presence::server`], -//! [`Presence::server_groups`], [`Presence::channel_groups`]); snapshots and -//! deltas do not carry them (other sources leave them empty). - -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use crate::server::{BannerMode, ServerDetails}; - -pub type ChannelId = u64; -pub type ClientId = u16; -/// A server or channel group id. -pub type GroupId = u64; - -fn is_zero_i32(n: &i32) -> bool { - *n == 0 -} - -fn is_zero_u32(n: &u32) -> bool { - *n == 0 -} - -fn is_false(b: &bool) -> bool { - !*b -} - -fn is_default(v: &T) -> bool { - *v == T::default() -} - -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChannelInfo { - pub id: ChannelId, - /// `0` for top-level channels. - pub parent: ChannelId, - /// Id of the sibling directly above, `0` for the first. - pub order: ChannelId, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub topic: Option, - #[serde(default)] - pub has_password: bool, - /// `None` means unlimited. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub max_clients: Option, - #[serde(default)] - pub needed_subscribe_power: i32, - #[serde(default)] - pub needed_talk_power: i32, - #[serde(default)] - pub is_default: bool, - /// Icon id (`channel_icon_id`); 0: none. - #[serde(default, skip_serializing_if = "is_zero_u32")] - pub icon: u32, - /// The address of the channel's banner picture (TeamSpeak 6, - /// `channel_banner_gfx_url`), drawn behind the channel. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub banner_gfx_url: Option, - #[serde(default, skip_serializing_if = "is_default")] - pub banner_mode: BannerMode, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ClientInfo { - pub id: ClientId, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub uid: Option, - pub nickname: String, - pub channel: ChannelId, - /// ServerQuery clients (bots, our own relays). UIs normally hide them. - #[serde(default)] - pub is_query: bool, - /// Away, with the away message (empty without one); `None`: not away. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub away: Option, - #[serde(default)] - pub input_muted: bool, - #[serde(default)] - pub output_muted: bool, - /// `None` when the source cannot tell (query sessions see no voice). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub talking: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub streaming: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub server_groups: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub country: Option, - /// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`: - /// no avatar. A new hash means a new avatar. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub avatar: Option, - /// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from - /// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the - /// server has no avatar for the client. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub myts_avatar: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub description: Option, - #[serde(default, skip_serializing_if = "is_zero_i32")] - pub talk_power: i32, - /// Allowed to talk regardless of talk power (`client_is_talker`). - #[serde(default, skip_serializing_if = "is_false")] - pub talker: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub channel_group: Option, - /// Badge GUIDs, in display order ([`shown_badges`]). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub badges: Vec, - /// Icon id (`client_icon_id`); 0: none. - #[serde(default, skip_serializing_if = "is_zero_u32")] - pub icon: u32, - #[serde(default, skip_serializing_if = "is_false")] - pub recording: bool, - #[serde(default, skip_serializing_if = "is_false")] - pub priority_speaker: bool, - #[serde(default, skip_serializing_if = "is_false")] - pub channel_commander: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub database_id: Option, -} - -/// Badge GUIDs of a `client_badges` value -/// (`Overwolf=0:badges=,`). -pub fn parse_badges(value: &str) -> Vec { - value - .split(':') - .filter_map(|part| part.strip_prefix("badges=")) - .flat_map(|list| list.split(',')) - .map(str::trim) - .filter(|g| !g.is_empty()) - .map(str::to_owned) - .collect() -} - -/// The badges a client shows: those a TeamSpeak 6 server verified -/// (`client_signed_badges`, ids joined by `,`) first, then those of its -/// `client_badges` ([`parse_badges`]), each once. -pub fn shown_badges(badges: &str, signed: &str) -> Vec { - let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned); - let mut shown: Vec = Vec::new(); - for guid in signed.chain(parse_badges(badges)) { - if !shown.iter().any(|g| g.eq_ignore_ascii_case(&guid)) { - shown.push(guid); - } - } - shown -} - -/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak -/// 6): `,;,…`, states as myTeamSpeak's -/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the -/// official client reads it: an entry that is not `,` (an -/// empty one too, from a trailing `;`) makes the whole value no avatar; -/// the "online" picture is shown whatever the client's state (an unknown -/// state counts as online), else away, do not disturb, offline, the first -/// of a kind. Only an HTTPS link of at most 4 KiB. -pub fn myts_avatar_url(value: &str) -> Option { - let mut best: Option<(u8, &str)> = None; - for entry in value.split(';') { - let mut parts = entry.split(','); - let state: u32 = parts.next()?.trim().parse().ok()?; - let url = parts.next()?.trim(); - let rank = match state { - 3 => 1, - 1 => 2, - 4 => 3, - _ => 0, - }; - if best.is_none_or(|(r, _)| rank < r) { - best = Some((rank, url)); - } - } - let url = best?.1; - (url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned()) -} - -/// How a group's name is shown next to its members. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum GroupNamingMode { - #[default] - None, - /// Before the nickname: `[Admin] Alice`. - Before, - /// After the nickname: `Alice [Admin]`. - After, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum GroupType { - /// For new virtual servers; nobody is a member. - Template, - #[default] - Regular, - /// ServerQuery clients. - Query, -} - -/// A server or channel group. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct GroupInfo { - pub id: GroupId, - pub name: String, - /// Icon id; 0: none. - #[serde(default, skip_serializing_if = "is_zero_u32")] - pub icon: u32, - /// Display order: lower first, then by id. - #[serde(default)] - pub sort_id: i32, - #[serde(default)] - pub naming_mode: GroupNamingMode, - #[serde(default)] - pub group_type: GroupType, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PresenceSnapshot { - pub server_name: String, - pub channels: Vec, - pub clients: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum PresenceDelta { - ChannelAdded(ChannelInfo), - ChannelChanged(ChannelInfo), - ChannelRemoved { id: ChannelId }, - ClientJoined(ClientInfo), - ClientChanged(ClientInfo), - ClientMoved { id: ClientId, channel: ChannelId }, - ClientLeft { id: ClientId }, - ServerRenamed { name: String }, -} - -/// Current state; apply deltas as they arrive. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Presence { - pub server_name: String, - pub channels: BTreeMap, - pub clients: BTreeMap, - /// What the source knows about the server (a voice connection: all of - /// it; other sources: nothing). - pub server: ServerDetails, - pub server_groups: BTreeMap, - pub channel_groups: BTreeMap, -} - -impl Presence { - pub fn from_snapshot(s: PresenceSnapshot) -> Self { - Self { - server_name: s.server_name, - channels: s.channels.into_iter().map(|c| (c.id, c)).collect(), - clients: s.clients.into_iter().map(|c| (c.id, c)).collect(), - ..Self::default() - } - } - - /// The client with this unique id, if present (the first of several - /// connections with the same identity). - pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> { - self.clients.values().find(|c| c.uid.as_deref() == Some(uid)) - } - - /// Groups in display order (sort id, then id). - pub fn sorted_groups(groups: &BTreeMap) -> Vec<&GroupInfo> { - let mut sorted: Vec<_> = groups.values().collect(); - sorted.sort_by_key(|g| (g.sort_id, g.id)); - sorted - } - - pub fn snapshot(&self) -> PresenceSnapshot { - PresenceSnapshot { - server_name: self.server_name.clone(), - channels: self.channels.values().cloned().collect(), - clients: self.clients.values().cloned().collect(), - } - } - - /// Apply a delta. Returns `false` if it referred to something unknown - /// (the caller may want to resynchronise). - pub fn apply(&mut self, delta: &PresenceDelta) -> bool { - match delta { - PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => { - self.channels.insert(c.id, c.clone()); - true - } - PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(), - PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => { - self.clients.insert(c.id, c.clone()); - true - } - PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) { - Some(c) => { - c.channel = *channel; - true - } - None => false, - }, - PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(), - PresenceDelta::ServerRenamed { name } => { - self.server_name = name.clone(); - true - } - } - } - - /// Deltas that turn `self` into `new`, for sources that poll. - pub fn diff(&self, new: &Presence) -> Vec { - let mut out = Vec::new(); - if self.server_name != new.server_name { - out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() }); - } - for (id, c) in &new.channels { - match self.channels.get(id) { - None => out.push(PresenceDelta::ChannelAdded(c.clone())), - Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())), - _ => {} - } - } - for (id, c) in &new.clients { - match self.clients.get(id) { - None => out.push(PresenceDelta::ClientJoined(c.clone())), - Some(old) if old == c => {} - Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => { - out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel }); - } - Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())), - } - } - for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) { - out.push(PresenceDelta::ClientLeft { id: *id }); - } - // Channels last, so clients leave a removed channel first. - for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) { - out.push(PresenceDelta::ChannelRemoved { id: *id }); - } - out - } - - /// Clients in a channel, excluding query clients. - pub fn members(&self, channel: ChannelId) -> impl Iterator { - self.clients.values().filter(move |c| c.channel == channel && !c.is_query) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn ch(id: u64, name: &str) -> ChannelInfo { - ChannelInfo { id, name: name.into(), ..Default::default() } - } - - fn cl(id: u16, name: &str, channel: u64) -> ClientInfo { - ClientInfo { id, nickname: name.into(), channel, ..Default::default() } - } - - fn presence(channels: Vec, clients: Vec) -> Presence { - Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients }) - } - - #[test] - fn diff_then_apply_reaches_target() { - let old = presence( - vec![ch(1, "Lobby"), ch(2, "Games")], - vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)], - ); - let mut muted = cl(2, "Bob", 1); - muted.input_muted = true; - let new = presence( - vec![ch(1, "Lobby"), ch(3, "New")], - vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)], - ); - let deltas = old.diff(&new); - assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 })); - assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 })); - assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 })); - assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2))); - let mut state = old.clone(); - for d in &deltas { - assert!(state.apply(d)); - } - assert_eq!(state, new); - assert!(new.diff(&new).is_empty()); - } - - #[test] - fn myts_avatars_as_the_official_client_reads_them() { - let on = "https://a.example.test/on.png"; - assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on)); - // Away before do not disturb before offline; the first of a kind. - assert_eq!( - myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b") - .as_deref(), - Some("https://a/away") - ); - assert_eq!( - myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(), - Some("https://a/dnd") - ); - // An unknown state counts as online. - assert_eq!( - myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(), - Some("https://a/x") - ); - // One bad entry spoils the value. - for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] { - assert_eq!(myts_avatar_url(bad), None, "{bad:?}"); - } - // Only HTTPS, and not endless. - assert_eq!(myts_avatar_url("2,http://a/on"), None); - assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None); - // Older JSON without the field still loads. - let client: ClientInfo = - serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap(); - assert_eq!(client.myts_avatar, None); - } - - #[test] - fn badges_and_groups() { - assert_eq!( - parse_badges( - "Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157" - ), - ["c9e97536-5a2d-4c8e-a135-af404587a472", "450f81c1-ab41-4211-a338-222fa94ed157"] - ); - assert!(parse_badges("").is_empty()); - assert!(parse_badges("Overwolf=1").is_empty()); - // TeamSpeak 6's verified badges first, each once. - assert_eq!( - shown_badges( - "Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157", - "450F81C1-AB41-4211-A338-222FA94ED157,1cb07348-34a4-4741-b50f-c41e584370f7" - ), - [ - "450F81C1-AB41-4211-A338-222FA94ED157", - "1cb07348-34a4-4741-b50f-c41e584370f7", - "c9e97536-5a2d-4c8e-a135-af404587a472" - ] - ); - assert!(shown_badges("", "").is_empty()); - let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() }; - let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]); - let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect(); - assert_eq!(order, [2, 3, 1]); - let mut alice = cl(1, "Alice", 1); - alice.uid = Some("A=".into()); - let p = presence(vec![ch(1, "Lobby")], vec![alice, cl(2, "Bob", 1)]); - assert_eq!(p.client_by_uid("A=").map(|c| c.id), Some(1)); - assert!(p.client_by_uid("B=").is_none()); - } - - #[test] - fn old_json_without_new_fields() { - let c: ClientInfo = - serde_json::from_str(r#"{"id":1,"nickname":"a","channel":2,"away":""}"#).unwrap(); - assert_eq!(c.away.as_deref(), Some("")); - assert_eq!((c.talk_power, c.avatar.as_ref(), c.badges.len()), (0, None, 0)); - // Defaults stay off the wire. - assert_eq!( - serde_json::to_string(&cl(1, "a", 2)).unwrap(), - r#"{"id":1,"nickname":"a","channel":2,"is_query":false,"input_muted":false,"output_muted":false}"# - ); - } - - #[test] - fn members_skip_query_clients() { - let mut bot = cl(9, "bot", 1); - bot.is_query = true; - let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]); - assert_eq!(p.members(1).count(), 1); - } - - #[test] - fn delta_json_is_tagged() { - let json = - serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap(); - assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#); - let back: PresenceDelta = serde_json::from_str(&json).unwrap(); - assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 }); - } -} diff --git a/crates/voelin-model/src/server.rs b/crates/voelin-model/src/server.rs deleted file mode 100644 index f88b188..0000000 --- a/crates/voelin-model/src/server.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! Server software detection and the capabilities that follow from it. - -use std::fmt; - -use serde::{Deserialize, Serialize}; - -/// Parsed `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]` or -/// `6.0.0-beta13.1 [Build: 1790080330]`. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub struct ServerVersion { - pub major: u32, - pub minor: u32, - pub patch: u32, - /// Pre-release tag such as `beta13.1`. - pub pre: Option, - /// Build timestamp (seconds since the Unix epoch). - pub build: Option, -} - -impl ServerVersion { - pub fn parse(s: &str) -> Option { - let s = s.trim(); - let (version, rest) = s.split_once(' ').unwrap_or((s, "")); - let build = rest - .trim() - .strip_prefix("[Build:") - .and_then(|b| b.strip_suffix(']')) - .and_then(|b| b.trim().parse().ok()); - let (numbers, pre) = match version.split_once('-') { - Some((n, p)) => (n, Some(p.to_string())), - None => (version, None), - }; - let mut parts = numbers.split('.').map(|p| p.parse::()); - let major = parts.next()?.ok()?; - let minor = parts.next().unwrap_or(Ok(0)).ok()?; - let patch = parts.next().unwrap_or(Ok(0)).ok()?; - Some(Self { major, minor, patch, pre, build }) - } -} - -impl fmt::Display for ServerVersion { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?; - if let Some(pre) = &self.pre { - write!(f, "-{pre}")?; - } - Ok(()) - } -} - -/// Which server software we are talking to. -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ServerFlavor { - /// TeamSpeak 3 server (3.x). - Ts3(ServerVersion), - /// TeamSpeak 6 server (6.x; TeamSpeak 5 server betas are treated alike). - Ts6(ServerVersion), - /// Unparseable or unexpected version string. - Unknown(String), -} - -impl ServerFlavor { - /// Classify a `virtualserver_version` string. - pub fn from_version_string(s: &str) -> Self { - match ServerVersion::parse(s) { - Some(v) if v.major == 3 => ServerFlavor::Ts3(v), - Some(v) if v.major >= 5 => ServerFlavor::Ts6(v), - _ => ServerFlavor::Unknown(s.to_string()), - } - } - - pub fn version(&self) -> Option<&ServerVersion> { - match self { - ServerFlavor::Ts3(v) | ServerFlavor::Ts6(v) => Some(v), - ServerFlavor::Unknown(_) => None, - } - } - - pub fn capabilities(&self) -> Capabilities { - match self { - ServerFlavor::Ts3(_) => Capabilities { - streams: false, - raw_query: true, - ssh_query: true, - http_query: false, - file_transfer: true, - offline_messages: true, - }, - // Verified against 6.0.0-beta13.1: file transfer and offline - // messages work as on TeamSpeak 3. - ServerFlavor::Ts6(_) => Capabilities { - streams: true, - raw_query: false, - ssh_query: true, - http_query: true, - file_transfer: true, - offline_messages: true, - }, - ServerFlavor::Unknown(_) => Capabilities::default(), - } - } -} - -/// Where the host message shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum HostMessageMode { - /// Not shown. - #[default] - None, - /// In the chat log. - Log, - /// In a dialog. - Modal, - /// In a dialog; the connection ends when it is closed. - ModalQuit, -} - -/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is -/// scaled to its area: `0`, `1` and `2` on the wire. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum BannerMode { - /// As it is. - #[default] - NoAdjust, - /// Stretched to the banner area. - IgnoreAspect, - /// Scaled to fit, keeping its aspect ratio. - KeepAspect, -} - -impl BannerMode { - /// From its number on the wire; an unknown one shows the picture as it - /// is. - pub fn from_wire(value: &str) -> Self { - match value.trim() { - "1" => Self::IgnoreAspect, - "2" => Self::KeepAspect, - _ => Self::NoAdjust, - } - } -} - -/// What a server tells its (voice) clients about itself. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ServerDetails { - pub name: String, - /// `virtualserver_unique_identifier` (the key of its chat history). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub uid: Option, - #[serde(default)] - pub welcome_message: String, - #[serde(default)] - pub host_message: String, - #[serde(default)] - pub host_message_mode: HostMessageMode, - /// Where a click on the banner leads. - #[serde(default)] - pub banner_url: String, - /// The banner image. - #[serde(default)] - pub banner_gfx_url: String, - /// Reload the banner image this often (seconds); 0: never. - #[serde(default)] - pub banner_gfx_interval_s: u64, - #[serde(default)] - pub banner_mode: BannerMode, - #[serde(default)] - pub host_button_tooltip: String, - #[serde(default)] - pub host_button_url: String, - /// The host button's image. - #[serde(default)] - pub host_button_gfx_url: String, - /// Icon id (`virtualserver_icon_id`); 0: none. - #[serde(default)] - pub icon: u32, - /// Server platform, e.g. `Linux`. - #[serde(default)] - pub platform: String, - /// `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]`. - #[serde(default)] - pub version: String, - #[serde(default)] - pub max_clients: u16, - /// How much everyone else is dimmed while a priority speaker talks - /// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`, - /// rounded). - #[serde(default)] - pub priority_speaker_dimm_db: i32, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_server_group: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_channel_group: Option, -} - -/// Features that depend on the server software. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Capabilities { - /// Screen sharing / video streams (TeamSpeak 6). - pub streams: bool, - /// Raw TCP ServerQuery (TeamSpeak 3 only; may still be disabled by the admin). - pub raw_query: bool, - /// SSH ServerQuery. - pub ssh_query: bool, - /// HTTP WebQuery (TeamSpeak 6), request/response only, no events. - pub http_query: bool, - /// Channel file browsers, avatars and icons (`ftinit*` over TCP). - #[serde(default)] - pub file_transfer: bool, - /// Offline messages to a unique id (`messageadd`, `messagelist`, …). - #[serde(default)] - pub offline_messages: bool, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_ts3() { - let v = ServerVersion::parse("3.13.8 [Build: 1779874471]").unwrap(); - assert_eq!((v.major, v.minor, v.patch), (3, 13, 8)); - assert_eq!(v.pre, None); - assert_eq!(v.build, Some(1_779_874_471)); - let flavor = ServerFlavor::from_version_string("3.13.8 [Build: 1779874471]"); - assert!(matches!(flavor, ServerFlavor::Ts3(_))); - assert!(!flavor.capabilities().streams); - } - - #[test] - fn parses_ts6_beta() { - let s = "6.0.0-beta13.1 [Build: 1790080330]"; - let v = ServerVersion::parse(s).unwrap(); - assert_eq!(v.pre.as_deref(), Some("beta13.1")); - assert_eq!(v.to_string(), "6.0.0-beta13.1"); - let flavor = ServerFlavor::from_version_string(s); - assert!(matches!(flavor, ServerFlavor::Ts6(_))); - assert!(flavor.capabilities().streams); - assert!(!flavor.capabilities().raw_query); - } - - #[test] - fn handles_garbage() { - assert!(matches!(ServerFlavor::from_version_string(""), ServerFlavor::Unknown(_))); - assert!(matches!(ServerFlavor::from_version_string("x.y"), ServerFlavor::Unknown(_))); - assert_eq!(ServerVersion::parse("3").unwrap().minor, 0); - } -} diff --git a/crates/voelin-model/src/tree.rs b/crates/voelin-model/src/tree.rs deleted file mode 100644 index fe97c6e..0000000 --- a/crates/voelin-model/src/tree.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Flatten presence into display rows in TeamSpeak's channel order, and -//! read the names of spacer channels. - -use std::collections::HashMap; - -use crate::presence::{ChannelId, ChannelInfo, ClientInfo, Presence}; - -/// One line of a channel tree. -#[derive(Clone, Debug, PartialEq)] -pub enum TreeRow<'a> { - Channel { depth: usize, channel: &'a ChannelInfo }, - Client { depth: usize, client: &'a ClientInfo }, -} - -/// Sort siblings by following the `order` links (each channel names the -/// sibling directly above it). Channels whose predecessor is missing are -/// appended at the end, sorted by id, so nothing is ever dropped. -pub fn order_siblings(mut siblings: Vec<&ChannelInfo>) -> Vec<&ChannelInfo> { - siblings.sort_by_key(|c| c.id); - let mut by_prev: HashMap = HashMap::new(); - for c in &siblings { - by_prev.entry(c.order).or_insert(c); - } - let mut sorted = Vec::with_capacity(siblings.len()); - let mut prev = 0; - while let Some(c) = by_prev.remove(&prev) { - sorted.push(c); - prev = c.id; - } - for c in siblings { - if !sorted.iter().any(|s| s.id == c.id) { - sorted.push(c); - } - } - sorted -} - -/// Channels and their (non-query) clients, depth-first. Clients are sorted by -/// name; `collapsed` channels hide their sub-channels and clients. -pub fn tree_rows<'a>(p: &'a Presence, collapsed: &dyn Fn(ChannelId) -> bool) -> Vec> { - let mut rows = Vec::new(); - add_level(p, 0, 0, collapsed, &mut rows); - rows -} - -fn add_level<'a>( - p: &'a Presence, - parent: ChannelId, - depth: usize, - collapsed: &dyn Fn(ChannelId) -> bool, - rows: &mut Vec>, -) { - let siblings = order_siblings(p.channels.values().filter(|c| c.parent == parent).collect()); - for channel in siblings { - rows.push(TreeRow::Channel { depth, channel }); - if collapsed(channel.id) { - continue; - } - let mut members: Vec<_> = p.members(channel.id).collect(); - members.sort_by(|a, b| a.nickname.to_lowercase().cmp(&b.nickname.to_lowercase())); - for client in members { - rows.push(TreeRow::Client { depth: depth + 1, client }); - } - add_level(p, channel.id, depth + 1, collapsed, rows); - } -} - -/// How a TeamSpeak spacer channel draws its text. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Spacer { - Left, - Center, - Right, - /// The text repeated across the row: a line such as `---`. - Fill, -} - -impl Spacer { - /// Whether a spacer with this text only separates the rows around it - /// (a line, or no text): nothing to search for or pick. - pub fn separates(self, text: &str) -> bool { - self == Spacer::Fill || text.trim().is_empty() - } -} - -/// A spacer name split into its kind and its text: `[cspacer]Games` is a -/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an -/// empty row. The part between `spacer` and `]` only keeps the names -/// unique, so anything goes there. Anything else is not a spacer. -pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> { - let (inside, text) = name.strip_prefix('[')?.split_once(']')?; - let (kind, _suffix) = inside.split_once("spacer")?; - let kind = match kind { - "" | "l" => Spacer::Left, - "c" => Spacer::Center, - "r" => Spacer::Right, - "*" => Spacer::Fill, - _ => return None, - }; - Some((kind, text)) -} - -/// A channel's name as shown, and its spacer kind. Only top-level channels -/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is. -/// Names sent to the server (joining by name, invite links) stay raw. -pub fn channel_title(channel: &ChannelInfo) -> (&str, Option) { - match parse_spacer(&channel.name).filter(|_| channel.parent == 0) { - Some((kind, text)) => (text, Some(kind)), - None => (&channel.name, None), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::presence::PresenceSnapshot; - - fn ch(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo { - ChannelInfo { id, parent, order, name: name.into(), ..Default::default() } - } - - fn cl(id: u16, name: &str, channel: u64) -> ClientInfo { - ClientInfo { id, nickname: name.into(), channel, ..Default::default() } - } - - #[test] - fn follows_order_links() { - let channels = [ch(5, 0, 3, "c"), ch(3, 0, 7, "b"), ch(7, 0, 0, "a")]; - let names: Vec<_> = - order_siblings(channels.iter().collect()).iter().map(|c| c.name.as_str()).collect(); - assert_eq!(names, ["a", "b", "c"]); - let broken = [ch(1, 0, 0, "a"), ch(2, 0, 99, "orphan")]; - assert_eq!(order_siblings(broken.iter().collect())[1].name, "orphan"); - } - - #[test] - fn rows_depth_first_with_collapse() { - let mut bot = cl(9, "bot", 1); - bot.is_query = true; - let p = Presence::from_snapshot(PresenceSnapshot { - server_name: "s".into(), - channels: vec![ch(1, 0, 0, "Lobby"), ch(2, 0, 1, "Games"), ch(3, 2, 0, "Squad")], - clients: vec![cl(1, "zed", 1), cl(2, "Alice", 1), bot, cl(3, "Bob", 3)], - }); - let describe = |rows: Vec| -> Vec { - rows.iter() - .map(|r| match r { - TreeRow::Channel { depth, channel } => format!("{depth}#{}", channel.name), - TreeRow::Client { depth, client } => format!("{depth}-{}", client.nickname), - }) - .collect() - }; - assert_eq!( - describe(tree_rows(&p, &|_| false)), - ["0#Lobby", "1-Alice", "1-zed", "0#Games", "1#Squad", "2-Bob"] - ); - assert_eq!( - describe(tree_rows(&p, &|c| c == 2)), - ["0#Lobby", "1-Alice", "1-zed", "0#Games"] - ); - } - - #[test] - fn spacer_names() { - use Spacer::*; - for (name, spacer) in [ - ("[spacer0]", Some((Left, ""))), - ("[spacer3]Hi", Some((Left, "Hi"))), - ("[lspacer]Hi", Some((Left, "Hi"))), - ("[rspacer9]Hi", Some((Right, "Hi"))), - ("[cspacer]Hi", Some((Center, "Hi"))), - ("[cspacerx]Hi", Some((Center, "Hi"))), - ("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))), - ("[*spacer1]-=", Some((Fill, "-="))), - ("[*spacer]", Some((Fill, ""))), - ("[cspacer2Games", None), - ("Games", None), - ("[Spacer]x", None), - ("[xspacer]x", None), - ("[spacr]x", None), - ("x[spacer]", None), - ] { - assert_eq!(parse_spacer(name), spacer, "{name}"); - } - assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" ")); - assert!(!Left.separates("Hi")); - // Only top-level channels are spacers: a sub-channel keeps its name. - assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right))); - assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None)); - assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None)); - } -} diff --git a/crates/voelin-observer/Cargo.toml b/crates/voelin-observer/Cargo.toml index 67bf4c5..ff2495b 100644 --- a/crates/voelin-observer/Cargo.toml +++ b/crates/voelin-observer/Cargo.toml @@ -12,7 +12,7 @@ publish.workspace = true thiserror = "2" tokio = { version = "1", features = ["macros", "rt", "sync", "time"] } tracing = "0.1" -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } voelin-query = { path = "../voelin-query" } [dev-dependencies] diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index 4b4a1dc..a1a0623 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -98,7 +98,7 @@ pub enum IdentityOrigin { /// Made by the app on its own because it had none; nobody chose it, so /// the official client's identity may take its place as the default. Created, - /// From another client (`voelin_core::identity`). + /// From another client (`voelin_core::ts::identity`). Imported, /// Made or chosen as the default by the user. User, diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index 6d903b0..f06af6c 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -29,7 +29,7 @@ unicode-segmentation = "1.13" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } voelin-gateway-proto = { path = "../voelin-gateway-proto" } -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } voelin-store = { path = "../voelin-store" } [dev-dependencies] diff --git a/crates/voelin-ui-vm/src/settings_pages/logic.rs b/crates/voelin-ui-vm/src/settings_pages/logic.rs index fd9e302..204fa4f 100644 --- a/crates/voelin-ui-vm/src/settings_pages/logic.rs +++ b/crates/voelin-ui-vm/src/settings_pages/logic.rs @@ -15,7 +15,6 @@ use std::sync::atomic::AtomicBool; use serde::Serialize; use serde::de::DeserializeOwned; -use voelin_core::identity::Found; use voelin_core::media::auto_bitrate; use voelin_core::media::voelin_media::EncoderInfo; use voelin_core::settings::{ @@ -29,6 +28,7 @@ use voelin_core::settings::{ STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, Settings, Source as SettingSource, StreamPermissions, }; +use voelin_core::ts::identity::Found; use voelin_gateway_proto::{ConfigSource, PermRule, feature}; use voelin_store::{Bookmark, IdentityEntry, IdentityOrigin}; diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index db3cfc7..07041f2 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -37,7 +37,7 @@ voelin-audio = { path = "../voelin-audio" } voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device"] } # Gateway data types (topics, pins, reactions, capability names). voelin-gateway-proto = { path = "../voelin-gateway-proto" } -voelin-model = { path = "../voelin-model" } +voelin-model = { workspace = true } # Crash reports and notices everywhere; hotkey backends on desktop (below). voelin-platform = { path = "../voelin-platform", default-features = false } voelin-query = { path = "../voelin-query" } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index dcccfb5..8d65c79 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -372,7 +372,7 @@ pub fn run(options: RunOptions) -> Result<()> { // with the sample data of VOELIN_DEMO_UI); the client's default // identity becomes ours while we have none the user chose. let imported = if prefs.get(&IDENTITY_IMPORT) && !switches.demo_ui { - voelin_core::identity::import_new(&store, &voelin_core::identity::discover()) + voelin_core::ts::identity::import_new(&store, &voelin_core::ts::identity::discover()) .unwrap_or_else(|e| { warn!(%e, "could not import TeamSpeak identities"); Default::default() diff --git a/crates/voelin-ui/src/identities.rs b/crates/voelin-ui/src/identities.rs index 8f08137..4fcd77f 100644 --- a/crates/voelin-ui/src/identities.rs +++ b/crates/voelin-ui/src/identities.rs @@ -1,7 +1,7 @@ //! The identity servers see us as: the store's default (schema 4, //! `Store::default_identity`), chosen under Settings → Profiles, and the //! import of the official clients' identities on start -//! (`voelin_core::identity::import_new`, app.rs). The rest of the Profiles +//! (`voelin_core::ts::identity::import_new`, app.rs). The rest of the Profiles //! page is in `settings_pages/`. use tracing::warn; diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 93853ee..a75dff6 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -5,7 +5,7 @@ use std::time::Instant; use slint::ComponentHandle; use tracing::{debug, info, warn}; -use voelin_core::identity::LaunchImport; +use voelin_core::ts::identity::LaunchImport; use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, VoiceState}; use voelin_model::ChannelId; use voelin_store::{Bookmark, QueryTransport}; @@ -20,7 +20,7 @@ use crate::vm::servers::{AfterConnect, JoinStep}; pub(crate) const CREATED_IDENTITY: &str = "Default"; /// What to tell the user about the identities imported from the official -/// clients at start ([`voelin_core::identity::import_new`]), if anything. +/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything. pub(crate) fn imported_status(report: &LaunchImport) -> Option { let n = report.added.len(); let names = report.added.iter().map(|f| f.nickname.as_str()).collect::>().join(", "); @@ -129,15 +129,15 @@ impl App { } let mut options = VoiceOptions::new(&b.address, &b.nickname); if let Some(spec) = &b.client_version { - match voelin_core::versions::resolve(spec) { - Ok(version) => options.client_version = version, - Err(error) => { - self.set_status(format!("Invalid client compatibility version: {error}")); - return false; - } + // The engine resolves the spec when it connects; asking now tells the + // user at once. + if let Err(error) = voelin_core::ts::versions::resolve(spec) { + self.set_status(format!("Invalid client compatibility version: {error}")); + return false; } + options.client_version = Some(spec.clone()); } - options.identity = Some(self.identity_for(Some(b.id))); + options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id)))); options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten(); options.channel = channel; options.channel_password = channel_password; @@ -161,7 +161,7 @@ impl App { .flatten() .map(|identity| identity.name) .filter(|name| { - ![CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME] + ![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME] .contains(&name.as_str()) }) .or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok()) @@ -288,7 +288,9 @@ impl App { self.engine.send(Command::ObserveGateway { session, urls, - identity: Box::new(self.identity_for(Some(b.id))), + identity: Box::new(voelin_core::ts::identity::to_blob( + &self.identity_for(Some(b.id)), + )), }); } return; @@ -300,25 +302,27 @@ impl App { self.engine.send(Command::ObserveGateway { session, urls, - identity: Box::new(self.identity_for(Some(b.id))), + identity: Box::new(voelin_core::ts::identity::to_blob( + &self.identity_for(Some(b.id)), + )), }); // Still the one the server publishes? self.discover_gateway(b.id); } else if let Some(q) = &b.query { let secret = self.secrets.get(&b.query_password_key()).ok().flatten(); let transport = match q.transport { - QueryTransport::Raw => voelin_query::Transport::Raw, - QueryTransport::Ssh => voelin_query::Transport::Ssh, - QueryTransport::Http => voelin_query::Transport::Http, + QueryTransport::Raw => voelin_core::QueryTransport::Raw, + QueryTransport::Ssh => voelin_core::QueryTransport::Ssh, + QueryTransport::Http => voelin_core::QueryTransport::Http, }; - let connect = voelin_query::Connect { + let connect = voelin_core::QueryLogin { transport, - addr: format!("{}:{}", q.host, q.port), + address: format!("{}:{}", q.host, q.port), user: q.user.clone(), secret, server_port: q.server_port, server_id: None, - line: Default::default(), + allowlisted: false, }; self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) }); } else { @@ -767,7 +771,7 @@ impl App { #[cfg(test)] mod tests { - use voelin_core::identity::Found; + use voelin_core::ts::identity::Found; use super::*; use voelin_store::QueryConfig; diff --git a/crates/voelin-ui/src/settings_pages/bind.rs b/crates/voelin-ui/src/settings_pages/bind.rs index e52c04f..50b8d05 100644 --- a/crates/voelin-ui/src/settings_pages/bind.rs +++ b/crates/voelin-ui/src/settings_pages/bind.rs @@ -559,7 +559,7 @@ impl App { let dir = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_else(|| ".".into()); let file = logic::export_file_stem(&entry.name); let path = dir.join(format!("{file}.ini")); - match voelin_core::identity::write_export(&path, &entry.name, &identity) { + match voelin_core::ts::identity::write_export(&path, &entry.name, &identity) { Ok(()) => self.set_identity_status(format!( "Exported to {} (it holds the private key: keep it safe).", path.display() @@ -608,7 +608,7 @@ impl App { .name("identity-level".into()) .spawn(move || { let better = - voelin_core::identity::improve_level(&identity, target, &cancel, |level| { + voelin_core::ts::identity::improve_level(&identity, target, &cancel, |level| { later(move |app| { if let Some(i) = app.pages.state.improving.get_mut(&id) { i.reached = i.reached.max(level); @@ -645,8 +645,8 @@ impl App { pub(crate) fn find_identities(&mut self) { let mut found = Vec::new(); let mut errors = Vec::new(); - for path in voelin_core::identity::discover() { - match voelin_core::identity::read(&path) { + for path in voelin_core::ts::identity::discover() { + match voelin_core::ts::identity::read(&path) { Ok(list) => found.extend(list), Err(e) => errors.push(e.to_string()), } @@ -676,11 +676,11 @@ impl App { pub(crate) fn import_identities(&mut self) { let picked: Vec<_> = self.pages.state.found.iter().filter(|(_, p)| *p).map(|(f, _)| f.clone()).collect(); - match voelin_core::identity::import(&self.store, &picked) { + match voelin_core::ts::identity::import(&self.store, &picked) { Ok(results) => { let added = results .iter() - .filter(|r| matches!(r, voelin_core::identity::Imported::Added(_))) + .filter(|r| matches!(r, voelin_core::ts::identity::Imported::Added(_))) .count(); self.set_identity_status(format!("{added} identities imported.")); } diff --git a/docs/architecture.md b/docs/architecture.md index 385dd3b..08a2609 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,14 +65,14 @@ fuzz/ cargo-fuzz targets | Crate | Responsibility | State | |---|---|---| -| `voelin-model` | UI-facing domain model (servers and their details, channels, clients, server and channel groups, chat and its file links, capabilities), no IO | done | +| `voelin-model` (VoelinProtocol, a git dependency) | UI-facing domain model (servers and their details, channels, clients, server and channel groups, chat and its file links, capabilities), no IO; with the replica of the protocol's entities and the permission functions | done | | `voelin-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery | done | | `voelin-observer` | Presence tracker + chat relay pool over `voelin-query` | done | | `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | | `voelin-store` | Identities (TeamSpeak, a Voelin key, the signed-in account, each with its account binding, as a `voelin-identity` `KeyStore`; see Identities), bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk; the voice packet types (`TalkerId`, `VoicePacket`, `EncodedVoice`), so it depends on no voice transport | v0 (no AEC yet) | | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam; its frame and simulcast layer types are `voelin-media`'s | sessions + transport | -| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, the `ServerLink` seam the voice source sits behind (`link.rs`; `TsLink` is the TeamSpeak implementation, for now in this crate), event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | +| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, the session seam (the `voelin_proto::link::Session` the voice source is, `link/`: `SessionLink`, `Backends`, `VoiceOptions`; the TeamSpeak implementation of it in `ts/`: `TsConnector`, `versions`, `identity`, still in this crate and public as `voelin_core::ts`), event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | | `voelin-ui-vm` | The view models, toolkit-free: engine state turned into plain rows and forms (servers, channel tree, chat with its BBCode reader, social, streams, the Stream Studio, the settings pages), the app's state (`AppState`, sessions and chat tabs), `ImageRef`/`Rgb`/`list::diff`, the Twemoji archive. Depends on `voelin-core`, `voelin-model`, `voelin-store`, `voelin-gateway-proto` and `voelin-audio`, on no UI toolkit; a front end converts its rows | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings; the Slint side of what `voelin-ui-vm` decides (the Bridge and model writes, windows, the engine's tasks) and the conversion of its rows into Slint values (see [ui.md](ui.md), "Two crates") | done (desktop) | | `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs; the frame and simulcast layer types of a stream (`stream::EncodedFrame`, `LayerSpec`, `LayerId`, `LayerSet`) | done (desktop hardware encoders through FFmpeg loaded at runtime, not run on a GPU yet; MediaCodec not run on a device yet) | @@ -88,71 +88,127 @@ the native command only when voice-connected *and* in that channel, otherwise th gateway, otherwise a local query relay. UI states: `Offline`, `Observing (Gateway|Query)` (invisible), `Connecting`, `Connected`. -## The server link +## The session seam A session's voice source, the connection that is visible on the server and -can talk, is a `voelin_core::link::ServerLink`, not a TeamSpeak connection -the session knows about. The trait has one method, -`spawn(options, ctx, cmds, events)`, which starts a connection on its own -task and returns: +can talk, is a `voelin_proto::link::Session`, the backend-neutral interface +that VoelinProtocol defines (`docs/protocol.md` section 1.3), not a +TeamSpeak connection that the session knows about. Nothing of `voelin-core` +above the TeamSpeak module names a TeamSpeak type: `rg 'tsclientlib|tsproto|voelin_query'` +over `crates/voelin-core/src` finds only `ts/` and the three files that +use them privately, `gateway.rs` and `query.rs` (the two observer sources, +which become a second `Session` to a gateway daemon later) and `stream.rs` +(the TeamSpeak 6 stream task, behind the `StreamPort` below). -- `options` is a `ConnectOptions` (the app calls it `VoiceOptions`): address, - nickname, password, channel to join, whether to open the audio devices; -- `ctx` is a `LinkCtx`: the session id, the event bus the link answers - requests on (file lists, transfers, offline messages, stream state), the - bus for the frames of watched streams, and the settings; -- `cmds` carries `LinkCmd`s in: chat, moves, mute, pokes, the encoded - voice frames from the audio thread, the file and offline-message requests, - `Stream(StreamCmd)` and `Disconnect`; -- `events` carries `LinkEvent`s out: `Connected` (name, `BackendInfo`, - `Capabilities`, our client id, the server's unique id), `Presence` (a full - snapshot each time), `OwnChannel`, `Chat`, `Poke`, `Audio` (a received - `VoicePacket`), `Talking`, `OwnStream`, `StreamAudio` (the audio of a watched - stream, for the audio thread's mixer), `StreamAudioEnded` (that stream's - audio is over), `Error` and `Disconnected`. `Disconnected` ends the - connection and is sent once, but it is not promised to be the last event: - the stream task of a connection winds down after the connection, so its - closing `OwnStream(Ended)` and `StreamAudioEnded` (and the bus events of - its streams) may follow it. `TsLink` ends the stream task as the - connection's loop ends, which usually puts them first, not always. The - session does not depend on it: on `Disconnected` it ends our own stream and - the audio of watched streams itself, and what the link says after that is - ignored like the events of a replaced link. +``` +UI ── Engine (Command / Event) ── session.rs (merge, dedup, history, contacts) + │ LinkCmd ↓ ↑ LinkEvent (crate-private) + SessionLink (replica, projection, media framing, + │ transfers, talk tracker) + │ Arc + pushes + MediaSink + │ (+ StreamPort for in-process connectors) + Backends ─────┼──────────────────────────┐ + (scheme registry) ▼ ▼ + ts::TsConnector → LinkSession any Connector: FakeConnector + (ts3server, teamspeak, no scheme) (tests), QuicConnector (later) +``` + +**The registry.** `voelin_core::Backends` holds the connectors by the scheme of +the address: `voelin_proto::link::Connectors` for plain connectors +(`Backends::register`) and the in-process ones that also hand the engine +local ports. An address without a scheme is a TeamSpeak bookmark and is +served as `ts3server`. `Engine::start` and `start_with` use +`Backends::default()`, which registers a `ts::TsConnector`; +`Engine::start_with_backends(settings, history, backends)` takes any +registry. An application that sets the main myTeamSpeak account keeps a +clone of its connector (`Backends::register_teamspeak`, +`TsConnector::set_myts_identity`, `TsConnector::set_myts_data`: every +connection of the connector, and its clones, presents it). + +**What a session asks for.** `Command::ConnectVoice` carries a `VoiceOptions`: +address, nickname, server password, channel to join and its password, +privilege key, whether to open the audio devices, the stream peer's network +settings, an `identity: Option` (a TeamSpeak identity as the key +store keeps it, see `ts::identity::to_blob`; a Voelin key goes the same way) +and a `client_version: Option` (a spec for `ts::versions::resolve`, +which only the TeamSpeak connector reads). `ObserveGateway` takes the identity +blob too, and `ObserveQuery` a `QueryLogin`. + +**SessionLink** (`link/session_link.rs`, with `project.rs` and `media.rs`) is +what `session.rs` talks to. It builds the connect parameters of the options +(`link/connect.rs`), opens the `Session` through `Backends`, runs the connect +sequence (the server, the HOME, SERVER and LIVE scopes, the seat in voice), +keeps a `voelin_model::replica::Replica` of what the host pushes, projects it +into the older model the UI still uses (`Presence`, `ClientInfo` and so on, +with the fix-ups F1 to F10 of [session-seam.md](session-seam.md)), frames +voice as RTP and derives who is talking from the media, copies the files of +transfers itself (progress, cancel, the picture limits) and turns every +`LinkCmd` into the `Session` call it stands for. `session.rs` and SessionLink +speak a vocabulary of their own, `LinkCmd` in and `LinkEvent` out, which is +crate-private (the module documentation of `link/session_link.rs` states its +contract): + +- `LinkCmd`: chat, moves, mute, pokes, the encoded voice frames from the + audio thread, the file and offline-message requests, `Stream(StreamCmd)` + and `Disconnect`; +- `LinkEvent`: `Connected` (name, `BackendInfo`, `Capabilities`, our client + id, the server's unique id), `Presence` (a full snapshot each time), + `OwnChannel`, `Chat`, `Poke`, `Audio` (a received `VoicePacket`), + `Talking`, `OwnStream`, `StreamAudio` (the audio of a watched stream, for + the audio thread's mixer), `StreamAudioEnded`, `Error` and `Disconnected`. + `Disconnected` ends the connection and is sent once, but it is not promised + to be the last event: the stream task of a connection winds down after it, + so its closing `OwnStream(Ended)` and `StreamAudioEnded` (and the bus + events of its streams) may follow. The session does not depend on it: on + `Disconnected` it ends our own stream and the audio of watched streams + itself, and what the connection says after that is ignored, like the + events of a replaced one (every connection has a generation). Everything backend-neutral stays in `session.rs`: merging the three sources, the dedup of a message that arrives twice, the chat history, contacts, the -privacy rules, the images and the gateway directory. The session tags each -link with a generation, so events of a replaced one are ignored. A link -reports what the server can do as `Capabilities`; with `streams` set it also -runs the stream task (`stream.rs`), which the session reaches only through -`LinkCmd::Stream(StreamCmd)` (start, stop, answer a viewer, watch, layers, -frames, friends, the gateway directory, shutdown) and which reports our own -stream's life back as `LinkEvent::OwnStream`. The stream task's requests -and the server's stream notifications never leave the link. +privacy rules, the images and the gateway directory. The answers that need +not pass the session first (file lists, transfers, offline messages, stream +state) go straight to the event bus, and the frames of watched streams to +`Engine::subscribe_frames`. -`Engine::start_with_link(settings, history, link)` takes the link; -`Engine::start` and `start_with` use `TsLink` (`ts_link.rs`), the -TeamSpeak 3 and 6 connection of `tsclientlib`, which runs `voice.rs` with -`book.rs`, `stream.rs`, `versions.rs` and `identity.rs`. `tests/link_fake.rs` -drives the session with an in-memory link instead: it plays scripted -`LinkEvent`s (connect, presence, a message twice, a disconnect, a replaced -connection) and checks the presence, chat, dedup and history the session -makes of them, and the commands it gives back, with no TeamSpeak server or -crate involved. +**The TeamSpeak module** (`voelin_core::ts`, `src/ts/`) is the TeamSpeak side +and is what moves to VoelinGateWay (`voelin-gateway-ts`). `ts_link.rs` and +`voice.rs` are the connection of `tsclientlib` (chat, voice, files, pokes, +offline messages and the stream task's requests), `book.rs` its presence from +the library's book, and `ts_session/` makes a `Session` of it: a +`LinkSession` writes the connection's snapshots, messages, pokes and voice as +v1 entities, pushes and RTP and answers requests with the connection's help, +and `TsConnector` makes them for `ts3server://` and `teamspeak://` +addresses and addresses without a scheme. The inner trait between them +(`ts_link::ServerLink`) is the module's own, and so are the TeamSpeak-typed +options it connects with. `versions` (the signed client versions a +TeamSpeak client may claim) and `identity` (reading and importing the official +clients' identities, the security level) are public, with `TsConnector`: +they are the only places of the crate's API that name `tsclientlib` and +`tsproto` types. -Where this is going: `ServerLink` is this crate's interim seam. `TsLink` and -the modules it owns move to VoelinGateWay (`voelin-gateway-ts`, the -in-process TeamSpeak gateway), and the QUIC transport of VoelinProtocol -becomes the other implementation, both behind the backend-neutral -`voelin_proto::link::Session` that the protocol spec defines (the spec -replaces `voelin_core::link::ServerLink` by it, because the gateway -implements the trait and the client depends on the gateway). The seam is not -backend-neutral yet. What still has TeamSpeak types, or TeamSpeak's shape, and -changes when `TsLink` leaves: +**Streams.** TeamSpeak 6 streams are peer to peer and not v1 entities yet, so +their commands and events pass the session through a local `StreamPort` that +an in-process connector hands over: with `Capabilities::streams` set the +connection runs the stream task (`stream.rs`), which the session reaches +only through `LinkCmd::Stream(StreamCmd)` (start, stop, answer a viewer, +watch, layers, frames, friends, the gateway directory, shutdown) and which +reports our own stream's life back as `LinkEvent::OwnStream`. The stream +task's requests and the server's stream notifications never leave the +connection. When the session replaces a connection it gives the old one +`StreamCmd::Shutdown` before `Disconnect`. + +**Tests.** `tests/session_fake.rs` drives the engine through +`Engine::start_with_backends` on the protocol repository's `FakeHost` and +`FakeSession`: presence, chat, dedup, history, transfers, a reconnect. The +unit tests of `link/` and `ts/ts_session/` check the mapping both ways with a +recording link inside, run the protocol's conformance suite against +`SessionLink` and, against the TeamSpeak development servers +(`VOELIN_LIVE=1`), against `TsConnector`. + +What is still TeamSpeak's shape, and changes when the TeamSpeak module +leaves (the second half of the decoupling): -- `ConnectOptions.identity` and `ConnectOptions.client_version` - (`tsclientlib` types), and the myTeamSpeak account proof in `LinkCtx` - (`myts_identity` of `tsproto`, `myts_data` of `tsclientlib`); - client ids are TeamSpeak's `u16`: our own in `Connected`, `Poke` and `Talking`, `LinkCmd::Poke`, a chat message's `author_id`, and the viewer and streamer ids of the stream API; @@ -160,10 +216,14 @@ changes when `TsLink` leaves: server and channel groups, talk power, icons, badges, the myTeamSpeak avatar; - the stream vocabulary of `voelin-stream` (the TeamSpeak 6 stream - protocol): `PeerConfig` in `ConnectOptions.stream_peer`, `MediaFrame` in + protocol): `PeerConfig` in `VoiceOptions.stream_peer`, `MediaFrame` in the frames of watched streams, `VideoFormat` in `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource`, which `voelin_core::stream` - re-exports with them (see Streams, below). + re-exports with them (see Streams, below); +- the TeamSpeak module's ids and uids (`ts/ts_session/ids.rs` and + `entities::user_uid`) are the rule that SessionLink's projection undoes the + few synthetic ids of; it is the one place the engine reaches into `ts/` + besides `Backends::default`. ## What the engine tells of the server's software @@ -176,7 +236,7 @@ kinds, files, offline messages). The UI shows `product` on a server's chip and `BackendInfo::label()` in the status line, and branches on capabilities only. The TeamSpeak 3 / 6 classification (`voelin_model::ServerFlavor`, from the `virtualserver_version` string) happens in the voice source -(`voice.rs::backend_of`), which puts both in `LinkEvent::Connected`; no +(`ts/voice.rs::backend_of`), which puts both in `LinkEvent::Connected`; no `ServerFlavor` appears in the engine's public API, so another link (a Voelin server) can fill the same two fields. @@ -493,13 +553,13 @@ stream task converts what `Streams` reports, and what the UI asks for own types (its `StreamInfo`, `ViewerInfo`, `StreamSetup`, `SrtpProfile`, `EndReason`) no longer show in `Command` and `Event`. Still `voelin-stream`'s in the engine's API are the peer and media vocabulary: -`PeerConfig` (in `ConnectOptions`), `MediaFrame` (the frames of watched +`PeerConfig` (in `VoiceOptions`), `MediaFrame` (the frames of watched streams), `VideoFormat` and `VideoCodec` (on the `StreamSink`), `FrameSource`, `SyntheticSource`; they move out of the core with the stream task (the decoupling plan's next steps). In `voelin-core` a stream task per voice connection runs `Streams`. The link -owns the task (see [The server link](#the-server-link)): the TeamSpeak +owns the task (see [The session seam](#the-session-seam)): the TeamSpeak connection hands it the `MessageEvent`s as notifications and the clients' channels, and sends its requests; the session talks to it with `LinkCmd::Stream(StreamCmd)`. Encoders push frames through diff --git a/docs/audio.md b/docs/audio.md index 99c1b5d..3c47147 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -27,12 +27,12 @@ crosses its boundary are the plain types of `voelin_audio::packet`: The transport adapter converts between these and its wire format; for the TeamSpeak connection that is `out_audio` and `voice_packet` in -`voelin-core/src/voice.rs`, the only place that builds TeamSpeak audio packets +`voelin-core/src/ts/voice.rs`, the only place that builds TeamSpeak audio packets from `EncodedVoice` or reads them into `VoicePacket`s (codecs other than Opus are dropped there, as the jitter buffer never played them). The audio thread, the session and the mixer see only the types above, and so does the link's seam: `LinkCmd::Audio` carries an `EncodedVoice` out and `LinkEvent::Audio` a -`VoicePacket` in (`voelin-core/src/link.rs`). +`VoicePacket` in (`voelin-core/src/link/mod.rs`). ## Echo cancellation, noise suppression, gain control diff --git a/docs/building.md b/docs/building.md index 9810b5c..fcc0e27 100644 --- a/docs/building.md +++ b/docs/building.md @@ -128,16 +128,21 @@ the proxy is on localhost. If the proxy inspects TLS, set ## Depending on VoelinProtocol `voelin-store` uses `voelin-identity` (the identity blobs, the account-bound -`KeyStore` and the sign-out rules) from the **private** VoelinProtocol -repository, as a Cargo git dependency in the workspace `Cargo.toml`: +`KeyStore` and the sign-out rules), `voelin-core` uses `voelin-proto` (the +session seam `voelin_proto::link` and the v1 messages), and almost every +crate uses `voelin-model` (the domain model and the replica of the protocol's +entities), all from the **private** VoelinProtocol repository, as Cargo git +dependencies in the workspace `Cargo.toml`: ```toml [workspace.dependencies] voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" } +voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" } +voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" } ``` -It is pinned by commit until the protocol tags a release that has it; moving -to a newer protocol means changing the `rev` (later a `tag`) and committing +They are pinned by one commit until the protocol tags a release; moving +to a newer protocol means changing the `rev` of all three (later a `tag`) and committing the resulting `Cargo.lock` together with `THIRD_PARTY_NOTICES.md`, which `scripts/notices.sh` regenerates (the CI notices job fails on a stale one). Cargo fetches it over SSH, so the machine needs an SSH key that can read @@ -167,8 +172,8 @@ per-developer `.cargo/config.toml` in the root of this repository: # VoelinClient/.cargo/config.toml (per developer, never committed) [patch."ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git"] voelin-identity = { path = "../VoelinProtocol/crates/voelin-identity" } -# voelin-proto is a dependency of voelin-identity from the same repository: voelin-proto = { path = "../VoelinProtocol/crates/voelin-proto" } +voelin-model = { path = "../VoelinProtocol/crates/voelin-model" } ``` - Relative paths in a Cargo config file resolve from the directory that @@ -179,5 +184,5 @@ voelin-proto = { path = "../VoelinProtocol/crates/voelin-proto" } - `/.cargo/` is in `.gitignore`: the file is yours and is never committed. - With the patch active Cargo rewrites `Cargo.lock` (the patched crates lose their git `source`). Do not commit that: run `git checkout Cargo.lock` before - committing, or remove the file and run `cargo update -p voelin-identity` - after changing the `rev`. CI builds with `--locked` and has no patch. + committing, or remove the file and run `cargo update -p voelin-identity -p voelin-proto -p voelin-model` + after changing the `rev` (for all three crates). CI builds with `--locked` and has no patch. diff --git a/docs/identity.md b/docs/identity.md index bba53c9..468fce9 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -162,7 +162,7 @@ installs keep `settings.db` next to the executable; point `--from` at it. ## What Voelin does -`voelin_core::identity` reads and writes these forms; `voelinctl` drives it: +`voelin_core::ts::identity` reads and writes these forms; `voelinctl` drives it: ``` voelinctl identity import --auto [--dry-run] [--store ] @@ -175,7 +175,7 @@ voelinctl identity export [--store ] `/voelin/client.db`, so the CLI and the app share identities. **On every start** the app does the same as `import --auto` -(`voelin_core::identity::import_new`): identities found in the default +(`voelin_core::ts::identity::import_new`): identities found in the default locations that the client database does not have yet are added, the files are only read. The user should appear as on the official client, so the identity the official client uses by default (field 5 of its payload, below; diff --git a/docs/research/ui-review.md b/docs/research/ui-review.md index 3054e43..85aaf4f 100644 --- a/docs/research/ui-review.md +++ b/docs/research/ui-review.md @@ -203,14 +203,14 @@ is not new in TS6. It is the classic client that TS3 already had. | Assigning server and channel groups, privilege keys (tokens) | none | | | Permission editor | none | TS6 discusses a simpler "easy view"; start there | | Server edit, "Recent server events" (log), complaints, client database, snapshots (TS6 beta4) | none | For admins; lower priority | -| Whisper lists and whisper hotkeys | incoming whispers only (`out_audio` in `voelin-core/src/voice.rs`: C2S only) | A TS signature feature: team leads whisper to the other leads | +| Whisper lists and whisper hotkeys | incoming whispers only (`out_audio` in `voelin-core/src/ts/voice.rs`: C2S only) | A TS signature feature: team leads whisper to the other leads | | Asking for talk power | none (`client_talk_request` is not modelled) | Moderated channels | | Channel description (BBCode, pictures) | none (`ChannelInfo` has the topic only) | Shown when a channel is selected | | Server welcome message and host message in the chat | only stripped, in Home's news | Official clients print them in the Server tab, and host message mode 3 as a dialog | | Notification sounds (sound pack): someone joined or left the channel, poke, message, connection lost, muted | none | Important for a voice app used while gaming: people do not look at the window | | Hotkeys for mute, deafen, away, whisper, switching channel | PTT only | | | Away with a message, auto-away when idle, mute while away | away is only shown | | -| Subscribing to channels one by one | always all channels (`voice.rs:424`) | Costs bandwidth and presence noise on large servers | +| Subscribing to channels one by one | always all channels (`voelin-core/src/ts/voice.rs`, right after the connection is made) | Costs bandwidth and presence noise on large servers | | Bookmark folders, importing the official clients' bookmarks | flat list; no import | TS6 syncs bookmarks through myTeamSpeak | | Client info: version, platform, connected for, idle for, country flag, badges | partly (country as text) | | | A file browser for the channel's files | none (the engine has `ListFiles`, `DeleteFiles`, `RenameFile`, `CreateDirectory`) | Only the UI is missing | diff --git a/docs/session-seam.md b/docs/session-seam.md new file mode 100644 index 0000000..169d023 --- /dev/null +++ b/docs/session-seam.md @@ -0,0 +1,1722 @@ +# The session seam: the engine on `voelin_proto::link::Session` + +Status: design (2026-10-20); slices 1, 2 and 3 are implemented (section 13 +says how slice 1 differs from this text, sections 14 and 15 what its reviews +changed, section 16 what slice 2 built, found and corrected, section 17 what +slice 3 moved, changed and ran, and 17.7 the round after its review, which +brought the branch onto main `ad20979`); section 10 has the slices. + +Design for the first half of plan step 7 (Phase 4): the engine consumes +`voelin_proto::link::Session`, `ServerLink` becomes an adapter over it, and +the TeamSpeak link (`TsLink`) becomes a `Session` implementation that still +lives in this repository, in process. The second half (the TeamSpeak +`Session` implementation moves to VoelinGateWay as `voelin-gateway-ts`, and +`voelin-stream`'s dependency on `voelin-media` is split) is out of scope +here; section 11 lists what it has to do. + +Read for this design: `crates/voelin-core/src/link.rs`, `ts_link.rs`, +`voice.rs`, `book.rs`, `stream.rs`, `files.rs`, `session.rs` (its use of the +link), `tests/link_fake.rs`, `voelin-audio/src/packet.rs`; and in +VoelinProtocol (main `c8e0e5a`) `crates/voelin-proto/src/link.rs`, +`media.rs` with `media/`, `test_util/` (FakeHost, FakeSession, +FakeConnector, FakeAccountAgent, the conformance suite), +`proto/voelin/v1/*.proto`, `crates/voelin-model/src/replica/` and +`docs/protocol.md` sections 1.2, 1.3, 2.4, 2.5, 4.7, 5, 6, 9.1, 11 and 13.8. + +## 1. Terms and the decisions in one place + +| Term | Meaning here | +|---|---| +| **engine** | `voelin-core` without the TeamSpeak implementation: `lib.rs`, `session.rs`, history, contacts, cache, settings, the audio thread, the adapter below. | +| **SessionLink** | New, engine side. A `ServerLink` whose connections are `Arc`s from the registry: it turns `LinkCmd`s into `Session` calls and pushes, signals and media into `LinkEvent`s. `session.rs` keeps talking `LinkCmd`/`LinkEvent` to it. | +| **Backends** | New, engine side. The registry of connectors by address scheme: `voelin_proto::link::Connectors` plus the in-process connectors that also hand the engine local ports (below). | +| **LinkSession** | New, TeamSpeak side. A `Session` over any `ServerLink`, generic in the link. `LinkSession` is the in-process TeamSpeak `Session`; `LinkSession` is what the link tests run through. | +| **TsConnector** | New, TeamSpeak side. The `Connector` for `ts3server` and `teamspeak` (and addresses without a scheme) that makes `LinkSession`s. | +| **StreamPort** | New, local extension. The in-process channel that carries `LinkCmd::Stream` and the stream events past the `Session` trait while TeamSpeak 6 streams are not yet v1 entities (section 6.4). | +| **old model** | The client's TeamSpeak-shaped types (`Presence`, `ChannelInfo`, `ClientInfo`, `ChatMessage`, `ServerDetails`) that `session.rs` and the UI use. | + +Decisions: + +1. **Two adapters, one vocabulary in the middle.** `session.rs` is not + rewritten: it keeps `LinkCmd`/`LinkEvent`. SessionLink translates them to + and from v1; LinkSession translates v1 to and from the inner link's + `LinkCmd`/`LinkEvent`. With a fake link inside, the pair round-trips, so + the existing FakeLink tests check both translations (slice 1). +2. **The engine keeps a replica.** SessionLink feeds every push into + `voelin_model::replica::Replica` and projects it into the old model with + `replica::convert` plus the fix-ups of section 5.3. This needs the + protocol's `voelin-model` (a superset of the client's, byte for byte the + same in `presence.rs`, `server.rs`, `chat.rs`, `percent.rs`), so slice 1 + switches the client's `voelin-model` to the protocol crate (the plan's + section 4 already moves it there). Two crates named `voelin-model` in one + graph would make `scripts/own-crates.sh`'s `-p voelin-model` ambiguous, so + there is no half-way. +3. **Streams stay on a local port in this half.** TeamSpeak 6 streams are + peer to peer; v1 carries only their signalling (`Stream`, `Viewer`, + `RespondViewer`, `KickViewer`, `Signal{stream}`, protocol 6.11 and 11.1). + Moving the str0m peer out of the TeamSpeak stream task and mapping its + signalling is the second half's first item; here `LinkCmd::Stream` and + the stream events pass through `StreamPort`, unchanged. +4. **File transfers go through v1 now.** `read_file`/`write_file` carry them; + the engine does the copying, progress and cancel itself, and the + TeamSpeak side hands out the raw transfer connection (two new inner + commands, section 8). +5. **TeamSpeak-only connect options ride the `ts3server://` link** that + `voelin_model::link::ServerLink::to_url` already writes (`channel`/`cid`, + `channelpassword`), until v1 has a field for them (follow-up P1); the + client version `TsConnector` impersonates rides it too, as a parameter of + our own (`client_version`). +6. **No TeamSpeak type crosses the seam**: what crosses is `voelin_proto` + types, the old model (TeamSpeak-shaped, but the client's own types), + `voelin-audio` packets and the core-owned stream types. Section 10 says + which public items still name `voelin-stream` peer types, and why. + +## 2. Shape after this half + +``` +UI ── Engine (Command / Event) ── session.rs (merge, dedup, history, contacts) + │ LinkCmd ↓ ↑ LinkEvent + SessionLink (engine side: replica, projection, + │ media framing, transfers, talk tracker) + │ Arc + pushes + MediaSink + │ (+ StreamPort for in-process connectors) + Backends ─────┼──────────────────────────┐ + (scheme registry) ▼ ▼ + TsConnector → LinkSession any Connector: FakeConnector + (ts3server, teamspeak, no scheme) (tests), QuicConnector (later) + │ LinkCmd ↓ ↑ LinkEvent (inner, TS side) + TsLink: voice.rs, book.rs, stream.rs, versions.rs, + identity.rs on tsclientlib, voelin-stream +``` + +The gateway (`tsgw`) and ServerQuery sources of a session are not behind +the seam in this half: they are the other two sources of `session.rs` +(`gateway.rs`, `query.rs`) and become a second `Session` to a gateway daemon +later (protocol 11.2, follow-up H5). Only their public command types change +in slice 3 (section 10). + +## 3. The mapping + +### 3.1 `LinkCmd` → `Session` + +Every variant of `voelin_core::link::LinkCmd`. "SessionLink" is what the +engine does; "LinkSession" is how the TeamSpeak side answers. `S` is the +server id from the connect sequence (section 4.2), `P` our participant id, +`slot` our media slot. Text in errors is reproduced exactly as `TsLink` +writes it today (section 4.6). + +| `LinkCmd` | Session call (SessionLink) | Answer and what the engine reports | LinkSession (TeamSpeak side) | +|---|---|---|---| +| `SendChat(target, text)` | `request(Put{writes:[Message{channel_id, text, format, nonce}]})`. `Channel(cid)`: that channel. `Server`: the channel of kind `SERVER_CHAT` in SERVER(S). `Private(uid)`: the DM channel in HOME whose other recipient's `User` has that uid; without one, first `request(Put{Channel{server_id:0, kind:DM, recipients:[user]}})`. `format`: `BBCODE` when the session offers `chat.bbcode`, else `MARKDOWN`. | `Entities` ignored (the `Change` that follows is the echo, section 3.2). `Rejected` → `LinkEvent::Error("message: {Error.message}")`. No `User` for `uid` → `Error("private message: the client is not on the server (send an offline message instead)")`, without a request. | Inner `SendChat`. A VOICE channel other than our own is refused `NOT_IN_CHANNEL`. Answered at once with the message as written (local id and rev): `TsLink` reports success of a text message nowhere, failures come later as a notice (section 3.2). The answer adds no `Change`: the inner link's echo is the `Change`, with an id of its own, because the inner link does not tie the echo to the send (H1 does). A `Put Channel{DM}` answers the synthetic DM channel (section 5.2) and puts it in HOME. | +| `Move(channel, password)` | `request(JoinVoice{server_id:S, channel_id, password})` (`None` → empty). | Own `VoiceState` → nothing (the move shows in LIVE). `Rejected` → `Event::JoinFailed{channel, reason}`: `PASSWORD` → `JoinFailure::Password`, `FULL` → `Full`, any other → `Other(Error.message)`. | Already in that channel and no move of ours on its way: answer the own `VoiceState`, send nothing (today `ChannelAlreadyIn` is silent too). While a move is on its way the snapshot is where we were, not where that move leaves us, so the request goes to the link whatever channel the snapshot shows (a move back into the channel we never left is answered when the first move is refused, or when its channel is the snapshot's). Else inner `Move`; answered when our channel becomes `channel_id` (own `VoiceState`), refused when the inner link reports `Event::JoinFailed` for it (`Password` → `PASSWORD`, `Full` → `FULL`, `Other(text)` → `FORBIDDEN` with `text`), `SessionError::Timeout` after 10 s. The first `JoinVoice` of a connection confirms the seat (section 4.2). | +| `SetInputMuted(b)` | `notify(Put{Write{VoiceState{S, P, self_mute:b}, paths:[self_mute]}})` (protocol 4.7: own voice flags are fire and forget). | `Err` only for a closed session: ignored. | Inner `SetInputMuted(b)`. | +| `SetOutputMuted(b)` | `notify(Put{Write{VoiceState{S, P, self_deaf:b}, paths:[self_deaf]}})`. | As above. | Inner `SetOutputMuted(b)`. | +| `Audio(EncodedVoice)` | `send_media(MediaClass::Voice, MediaPacket{flow: FlowId::new(slot, voice_sub::CHANNEL), rtp})`, RTP as in section 6.1. | `Dropped`: counted (stats). `NotOwned` (no slot yet), `TooLarge` (over `stats().max_rtp`): dropped, logged once per connection. `Closed`: ignored. | Inner `Audio(EncodedVoice{codec, payload})` for our own slot only (section 6.2). | +| `Stream(StreamCmd)` | None in this half: `StreamPort::send(cmd)` (section 6.4; the v1 mapping of every `StreamCmd` is table 6.4). Without a port the engine reports no `streams` capability, so `session.rs` never sends it. | Bus events and `OwnStream`/`StreamAudio`/`StreamAudioEnded` come back through the port. | Inner `Stream(cmd)`, in issue order with everything else (one queue). | +| `Poke{client, message}` | `request(Signal{to:SignalTarget{server_id:S, participant_id:client}, body:Poke{message}})`. | `Ack` → nothing. `Rejected` → `Error("poke: {Error.message}")`. | Inner `Poke`; answered `Ack` at once (failures come as a notice). | +| `ListFiles{request, dir}` | `request(List{kind:FILE, parent:dir.channel, path:dir.path, password})` (refused locally without `files`). | `Event::FileList{request, channel, path: files::normalize_dir(path), result}`: `Ok` with each `FileEntry` as `files::FileEntry{name, size, modified_s: modified_ms/1000, is_dir}`, or `Err(text)`. | Inner `ListFiles` with a request id of its own; its `Event::FileList` becomes the `Entities` answer (`modified_ms = modified_s * 1000`), or `Rejected` with the text. | +| `Download{transfer, file, sink, report}` | `report(Requested)`, then `read_file(FileRead{target: Path(FilePath{channel_id, path, password}), offset: sink.offset(), length:0})`; the engine runs `files::download` (made generic over `AsyncRead`) on `Download.body` with `FileEntry.size` from `head`. A picture (`transfer: None`) keeps today's limit (`cache::MAX_PICTURE_BYTES`) and deadline (`image_download_time`), now applied here. | `TransferState`s through `report`, as today. `Err` → `report(Failed(text))`. The task is kept under `transfer` for `CancelTransfer`. | Inner `OpenRead` (new, section 8): the TeamSpeak transfer connection itself becomes `body`, `head` is `FileEntry{size}`. No deadline of its own: the engine puts one on a picture's negotiation (`IMAGE_NEGOTIATION`) and none on a file the user asked for, and a caller that drops the call takes the inner job with it. | +| `Upload{transfer, file, from, overwrite, resume, report}` | Size and kind of `from` checked here (today's texts: "{path} is not a file", "{path}: {error}"). With `resume`, the offset is the `size` of the target in `List{FILE}` of its directory (0 when absent). `write_file(FileWrite{target: Path(...), size, offset, overwrite})`; the engine runs `files::upload` (generic over `AsyncWrite`) into `Upload.body`, then awaits `Upload.done`. | `TransferState`s as today; `Done` after `done` resolved. | Inner `OpenWrite` (new): the transfer connection becomes `body`; the server's seek position must equal `offset`, else `CONFLICT` "the server has N bytes" (follow-up P4). `done` resolves when the inner job reports the end. No deadline of its own, as for a download. | +| `CancelTransfer(id)` | No call: the engine aborts its copy task (dropping the body cancels on both v1 and TeamSpeak), removes the `.part` file, reports `Cancelled`; an unknown id is logged, as today. | — | The dropped connection ends the TeamSpeak transfer. | +| `DeleteFiles{request, channel, password, paths}` | `request(Delete{keys:[FileEntry{channel_id, path: dir, name, password}...]})`, one key per path (`/dir/name` split at the last `/`). | `request: Some` → `Event::RequestDone{request, result}`; `None` → nothing (best effort). | Keys grouped by channel → inner `DeleteFiles{request: Some(own id)}` each; `RequestDone` → `Ack` or `Rejected`. | +| `RenameFile{request, from, to}` | `request(Put{writes:[Write{FileEntry{channel_id: to.channel, path, name, password: to.password, from_channel_id: from.channel, from_path: from.path, from_password}}]})` (a create of an unused key: no `paths`). | `RequestDone{request, result}`. | Inner `RenameFile`. | +| `CreateDirectory{request, dir}` | `request(Put{writes:[Write{FileEntry{channel_id, path, name, is_dir: true, password}}]})`. | `RequestDone{request, result}`. | Inner `CreateDirectory`. | +| `SetAvatarHash{request, hash}` | `request(Put{writes:[Write{User{id: own user, avatar: Image{hash}}, paths:[avatar.hash]}]})` (the leaf path, so the myTeamSpeak `url` in the same `Image` stays). | `Some(request)` → `RequestDone`; `None` → `Rejected` becomes `Error("avatar: …")`. | Inner `SetAvatarHash`. (`replica::convert` reads the TeamSpeak avatar from `User.avatar.hash`; follow-up P7 on `Member.avatar`.) | +| `OfflineList{request}` | `request(List{kind:MAIL})` (refused locally without `mailbox`). | `Event::OfflineMessages{request, result}` from the `Mail`s (`OfflineMessageInfo` fields from `id`, `from_uid`, `from_name`, `subject`, `ts_ms`, `read`). | Inner `OfflineList`; its event becomes `Entities[Mail…]`. | +| `OfflineGet{request, id}` | `request(List{kind:MAIL, ids:[id]})` (v1: `List{MAIL, ids}` returns the text). | `Event::OfflineMessage{request, result}`. | Inner `OfflineGet`. | +| `OfflineAdd{request, to_uid, subject, text}` | `request(Put{writes:[Write{Mail{id:0, to_uid, subject, text}}]})`. | `RequestDone`. | Inner `OfflineAdd`; answers the mail as written (id 0: `messageadd` returns none). | +| `OfflineDelete{request, id}` | `request(Delete{keys:[Mail{id}]})`. | `RequestDone`. | Inner `OfflineDelete`. | +| `OfflineFlag{request, id, read}` | `request(Put{writes:[Write{Mail{id, read}, paths:[read]}]})`. | `RequestDone`. | Inner `OfflineFlag`. | +| `Disconnect` | `close(CloseCode::Normal, "")`, then `closed()`. A closed command channel does the same. | `LinkEvent::Disconnected(None)` (section 4.5). | Inner `Disconnect`; `closed()` resolves `Local(Normal)` when the inner link reports its end. | + +Requests with a `RequestId` that cannot be sent (no session yet, closed) +answer as today: `session.rs` already reports "not connected with voice" +before a link exists; SessionLink reports `SessionError` texts (4.6). + +`LinkSession::notify` follows the `Session` contract (it errors for a closed +session or a misplaced op, as `FakeSession` does): `Hello`, `List`, +`FileRead` and `FileWrite` are `Protocol` errors, because they have a stream +and an answer of their own (`placement`); our own mute flags go to the link; +any other op of the control stream is run as the request it is, and its +answer, or its refusal, is told to nobody. + +### 3.2 `Session` → `LinkEvent` + +Every variant of `voelin_core::link::LinkEvent`. + +| `LinkEvent` | Source on the `Session` side | Rule | +|---|---|---| +| `Connected{name, backend, capabilities, own_client, server_uid, own_uid}` | `Welcome`, the SERVER(S) sync, the answer to the first `JoinVoice`, the own `User`. | Sent once, after the connect sequence (4.2). `name` = `Server.name`; `backend` from `Welcome.host.backend` (table 4.7); `capabilities` from `features()` (table 4.7); `own_client` = `P` as `u16`; `server_uid` = `server_key(Server.uid)` (5.3, F3); `own_uid` = `uid_text` of the own `User` (the `User` of our `VoiceState.user_id`, else `Welcome.user_id`), `None` when the replica has none yet. | +| `Presence(Box)` | `Change`/`SyncEnd` of SERVER(S) and LIVE(S); talk tracker. | After the pushes that are there now are applied (drain, then one snapshot), if SERVER or LIVE changed: `replica.presence_model(S)` with the fix-ups F1-F10. One TeamSpeak book update is one inner `Presence`, one or two `Change`s, and still one snapshot. | +| `OwnChannel(cid)` | Our `VoiceState.channel_id` in LIVE. | After every `Presence`, when known and not 0 (as `TsLink` does after every snapshot). Our `VoiceState` is the one of the seat, and behind a TeamSpeak server it follows the seat to the participant that is us after the link's own reconnect (4.4); the `OwnChannel` of the inner link only tells `LinkSession` that a move has arrived. | +| `Chat(ChatMessage)` | `Change.put` of a `Message`, and messages of a `SyncBegin`..`SyncEnd`, in a subscribed CHAT scope (4.3). | Once per `(channel_id, id)` per connection, and only once the replica can show it: a full sync stages its messages until its `SyncEnd`, so the messages of a CHAT scope are reported at its `SyncEnd` as well (4.3). `replica.chat_message(channel, id)` gives target, author name, author uid, author participant, `ts_ms`, `via_relay` (`MESSAGE_FLAG_RELAYED`). Answers to our own `Put` are not applied to the replica: our own message is reported when its `Change` arrives, which is today's echo, and `session.rs` merges it with the row it stored (test `a_sent_message_and_its_echo_are_one_message`). | +| `Poke{from, from_uid, from_name, message}` | Push `Signal{from_user, from_participant, body: Poke{message}}`. | `from` = `from_participant` as `u16`; `from_uid` = `uid_text` of `User(from_user)`; `from_name` = the participant's `VoiceState.nick`, else the `User.name`. A sender outside our view is delivered as a bare `User` first (5.2). | +| `Audio(VoicePacket)` | `MediaSink` packets on a voice slot. | Section 6.1. | +| `Talking{client, talking}` | `MediaSink` packets on a voice slot (protocol 6.4: talking in the own channel comes from media), and `Signal{speaking}` (below). | The first packet of a slot → `true`; 400 ms without one → `false` (250 ms tick): the rule of `voice.rs` today. `TsLink` also hears talkers whose packets it does not forward as Opus (Speex, CELT): `LinkSession` passes the inner link's `Talking` on as `Signal{speaking}`, and SessionLink holds such a talker as talking until the host says `on: false` (no silence ends it). Also fills `ClientInfo.talking` (F8). | +| `OwnStream(OwnStreamEvent)` | `StreamPort` events. | Passed through. | +| `StreamAudio{stream, time, data}` | `StreamPort` events. | Passed through. | +| `StreamAudioEnded(stream)` | `StreamPort` events. | Passed through. | +| `Error(text)` | (a) `Rejected` answers to commands that have no `RequestId` (`SendChat`, `Poke`, `SetAvatarHash{request: None}`); (b) push `Signal{notice{level: ERROR or WARNING}}`; (c) `ScopeClosed` of SERVER(S) or LIVE(S). | (a) `"{what}: {Error.message}"`, `what` = `message`, `poke`, `avatar` (today's labels); (b) `Notice.text`; (c) `ScopeClosed.message`, and the presence is emptied. | +| `Disconnected(reason)` | `closed()`; a failed `connect`; a connect sequence that does not finish. | Section 4.5. Sent once; the `StreamPort`'s closing events may follow, as the contract of `link.rs` already allows. | + +What the `Session` side produces and no `LinkEvent` carries, with the +decision for each: + +| Session output | Decision in this half | +|---|---| +| `Push::SyncBegin`/`SyncEnd`/`Change` of HOME | Applied to the replica: DM channels (CHAT subscriptions, 4.3), the own `User`, bare `User`s of senders. No event of their own. | +| `Push::Heads` | Ignored: no unread source in the engine uses it yet (TeamSpeak sends none). | +| `Push::HostUpdate` | Updates the feature set SessionLink checks requests against. Capabilities are not announced again: `LinkEvent` has no update, and TeamSpeak never sends one. Follow-up (client): `Event::ServerInfo` again on a `HostUpdate`. | +| `Push::ScopeClosed` | CHAT: unsubscribed, nothing reported. SERVER or LIVE: `Error` and an empty presence (row `Error` above). HOME: logged. | +| `Signal{typing}` | Ignored (the engine has no typing indicator; TeamSpeak types only in DMs). | +| `Signal{stream}`, `Signal{layer_target}` | Not sent by `LinkSession` (streams use the port). Ignored with a log. Second half: the engine's stream task (H2). | +| `Signal{encoder_hint}` | Ignored. Follow-up (client): Opus bitrate and `packet_loss_perc` from it (protocol 6.7). | +| `Signal{reminder}` | Ignored (no events feature in the engine). | +| `Signal{notice{level: INFO}}` | Logged at info. | +| `Signal{speaking}` | A hint next to the media: the host says a participant talks or stopped (`LinkSession` sends it for the inner link's `Talking`, which is all there is for a talker without Opus). Not asked for with `SUBSCRIBE_OPTION_SPEAKING`; talking in other channels stays a follow-up (P13). | +| Media on stream slots (sub 0-4), `FlowId::FEEDBACK`, `FlowId::PROBE` | Dropped (no SFU streams in this half). | +| `stats()` (`LinkStats`) | Section 4.7. | +| `Connected.host_uid` | Not pinned for TeamSpeak (`[0; 32]`, no host key). Kept for a later pin store for `voelin://` hosts. | +| `Welcome.resume_token`, `Welcome.ice`, `Welcome.observed_addr`, `Welcome.time_ms` | Kept by SessionLink, unused in this half (4.4). | +| `Welcome.limits` | `max_chat_subscriptions` bounds the CHAT scopes (4.3). `max_message_chars` is not enforced (the UI's own limit stays). | + +## 4. How the engine owns a `Session` + +### 4.1 The registry + +`voelin_core::link::Backends` holds the connectors by scheme: + +- `connectors: voelin_proto::link::Connectors` for plain connectors + (`Backends::register(Arc)`: `FakeConnector` in tests, the + QUIC connector later); +- in-process connectors that also give local ports: a crate-private trait + `LocalConnector: Connector` with + `connect_local(params, LocalCtx) -> BoxFuture>`, + where `LocalCtx` is what an in-process backend needs besides + `ConnectParams` (session id, the event bus, the frames bus, the settings, + the stream peer configuration, whether audio is open) and `LocalConnected` + is `Connected` plus `Option`. + +Lookup: the scheme of `ConnectParams.address` (lowercase, before `://`); an +address without a scheme is a TeamSpeak bookmark and gets `ts3server`. A +local connector for the scheme wins over a plain one; none → `Disconnected` +with "no connector for {address}" (the text of `Connectors::connect`, but with the address cut at `?` and `#`: the text is shown and logged, and a TeamSpeak link carries a channel password and a pin). + +`Engine::start` and `start_with` use `Backends::default()`, which registers a +`TsConnector` (schemes `ts3server`, `teamspeak`) of its own. The connector owns +the myTeamSpeak account (4.8: since `a451f02` it holds the senders and has the +setters; an application that sets the account registers its connector with +`Backends::register_teamspeak`). New: +`Engine::start_with_backends(settings, history, backends)`. +`Engine::start_with_link(settings, history, link)` stayed in slices 1 and 2: it +registered a local `LinkConnector` that answers every scheme with a +`LinkSession` over the given link, so the link tests went through the whole +adapter. Slice 3 removed it (17): the tests that needed it build the same +registry themselves. + +### 4.2 Connect sequence + +SessionLink is a `ServerLink`: `session.rs` calls `spawn` exactly as today +and shows `Connecting` until `Connected`. + +1. Build `ConnectParams` (section 7 for the credential). In slice 1 the + options still carry TeamSpeak types, so one function of the TeamSpeak + module, `ts_session::connect_params(&ConnectOptions)`, builds them; it + also writes the resolved client version into the link parameter + `client_version` in a text form of its own. Slice 3 moves the building + into SessionLink over the neutral `VoiceOptions`, and `client_version` + carries the user's spec instead. The fields: + `address` = the `ts3server://` link of the bookmark address with + `channel`/`cid` and `channelpassword` (`ServerLink::to_url` of the model's + `link.rs`; a name clash with the trait, nothing more), or the address as + given when it has a scheme; `hello` = `Hello{version:1, client: + ClientInfo{name:"Voelin", version, platform, kind}, nickname, password: + server password, invite_code: privilege key, ..}`; `host_pin: None`; + `trust`: refuses (no TOFU dialog yet; TeamSpeak has no host key); + `media`: SessionLink's sink; `push_capacity: 1024`; `timeout: 35 s` (the + TeamSpeak connect gives up at 30 s with its own text, which should win); + `account: None`, `issuer_trust: Unknown`, `linked: []`. + The link can hold a channel password: neither side logs it (the + connector logs the host and port), and `session.rs` keeps keying history + and aliases by the bookmark address, not by the link. + What the link round trip (`address_link` here, `inner_options` on the + TeamSpeak side) does to an address, since a link cannot say all an address + can: a bookmark `host[:port]` whose port is not a number from 1 to 65535 + (`host:99999`, `host:abc`, `[::1]:`) is **refused** in words, where the + link would drop the port and connect to the default one; so is a bookmark + whose host holds a `?`, `#`, `/` or `%`, white space or a control + character (the link ends a host at the first three, decodes the fourth, and + a `?` would hide the channel behind the next one), or is empty or an + unclosed `[`. The TeamSpeak library could not resolve any of them + either. **Normalised**, not refused: blanks around a bookmark are cut; + `[v6]` with no port comes back as `v6` (the library reads both); an empty + server password, channel, channel password or privilege key is none (the + channel password already was); an address that is a `ts3server://` link + keeps the model's rules for links (a `port=` that is no port is ignored, + other keys are ignored), and the options given next to it win over its + parameters. The error shows the address without its query (the connect + fails with `Disconnected(Some(text))` before any connector is asked). +2. `Backends::connect`. `Err(e)` → `Disconnected(Some(text(e)))`, end. +3. `request(List{kind: SERVER})`; the server `S` is the only one listed (or + the lowest id; follow-up P3 for hosts with several). `FakeHost` files no + `Server` stub in HOME (follow-up P9), so HOME is not used to find it. +4. `Subscribe` HOME, SERVER(S) and LIVE(S), each after `replica.subscribe`. +5. Apply pushes until the three `SyncEnd`s. 30 s without them → close, + `Disconnected(Some("timed out while connecting"))`. If the push channel + ends meanwhile the session has ended: `closed()` says why, and that is + the reason of `Disconnected` (a kick during the syncs is shown as one). +6. `request(JoinVoice{server_id:S, channel_id, password})`: `channel_id` from + the bookmark's channel (`/` directly, a path resolved in the synced + tree with `split_channel_path`), else `Server.default_channel_id`. The + answer is our `VoiceState`: `P`, `slot`. TeamSpeak seats a client at + connect, so `LinkSession` answers the first `JoinVoice` of a connection + with the seat it has (participant = our client id, channel as far as it + knows it, 0 before the first snapshot) and moves nothing; the seat was + chosen by the link's `channel` parameter. A refused first `JoinVoice` → + close, `Disconnected(Some(Error.message))`. +7. Report `Connected`, then `Presence`, then `OwnChannel` (the order + `session.rs` and its tests expect). +8. Subscribe CHAT for the server chat, our channel and each DM (4.3). +9. Loop, `select!` biased in this order: the command channel, media, + pushes, the stream port, the session's own notices, `closed()`, the 250 ms + tick (talk tracker, stats). The bias is no order: the events that come from media (`Talking`, + `Audio`) and the ones that come from pushes (`Presence`, `Chat`, `Poke`, + `Error`) travel in two channels, and nothing in the engine, the tests + included, may rely on one coming before the other (section 13). A packet + from a slot the replica does not know yet fetches the queued pushes first + and tries again (`on_media`). + +`LinkSession` answers `List{SERVER}`, `Subscribe` and `Unsubscribe` from its +own state, without an inner command; an op it does not implement is +`UNSUPPORTED` with the op's feature in `Error.feature`. + +### 4.3 Which CHAT scopes + +TeamSpeak delivers the chat of our own channel, the server chat and private +messages; everything else needs a gateway. SessionLink subscribes exactly +that: CHAT(server chat channel), CHAT(our channel) (re-subscribed when we +move, the old one unsubscribed), and CHAT(dm) for each DM channel HOME +holds. + +The number of CHAT scopes is `Welcome.limits.max_chat_subscriptions` (0 or +no `Limits`: the v1.0 default, 16). `LinkSession` says 65,536 and enforces +it: it is no limit a connection reaches, because a private message from +somebody new makes a conversation, and a connection on a busy server meets +more than 16 people. Against a host with a small limit the server chat and +our channel come first, then the private conversations, the newest +(highest id) first. + +A message that arrives before its +scope is subscribed is not lost: `LinkSession` keeps the messages of the +connection per channel (the 50 newest, the default CHAT window of +protocol 5.4) and sends them in the full sync; SessionLink reports each +`(channel, id)` once. A full sync is staged by the replica until its +`SyncEnd`, so a message of its `Change`s cannot be read when the `Change` +is applied (and `SyncBegin`, `Change` and `SyncEnd` may come in different +batches): SessionLink marks a message as reported only once it has shown it, +and at the `SyncEnd` of a CHAT scope it shows the messages of that channel +it has not shown yet (test +`the_messages_of_a_chat_sync_are_reported_when_the_sync_ends`). A first private message from someone new therefore +arrives as: HOME `Change` (the DM channel), Subscribe CHAT(dm), its sync. +A cursor kept per CHAT scope makes a re-subscription after moving back a +delta where the session offers `sync.delta` (`LinkSession` does, within one +connection). + +### 4.4 Reconnect and resume + +- **Engine-initiated** (`Command::ConnectVoice` again): unchanged. + `session.rs` gives the old link `StreamCmd::Shutdown`, then `Disconnect`; + both reach the old session through one ordered queue (4.5), and the + generation filter drops what the old one still says. +- **Transport**: TeamSpeak's own reconnect inside `tsclientlib` + (`DisconnectedTemporarily`) stays invisible at the seam, as it is today + (the snapshots go on). The connection comes back as another client: a new + client id, the same unique id and database id. `LinkEvent::Connected` is + not repeated (as today), but the engine does not stay the client of the + connect: *we are the client of our unique id*. + `LinkSession` takes the client it was for as long as that client is in + the snapshots, and when it is gone the client of our unique id (the + newest, when a ghost of the old connection lingers: while the ghost is + there we stay on it, as a second client of one identity may be a second + connection of ours); the own client keeps the database id when two + clients share it, so the user we are is the same through the reconnect; + `Session.send_media` follows the slot. SessionLink (behind a TeamSpeak + host only: a participant is ours for the life of any other session) keeps + its seat while the participant is ours, and moves it to the participant + that carries our user id when the seat is gone or no longer carries it; a + seat whose user id changed by itself (the snapshot that tells our database + id came after the seat) is followed. `OwnChannel`, the voice flags, the + uplink slot and the chat scope of our channel follow the seat (tests + `the_engine_follows_a_reconnect_that_makes_us_another_client`, + `we_stay_the_client_we_were_while_it_is_there`). The native TeamSpeak + session of the second half starts a new epoch instead (H1). +- **Resume**: `LinkSession` does not offer `resume`. SessionLink keeps the + last `Welcome.resume_token` and the CHAT cursors per session and address, + and sends neither in this half: no `voelin://` connector is registered. + Reconnecting with backoff (protocol 2.5) is the SDK's (H8). Until then a + reconnect to a v1 host replays the window of each CHAT scope: the engine + stores every replayed message again, and shows again those that `Dedup` no + longer holds (F3, 16.5). + +### 4.5 Close + +| How it ended | `closed()` | `LinkEvent::Disconnected` | +|---|---|---| +| `LinkCmd::Disconnect`, or the command channel closed | `Local(Normal)` | `None` | +| The inner link ended unasked without a reason | `Remote{code: Normal, reason: ""}` | `None` | +| The inner link ended with a reason (kicked, server gone, timeout) | `Network(reason)` | `Some(reason)` | +| A v1 host closed with a code | `Remote{code, reason}` | `Some(reason)`, or the code's name when `reason` is empty; `None` for `Normal` with no reason | +| Idle timeout | `TimedOut` | `Some("timed out")` | + +`LinkSession` keeps one queue for everything that reaches the inner link: +`Session` calls, `StreamPort` sends and `close`. The order a caller issues +them in is the order the inner link sees (the `Session` contract for +mutations, and what `a_reconnect_shuts_the_streams_down_before_the_old_connection` +checks: `Stream(Shutdown)` before `Disconnect`). + +### 4.6 Errors and their texts + +`text(SessionError)`: `Rejected(e)` → `e.message`; `Closed(reason)` → the +reason as in 4.5; `Timeout` → "timed out while connecting" during connect, +"timed out" otherwise; `Unsupported(f)` → "not offered by this server: {f}"; +`HostIdentity(t)`, `Protocol(t)` → `t`; `Io(e)` → `e.to_string()`. +`LinkSession` puts `TsLink`'s own texts in `Error.message` and +`CloseReason::Network`, so what the user reads does not change. + +### 4.7 Where `Features`, `BackendInfo` and `LinkStats` surface + +`Welcome.host.backend` → `BackendInfo`: + +| v1 `BackendInfo{product, flavor}` | engine `BackendInfo.product` | +|---|---| +| `teamspeak`, `ts3` | `TeamSpeak 3` | +| `teamspeak`, `ts6` | `TeamSpeak 6` | +| `teamspeak`, empty (not recognised) | empty (`version` = what the server said) | +| anything else | `product` as given | + +`LinkSession` writes the inverse from the inner `Connected.backend` +(`TeamSpeak 3` → `teamspeak`/`ts3`, ...), so every value round-trips. + +`features()` (narrowed by `Server.features`) → `Capabilities`. SessionLink keeps +the host's set (`Session::features()`, replaced by each `HostUpdate`) and the +set of the server (`Features::narrowed(&Server.features)`, recomputed when +the SERVER scope changes or syncs and after a `HostUpdate`); `Capabilities`, +the local refusals (`Features::require`) and the presence fix-ups use the +narrowed one. `LinkSession` files no `Server.features` (an empty list keeps +all of them): + +| `Capabilities` | from | +|---|---| +| `streams` | `streams`, and the connection has a `StreamPort` (this half) | +| `file_transfer` | `files` | +| `offline_messages` | `mailbox` | +| `raw_query`, `ssh_query`, `http_query` | no feature: they describe ServerQuery access to a TeamSpeak server, not the session. Derived from the flavor as `ServerFlavor::capabilities` does (`ts3`: raw and SSH; `ts6`: SSH and HTTP). They go with the query observer (H5); follow-up P10. | + +`LinkSession`'s features are what it implements: `voice`, `chat`, +`chat.bbcode`, `dm`, `sync.delta`, `roles`, `roles.channel`; with file +transfer `files`, `files.upload`; with offline messages `mailbox`; with +streams `streams`, `streams.p2p`, `streams.audio`, `streams.approval`. Not +`voice.whisper`, `chat.typing` or the moderation set: the inner link cannot +do them (the native session of H1 offers the whole TeamSpeak column of +protocol 9.1). SessionLink refuses locally (`Features::require`) what needs a +missing feature: `List{FILE}`, file reads and writes (`files`, +`files.upload`), `Mail` (`mailbox`). + +`LinkStats`: no UI surface in this half (the engine has no event for +connection quality). SessionLink reads `stats()` on the tick: `max_rtp` +bounds outgoing voice packets; `rtt`, `loss`, `media_dropped` and `degraded` +are logged at debug every 10 s and when `degraded` changes. `LinkSession` +reports `max_rtp: MAX_RTP` and zeros. Follow-ups: an engine event for +connection quality, and the encoder's FEC and loss from `LinkStats` and +`encoder_hint` (protocol 6.7). + +### 4.8 What `LinkCtx` becomes + +| `LinkCtx` field | Where it goes | +|---|---| +| `session` | SessionLink (it reports with it); `LocalCtx.session` for the stream task. | +| `events` | SessionLink reports answers itself; `LocalCtx.events` for the stream task's bus events. Inside `LinkSession`, the inner link gets a bus of its own: `FileList`, `JoinFailed`, `OfflineMessages`, `OfflineMessage` and `RequestDone` from it answer pending requests, every other event (the stream task's) is forwarded to the engine's bus unchanged. Capacity 4096, and every pending request has a timeout, so a lagging receiver cannot hang one forever. | +| `frames` | `LocalCtx.frames`, passed to the inner link as is. | +| `settings` | SessionLink (progress cadence `files.progress_ms`); `LocalCtx.settings` for the stream task. | +| `myts_identity`, `myts_data` | `TsConnector` (it got the engine's watches in slices 1 and 2; since slice 3 it owns the senders and has the setters, 17); the account hook of section 7 replaces them later (H4). | + +## 5. Presence across the seam + +### 5.1 The rule + +`project(translate(p)) == p` for every presence a TeamSpeak link reports: +`translate` is `LinkSession`'s old model → v1 entities, `project` is +SessionLink's replica → old model. A unit test checks it on the book +fixtures of `book.rs` (TeamSpeak 3 and 6) and on a generated set of +TeamSpeak-shaped presences; the FakeLink tests check it end to end. + +### 5.2 Ids and entities on the TeamSpeak side + +Protocol 11.1 "Ids", made concrete for `LinkSession`: + +| v1 | from the old model | +|---|---| +| server id | 1 (one virtual server per connection) | +| `Server` (SERVER(1)) | `ServerDetails` and `server_name`; `uid` = `ts:` + the server uid `TsLink` computes; `host_message_mode`, banner, host button, icon (`Image{hash: id}`), `max_members`, `priority_dim_db`, `default_role_id` = sgid, `default_channel_role_id` = cgid with bit 62; `foreign{system:"teamspeak", kind:"server", json:{"platform", "version"}}`, the strings the server sent (F4, F5) | +| channel id | cid; `kind: VOICE`; `position` from the order chain (1024 per step); `needed{TALK}`; `icon`; banner; `max_members` (with `foreign{"max_clients":0}` for a limit of 0, F7) | +| server chat | `Channel{id: 1 << 63, kind: SERVER_CHAT}` in SERVER(1) | +| DM channel | `Channel{id, server_id: 0, kind: DM, recipients: [own user, peer user]}` in HOME, made when a message to or from the peer needs it; `id` has bit 63 set and the FNV-1a 64 hash of the peer's uid in the low 63 bits (1 when they come out 0, so it never equals the server chat's id) | +| role id | sgid (`RoleScope::SERVER`); cgid with bit 62 (`RoleScope::CHANNEL`); `position` = −`sort_id`; `name_mode`; `kind`; `icon` | +| user id | `database_id`; a sender with none, or outside our view, gets bit 63 set and the FNV-1a 64 hash of its uid in the low 63 bits | +| `User` | `uid` = base64-decoded unique id, `uid_kind` `TS3` (`TS6` on a TeamSpeak 6 server); a uid that is not canonical base64 (a ServerQuery client's login name) leaves `uid` empty and goes into `foreign{system:"teamspeak", kind:"user", json:{"uid"}}` (F10); `name`; `avatar: Image{hash: avatar MD5, url: myTeamSpeak avatar}`; `badges`; `country` | +| `Member` | `roles` = server groups; `channel_roles` = {channel: channel group with bit 62}; `description`; `foreign{system:"teamspeak", kind:"client", json:{"icon"}}` (F6) | +| `Presence` | `status: IDLE` with `text` = away message when away, else `ONLINE` | +| participant id | client id; `VoiceState{nick, channel_id, slot: client id + 1, self_mute, self_deaf, talker, talk_power, priority_speaker, channel_commander, recording, streaming, kind: QUERY for query clients}` | +| message id | per connection: milliseconds since the Unix epoch shifted left by 12 bits, plus a counter in the low 12 bits | +| rev, epoch | one counter per `LinkSession` from 1; the epoch is new per connection | +| `Mail` id | the TeamSpeak offline message id | + +Each inner `Presence` is diffed against the previous one: changed entities +are put, gone ones deleted, one `Change` per scope. A poke or chat message +from someone the snapshot does not hold is preceded by a `Change` that puts a +bare `User` (synthetic id, uid, name) into LIVE: it shows in no presence (no +`VoiceState`) and lets the engine name the sender (follow-up P5). A sender +the link names by its client id only (no unique id) gets the same: a `User` of +the synthetic id of `client:` with the name the link gave and no uid, +replaced when the same client id comes back with another name (the link hands +a client id to whoever connects next). + +### 5.3 The engine's projection: `presence_model` and its fix-ups + +`replica::convert` targets the old model already. Where it says less than +`TsLink` does, SessionLink fixes the result up in one module +(`link/project.rs`), each fix with a follow-up for the protocol repository +(P6, P7). The old model is TeamSpeak-shaped, and these fix-ups apply the +TeamSpeak gateway's id rules of protocol 11.1 so the UI keeps the ids it +has; they go when the UI reads the replica (H7). + +| | Fix-up | Why | +|---|---|---| +| F1 | Leave out channels of kind `SERVER_CHAT`, `DM`, `GROUP_DM`, `THREAD`. | `presence_model` leaves out threads only; the server chat would show as a channel. | +| F2 | On a TeamSpeak backend (`backend.product == "teamspeak"`), clear bit 62 of `RoleScope::CHANNEL` role ids (channel groups, `ClientInfo.channel_group`, `ServerDetails.default_channel_group`). | Today's ids are TeamSpeak's cgids; requests to the gateway and the UI's group lookups use them. | +| F3 | `server_key(uid)`: `Server.uid` without a leading `ts:`; used for `server_uid` and `ServerDetails.uid`. | History rows, aliases and the merge with the gateway and query sources are keyed by today's form. Goes with H5 (and a history key migration). | +| F4 | `ServerDetails.version` from `Server.foreign` (`teamspeak`/`server`, key `version`), else `Welcome.host.backend.version`. | `server_details` leaves it empty by design, and `BackendInfo.version` is the parsed version, not always the string the server sent. | +| F5 | `ServerDetails.platform` from `Server.foreign` (`teamspeak`/`server`, key `platform`). | v1 has no field for the server's OS. | +| F6 | `ClientInfo.icon` from `Member.foreign` (`teamspeak`/`client`, key `icon`). | v1 has no client icon; `client_info` sets 0. | +| F7 | `ChannelInfo.max_clients = Some(0)` from `Channel.foreign` key `max_clients`. | `max_members: 0` means unlimited; a TeamSpeak limit of 0 cannot be said. | +| F8 | `ClientInfo.talking` = `Some(talk tracker)` where the session offers `voice`, else `None`. | Talking comes from media (protocol 6.4); `client_info` sets `None`. | +| F9 | `ClientInfo.streaming = None` where the session lacks `streams`. | `client_info` always gives `Some`; TeamSpeak 3 reports none. | +| F10 | `ClientInfo.uid`, a message author's and a poke sender's uid from `User.foreign` (`teamspeak`/`user`, key `uid`) when `User.uid` is empty. | ServerQuery clients' uids are login names, which `User.uid` (bytes, base64 for TeamSpeak) cannot hold. | + +### 5.4 Normalised fixtures + +A TeamSpeak link never reports some states the FakeLink fixtures use; through +the adapter they come back normalised, so slice 1 changes the fixture +builders, never the assertions (except one, below): + +- sibling channels form an order chain (`GAMES.order = LOBBY`, not both 0); +- every client has a `database_id`, `talking: Some(false)` and the + `channel_group` it would have (`None` stays `None`); +- `presence().server` names the server and its uid as `TsLink` fills them; +- `Talking` is played as a voice packet of the talker (`LinkEvent::Audio`), + because the engine derives it from media; the test still expects + `Event::Talking{client: 8, talking: true}`; +- `commands_reach_the_link` no longer expects the engine's request id (5) + in the inner `ListFiles`: the id the inner link sees is `LinkSession`'s + (v1 request ids belong to the session). This is the one changed + assertion. +- `presence_follows_the_link_until_it_disconnects` is the second changed test + (after the request id, above): it plays the voice packet and waits for + `Talking` before it plays the `Poke` and the `Error`, where the baseline + played `Talking`, `Poke` and `Error` in one go and waited for them in that + order. Its assertions are the baseline's; the steps are reordered because + the media path and the push path have no order between them (section 13), + and the first version of the test relied on one (it failed in 22 of 300 isolated runs on the first implementation; the fixed test, 0 of 300). + +## 6. Media across the seam + +### 6.1 Voice, engine side + +`voelin-audio`'s `EncodedVoice`/`VoicePacket` stay what the audio thread +speaks; SessionLink frames them in the v1 media codec (`voelin_proto::media`). + +Sending (`LinkCmd::Audio`): flow `FlowId::new(slot, voice_sub::CHANNEL)` +(the engine has no whisper or priority voice yet), `RtpHeader::new(PT_OPUS, +seq, timestamp)`, SSRC = flow; `seq` counts every packet from 0; +`timestamp` advances by the previous packet's Opus duration +(`media::opus::packet_ticks`, 960 for 20 ms); marker on the first packet of a +spurt; `EncodedVoice::is_end()` becomes an RTP packet with an empty payload, +sent once (protocol 6.4 sends it twice; the TeamSpeak side would turn that +into two TeamSpeak end packets, so twice waits for H1). `MediaClass::Voice`. + +Receiving (`MediaSink::media`, never blocking: into the loop's queue): a +voice flow is `slot` → our replica's `VoiceState` with that slot → +`TalkerId(participant as u16)`; `sub` 1-6 → `whisper: true`; `seq` = RTP +sequence; `payload` = RTP payload (empty ends the spurt; `VoicePacket::is_end` +also takes one byte); `codec` = `Music` when the Opus TOC has the stereo flag, +else `Voice`. The codec is informational on this path: the jitter buffer +decodes every talker with one stereo decoder (`jitter.rs`), so a frame coded +mono inside a music stream decodes the same. Unknown slots are dropped +(logged once). The talk tracker sees every voice packet. + +### 6.2 Voice, TeamSpeak side + +`LinkSession` re-wraps, never transcodes (protocol 1.2): an inner +`VoicePacket` becomes RTP on the talker's slot (client id + 1), sub 1 for +whispers else 0, `seq` = TeamSpeak packet id, timestamp from the TOC +durations on an unwrapped packet-id counter and wall-clock time across +silences, marker after an end or 250 ms of silence, empty payload for the +end. Sub 7 (priority voice) is not used: the mixer dims by the presence's +`priority_speaker` flag, as today. Uplink: RTP on our slot loses its header +and becomes `EncodedVoice{codec: Music if the TOC is stereo else Voice, +payload}`; the engine encodes `VoiceCodec::Voice` only (`audio.rs`), so +TeamSpeak keeps receiving Opus Voice. Packets of another slot are +`NotOwned`, over `MAX_RTP` `TooLarge`. + +### 6.3 Media classes + +| Class | Used in this half | +|---|---| +| `Voice` | our voice | +| `StreamAudio`, `Video`, `Feedback`, `Probe` | not used: TeamSpeak 6 streams are peer to peer, so no stream media crosses a `Session` (protocol 6.11, 11.1); the SFU path comes with VoelinServer | + +### 6.4 Streams: the port now, v1 later + +`StreamPort` is `{ cmds: UnboundedSender, events: +UnboundedReceiver }`, `StreamEvent` = `OwnStream`, `StreamAudio`, +`StreamAudioEnded`; the stream task's bus events go to the engine's bus, +its frames to the frames bus (both through `LocalCtx`). The watched streams' +video (`StreamFrame`) and audio never cross the `Session` trait in this half. + +The v1 mapping the second half implements (H2), per `StreamCmd` variant: + +| `StreamCmd` | v1 (peer to peer, what TeamSpeak 6 needs) | SFU (VoelinServer, later) | +|---|---|---| +| `Start{setup, auto_accept}` | `Put Stream{kind, title, mode: P2P, access: OPEN if auto_accept else ASK, viewer_limit, audio, bitrate_kbps}`; `accessibility` and `mode` 1 in `Stream.foreign` | `mode: SFU`, `layers` | +| `Stop` | `Delete Stream{id}` | same | +| `Respond{viewer, accept}` | `RespondViewer{stream_id, participant_id, accept, offer}` (offer from the engine's peer) | without offer | +| `Kick{viewer}` | `KickViewer{stream_id, participant_id, reason: KICKED}` | same | +| `Watch{stream_id}` | `Put Viewer{stream_id, participant_id: P, audio, decodes}` | same | +| `Leave{stream_id}` | `Delete Viewer` (own) | same | +| `RequestKeyframe{stream_id}` | inside the WebRTC peer (PLI) | RTCP PLI on `FlowId::FEEDBACK` (`MediaClass::Feedback`) | +| `Undecodable{stream_id}` | renegotiate without the codec (`Signal{stream: offer}`) | `Put Viewer{decodes}` | +| `WatchLayer{stream_id, layer}` | `Signal{stream: layer}` (`x-voelin-layer`) | `Put Viewer{max_layer}` | +| `Layers(specs)` | `Put Stream{layers}` and the local encoders | same | +| `LayerFormat{layer, format}` | local (encoder to peer) | local | +| `SrtpProfiles(names)` | local (peer configuration) | n/a | +| `Frame(frame)`, `VideoFrame(frame, format)` | local (the peer sends them) | `send_media(Video, RTP on the stream slot, sub = layer)` | +| `Friends(clients)` | local (`stream.permissions` decides who is admitted) | `access: FRIENDS` on the host | +| `Directory(streams)` | the gateway daemon's session (protocol 11.2) | n/a | +| `Shutdown(reason)` | local (peer teardown), then `close` | same | + +And back: `OwnStream` ← our `Stream` in LIVE (put, viewer count, delete); +`StreamAudio` ← the peer (SFU: stream slot sub 4, `MediaClass::StreamAudio`); +`StreamAudioEnded` ← the stream or our `Viewer` deleted; the bus events +`StreamsChanged`, `StreamViewers`, `StreamViewerRequest` (a `Viewer` in state +`PENDING`), `WatchState` ← `Stream` and `Viewer` entities; `StreamLayerBitrate` +← the peer's estimate (SFU: `Signal{layer_target}`). + +## 7. Identity and credentials + +- **TeamSpeak identities** go as `Credential::Foreign{kind: "teamspeak", + blob}`, `blob` = the JSON of the `KIND_TEAMSPEAK` `IdentityBlob` of the + KeyStore (`voelin-store` keeps tsproto's `Identity` JSON verbatim). + `TsConnector` parses it back into the `tsclientlib::Identity` it connects + with. No identity in the options (`voelinctl` without `--identity`) is an + empty blob, and the connector generates one as `tsclientlib` does today + (follow-up P11 writes the convention down). +- **The Voelin key** goes as `Credential::Voelin(Arc)`: a + `KIND_VOELIN` blob's `voelin_key()` (`IdentityKey` implements `Signer`), or + a `FileSigner`. Nothing uses it in this half (no `voelin://` connector), but + the conversion is there and tested. +- **The account** is a hook: `ConnectParams.account` is `None` and + `issuer_trust` `Unknown`. `Backends` gets an + `Option>` slot, set by nobody yet. A blob whose + binding has custody SERVICE (no local secret) would be + `Credential::Account{kind: "teamspeak", integration_id}`; without an agent + the connector fails the connect (its contract in `ConnectParams`), and the + engine reports that as `Disconnected`. No such blob reaches the engine + yet. myTeamSpeak keeps going through `TsConnector`'s + watches (4.8) until it moves to `AccountAgent::use_integration` + (`myteamspeak.handshake`, protocol 13.8; H4). +- **Host trust**: `TsConnector` ignores `trust` and `host_pin` (no TLS). The + engine passes a `HostTrust` that refuses until the UI has a TOFU dialog. +- **Slice 1 keeps the API**: `VoiceOptions.identity` is still a + `tsclientlib::Identity`; one function in the TeamSpeak module turns it into + the `Credential`. Slice 3 makes it an `IdentityBlob` (section 10). + +## 8. Files + +The engine owns transfers end to end: progress (`files.progress_ms`), the +`.part` file and its rename, cancel, resume, the picture limits. The +TeamSpeak side only opens the transfer connection, through two inner +commands added to `LinkCmd` in slice 1: + +- `OpenRead{file: Remote, offset, reply: oneshot>}`: + `download_file`, then the `FileDownload` stream and its size go to `reply` + instead of into `files::download`; `FiletransferFailed` → `Err` with the + text `transfer_error` writes today. +- `OpenWrite{file, size, overwrite, resume, reply: oneshot>}`: + `upload_file`, then the `FileUpload` stream and its `seek_position`. + +`files::download` and `files::upload` take `AsyncRead`/`AsyncWrite` instead +of `TcpStream` (their tests keep using TCP). The old `Download`, `Upload` and +`CancelTransfer` handling in `voice.rs` is dead for `LinkSession` from +slice 1 (it never sends them inward) and is deleted in slice 3. Avatars and +icons keep their channel-0 paths (`/avatar_`, `/icon_`) as +`FilePath` reads; v1 has them as attachments (H6). + +## 9. Tests + +### 9.1 `tests/link_fake.rs` through the adapter (slice 1) + +`Engine::start_with_link(FakeLink)` now wraps the link in `LinkSession` and +drives it through SessionLink, so all seven tests run both translations: + +| Test | What it proves through the adapter | +|---|---| +| `presence_follows_the_link_until_it_disconnects` | connect sequence and event order, presence round trip, poke, talking from media, notice → `Error`, `Disconnected(Some)` | +| `commands_reach_the_link` | `SendChat`, `Move`, `SetInputMuted`, `Poke`, `ListFiles` survive both translations; no streams without the capability; stream commands through `StreamPort`; replaced link gets `Disconnect` | +| `a_reconnect_shuts_the_streams_down_before_the_old_connection` | `StreamPort` and `close` share one ordered queue | +| `a_sent_message_and_its_echo_are_one_message` | our message's `Change` is today's echo | +| `a_message_that_comes_twice_is_shown_once` | four `Change`s, `RELAYED` flag, dedup in `session.rs` | +| `history_is_kept_across_the_connection` | DM channel in HOME, late CHAT subscription, `Private(uid)` target | +| `a_replaced_connection_is_ignored` | generation filter with a link that keeps talking after `Disconnect` | + +### 9.2 FakeSession and FakeHost (slice 2) + +New `tests/session_fake.rs`: `Engine::start_with_backends` with a +`FakeConnector` (scheme `fake`) registered, `VoiceOptions::new("fake://host", +...)`, the `FakeHost` filled with `Server`, VOICE `Channel`s, `Role`s, +`User`s, `Member`s and `VoiceState`s through `FakeHost::put` (it stores what +a client cannot set, such as authors), `FakeHandle` for pushes, media, +scripts, held requests and kills. `voelin-proto` with `test-util` is a +dev-dependency of `voelin-core`. + +| link_fake test | FakeSession version | +|---|---| +| `presence_follows_the_link_until_it_disconnects` | host state + `JoinVoice` (the fake assigns `P` and `slot`); `Welcome.host.backend` set with `FakeHost::set_welcome`; poke as `FakeHandle::push(Signal{poke})`; talking by `inject_media` on alice's slot; `Signal{notice}` → `Error`; `kill(Network("server shut down"))` → `"voice: server shut down"`. | +| `commands_reach_the_link` | `FakeHandle::requests()` shows `Put{Message}`, `JoinVoice{password}`, the `notify` (id 0) of `self_mute`, `Signal{poke}` (the fake answers signals `Ack`), and `List{FILE}` (the fake refuses `List.path`: scripted with `Script::answer("list", ...)`). The stream half stays a link test (below). | +| `a_reconnect_shuts_the_streams_down_before_the_old_connection` | stays a link test: it checks the `StreamPort` ordering, which a `FakeSession` has no part in (until H2). | +| `a_sent_message_and_its_echo_are_one_message` | the fake stores our `Put` and pushes its `Change` to CHAT(our channel). | +| `a_message_that_comes_twice_is_shown_once` | four `FakeHost::put(Message)`, one with `MESSAGE_FLAG_RELAYED`. | +| `history_is_kept_across_the_connection` | a DM `Channel{server_id: 0}` (HOME) and its messages; `close` and reopen. | +| `a_replaced_connection_is_ignored` | stays a link test: a closed `FakeSession` stops pushing, so the stale events cannot be produced on purpose. | + +New tests the v1 path needs: a connect that fails (`FakeConnector::fail_next`) +→ `Disconnected(Some(text))`; CHAT re-subscription after moving back is a +delta (`sync.delta`); `ScopeClosed` of CHAT and of LIVE; `Rejected` answers +→ `RequestDone`/`Error` texts; our voice in `FakeHandle::sent_media()` (PT +111, SSRC = flow, marker, empty end, sequence); download and upload against +the fake's channel files, resume offset from a scripted `List`; offline +messages through scripted `Mail` answers (the fake does not store `Mail`); +`HostUpdate` changing the refused features; the conformance suite run +against a `FakeSession` reached through `Backends` (17 cases, a check that +the registry hands the session over untouched). + +The link tests that stay (`a_reconnect_shuts_the_streams_down...`, the stream +half of `commands_reach_the_link`, `a_replaced_connection_is_ignored`) remain +in `tests/link_fake.rs` in slice 2 and move into the crate in slice 3, when +`ServerLink` is no longer public. + +This table and the list above it are the design; section 16.4 lists where the +running code differs (the CHAT re-subscription is a full sync, not a delta; a +reconnect resumes nothing; the conformance run and the live TeamSpeak tests are +in-crate tests, not files of `tests/`). + +### 9.3 The conformance suite against the TeamSpeak `Session` + +`conformance::run_case` with a harness that opens a `LinkSession` +through `TsConnector` on the dev servers (`VOELIN_LIVE=1`, TeamSpeak 3 and 6 +of `dev/docker-compose.yml`). The suite's `Fixture` needs a `FakeHandle` of +the backend; the TeamSpeak server has none, so the harness passes the handle +of an unrelated `FakeHost` and runs only the cases that never touch it: + +| Case | Expected | Why | +|---|---|---| +| `welcome_matches_features` | passes | session only | +| `close_ends_the_session` | passes | session only | +| `a_stale_rev_conflicts_and_a_patch_writes_only_its_paths` | skipped | no `chat.edit` | +| `requests_apply_in_the_order_they_were_issued` | skipped | no `chat.edit` | +| `list_pages_history` | skipped | no `chat.history` (the embedded gateway keeps no history) | +| `idempotency_keys_apply_a_put_once` | skipped | no `idempotency` | +| `subscribe_syncs_the_scope` | cannot pass | writes to channel 4001, which the server lacks; TeamSpeak channel chat reaches only the own channel | +| `subscribe_resumes_from_a_cursor` | cannot pass | same (4002) | +| `put_answers_entities_and_pushes_the_change_with_the_same_rev` | cannot pass | same (4003) | +| `delete_answers_an_ack_and_pushes_the_removal` | cannot pass | TeamSpeak cannot delete a message; the case needs only `chat` instead of `chat.delete`, so it fails instead of skipping (P8) | +| `a_key_names_an_entity_without_its_server` | cannot pass | needs nothing, but creates `ScheduledEvent` and `Emoji`, which TeamSpeak lacks (P8) | +| `cancel_before_apply_is_cancelled` | cannot run | holds the backend (`FakeHandle::hold`) | +| `notifications_are_fire_and_forget` | cannot run | reads the backend's request log; typing goes to channel 1 | +| `renew_account_follows_the_feature` | cannot run | changes the backend's features by `FakeHandle::push` | +| `media_loops_back` | cannot pass | a TeamSpeak server does not return a client's own voice | +| `files_round_trip` | cannot pass | writes an `AttachmentSlot`; TeamSpeak has channel files, no message attachments; the case needs `files` instead of `chat.attachments` (P8) | +| `the_backend_can_end_the_session` | cannot run | `FakeHandle::kill`; and `LinkSession` reports a kick as `Network(text)`, not `Remote{KICKED}`, until H1 | + +What the suite cannot reach is covered by TeamSpeak session tests of their +own (live, both servers): an own-channel `Put Message` answered, then +pushed to the other session's CHAT scope and back to ours as a `Change` (ids +agree only with H1's native session); `JoinVoice` refusal codes +(`PASSWORD`, `FULL`); a poke `Signal` between two sessions; voice RTP from +one session's slot reaching the other's `MediaSink` (sequence, marker, end); +a channel file written with `write_file` and read back from an offset with +`read_file`. + +The table above is the prediction. Section 16.2 has the verdicts the run +gave, on both servers, and what the run found on the way: the first version +of the harness ended its sessions by itself (16.5, F2), which made +`close_ends_the_session` pass for the wrong reason, and the reasons of the +cases that do not apply are what those cases did when they were run. + +## 10. Slices + +Every slice: `cargo fmt --all --check`; `cargo clippy $(scripts/own-crates.sh) +--all-targets --no-deps --locked -- -D warnings`; `cargo test -p voelin-core +--locked` (also `--features media`), the tests of every crate the slice +touches; `cargo check --workspace --locked`; `cargo deny --locked check`; +`scripts/notices.sh` with `THIRD_PARTY_NOTICES.md` regenerated whenever +`Cargo.lock` changes; docs on new public items; the live tests and +`scripts/it-smoke.sh` engine scenarios against the TeamSpeak dev servers +(this repository's `dev/docker-compose.yml`, the same as VoelinGateWay's) +with the results compared to the baseline. One commit per step is fine; no +history rewrite. + +### Slice 0 (precondition): baseline + +On `main` (`59fec5b`), before any code: `VOELIN_LIVE=1 cargo test -p +voelin-core --features media-desktop --test live --test voice_features +--test stream_live --test media_live`, and `scripts/it-smoke.sh ts3 ts6`. +Record which pass, which fail and why: the plan notes they have not run +since Phase 4 step 1, and slice 1's "no behaviour change" is measured +against this record, not against an assumption. + +### Slice 1: the adapter + +1. **Protocol crates at one revision.** `voelin-identity`, `voelin-proto` + and `voelin-model` from VoelinProtocol at one rev (main `c8e0e5a` or + later: it has `AccountAgent`, `IssuerTrust`, `Credential::Account`; + `voelin-identity` changed only in `cert.rs` and `revocation.rs` since + `64808cc`). `crates/voelin-model` is removed and every crate that used it + takes `voelin-model = { workspace = true }` (`voelin-core`, `-ui`, + `-gateway`, `-gateway-proto`, `-observer`, `-android`, `voelinctl`: a + one-line manifest change each, the UI's being a compile fix); the + `[patch]` recipe of `docs/building.md` gains `voelin-model`. + Acceptance: whole workspace builds, all tests green, no source change + besides manifests. Of the model crate's files only `lib.rs` (two more + modules, `perms` and `replica`) and `badges.rs`, `link.rs`, `tree.rs` + (a doc comment and two equivalent expressions) differ. +2. **The seam.** `link/` (Backends, SessionLink, project, media), + `ts_session.rs` (LinkSession, TsConnector, `LinkConnector` for + `start_with_link`), `OpenRead`/`OpenWrite` in `voice.rs`, `files.rs` + generic, `Engine::start_with_backends`. + Acceptance: + - `git diff main -- crates/voelin-core/src/session.rs` is empty; + - the seven tests of `tests/link_fake.rs` pass through the adapter with + only the fixture changes of 5.4; + - unit tests: the presence round trip of 5.1 (book fixtures and generated + presences), `LinkCmd` → v1 → inner `LinkCmd` for every row of + table 3.1 with a recording link, v1 media framing both ways (sequence, + marker, end, whisper, TOC codec), talk tracker timing (400 ms), the close + table of 4.5, the error texts of 4.6, the backend and capability tables + of 4.7; + - live tests and smoke scenarios: no result worse than the baseline + (section 0), in particular `engine_voice_check` (files, avatar, poke, + private and offline messages, friend online, blocked poke), voice + round trip, the TeamSpeak 6 stream scenarios; + - `rg -n 'tsclientlib|tsproto|voelin_query'` over the new + Session-facing modules (`link/backends.rs`, `link/session_link.rs`, + `link/project.rs`, `link/media.rs`) is empty; TeamSpeak types appear + only in `ts_session.rs` and the files that had them before + (`link/mod.rs` keeps `ConnectOptions` and `LinkCtx` until slice 3). + No public item is removed in this slice. + +### Slice 2: tests on FakeSession and FakeHost + +Implemented; section 16 says how, what it found, and what ran. + +- `tests/session_fake.rs` as in 9.2, the conformance run through `Backends` + (17 of 17), the live TeamSpeak conformance subset of 9.3 with the expected + verdicts asserted per case (2 pass, 4 skipped, the rest not run, each with + the reason of the table in a comment), and the TeamSpeak session tests of + 9.3. +- `tests/link_fake.rs` keeps only the three link tests named in 9.2. +- Acceptance: all of it green on both dev servers; a deliberately broken + translation (for instance a dropped `self_mute` path) makes a + `session_fake` test fail, shown once in the report. + +### Slice 3: the `ServerLink` layer where it is redundant; TeamSpeak types out of the API + +Implemented; section 17 says how, what differs from this list, and what ran. + +- `ServerLink`, `TsLink`, `Engine::start_with_link`, `LinkCtx`, `LinkCmd`, + `LinkEvent` and `Remote` are no longer public (the engine keeps `LinkCmd` + and `LinkEvent` as `session.rs`'s private vocabulary; the TeamSpeak module + keeps the inner trait). The remaining link tests become unit tests in the + crate. +- `src/ts/` holds the TeamSpeak implementation: `ts_link.rs`, `voice.rs`, + `book.rs`, `ts_session.rs`, `versions.rs`, `identity.rs` (moved with + history). Public as `voelin_core::ts`: `TsConnector` (with + `set_myts_identity` and `set_myts_data`), `versions`, `identity`. This + module is what moves to VoelinGateWay. +- `VoiceOptions` (no longer an alias of `ConnectOptions`): `identity: + Option`, `client_version: Option` (a spec for + `ts::versions::resolve`, passed to `TsConnector` as the link parameter + `client_version`; `Link::parse` ignores unknown keys), `stream_peer: + PeerConfig`, the rest unchanged. +- `Command::SetMytsIdentity` and `SetMytsData` removed (nothing sends them; + `TsConnector`'s setters replace them). `ObserveGateway.identity` becomes a + `Box` (`gateway.rs` parses it); `ObserveQuery.connect` + becomes a core-owned `QueryLogin` (transport, address, user, secret, + server port, server id) that `query.rs` turns into `voelin_query::Connect`. + The public `gateway::connect(url, identity)` takes the blob too (nothing + outside the crate calls it today). +- `voice.rs` loses `Download`, `Upload`, `CancelTransfer`; the picture limits + live in SessionLink only. +- `docs/architecture.md`: "The server link" becomes "The session seam" + (registry, SessionLink, the TeamSpeak module, `StreamPort`, the fix-ups of + 5.3, what is still TeamSpeak-shaped: `u16` client ids and the old model); + the crate table row of `voelin-core` follows; this document's status line. +- `CHANGELOG.md`: it lists user-visible changes only. An entry under + "Changed" only if a difference against the baseline remains visible (none + is intended); the reviewer confirms none was needed. +- UI and `voelinctl`: compile fixes only (identity blob instead of + `tsclientlib::Identity`, the spec string for `client_version`, + `voelin_core::ts::{versions, identity}` paths, `QueryLogin`). +- Acceptance: + - `rg -n 'tsclientlib|tsproto|voelin_query' crates/voelin-core/src --glob + '!**/ts/**' --glob '!gateway.rs' --glob '!query.rs' --glob '!stream.rs'` + from the repository root (from `crates/voelin-core/src` the first glob is + `'!ts/**'`: a glob is relative to the directory `rg` runs in) is + empty, and the four exceptions use them privately: `gateway.rs` and + `query.rs` are the two observer sources (H5), `stream.rs` is the + TeamSpeak 6 stream task behind `StreamPort` (H2, H3); + - `session.rs` names no TeamSpeak crate; + - no public item outside `voelin_core::ts` names a type of + `tsclientlib`, `tsproto*` or `voelin-query` (checked with `cargo doc` + and a grep of `pub` items); `voelin_core::stream` still re-exports the + WebRTC peer types of `voelin-stream` (`PeerConfig`, `MediaFrame`, + `MediaKind`, `MediaTime`, `Frequency`, `VideoFormat`, `VideoCodec`, + `Codec`, `FrameSource`, `SyntheticSource`): they belong to the peer, + which protocol 6.11 and 11.1 keep in the client, and land in a crate of + their own when `voelin-stream` is split (H3); + - `cargo tree -p voelin-core -e normal | grep -E 'tsclientlib|tsproto'` + may still list them (the TeamSpeak module is still in the crate); + - all of slice 1's and slice 2's checks, live tests and smoke included. + +## 11. Follow-ups + +### 11.1 For the protocol repository (seam, schema, model, suite) + +Nothing here blocks this half: each has a workaround above. + +| # | What | Workaround meanwhile | +|---|---|---| +| P1 | `Hello` has no initial voice channel (path or id, password) for backends that seat a client at connect; a Voelin host could also take it to save the `JoinVoice` round trip. | `ts3server://` link parameters `channel`/`cid`, `channelpassword` (4.2). | +| P2 | Write down that the first `JoinVoice` of a session that its backend seated at connect answers the seat without moving (11.1). | `LinkSession` does it. | +| P3 | A host with several servers: the address (or `Welcome`) should name the one to use. | `List{SERVER}`, the only or lowest one. | +| P4 | `write_file` should answer the offset the backend appends at (`Upload.offset`), so a resume needs no `List`. | `List{FILE}` before a resumed upload; `CONFLICT` on a mismatch. | +| P5 | No sender name or uid for a `Signal` (poke) or message author outside the receiver's view (hidden ServerQuery clients). | A bare `User` with a synthetic id before the signal (5.2). | +| P6 | Schema gaps of TeamSpeak presence: a client icon, a channel limit of 0, the server's platform and version string as sent, a uid that is no byte string (ServerQuery login names). | `Foreign` keys `icon`, `max_clients`, `platform`, `version`, `uid` (F4-F7, F10). | +| P7 | `replica::convert`: SERVER_CHAT and DM channels in `presence_model`; the per-server TeamSpeak avatar read from `User.avatar` instead of `Member.avatar`; `streaming: Some(false)` without the feature; empty `version`; channel role ids not given back; client icon 0; `talking` always `None`. | Fix-ups F1-F10. | +| P8 | Conformance suite: a backend driver trait (hold, release, kill, push, request log) instead of `FakeHandle`, so backend-driven cases run on any backend; chat channel and server chosen by the harness instead of 4001-4020; `needs` fixed (`chat.delete` for the delete case; events and emoji for `a_key_names_...`; `chat.attachments` or a `FilePath` variant for `files_round_trip`); a two-session `media_loops_back` for backends that do not loop back. | The subset of 9.3 and TeamSpeak tests of our own. | +| P9 | `FakeHost` files no `Server` stub or own `Member` in HOME (protocol 5.2). | `List{SERVER}` (4.2). | +| P10 | ServerQuery capabilities (raw, SSH, HTTP) have no feature string. | From the flavor (4.7); they leave with the observer (H5). | +| P11 | Protocol 11.1 could name `Hello.invite_code` ↔ `client_default_token` (privilege keys), and section 13.8 the empty `Credential::Foreign` blob as "generate an identity". | Done that way here. | + +### 11.2 The second half (TeamSpeak `Session` to VoelinGateWay) + +| # | What | +|---|---| +| H1 | A native TeamSpeak `Session` replaces `LinkSession`: `voice.rs` speaks v1 (book → entities without the old model, notifications → `Change`s), real answers for chat and pokes (read-your-writes, errors on the request), a kick as `Remote{KICKED}`, `tsclientlib`'s own reconnect as a new epoch and a full resync, ping and loss in `LinkStats`, whispers (sub 1-6), priority voice (sub 7), typing, the end of a spurt sent twice collapsed to one TeamSpeak packet, every TeamSpeak feature of protocol 9.1. | +| H2 | Streams on v1: the stream task's WebRTC peer moves to the engine and speaks `Stream`/`Viewer`/`RespondViewer`/`KickViewer`/`Signal{stream}` (table 6.4); the TeamSpeak session translates TeamSpeak 6's stream commands (`setupstream`, `joinstreamrequest`, `respondjoinstreamrequest`, `removeclientfromstream`, `streamsignaling`, the notifications); `StreamPort` and `LocalConnector`'s stream part go. | +| H3 | `voelin-stream` split rather than inverted: the TeamSpeak 6 signalling (commands, notifications, signal JSON) goes to VoelinGateWay with the TeamSpeak session; the str0m peer with `PeerConfig`, `MediaFrame`, `VideoFormat`, codecs and simulcast stays client side (with `voelin-media`, or a crate of its own), because protocol 6.11 and 11.1 put the peer in the client. Then nothing in VoelinGateWay depends on `voelin-media`, and the cycle the plan worries about cannot form. | +| H4 | myTeamSpeak through `AccountAgent` (`myteamspeak.handshake` with the 32-byte digest, the presentation, sign-out clearing, protocol 13.8) instead of `TsConnector`'s watches; `Credential::Account` for custody SERVICE identities. | +| H5 | The gateway (`tsgw`) and query sources become a second `Session` to a gateway daemon (protocol 11.2); then F3's `ts:` rule (with a history key migration) and the query capabilities go. | +| H6 | Avatars and icons as attachments (`Image.attachment_id`, content-addressed cache) instead of channel-0 paths. | +| H7 | The UI on the replica (Phase 5): the old-model projection and F1-F10 go; `u16` client ids widen to `u32` participants. | +| H8 | Reconnect with backoff, resume tokens and persisted cursors move to `voelin-sdk` once it exists; the engine consumes the SDK. | +| H9 | Move `src/ts/` (with its live tests) to `voelin-gateway-ts` (features `basic`, `streams`), first behind a `ts` feature of `voelin-core`, then by git tag; the exit check of plan step 6, `cargo tree -p voelin-core -e normal \| grep -E 'tsclientlib\|tsproto'` empty, holds after H1-H3 and this. Two edges run from the engine into `src/ts/` and have to be cut first: `Backends::default` registers `ts::TsConnector` (the `ts` feature makes it optional), and `link/project.rs` and `link/session_link.rs` import `ts::ts_session::{entities::user_uid, ids}`, the id and uid rule that the projection undoes the synthetic ids with (it moves to the engine side, or into `voelin-model`'s replica conversion, which already has `uid_text`). | + +### 11.3 Coordination + +- `phase5/ui-vm` adds `crates/voelin-ui-vm` and moves UI logic (servers, + settings) into it. Slice 1's model switch needs its manifest on + `voelin-model.workspace = true`; slice 3's API changes (identity blob, + `client_version` spec, `ts::` paths, `QueryLogin`) need compile fixes where + that branch moved `VoiceOptions` and `ObserveQuery` construction. Merge + `phase5/ui-vm` before slice 3, or plan the fixes on top of it. +- Branches that still edit `crates/voelin-model` must make those changes in + VoelinProtocol after slice 1. + +## 12. Risks + +| Risk | Mitigation | +|---|---| +| A presence field gets lost between the two translations (a UI detail disappears). | Round-trip tests on the book fixtures and generated presences; F1-F10 listed; live smoke against the baseline. | +| Event timing changes: `Connected` now follows three syncs and a `JoinVoice`; snapshots are coalesced. | All in process for TeamSpeak (microseconds); the FakeLink tests pin the order; `session.rs` is unchanged. | +| The inner bus of `LinkSession` lags and a request never gets its answer. | Capacity 4096, a timeout on every pending request, lag logged. | +| The consumer of the push channel lags and stalls the voice and the commands that share the task. | The task never waits on the channel: what does not fit is dropped and the scope is sent again whole when there is room (14). | +| A uid that round-trips through `User.uid` on one side and through `Foreign` on the other (F10) would key contacts and private history differently. | Both sides use one rule (canonical base64 → bytes, anything else → `Foreign`), asserted by the round-trip test on TeamSpeak 3 and 6 uids, ServerQuery login names and the FakeLink fixtures' `alice=`; checked live (contacts and private history keyed by uid). | +| The model crate switch collides with other branches. | 11.3; the switch is manifest-only. | +| Two adapters cost CPU per voice packet (RTP wrap and unwrap in process). | About a hundred bytes copied per 20 ms per talker; measured in slice 1 by a unit test (`a_voice_packet_costs_microseconds_through_both_adapters`, section 13). | + +## 13. Slice 1 as implemented + +Slice 1 (the adapter, section 10) is in `phase4/session-seam`: step 1 is the +commit that takes `voelin-model` from the protocol repository, step 2 the +commit that puts the engine on the `Session`. `session.rs` is unchanged +(`git diff 59fec5b -- crates/voelin-core/src/session.rs` is empty), and no +public item was removed. Where the code differs from the text above: + +- **Files.** `ts_session` is a directory (`mod.rs` with `LinkConnector`, + `TsConnector`, `connect_params` and the `Session` impl; `driver.rs`, the + task that plays the host; `entities.rs`, the presence as v1 entities and + its diff; `ids.rs`; `media.rs`, voice as RTP and back). The unit tests of + the mapping are `link/tests.rs`; the presence round trip is in `book.rs`, + next to the book fixtures. `bytes` is a direct dependency now (the RTP + packets of `MediaPacket`). +- **`LinkSession` is not generic.** It holds the inner link as an + `Arc`; `LinkConnector::new(link, schemes)` and + `LinkConnector::any(link)` are the generic part, and `TsConnector` is a + `LinkConnector` over `TsLink` for `ts3server` and `teamspeak`. +- **The account-proof watches** (`myts_identity`, `myts_data`) travel in + `LocalCtx`, from the engine's `LinkCtx` to the connection, not in + `TsConnector` (section 4.8): `Engine::start_with_backends` takes a + registry that is made before the engine exists, so the watches cannot be + handed to a connector in it. `LocalCtx::standalone()` makes a context + (with the watches' senders kept alive) for a connector called outside an + engine; the plain `Connector::connect` of `LinkConnector` uses it. +- **`OpenWrite` hands a connection, not a write half** (`BoxDuplex`): the + upload's `done` has to see the server close it. `UploadBody` reports the + shutdown of the body to `done`, which then waits for the end of the + connection (30 s at most), as `files::upload` always did. +- **Media and pushes have no order between them.** `Talking` and `Audio` come + from the media queue (a `MediaSink` that never blocks), `Poke`, `Chat`, + `Error` and `Presence` from the push channel, and the loop of SessionLink + cannot order two channels: it polls the media queue before the pushes (the + design text had the reverse), which makes a talker's packet reach the + engine early when both are there, and that is all it does. `Talking` and + `Audio` therefore have no defined order relative to `Poke`, `Chat`, `Error` + and `Presence`, and the engine and its tests must not depend on one. (A + packet from a slot the replica does not know yet fetches the queued pushes + first and tries again, so a talker's first packet is not lost either way.) + The first version of the fake-link test of presence played `Audio`, `Poke` + and `Error` in one go and waited for `Talking`, the poke and the error in + that order; it failed in 22 of 300 isolated runs, whenever the pushes were + polled first. It waits for `Talking` before it plays the rest now (5.4). +- **The stream task's reports wait for the engine's announcement.** The + TeamSpeak 6 stream task puts `Event::StreamsChanged` and the like on the + engine's bus itself. Behind a session the engine learns of the connection + only after the connect sequence (a few requests through the driver), while + the stream task lists the server's streams as soon as the server tells it; + a client that acts on the first list (`voelinctl gateway --engine + --watch-streamer`, the `directory_check` of `scripts/it-smoke.sh`) sent + `WatchStream` before the engine knew it had voice, and failed with `not + connected with voice` in half of the runs (3 of 6; the baseline binary + passed all 4 runs the server's clone limit did not end first, the two + alternating on one TeamSpeak 6 server). The + driver of `ts_session` therefore holds the stream task's bus events back + (`Held` in `ts_session/driver.rs`; only for a link with streams, and only + the events that are no answer to a request) until the engine's first + stream command, which `session.rs` sends in its handling of `Connected` + right after it has emitted the state, or for 3 seconds. Three unit tests + pin it (`link/tests.rs`: held until the first stream command, not held for + ever, not held for a link without streams); the same probe passes 8 of 8 + with it. +- **CHAT scopes are re-subscribed in full.** The replica drops a scope's + cursor and entities when it is unsubscribed and refuses a delta sync + without a baseline, so SessionLink does not keep cursors for a delta + after moving back (section 4.3); the full sync repeats the window and the + engine's `seen` set reports each `(channel, id)` once. `LinkSession` does + answer `Subscribe.since` of its own epoch with a delta. +- **Fixtures** (section 5.4), beyond the builders listed there: + `presence()` gives the own client the unique id the `Connected` event names + and the server the version of the backend; in + `a_replaced_connection_is_ignored` the new connection's presence puts the + own client in the lobby, where its `OwnChannel` and its channel chat are + (a TeamSpeak server delivers channel chat for the channel we are in only, + section 4.3). In the book round trip a TeamSpeak 6 client with no + streaming flag in the book comes back as `Some(false)` (v1 has no + "unknown"). +- **Known limits.** Two clients with one identity (one database id) are two + users of the replica (the own client keeps the database id, else the lower + client id; the other gets a user id made of its client id). A `Put Message` before any snapshot is handed to the link + whatever the channel. `Welcome.limits` is partly filled. `Backends` has a + slot for an `AccountAgent` and for a `HostTrust` (refusing by default); + nothing sets either yet. + +Follow-ups for the protocol repository, found while writing the code: + +- **P12.** `FileEntry.from_path` should say whether it includes the file's + name. The TeamSpeak side reads it as the whole old path (`/dir/name`), + with `path` and `name` of the entry the new place. +- **P13.** `Signal{speaking}` is for talking in channels the user is not in + (protocol 5.6, 6.4). A host that hears a talker in our own channel and + does not carry the voice as media (TeamSpeak's Speex and CELT talkers) has + no way to say so but that signal, which `LinkSession` uses for them + (SessionLink believes it until `on: false`). The protocol should say that + the signal may do this, or give such a talker a flag on the `VoiceState`. +- **P14.** Say what a backend that reconnects inside a session (TeamSpeak's + `tsclientlib`) tells its consumer: today the participant id of the session + changes without a word, and a consumer has to find itself again by its + user. A `Change` that puts the new `VoiceState` and deletes the old one is + all there is; the native session of H1 starts a new epoch instead. + +What ran against the baseline (main `59fec5b`; the dev servers of +`dev/docker-compose.yml` as the compose project `voelin-seam`, TeamSpeak +3.13.8 and 6.0.0-beta13.1): + +| Check | Baseline | Adapter | +|---|---|---| +| `scripts/it-smoke.sh ts3 ts6`, every per-server scenario (connect and tree, server and channel chat, voice tone, invisible presence, relay chat, gateway, history, pins and reactions, streams and late and elsewhere streams on TS6, the engine's voice features: file upload, link, list, download and delete; avatar; poke; private and offline messages; friend; blocked poke) | all pass | all pass, the same output apart from counters and ids (the run before the fix of the stream reports, above, failed `directory_check`) | +| the script's last stage, `cargo test -p voelin-core --features media-desktop --test live --test stream_live --test media_live` (parallel) | 5 pass, `ts6_banners` fails (4 HTTP requests where 0 are expected: another test's engine shares the mock server) | the same | +| `live` (serial, `--test-threads=1`) | 6 of 6 | 6 of 6 | +| `voice_features`, `stream_live`, `media_live` (serial) | 3, 3, 2 pass | 3, 3, 2 pass | + +`cargo test -p voelin-core` has two failures that exist on the baseline too +(`discover::tests::without_records_the_gateway_itself_is_asked`, +`web::tests::pictures_go_through_the_proxy_named_for_each_hop`: both reach a +server bound to `127.0.0.1` through the name `localhost`, which resolves to +`::1` only on the machine the tests ran on; the modules are unchanged). + +The CPU cost of the second adapter per voice packet (section 12) is measured +by the unit test `a_voice_packet_costs_microseconds_through_both_adapters` +(`link/tests.rs`): 5,000 Opus packets of 20 ms each way through both +adapters and the recording link, in a debug build, took about 7 microseconds +per packet to the host and 10 microseconds from it. At one talker that is +well under a tenth of a percent of a core; the test bounds each direction at +500 microseconds. `tests/session_backends.rs` adds two integration tests: +the engine over the protocol repository's `FakeConnector` through +`Engine::start_with_backends` (connect, the server's name, the channels, a +move, disconnect), and the registry's error text for an address no connector +serves. + +## 14. Review round 2 of slice 1 + +The review of the first implementation found eight defects; each is fixed in +its own place above and tested. + +| Finding | Fix | Test | +|---|---|---| +| Chat messages of a CHAT scope's initial full sync were lost when `SyncBegin` and `Change` were in one batch and `SyncEnd` in the next: `(channel, id)` was marked as reported before the replica could show the message. | A message is marked as reported only when it was shown; at the `SyncEnd` of a CHAT scope the messages of that channel not shown yet are (4.3). | `the_messages_of_a_chat_sync_are_reported_when_the_sync_ends`, `a_message_that_comes_before_its_scope_is_reported_with_the_sync` (`link/session_link.rs`) | +| The own client id was pinned for the connection: after `tsclientlib`'s reconnect (a new client id) `OwnChannel` and the own channel's chat stopped. | Both sides find us again by our unique id and user (4.4); the own client keeps the database id of an identity that is there twice. | `the_engine_follows_a_reconnect_that_makes_us_another_client`, `we_stay_the_client_we_were_while_it_is_there`, `the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice` | +| CHAT subscriptions were capped at 16 in process: the 15th private peer's messages were never delivered. | `LinkSession` says 65,536; SessionLink sizes its scopes from `Welcome.limits` (16 only when the host says nothing), server chat and own channel first, newest private conversations next (4.3). | `private_messages_from_more_than_16_peers_all_arrive`, the limits in `the_welcome_names_the_host_the_user_and_what_the_link_can_do` | +| `LinkSession::notify` accepted `List`, `FileRead` and `FileWrite` and ignored them. | A misplaced op is a `Protocol` error; any other op of the control stream is run (3.1). | `a_notify_needs_the_control_stream_and_is_run_as_the_request_it_is` | +| A push channel that ended during the connect syncs threw the session's close reason away. | The reason of `closed()` is the reason of `Disconnected` (4.2). | `a_session_that_ends_during_the_connect_syncs_says_why` | +| `LinkSession` awaited `pushes.send()`: a lagging consumer stalled voice and commands. | Nothing in the task waits: a push that finds the channel full is dropped, the scope is marked as lagged and sent again whole (`SyncBegin`..`SyncEnd`, all or none) when the channel has room, as `ConnectParams.push_capacity` documents; a scope bigger than the channel is sent in bigger chunks, so that it fits an empty channel. Signals have no scope: they are dropped. | `a_consumer_that_lags_loses_the_queue_and_gets_the_scope_again`, `a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks` | +| An address no connector serves was echoed in full, with `?channelpassword=`. | The text cuts the address at `?` and `#` (4.1). | `the_text_of_an_address_nobody_serves_keeps_the_channel_password_out`, `an_address_is_shown_without_its_secrets` | +| `LinkEvent::Talking` of the inner link was ignored, and its documentation unchanged: Speex and CELT talkers were no longer shown as talking. | The docs of `Talking`, `OwnChannel` and `Connected.own_client` say what the adapter derives; the inner link's `Talking` goes on as `Signal{speaking}`, a hint that SessionLink believes until it is over (P13). | `a_talker_the_link_hears_but_does_not_forward_is_shown_as_talking`, `a_host_that_says_someone_talks_is_believed_until_it_says_otherwise` | + +## 15. Review round 3 of slice 1 + +The third review found seven defects (two major, five minor); each is fixed in +its own commit, in its own place above, and tested. The tests that exercise +the engine's behaviour fail on the code before the commit that fixes them. + +| Finding | Fix | Test | +|---|---|---| +| **Major.** `presence_follows_the_link_until_it_disconnects` failed in about 7 % of isolated runs (22 of 300 on the first implementation): `Talking` comes from the media queue, `Poke` and `Error` from the push channel, and the loop cannot order two channels; with the push polled first the wait for `Talking` swallowed the other two events and the next wait timed out. | The test is the second changed test of the fixtures (5.4): it plays the voice packet, waits for `Talking`, and only then plays the poke and the error. Section 13 says that `Talking` and `Audio` have no defined order relative to `Poke`, `Chat`, `Error` and `Presence` (it had implied media first), 4.2 step 9 says the bias is no order, and 5.4 records the change of the test. | the test itself: 0 failures in 300 isolated runs, and 0 in 40 runs of the whole `link_fake` binary | +| **Major.** `Driver::join` answered a `JoinVoice` with the own voice state and sent no `Move` whenever the snapshot showed us in the channel: a second request back into the old channel, made while the first move was still on its way, was dropped without an error and the user stayed in the first move's channel. | The shortcut stays for the first `JoinVoice` (the seat) and for a move into the channel we are in while no move of ours is pending; otherwise the request goes to the link in order. The link says nothing to a move into the channel it is in, so a refusal of the first move (`JoinFailed`) now settles the pending moves into the channel the snapshots show, instead of leaving them to the ten seconds (3.1). | `a_move_made_while_another_is_on_its_way_reaches_the_link`, `a_move_back_after_a_refused_move_is_answered_though_the_link_says_nothing` | +| `Session::features()` was never narrowed by `Server.features` (4.7 said it was). | SessionLink keeps the host's set and the server's (`Features::narrowed`), recomputed when the SERVER scope changes or syncs and after a `HostUpdate` (4.7). | `the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list` | +| User-initiated file transfers got a 30 s negotiation deadline they never had (pictures had one, `IMAGE_NEGOTIATION`, and keep it in SessionLink). | `LinkSession` waits for the link's `OpenRead` and `OpenWrite` without a deadline; a caller that drops the call is noticed through the closed reply channel and takes the inner job with it (3.1). | `a_transfer_waits_for_the_server_for_as_long_as_the_caller_does` (virtual time) | +| A poke from a sender with no unique id who is not on the snapshot lost its name (no `User` entity in LIVE for the synthetic `client:N` id). | The driver puts a bare `User` with the name and no uid into LIVE for that id, replaced when the same client id comes back with another name (5.2). | `a_poke_from_a_sender_with_no_unique_id_outside_the_snapshot_is_named` | +| The `ts3server://` round trip of `address_link` and `inner_options` changed what the link was given for odd bookmark addresses: a port that is no `u16` was dropped silently, empty option strings became none, a bare host with a `?` lost the channel. | A port that is not a number from 1 to 65535 and a host that a link cannot carry (empty, `?`, `#`, `/`, `%`, white space, an unclosed `[`) fail the connect in words (`connect_params` returns a `Result`); the remaining normalisations are listed in 4.2. | `a_bookmark_the_link_would_change_is_refused`, `the_bookmarks_a_server_has_come_back_with_their_channel`, `empty_options_come_back_as_none` (`ts_session/mod.rs`), `a_bookmark_with_a_port_that_is_no_port_does_not_connect` | +| One nightly rustfmt difference in `link/tests.rs` (`.count()` and `== 3` on separate lines). | The count is bound to a local, so both rustfmt versions format it alike. | `cargo fmt` stable (1.94) clean; nightly differs from the baseline's six diffs only (`history.rs`, `encoder.rs`, `discovery.rs`, `chat.rs`, `studio.rs`, `engine.rs`) | + +What the fixes leave as it was: a move into the channel we are in, with none +pending, is still answered without asking the link (the baseline's link answered +it with nothing, so the user saw nothing either way), as 3.1 designed. One window +remains, where the baseline sent the `Move`: a move that the server made by +itself (a moderator moving the user) and that the snapshot has not shown yet +makes a `JoinVoice` into the channel the snapshot still shows a no-op, until the +snapshot catches up. The reviewer offered dropping the shortcut altogether; the +cost of that is the ten seconds a swallowed `ChannelAlreadyIn` leaves a request +waiting (and a request per click on the own channel), so it is kept for the +case where nothing is pending. And the 30 s `ANSWER_TIME` still bounds the +requests that are answered with data (file lists, deletes, offline messages), +which the baseline did not bound. + +### What ran + +Checks of this round, on the head of the branch (Rust 1.94 and nightly +2026-10-19, in a nix shell with the native libraries; the baseline was not run +again, the comparison with it is the table of section 13): + +- `cargo fmt` on the own crates (`scripts/own-crates.sh`): clean on 1.94; + nightly shows the baseline's six differences only. (`cargo fmt --all` on 1.94 + rewrites the vendored `crates/proto`, which has a nightly-only style, so it + is not the check.) +- `cargo clippy $(scripts/own-crates.sh) --all-targets --locked --no-deps -- + -D warnings`: clean on 1.94. Nightly clippy reports five lints in code this + branch did not touch (`result_large_err` of `shutdown_connection` in + `voice.rs`, four `chunks_exact` in `audio.rs`) and none in the new code. + Every commit of the round passes it on 1.94 alone. +- `cargo test -p voelin-core --locked --no-fail-fast`: everything passes on + 1.94 and on nightly but the two tests that fail on the baseline too + (`discover::tests::without_records_the_gateway_itself_is_asked`, + `web::tests::pictures_go_through_the_proxy_named_for_each_hop`). The + presence test of `link_fake` passed 300 isolated runs of 300 (22 failures + of 300 with the test as it was), and the whole `link_fake` binary 40 of 40. +- `cargo check --workspace --all-targets --locked` on 1.94 and on nightly + (includes `voelin-ui`, `voelinctl` and the gateway binaries). +- Live, against fresh dev servers (compose project `voelin-seam3`, TeamSpeak + 3.13.8 and 6.0.0-beta13.1): `scripts/it-smoke.sh ts3 ts6`, every per-server + scenario passes; the script's last stage fails in `ts6_banners` only (its + assertion "disabled policy must prevent HTTP requests"), as it does on the + baseline. Run by hand, serially: + `live` 6 of 6, `media_live` 2, `stream_live` 3, `voice_features` 3 and + `voelin-stream`'s `live_ts6` 1 pass. + + +## 16. Slice 2 as implemented + +Slice 2 (section 10: the tests on `FakeSession` and `FakeHost`, the conformance +suite, the TeamSpeak session tests) is in `phase4/session-seam`. It adds tests +and two small changes to the code under test, each found by a test, each in a +commit of its own (F1 and F2 in 16.5); a third finding (F3) is open, and a +fourth (F4) is an observation. + +### 16.1 What was built + +| File | What | Tests | +|---|---|---| +| `tests/session_fake.rs` | The engine through `Engine::start_with_backends` with a `FakeConnector` (scheme `fake`) and a `FakeHost` filled with `put`; `FakeHandle` plays the backend of one session. Public API only. | 16 run, 2 ignored (F3); 18 run since the review of slice 2 split two tests out (17.1) | +| `tests/link_fake.rs` | Trimmed to the three tests that need the inner link: the stream commands (`stream_commands_reach_a_link_with_streams`), the order of a reconnect's shutdown, a replaced connection that keeps talking. Slice 3 made the inner link crate-private and moved the file into the crate (`src/link/fake_link_tests.rs`, 17.1). | 3 | +| `src/link/fake_tests.rs` | What needs the crate's private parts: our voice as RTP read from `sent_media`, the voice of other slots, our own voice coming back, the conformance suite through `Backends::connect`. | 4 | +| `src/link/tests.rs` | One more test: a session made outside an engine keeps its watches open (F2). (Slice 3 replaced it: the connector owns the watches, 17.1.) | 1 | +| `src/ts/ts_session/live_tests.rs` | The TeamSpeak `Session` on both development servers (`VOELIN_LIVE=1`): the conformance subset and the session scenarios of 9.3. It raises the servers' anti-flood limits itself before the first connection (16.8). | 12 live, 2 ignored | + +`scripts/it-smoke.sh` runs the live module before its engine stage. + +The scenarios of `link_fake.rs` that moved: + +| Was in `link_fake.rs` | Now | What is new in the version on the fake host | +|---|---|---| +| `presence_follows_the_link_until_it_disconnects` | `presence_follows_the_host_until_it_ends` | the server's name and backend from `Welcome`, the tree from `Channel`s with `position`, participants from `VoiceState`s and `User`s, talking from `inject_media`, the poke as a `Signal`, the notice as `Error`, the end as `kill(Network(..))` | +| `commands_reach_the_link` (minus streams) | `commands_reach_the_host_as_requests` | what the host received: `Put{Message}` (Markdown without `chat.bbcode`), `JoinVoice` with the password, the flags as notifications (id 0) patching one leaf path, `Signal{poke}`, `List{FILE}` (the fake refuses `List.path`, so the answer is scripted) | +| `a_sent_message_and_its_echo_are_one_message` | same name | the fake stores our `Put` and pushes its `Change` | +| `a_message_that_comes_twice_is_shown_once` | same name | four `FakeHost::put(Message)`, one with `MESSAGE_FLAG_RELAYED` | +| `history_is_kept_across_the_connection` | `history_is_kept_across_the_session` | a DM `Channel{server_id: 0}` in HOME, found through the other recipient's unique id | + +New in `session_fake.rs`: how a session ends and the text the user reads (a +kick with a reason, an idle timeout, a close with no reason, the user's own +close as `Local(Normal)`); what a host refuses in its own words (`message:`, +`poke:`, `PASSWORD`, `FULL`, other, and a private message to nobody without a +request); closed scopes (a CHAT scope says nothing, a LIVE scope is an error +and an empty presence); a `HostUpdate` that removes `files`, so that the engine +refuses a file list without asking, and adds it and `mailbox` again; offline +messages as scripted `Mail` and the `Put`/`Delete` the host received; a file +written with `write_file`, read back with `read_file`, a missing file, and a +resumed upload that continues where the host's copy ends (the copy is left by +another session of the host that dropped its upload); `CreateDirectory`, +`RenameFile` and `DeleteFiles` as `FileEntry` puts and deletes; media routed to +the talker of its slot (an unknown slot, a whisper, 400 ms of silence); a +reconnect (the host sees the first session closed, the second has another +participant, a message said while away arrives, and the replay of the one +message seen is not shown again, because `Dedup` still holds it; every +replayed message is stored again, and one older than `Dedup`'s 4 s is shown +again, which the two ignored tests of F3 pin); a connect that fails, and a +second that works. + +### 16.2 The conformance suite + +**Through the registry.** `the_conformance_suite_passes_on_a_session_of_the_registry` +runs the 17 cases of `c8e0e5a` against the `FakeSession` that +`Backends::connect(params, LocalCtx::standalone())` hands over: 17 of 17 +pass, none is skipped. The registry adds nothing to a plain connector's +session (`host_uid` is the connector's, there is no stream port), so the +request ids the host sees are the session's own (`shared_request_ids`). + +**Against TeamSpeak.** `ts3_conformance_subset` and `ts6_conformance_subset` +open a `TsConnector` session per case on the development servers, and give the +suite the `FakeHandle` of an unrelated fake host as its backend. The verdict of +every case is asserted (2 pass, 4 skipped, 11 not run), and a case the suite +gains fails until it is listed in `EXPECTED`. The verdicts are the same on +TeamSpeak 3.13.8 and 6.0.0-beta13.1: + +| Case | Verdict | Why (what the case did when it was run) | +|---|---|---| +| `welcome_matches_features` | passes | session only | +| `close_ends_the_session` | passes | session only: `closed()` is `Local(Normal)`, later requests, notifications and media are `Closed`, the push channel ends | +| `a_stale_rev_conflicts_and_a_patch_writes_only_its_paths` | skipped | no `chat.edit` | +| `requests_apply_in_the_order_they_were_issued` | skipped | no `chat.edit` | +| `list_pages_history` | skipped | no `chat.history` | +| `idempotency_keys_apply_a_put_once` | skipped | no `idempotency` | +| `subscribe_syncs_the_scope` | cannot pass | writes to channel 4001: rejected (`NotFound`) no such channel | +| `subscribe_resumes_from_a_cursor` | cannot pass | channel 4002, the same | +| `put_answers_entities_and_pushes_the_change_with_the_same_rev` | cannot pass | channel 4003, the same | +| `delete_answers_an_ack_and_pushes_the_removal` | cannot pass | channel 4004, the same; and TeamSpeak cannot delete a message, where the case needs `chat` only (P8) | +| `a_key_names_an_entity_without_its_server` | cannot pass | server 4020: rejected (`NotFound`) no such server; and it creates a `ScheduledEvent` and an `Emoji`, which TeamSpeak lacks, though it needs no feature (P8) | +| `files_round_trip` | cannot pass | writes an `AttachmentSlot`: rejected (`Unsupported`) "attachments are not offered by this connection"; TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8) | +| `media_loops_back` | cannot pass | a TeamSpeak server does not return a client's own voice: the packet never loops back | +| `cancel_before_apply_is_cancelled` | cannot run | holds the unrelated fake host, so the request is answered while it "holds" | +| `notifications_are_fire_and_forget` | cannot run | reads the request log of the unrelated fake host: the notification never arrives (and it types into channel 1) | +| `renew_account_follows_the_feature` | cannot run | pushes a `HostUpdate` into the unrelated fake session's push channel, which is closed | +| `the_backend_can_end_the_session` | cannot run | kills the unrelated fake session, so `closed()` of the TeamSpeak session never resolves; and a kick is `Network(text)`, not `Remote{KICKED}`, until H1 | + +The cases that cannot pass or cannot run are not part of the default run: the +two ignored tests `ts3_cases_that_do_not_apply_fail` and +`ts6_cases_that_do_not_apply_fail` run each of them (with a step of 3 s) and +assert that it fails, printing the first line of the failure, so that a case +that starts to pass (with the native session of H1) is noticed. The table above +is what they printed. + +### 16.3 The TeamSpeak session scenarios + +Six live tests per server, on sessions that `TsConnector` made through the +plain `Connector` interface and that were driven the way section 4.2 drives a +session (list the server, subscribe HOME, SERVER and LIVE, take the seat, wait +for the LIVE scope to show it): + +| Test | What it checks | +|---|---| +| `chat_in_the_own_channel` | `Put Message` in the channel both sessions are in is answered with the message as written; the other session gets the `Change` in its CHAT scope, ours gets the echo (the ids agree only with H1's native session, so only "not zero" is asserted) | +| `refused_moves` | with a Normal-group key and a locked and a full channel made through ServerQuery: `JoinVoice` without or with a wrong password is `Rejected(PASSWORD)`, with the right one it seats us in that channel, a full channel is `Rejected(FULL)` | +| `poke_between_sessions` | `Signal{poke}` to the other participant reaches it as a `Signal` from our participant with the words | +| `voice_between_sessions` | five Opus frames and an end sent on our slot reach the other session's `MediaSink` on our slot, the first with the marker, the sequence counting up by one (it is TeamSpeak's packet id), the last an empty payload; media on a slot that is not ours is refused before it leaves | +| `channel_file_from_an_offset` | with a Server Admin key (guests may not upload): `write_file` of 3,000 bytes, `read_file` from offset 1,000 gives the file's size in the head and the bytes from the offset; the file is deleted afterwards | +| `conformance_subset` | 16.2 | + +### 16.4 Where the code differs from sections 9.2 and 9.3 + +- **The CHAT re-subscription after moving back is a full sync**, not a delta + (13): `the_chat_of_a_channel_is_resubscribed_when_we_move_back` asserts two + `Subscribe`s of the channel without `since`, the missed message once, and the + messages seen before not again. The `seen` set of `SessionLink` drops them, + within the one connection, before the engine is asked about them: the test + sends two of them 10 s apart, so that `Dedup` (4 s) no longer holds the older + one and could not have dropped it. (With one message only the test passed + without the `seen` check as well, because the newest message seen is held by + `Dedup` too; with the check disabled the two-message test sees "before" + again, 16.8.) +- **A reconnect resumes nothing** (4.4): the second session is another session + of the same host, with a `SessionLink` and a `seen` set of its own. + `a_reconnect_finds_the_state_the_first_session_left` asserts what that gives + (the state of the host, another participant, the first seat gone from the + host, the first session `Local(Normal)`, the message said while away shown + once). What it does not give is a clean replay: the host sends the window of + the CHAT scope again, and every replayed message is stored a second time, and + shown a second time unless `Dedup` still holds an equal one (it holds the + messages up to 4 s older than the last it was asked about). The one message + that test sends before the disconnect is inside that window, so its replay is + dropped. The two ignored tests of F3 (16.5) send two messages more than 4 s + apart and pin both effects. +- **Our voice in `FakeHandle::sent_media()`** is a test of `SessionLink` + (`link/fake_tests.rs`): no `Command` of the engine sends voice, the audio + thread does. +- **The conformance run and the live TeamSpeak tests are in-crate**: + `Backends::connect`, `LocalCtx` and `TsConnector` are crate-private, and + nothing was made public for a test. The live module runs with + `VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1`. + The servers must be the ones of `dev/docker-compose.yml` (the module logs in + to their ServerQuery as `serveradmin`) and may be freshly started: a server + with its default anti-flood limits bans the address of the tests after three + or four connections (`ConnectFailedBanned`), so the module raises + `virtualserver_antiflood_points_needed_ip_block` and + `virtualserver_antiflood_points_needed_command_block` itself, once per server + and run, and clears the bans of an earlier run (`bandelall`), as + `scripts/it-smoke.sh` does in `admin_args`. It leaves the limits raised. + Slice 3 makes `TsConnector` public as `voelin_core::ts` and can move them to + `tests/`. +- **The fake host does not model everything the scenarios use**: it refuses + `List.path` (a file list and the listing before a resumed upload are + scripted), stores no `Mail` and no `FileEntry` (scripted), and its scripts + take every request of their op, so a script is added after the connect, and + the one for `list` answers by the kind asked. A `HostUpdate` or a notice + has no event of its own: a test knows the engine has applied a push when the + notice it sent after it is reported. +- **`welcome_matches_features` and `close_ends_the_session` pass for the right + reason only since F2.** Before it, a session made outside an engine ended by + itself within a moment. + +### 16.5 What the tests found + +**F1 (fixed, `Drop the media that comes back on our own slot`).** A session +that loops our voice back made the engine hand our own packets to the audio +thread and show us as talking: the slot map holds every participant, ourselves +included. `FakeSession` loops media back by default, so that a test sees media +move; a Voelin host that did the same would have made the engine play us to +ourselves. `on_media` returns for the packets of our own slot. TeamSpeak never +sends a client its own voice, so nothing changes for the servers the engine +reaches. Test: `our_own_voice_coming_back_is_not_played_back` (it heard +`[1, 50]`, us and then alice, before the change). + +**F2 (fixed, `Keep the account watches of a session made outside an engine +open`).** `LocalCtx::standalone()` exists to hold the senders of the +myTeamSpeak watches for a connector called outside an engine, but +`connect_link` dropped it when it returned; the TeamSpeak link ends its +connection with "account source closed" when a watch has no sender, so every +session made through the plain `Connector` interface ended by itself a moment +after it was handed out. The engine's path was never affected. The context +now moves into the driver task. Found by the first live run of the suite +(`the_backend_can_end_the_session` saw that text; `close_ends_the_session` had +passed without the session being alive). Test: +`a_session_made_outside_an_engine_keeps_the_watches_of_its_link_open` (fails +with "the identity watch lost its sender" without the change). + +**F3 (open; two ignored tests, +`a_message_the_host_sends_again_after_a_reconnect_is_not_shown_again` and +`a_message_the_host_sends_again_after_a_reconnect_is_stored_once`).** After a +reconnect, a Voelin host sends the window of a CHAT scope again (the full sync +of 4.3), and the engine gets it wrong twice, in the store and on the display. +`seen` in `SessionLink` is per connection, so every message of the replay is +reported again; `session.rs` then stores each one (`store_live`, before +anything looks for a copy) and shows each one unless `Dedup` drops it. + +- **The store.** The store merges copies from different sources only, so a + replay over the same source is a second row, whatever `Dedup` does, and + `ChatMessage` does not carry the host's message id that would let it merge + them. +- **The display.** `Dedup` (`route.rs`) recognises a copy only while an equal + message (target, author, text, a timestamp within 2 s) is still held, and it + holds the messages up to 4 s older than the last one it was asked about. A + replayed message that is not equal to a held one is shown again as a live + `Event::Chat`, like a new message: every message of the replayed window that + is more than 4 s older than the newest message seen before the disconnect. + The newest message, and what is within 4 s of it, is dropped. + +The first version of the stored-once test sent one message before the +disconnect and looked at the rows only, and the display check of +`a_reconnect_finds_the_state_the_first_session_left` passed on that one message +because it is the newest one, so `Dedup` still held it: no test showed that the +display was wrong too. With two messages 10 s apart ("first" at `t`, "second" +at `t + 10 s`, then "while away" at `t + 30 s` said while the first session is +closed) the two tests see: + +| Test | Expected | Seen | +|---|---|---| +| `..._is_not_shown_again` | the events `["while away"]` | `["first", "while away"]` ("second" is held and dropped, "first" is shown again) | +| `..._is_stored_once` | the rows `["first", "second", "while away"]` | `["first", "first", "second", "second", "while away"]` | + +`a_reconnect_finds_the_state_the_first_session_left` stays in the default run +and proves only that a message inside `Dedup`'s window is not shown again. + +TeamSpeak never replays, and no `voelin://` connector is registered, so no host +the engine reaches today meets this. Not fixed here because the cure is the +resume of H8, not a patch: a cursor kept per CHAT scope and sent as +`Subscribe.since`, which makes the reconnect a delta and cures both effects (the +replayed window is never sent), but only within an epoch: after an epoch change +the host sends a full sync again, and then only the host's message id can tell a +copy, in the store (H10) and on the display. The cheaper candidates each carry a +risk (a time floor per channel for the messages of a connect-time sync would +hide a backlog of a host that was restored with older clocks; keeping the +reported ids across connections would hide new messages of a host whose ids +restart; widening `Dedup` would hide a message said twice on purpose). The two +ignored tests are the acceptance tests of whatever is chosen. + +**F4 (observation).** The first snapshot of the TeamSpeak link can come after +the session was handed out (the driver waits 250 ms for it, `FIRST_SNAPSHOT`), +so a consumer that subscribes at once gets an empty LIVE sync and the voice +states as changes after it, and the seat the first `JoinVoice` answers can +name channel 0. The engine's replica copes (it is built on changes); a +consumer that reads the seat's channel must wait for its `VoiceState` in LIVE, +as `Client::settle` in the live tests does. H1's native session should hold the +first sync back until it has the snapshot. + +### 16.6 Follow-ups from this slice + +For the protocol repository (workarounds as above): + +| # | What | Workaround meanwhile | +|---|---|---| +| P15 | The suite's `Fixture::backend` is a `FakeHandle` for every harness, so a session of a real backend hands it an unrelated fake host and the cases that touch the backend fail or wait instead of being skipped. Make it `Option` and let a case say that it needs the backend (extends P8). | `EXPECTED` in `live_tests.rs` names the cases to run. | +| P16 | Say whether a host sends a sender its own voice. `FakeSession` loops it back by default and `media_loops_back` pins that for the fake; a consumer cannot tell a rule of the protocol from a setting of the fake. | F1: the engine drops its own slot. | +| P17 | Say what a consumer that reconnects without a resume token does with the replay of a CHAT window (protocol 2.5, 5.4): the `Message` id is the key to merge on, and `Subscribe.since` of a previous connection's cursor is a delta only within an epoch. | F3: nothing yet (the replay is shown again and stored again). | + +For the second half: + +| # | What | +|---|---| +| H10 | CHAT cursors per session and address in `SessionLink` (or the SDK of H8), sent as `Subscribe.since` after a reconnect; then the two ignored tests of F3 run; the cursor cures the display and the store only within an epoch (16.5). For the full sync after an epoch change the host's message id also has to reach the store (or the store has to merge same-source copies by id) and the display. | +| H11 | The native TeamSpeak session of H1 holds the first sync back until it has the first snapshot (F4), and `ts_session/live_tests.rs` moves with `ts_session` to `voelin-gateway-ts`; its `EXPECTED` table is the conformance record of that crate. | + +### 16.7 The broken translation + +Acceptance asks for a deliberately broken translation that makes a +`session_fake` test fail. With the `self_mute` path dropped from +`LinkCmd::SetInputMuted` in `link/session_link.rs` (the line +`self.voice_flag("self_mute", |voice| voice.self_mute = muted);` removed, the +file restored afterwards), `commands_reach_the_host_as_requests` fails: + +``` +thread 'commands_reach_the_host_as_requests' panicked at .../voelin-proto/src/test_util/connector.rs:301:3: +timed out after 20s waiting for self_mute +``` + +### 16.8 What ran + +Environment: Rust 1.94 (`rust-toolchain.toml`) and nightly 2026-10-19, in a +`nix shell` with `gcc cmake gnumake pkg-config jq alsa-lib openssl libvpx dav1d +pipewire fontconfig libxkbcommon`. `nix shell` does not run the setup hooks, so +three things were added by hand: the `.dev` outputs of those libraries on +`PKG_CONFIG_PATH` (without them `alsa-sys` does not build), their `lib` +outputs on `LD_LIBRARY_PATH` (`voelinctl` needs `libvpx.so.12`), and +`LIBCLANG_PATH` with `BINDGEN_EXTRA_CLANG_ARGS` for `libspa-sys`. With that +`cargo check --workspace --all-targets --locked` passes on both toolchains. The +development servers were TeamSpeak 3.13.8 and 6.0.0-beta13.1 of +`dev/docker-compose.yml` (compose project `voelin-seam5`, reset with `down -v` +before each smoke run; the review round after the first version of this section +used `voelin-fix2`, reset the same way). + +The review round (the corrections of F3, 16.1 and 16.4, the live module's +anti-flood step) ran on 1.94.1 and on the nightly that the store held then, +`rustc 1.101.0-nightly (19833af72 2026-10-20)`: the nightly 2026-10-19 of the +first record was no longer there, so every nightly number below was measured +again on this one. The `nix shell` was the same set plus `expat` and the `.dev` +outputs of `freetype` and `libxkbcommon`; `PKG_CONFIG_PATH` took the `.dev` +outputs of all of them, `LD_LIBRARY_PATH` every output of every one of them +(the `out` output alone left `libvpx.so.12` unfound for `voelinctl`), and +`BINDGEN_EXTRA_CLANG_ARGS` the include directories of `glibc.dev` and of +`clang`'s resource directory. + +| Check | Result | +|---|---| +| `cargo fmt $(scripts/own-crates.sh) -- --check` | clean on 1.94. Nightly 2026-10-20 (measured again in the review round): the six differences of the baseline, in the same six files (`history.rs`, `encoder.rs`, `discovery.rs`, `chat.rs`, `studio.rs`, `engine.rs`), none in a file of this slice. (`cargo fmt --all` on 1.94 rewrites the vendored `crates/proto`, so it is not the check.) | +| `cargo clippy $(scripts/own-crates.sh) --all-targets --locked --no-deps -- -D warnings` | clean on 1.94, `voelin-ui` and the binaries included. Nightly 2026-10-20 (measured again in the review round): `-p voelin-core --all-targets` gives the five lints of the baseline in code this slice did not touch (`chunks_exact` four times in `audio.rs`, `result_large_err` in `voice.rs`), none in the new code; over all own crates this nightly stops earlier, in `voelin-audio` and `voelin-media`, on lints that are new to it (`chunks_exact` and `chunks_exact_mut` with a constant chunk size, a manual checked division, `sort_by_key`) in two crates the slice did not touch. Every commit of the slice was checked alone on 1.94 (fmt, clippy, its tests); the first from an archive of its tree, the two code commits of the review round (`81d1de8`: the tests of 16.4 and 16.5; `9283191`: the live module) from detached checkouts in this worktree (fmt of the own crates, clippy of `voelin-core --all-targets`, `session_fake` and `link_fake`), and the record of the round is a commit of this file only. | +| `cargo check --workspace --all-targets --locked` | passes on 1.94 and on nightly | +| `cargo test -p voelin-core --locked --no-fail-fast` | 1.94: 236 lib tests pass, 2 are ignored (the live "do not apply" tests), 2 fail; the integration tests pass (`session_fake` 16 and 2 ignored, `link_fake` 3, `session_backends` 2, `gateway` 8, `live` 6, `stream_live` 3, `voice_features` 3, `settings` 1). Nightly 2026-10-20: the same integration tests, and 235 lib tests pass with 3 failures: the two below and `identity::tests::improve_level_keeps_the_key` once in seven runs (it passed in six reruns of the single test; it makes a random identity and asserts that the counter grew, which it does not when the key already has the level asked for, so a flake, though that cause was not confirmed; `identity.rs` is unchanged since `59fec5b`). (Without `--no-fail-fast` the run stops at the lib's two baseline failures and the integration tests do not run.) The two failures are the baseline's (`discover::tests::without_records_the_gateway_itself_is_asked`, `web::tests::pictures_go_through_the_proxy_named_for_each_hop`: both reach a server bound to `127.0.0.1` through `localhost`, which resolves to `::1` here); they fail on an unchanged copy of `bfc52e2` too. | +| `cargo test -p voelin-core --locked --features media-desktop` | (first version of this record; not rerun in the review round, which changed tests, the live module and this file only) the same, and a third failure, `media::tests::peer_config_follows_codecs`, which depends on the codecs of the machine and fails on the unchanged copy of `bfc52e2` as well. (`--features media` alone does not compile the crate's tests: `src/media.rs` names `voelin_media::ffmpeg`, which only the desktop backends have; that is the baseline's.) | +| `link_fake` and `session_fake`, 15 consecutive runs (again on the head of the review round, with the changed move-back test) | 0 failures (load average about 4; 9 at the last run of the review round) | +| Mutation (16.7) | `commands_reach_the_host_as_requests` fails with the `self_mute` path dropped; the file was restored | +| Mutation (16.4), `if self.seen.contains(&(channel, id))` in `SessionLink::after` made `if false && ...` | `the_chat_of_a_channel_is_resubscribed_when_we_move_back` with its first version (one message seen before the move) still passes, and so does `a_reconnect_finds_the_state_the_first_session_left`: `Dedup` holds the newest message seen. With the two messages 10 s apart of the present version the test fails (`left: "before"`, `right: "while away"`); the file was restored | +| The two ignored tests of F3, `cargo test -p voelin-core --test session_fake -- --include-ignored` | the other 16 pass; `..._is_not_shown_again` sees `["first", "while away"]`, `..._is_stored_once` sees `["first", "first", "second", "second", "while away"]` (16.5); ten more runs of the two (`-- --ignored`): the same two values each time | +| `a_session_made_outside_an_engine_keeps_the_watches_of_its_link_open` without the change of F2 | fails ("the identity watch lost its sender") | +| `our_own_voice_coming_back_is_not_played_back` without the change of F1 | fails (`[1, 50]` heard) | +| Live module, `VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1` | 12 of 12 pass on both servers, in 16 s; three more serial runs and one parallel run the same; with `--include-ignored` the two ignored tests pass too, each non-applicable case failing as `EXPECTED` says (the output of 16.2) | +| The same command on a freshly started stack (`down -v`, `up -d`, nothing else run before) | Before the module raised the anti-flood limits itself: 4 passed, 8 failed (`ts3 did not connect: session closed: Network("Server refused connection: ConnectFailedBanned")`, the same for ts6). The module as it now is, run straight after that failing run (the ban still in force): 12 passed, 2 ignored. After a fresh reset: 12 passed, 2 ignored in 16 s, and 14 of 14 with `--include-ignored` in 51 s; after another reset, the same module in parallel (the default test threads): 12 passed, 2 ignored in 7 s, the tests that start together waiting for the one that raises the limits. Without that step the module passed only after `scripts/it-smoke.sh` had raised the limits (`admin_args`). `banclear` is refused by both servers (`error id=256 command not found`, read on TeamSpeak 3), `bandelall` is accepted by both. | +| `scripts/it-smoke.sh ts3 ts6` on an archive of `bfc52e2` (before) | every per-server scenario passes (connect and tree, server and channel chat, voice tone, invisible presence, relay chat, gateway, history, pins and reactions, the engine's voice features, and on TeamSpeak 6 the streams and the late and elsewhere streams); the last stage fails in `ts6_banners` (`live.rs:375`, "disabled policy must prevent HTTP requests"), as it does on `59fec5b` | +| `scripts/it-smoke.sh ts3 ts6` at the head of the slice (after) | the same output apart from ids and counters (compared line by line with the numbers and identifiers masked), plus the new stage of the live module (12 passed, 2 ignored); the last stage fails in `ts6_banners` at the same line | +| `scripts/it-smoke.sh ts3 ts6` in the review round, at `2089f7c` (before) and at `9283191` (after), each on a freshly reset stack (`COMPOSE_PROJECT_NAME=voelin-fix2`, the state directory under the scratch directory) | both: every per-server scenario of ts3 and ts6 passes, the live module stage gives 12 passed, 2 ignored (16.2 s before, 16.4 s after), and the last stage fails in `ts6_banners` at `live.rs:375` (5 passed, 1 failed), the baseline's failure. The two outputs have 102 lines each and are equal once uids, stream ids, file names and counters are masked (the only residue is the random token in `history-talker: offline-`). The review round changed tests, the live module and this file, so the smoke is unchanged by construction; it also shows that the raising of the limits in `admin_args` and the module's own coexist. | +| the live binaries by hand, serially, on the head (`--features media-desktop`) | `live` 6 of 6, `media_live` 2, `stream_live` 3, `voice_features` 3, `voelin-stream`'s `live_ts6` 1: those of the baseline | + +Not run: `cargo deny` (not installed in this environment; `Cargo.lock` and +`THIRD_PARTY_NOTICES.md` did not change, no dependency was added), the +Windows, Android and Flatpak builds. + +## 17. Slice 3 as implemented + +Slice 3 (section 10: the `ServerLink` layer where it is redundant, TeamSpeak +types out of the API) is in `phase4/session-seam`. The three non-blocking +minors of the review of slice 2 are in the first three commits, each of its +own; the slice itself follows, one commit per step, and every commit passes +`cargo fmt` and `cargo clippy --all-targets --no-deps --locked -- -D warnings` +alone (17.5). + +### 17.1 What was done + +| Commit | What | +|---|---| +| `dd9140e` | `cases_that_do_not_apply_fail` calls `the_suite_is_known()` first: a case the suite gains is no longer skipped by the zip with `EXPECTED`. | +| `b92379d` | The tail of `a_reconnect_finds_the_state_the_first_session_left` (a second `ConnectVoice` while connected replaces the session) is `connecting_while_connected_replaces_the_session`, and the end of `commands_reach_the_host_as_requests` (a host without streams is refused `StartStream` before any request) is `a_host_without_streams_is_not_asked_for_one`; the tests they were cut from check what their names say. `session_fake` runs 18 tests and ignores 2. | +| `362e2b9` | `presence_follows_the_host_until_it_ends` asserts `uid_of(client)` of the three clients (the base32 of the Voelin uid, the host's name for each) and `ServerDetails.uid`. | +| `029b846` | `ts_link.rs`, `voice.rs`, `book.rs`, `ts_session/`, `versions.rs` and `identity.rs` move under `crates/voelin-core/src/ts/` with `git mv` (`git log --follow` reaches their history), and the commit changes only module declarations, `use` paths and the path of `Versions.csv`. `voelin_core::versions` and `voelin_core::identity` are `voelin_core::ts::versions` and `voelin_core::ts::identity`; the UI and voelinctl follow with the paths. (`ts_session` has been a directory since slice 1: section 10 wrote `ts_session.rs`.) | +| `a451f02` | `Command::SetMytsIdentity` and `SetMytsData` are gone. `ts::TsConnector` is public, owns the account (`TsConnector::set_myts_identity`, `set_myts_data`; clones share it), and each connection holds the senders for as long as it runs, so a session outlives its connector (the F2 guarantee, now by construction: `a_connection_keeps_the_account_open_when_its_link_is_gone` in `ts/ts_link.rs` replaces the test of the standalone context's senders in `link/tests.rs`). `Backends::register_teamspeak(TsConnector)` is the public way to register a connector whose clone the application keeps; `Backends::default` registers one of its own. `LinkCtx`, `LocalCtx`, `SessionHandle` and `Session` lose the two watches. | +| `be84874` | `ObserveGateway.identity` is a `Box` and `gateway::connect(url, &IdentityBlob)` takes the blob: `gateway.rs` reads it itself, and a blob that is no TeamSpeak identity or cannot be read is `ErrorCode::AuthFailed` from `connect` and ends an observation with its reason, without a login (`an_identity_that_cannot_be_read_ends_observing_without_a_login`). `ObserveQuery.connect` is a `Box`, which `query.rs` turns into `voelin_query::Connect` (`QueryTransport` is the core's own enum). `voelin_core::IdentityBlob` re-exports `voelin_identity::IdentityBlob`, and `ts::identity::{to_blob, from_blob}` convert (`IdentityError::Blob`, whose text says where the JSON is wrong and never what it says). `voelin-identity` is a dependency of `voelin-core`: `Cargo.lock` gains that one edge. | +| `1edc52c` | `VoiceOptions` is a struct of its own (`identity: Option`, `client_version: Option`, `stream_peer: PeerConfig`, the rest as before). `link/connect.rs` builds the connect parameters (the bookmark's link, the hello, the credential of the identity's kind: a TeamSpeak identity as its JSON, none as the empty blob, a Voelin key as its signer, any other kind refused in words); the client version spec rides the address as `client_version=` and `ts_session::inner_options` resolves it with `ts::versions::resolve` (a spec it refuses fails the connect). `session.rs` holds `Arc`, the redundant trait between them is gone, and the trait that stays, `ServerLink`, is `ts/ts_link.rs`'s (with the TeamSpeak-typed `ConnectOptions`) for `TsLink` and for the in-memory link of the tests. `LinkCtx`, `LinkCmd`, `LinkEvent` and `Remote` are `pub(crate)`, `TsLink` is `pub(crate)`, `Engine::start_with_link` is removed (not made private), and `tests/link_fake.rs` is `src/link/fake_link_tests.rs` (`git mv`), three unit tests on the same fake link through `Engine::start_with_backends` and `LinkConnector::any`. The module documentation of `link/session_link.rs` carries the contract of the vocabulary that `link/mod.rs` had. | +| `d70a358` | `voice.rs` loses `Download`, `Upload` and `CancelTransfer` (the copying task, the progress cadence, the picture limits, the cancel table, `expire_image_jobs`); it keeps the two connection jobs `OpenRead` and `OpenWrite` and refuses the three commands in words. `files::upload` and its close wait go with it (SessionLink uses `upload_to`; the TCP test of the upload runs through that), and the test of `image_download_time` moves to `cache.rs`. The picture limits and the negotiation deadline are in `SessionLink` alone, tested in `link/tests.rs` as before. | +| `ca34f84` | `QueryLogin.allowlisted`, see 17.2. | +| `f63d459` | The crate's documentation builds with warnings denied: `RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core` failed on `efacb41` and on `59fec5b` alike (eight errors, six with `--features media-desktop`: the cache's module documentation linked to private items, the crate documentation to modules and a type that exist only with the media features), so the acceptance check could not pass without it. Plain code spans now. | +| `d0092e4` | `docs/architecture.md`: "The server link" is "The session seam", and the crate table row of `voelin-core` follows. | + +No `CHANGELOG.md` entry: no difference to the baseline is visible to a user +(the UI still checks a bookmark's client version before it connects, and says +the same thing when the spec is none; `QueryLogin` runs the connection with +the options the UI always passed). + +### 17.2 Where the code differs from the text of section 10 + +- **`QueryLogin` has a seventh field, `allowlisted`.** Section 10 lists + transport, address, user, secret, server port and server id. The live tests + (`tests/live.rs`: `ts3_engine`, `ts6_engine`) have always passed + `voelin_query::Connect` with `LineOptions::rate_limit: None`, because the + development servers allowlist their clients; the UI never did, it passed the + query crate's default (nine commands in three seconds). With the six fields + the engine's connections can only have the default limit, and both tests + failed on the first run after the slice (`timed out waiting for relayed + channel message`; the limit is the one difference between that run and the + baseline, and with the bit below the tests pass again, so the relay's + connect is slower than the two seconds the test gives it, behind the limit; + that was not investigated further). `allowlisted` is that one bit: `false` + is what the application says (it cannot know) and what the UI's login says, + so the application's connections are the ones they were; the tests say + `true`. +- **`ServerLink` is not made crate-private, it is moved**: the engine side + needs no trait (`session.rs` holds `SessionLink`), and `SessionLink` and + `TsLink` could not share one `spawn` any more, as the options of the one are + neutral and the options of the other have `tsclientlib` types. The trait is + `ts/ts_link.rs`'s, as the TeamSpeak module "keeps the inner trait". +- **The setters are reachable through `Backends::register_teamspeak`**, which + section 10 did not name: a public setter that nothing could reach would have + been a dead end. +- **`files::upload` and `CLOSE_WAIT` are deleted** (section 10 does not say): + `voice.rs` was their only user. +- **The acceptance `rg` has to be run from `crates/voelin-core/src`**: its glob + `!ts/**` is relative to the directory it runs in. From the repository root, + `--glob '!**/ts/**'` does the same. +- The bookmark-refusal tests that exercise `link/connect.rs` (`a_bookmark_the_link_would_change_is_refused`, + `the_bookmarks_a_server_has_come_back_with_their_channel`, `the_params_carry_what_the_session_needs_and_no_account_yet`) + still sit in `ts/ts_session/mod.rs`, where they were written, next to the + round trip they were part of; moving them is a tidy for later (17.6). + +### 17.3 What `phase5/ui-vm-2` has to absorb + +The parked branch is not touched. Every change of this slice that reaches an +application that builds `VoiceOptions`, the gateway and query commands or the +TeamSpeak helpers: + +- `VoiceOptions` is no alias of `ConnectOptions` any more (`voelin_core::ConnectOptions` + and `voelin_core::link::ConnectOptions` are gone, `VoiceOptions` is + `voelin_core::VoiceOptions`): `identity` is `Option` (was + `Option`; `voelin_core::ts::identity::to_blob(&identity)`), + `client_version` is `Option`, the spec for `ts::versions::resolve` that a + bookmark stores (was `Option`; keep the eager + `resolve` for the message and pass the spec string), `stream_peer` is + `PeerConfig` as before; the other fields are unchanged. +- `Command::SetMytsIdentity` and `Command::SetMytsData` are removed: the + account goes to the `TsConnector` the application registered + (`Backends::register_teamspeak`, `TsConnector::set_myts_identity`, + `set_myts_data`, `Engine::start_with_backends`). +- `Command::ObserveGateway.identity` is `Box` (was + `Box`); `gateway::connect(url, &IdentityBlob)` (was + `&tsclientlib::Identity`). +- `Command::ObserveQuery.connect` is `Box` (was + `Box`): `transport: QueryTransport` (`Raw`, `Ssh`, + `Http`), `address` (was `addr`), `user`, `secret`, `server_port`, + `server_id`, `allowlisted` (`false`); there is no `line`. +- `voelin_core::versions` and `voelin_core::identity` are + `voelin_core::ts::versions` and `voelin_core::ts::identity`; + `ts::identity::{to_blob, from_blob}` are new, `IdentityError` has a `Blob` + variant. `voelin_core::IdentityBlob` re-exports the protocol repository's type. +- No longer public: `ServerLink`, `TsLink`, `Engine::start_with_link`, + `link::{LinkCtx, LinkCmd, LinkEvent, Remote}` and the helper types of + `link` that came with them (`BoxRead`, `BoxDuplex`, `Duplex`). + `voelin_core::link` keeps `Backends` and `VoiceOptions`. +- `voelin_core::ts::TsConnector` is public, with `new`, `set_myts_identity` + and `set_myts_data`. + +### 17.4 The acceptance list of section 10 + +| Item | Result | +|---|---| +| `rg -n 'tsclientlib\|tsproto\|voelin_query'` over `crates/voelin-core/src` without `ts/`, `gateway.rs`, `query.rs` and `stream.rs` | empty (from `crates/voelin-core/src`, `--glob '!ts/**' --glob '!gateway.rs' --glob '!query.rs' --glob '!stream.rs'`). The four exceptions name the crates privately: `gateway.rs` in `login_identity`, `connect_watched`, `attempt` and the tests, `query.rs` in `QueryLogin::connect` and `run`, `stream.rs` in a private `use tsclientlib::ClientId`, and `ts/` is the module. | +| `session.rs` names no TeamSpeak crate | none of `tsclientlib`, `tsproto`, `voelin_query` occurs in it. | +| No public item outside `voelin_core::ts` names a type of `tsclientlib`, `tsproto*` or `voelin-query` | Checked on the rustdoc JSON of the crate (nightly: `RUSTDOCFLAGS='-Z unstable-options --output-format json' cargo doc --no-deps -p voelin-core --features media-desktop`), walking every item the crate exports (5,198 of them): every type reference whose crate is `tsclientlib`, `tsproto`, `tsproto_packets`, `tsproto_types`, `tsproto_structs`, `ts_bookkeeping` or `voelin_query` is in an item of `voelin_core::ts` (11 items: `to_blob`, `from_blob`, `export`, `write_export`, `improve_level`, `Found::identity`, `resolve`, `native_version`, `KnownVersion::to_version` and the two setters of `TsConnector`); none is anywhere else. The grep of `pub` items (`rg '^\s*pub(\(crate\))? .*(tsclientlib\|tsproto\|voelin_query)'` over the crate without `ts/`) is empty, too. | +| `voelin_core::stream` keeps the re-exports | `PeerConfig`, `MediaFrame`, `MediaKind`, `MediaTime`, `Frequency`, `VideoFormat`, `VideoCodec`, `Codec`, `FrameSource`, `SyntheticSource` are re-exported as before (`stream.rs` changed in one doc comment). | +| `cargo tree -p voelin-core -e normal \| grep -E 'tsclientlib\|tsproto'` | still lists `tsclientlib`, `tsproto`, `tsproto-packets` and `tsproto-types`, as the section says it may: the TeamSpeak module is in the crate. | +| The three review minors | `dd9140e`, `b92379d`, `362e2b9`. | + +### 17.5 What ran + +Environment: Rust 1.94.1 (`rust-toolchain.toml`) and the nightly of the Nix +store, `rustc 1.101.0-nightly (19833af72 2026-10-20)`. The development shell +`dev rust-nightly` does not build here (`cargo-llvm-cov` fails), so both +toolchains were taken from the store paths and put in front of `PATH` in a +`nix shell` of `gcc cmake gnumake pkg-config jq` and the `.dev` outputs of +`alsa-lib openssl libvpx dav1d pipewire fontconfig freetype libxkbcommon +expat`; `nix shell` runs no setup hooks, so `PKG_CONFIG_PATH` (the `.dev` +outputs), `LD_LIBRARY_PATH` (every output of those libraries; `voelinctl` +needs `libvpx.so.12`), `LIBCLANG_PATH` and `BINDGEN_EXTRA_CLANG_ARGS` +(`glibc.dev`'s and `clang`'s include directories) were set by hand. With that +`cargo check --workspace --all-targets --locked` passes on both toolchains, +`voelin-ui`, `voelinctl`, `voelin-android` and the gateway binaries included. +`cargo-about` 0.9.2, which `scripts/notices.sh` insists on (nixpkgs has +0.9.0), was installed with `cargo install` under the scratch directory, and +the TeamSpeak 3.13.8 and 6.0.0-beta13.1 servers of `dev/docker-compose.yml` +were fresh compose projects (`down -v`, `up -d`) for each smoke run. + +| Check | Result | +|---|---| +| `cargo fmt $(scripts/own-crates.sh) -- --check` | clean on 1.94. Nightly: the six files of the baseline and no other (`voelin-core/src/history.rs`, `voelin-media/src/ffmpeg/encoder.rs`, `voelin-stream/src/discovery.rs`, `voelin-ui/src/chat.rs`, `voelin-ui/src/studio.rs`, `tools/voelinctl/src/engine.rs`). `cargo fmt --all -- --check` on 1.94 differs in the vendored `crates/proto` only, as it did before (it has a nightly-only style), so it is not the check. | +| `cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings` | clean on 1.94 at the head. Every code commit of the slice alone (`dd9140e` to `f63d459`, ten of them) was checked out detached in this worktree and passes fmt and clippy: `voelin-core` for the commits that touch tests only, all own crates for the ones that touch the UI or voelinctl. Without `--no-deps`, the command of the task (`cargo clippy -p voelin-core --all-targets --locked -- -D warnings`) stops at the vendored `tsproto-structs` (eight lints) on `efacb41` and on the head alike. Nightly, `-p voelin-core --all-targets`: `result_large_err` of `shutdown_connection` (now in `ts/voice.rs`, the same code) and the `chunks_exact` lints of `audio.rs` that the baseline gave, none in new code. | +| `cargo test -p voelin-core --locked --no-fail-fast` | 1.94: 244 lib tests pass, 2 are ignored (the live "do not apply" tests), 2 fail, both the baseline's (`discover::tests::without_records_the_gateway_itself_is_asked` and `web::tests::pictures_go_through_the_proxy_named_for_each_hop`: `localhost` resolves to `::1` here); the integration tests pass (`gateway` 9, `session_fake` 18 and 2 ignored, `session_backends` 2, `settings` 1, `stream_live` 3, `voice_features` 3, `live` 6, which return at once without `VOELIN_LIVE`). Nightly: the same numbers. With `--features media-desktop` on 1.94: 264 pass, three fail (the two and `media::tests::peer_config_follows_codecs`, which depends on the machine's codecs and failed on the baseline too). `cargo test -p voelin-ui -p voelinctl`: 134 and 7 pass. | +| Repeated runs (1.94) | `session_fake` and the three tests of `link/fake_link_tests.rs`: 15 runs each, 0 failures; the `--lib` suite: 8 full runs. `session::banner_tests::a_failing_banner_is_logged_once_with_its_address` failed once in a full `--lib` run before the last commits (`lines == []`, the test reads the log lines of its own thread with `tracing::subscriber::with_default`) and passed in every run since and in five isolated ones; it was not reproduced and not chased (a module this slice did not touch, a test that depends on a global callsite cache). | +| `RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core` | passes, with and without `--features media-desktop` (it failed on `efacb41`, 17.1). | +| `scripts/notices.sh --check` (cargo-about 0.9.2) | `THIRD_PARTY_NOTICES.md is up to date`: `Cargo.lock` gained one line, the edge from `voelin-core` to `voelin-identity`, a crate already in the graph through `voelin-store`. `cargo deny` is not installed here. | +| `scripts/it-smoke.sh ts3 ts6`, every per-server scenario | the baseline (`efacb41`) and the head both pass them all (connect and tree, server and channel chat, voice tone, invisible presence, relay chat, gateway, history, pins and reactions, the engine's voice features, on TeamSpeak 6 the streams and the late and elsewhere ones). The outputs have 100 lines each and are equal line by line with the digits, base64 runs, uuids and ids masked, but for the random uid of the streamer in the stream-directory line. | +| The script's live module stage | 12 passed, 2 ignored on both (16.35 s before, 16.36 s after); `--include-ignored` at the head: 14 of 14 in 47 s (the two "do not apply" tests call `the_suite_is_known` first now). | +| The script's last stage (`live`, `stream_live`, `media_live`, in parallel) | both: 5 passed, 1 failed, `ts6_banners` ("disabled policy must prevent HTTP requests"), the baseline's failure. The line is `live.rs:375` before and `live.rs:396` after: the file grew by 21 lines in the slice (the `login` helper and its imports, 17.2), the assertion is the same. | +| The live binaries by hand, serially, `--features media-desktop` | before and after alike: `live` 6 of 6 (73.40 s, 73.39 s), `media_live` 2, `stream_live` 3, `voice_features` 3, `voelin-stream`'s `live_ts6` 1. | +| The first smoke run after the slice (head `d70a358`, before `ca34f84`) | `live` failed `ts3_engine` and `ts6_engine` (17.2: `QueryLogin` without `allowlisted`); it is not part of the comparison above, which is the second run on a freshly reset stack. | + +### 17.6 Follow-ups + +- **H9 gains two edges to cut** (11.2): `Backends::default` and the use of + `ts::ts_session::{entities::user_uid, ids}` in `link/project.rs` and + `link/session_link.rs`. +- The bookmark tests of `link/connect.rs` that still sit in + `ts/ts_session/mod.rs` (17.2) belong next to it. +- `QueryLogin.allowlisted` goes with the query observer (H5), which becomes a + `Session` of a gateway daemon. +- `Backends::default()` keeps its `TsConnector` to itself: an application that + sets the myTeamSpeak account builds its registry (`Backends::empty` and + `register_teamspeak`) and starts the engine with `start_with_backends`. + The account goes through `AccountAgent` with H4. +- Documents that still name the old paths and are not this slice's to change: + the comment of `voelin-store` (`voelin_core::identity`, a crate other + branches own) and `docs/research/ui-review.md` (research notes with line + numbers of `voice.rs`). + +### 17.7 The round after the review of slice 3 + +The review of slice 3 left four minors. This round closes them, one commit +each, and brings the branch onto `main` (`ad20979`), so that the tree the gate +judges is the tree that will be merged. No history was rewritten. + +| Commit | What | +|---|---| +| `e13d401` | Merge of `main` (`ad20979`, 13 commits: the merge of `phase5/ui-vm`, the toolkit-free `crates/voelin-ui-vm` and the logic/bind split of `crates/voelin-ui`), see below. | +| `87926e9` | Minor 1. `link::connect::credential` refuses a TeamSpeak `IdentityBlob` whose JSON is empty (or only white space) with `SessionError::Protocol("the TeamSpeak identity cannot be read: it is empty")`, before any connector is asked: sent as it was, it was the empty `Credential::Foreign` blob that the TeamSpeak connector reads as "make an identity up", which only `identity: None` may ask for. Two tests: `link::connect::tests::a_teamspeak_identity_without_json_is_refused` (`""` and `" \n\t"` are refused, none is still the empty blob) and, through the engine on the fake host, `a_teamspeak_identity_without_json_is_refused_and_no_session_is_made` (`ConnectVoice` ends in `Disconnected` with the error `voice: the TeamSpeak identity cannot be read: it is empty`; the connector's `connects()` is empty and `last_session()` is `None`; a connect without identity works afterwards). Both fail with the check switched off. The comment of `ts::identity::to_blob` ("a blob with no JSON is refused when it is used, in words") is unchanged and holds on both paths now: the gateway's `from_blob` always refused it (`ObserveGateway` ends with its reason, without a login). | +| `f0d20cc` | Minor 2. `QueryLogin.transport` has its doc comment, the only public field of the type without one. | +| `76a884a` | Minor 3. 4.1 (the `TsConnector` owns the myTeamSpeak account since `a451f02`; it is not registered "with the engine's watches"), the 16.1 table (`src/ts/ts_session/live_tests.rs`), the section 10 acceptance `rg` (given as run from the repository root, `--glob '!**/ts/**'`, and the glob it takes from `crates/voelin-core/src`), the module documentation of `ts/voice.rs` (it linked `crate::TsLink`, which is `ts::ts_link::TsLink` and crate-private), `link/tests.rs` (`ts/ts_session/driver.rs`), the comment on `IdentityOrigin::Imported` in `voelin-store` (`voelin_core::ts::identity`; one word, the crate is otherwise untouched) and `docs/research/ui-review.md` (`ts/voice.rs`; the line number of the channel subscription, which has moved twice since the note was written, is replaced by where the code is). One more of the same kind that the list did not name: `docs/audio.md` named `voelin-core/src/link.rs` for `LinkCmd::Audio`, which is `link/mod.rs`. | +| `f1df886` | Minor 4. `ts::voice::Voice::command` answered `LinkCmd::Download`, `Upload` and `CancelTransfer` with `anyhow::bail!`. The commit message and the slice 3 review said that this ends the whole TeamSpeak connection; it does not: the `Input::Cmd` arm of `ts/voice.rs` catches the error and sends it as `LinkEvent::Error`, which the driver turns into an error notice, and only an `Input::Item` error breaks the loop. What really happened before the change was one spurious error notice and a transfer whose `report` was never answered, so the transfer hung (the review of this round corrected the record). `Download` and `Upload` now answer their `report` with `TransferState::Failed("this link does not run transfers itself")` and the connection goes on; `CancelTransfer` has no report and nothing to cancel, and is logged at debug. (Making the variants unrepresentable for the inner link would mean a second command enum next to `LinkCmd`; the match arm is smaller.) Test: `ts::voice::account_tests::a_transfer_command_fails_the_transfer_and_not_the_connection` gives an unconnected `Voice` the three commands: each returns `Ok`, the two reports see exactly the `Failed`, nothing is pending. | + +**The merge.** Three conflicts: + +- `crates/voelin-ui/src/settings_pages.rs` (modify/delete): `main` split it + into `settings_pages/{mod,bind}.rs` and `voelin-ui-vm`'s + `settings_pages/logic.rs`; this branch had only changed its six + `voelin_core::identity::` paths. The file is deleted, and the six paths are + `voelin_core::ts::identity::` where the code now is (five in `bind.rs`, + `Found` in `logic.rs`; the import moves in its group, as `rustfmt` orders + it). +- `crates/voelin-ui/src/identities.rs`: the module comment, which names + `voelin_core::ts::identity::import_new` (this branch) and `settings_pages/` + (`main`). +- `docs/architecture.md`: the `voelin-core` row of this branch with the + `voelin-ui-vm` and `voelin-ui` rows of `main`. + +Not conflicts, but needed to compile: `voelin-ui-vm` named the in-tree +`voelin-model` by path, which `fb8e6b6` (an early commit of the branch) had taken out of the +workspace for the protocol repository's (`voelin-model = { workspace = true }` +now). Nothing else of `voelin-ui-vm` or of `voelin-ui`'s new `bind` modules +touched a type of this slice: `VoiceOptions`, `ObserveGateway`, `ObserveQuery` +and the removed commands are only built in `voelin-ui/src/servers.rs`, which +merged on its own and compiles (17.3's list is absorbed with these two +changes). `Cargo.lock`, `Cargo.toml`, `README.md`, `docs/ui.md`, +`crates/voelin-ui/Cargo.toml`, `app.rs` and `servers.rs` merged without a +conflict: the lock resolves with `--locked`, and its difference to `main`'s is +the branch's alone (the edges of `voelin-core` to `voelin-identity` and +`voelin-proto`, the revision `c8e0e5a` of the three protocol crates, and +`voelin-model` as a git package). `CHANGELOG.md` is `main`'s entry +(`voelin-ui-vm`); the branch adds none (17.1), and still needs none: nothing +of this round is visible to a user. + +**What ran.** Same environment as 17.5, taken again: the toolchains from the +store paths in front of `PATH` in a `nix shell` of `gcc cmake gnumake +pkg-config jq` and the `.dev` outputs of `alsa-lib openssl libvpx dav1d +pipewire fontconfig freetype libxkbcommon expat`, with `PKG_CONFIG_PATH` +(`.dev` outputs), `LD_LIBRARY_PATH` (the `.out`, `.lib` and `.dev` outputs of +those: the test binary of `voelin-ui` needs `libfontconfig.so.1`), +`LIBCLANG_PATH` and `BINDGEN_EXTRA_CLANG_ARGS` set by hand. With that, +`cargo check --workspace --all-targets --locked` passes on 1.94 at the merge +and at the head, `voelin-ui`, `voelin-ui-vm`, `voelinctl` and `voelin-android` +included. + +| Check | Result | +|---|---| +| `cargo fmt $(scripts/own-crates.sh) -- --check` | 1.94: clean at the head and at every commit (the merge first differed by the order of one `use` in `voelin-ui-vm`, fixed in the merge commit). Nightly: five files, the baseline's six without `voelin-ui/src/studio.rs`, which `main`'s split removed (`voelin-core/src/history.rs`, `voelin-media/src/ffmpeg/encoder.rs`, `voelin-stream/src/discovery.rs`, `voelin-ui/src/chat.rs`, `tools/voelinctl/src/engine.rs`); `voelin-ui-vm` is clean on both. | +| `cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings` | 1.94: clean at the merge (and `-p voelin-ui` alone) and at the head. Each of the five new commits was checked out detached in this worktree and passes `fmt` and `clippy`: the merge on all own crates and on `-p voelin-ui` alone, the four others on `-p voelin-core -p voelin-store`. Nightly, `-p voelin-core --all-targets`: the same five errors as in 17.5 (`result_large_err` of `shutdown_connection` in `ts/voice.rs`, four `chunks_exact` in `audio.rs`), none in new code. | +| `cargo test -p voelin-core --locked --no-fail-fast` | At the head, 1.94 and nightly: 246 lib tests pass (244 + the two of this round), 2 are ignored, 2 fail, the two of the baseline (`discover::tests::without_records_the_gateway_itself_is_asked`, `web::tests::pictures_go_through_the_proxy_named_for_each_hop`: `localhost` resolves to `::1` only here); the integration tests pass (`session_fake` 19 and 2 ignored, the others as in 17.5). At the merge, before the minors: 244, the same two, and the integration numbers of 17.5. `cargo test -p voelin-ui -p voelin-ui-vm -p voelinctl`: 35, 146 and 7 pass. `voelin-store` (a comment changed): 31 lib tests and 49 of its integration tests pass, but `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was` failed once, in a run under a load average of 8.5 from other jobs on this machine (it asserts that a checkpoint returned in under a second of wall clock); it passed in five isolated runs and three more runs of the crate; it was not chased (a crate this round left alone). | +| The lib suite 10 times in a row (1.94) | `cargo test -p voelin-core --lib`: ten runs, each 246 passed, 2 failed, 2 ignored, the same two failing tests every time, the banner test passing every time. The same ten runs with those two tests skipped (`--skip`): exit 0 every time (246 passed, 2 ignored). `session::banner_tests::a_failing_banner_is_logged_once_with_its_address` (17.5 saw it fail once) did not fail in these 20 full runs, so the test is as it was: a fix would be a guess at a cause nobody has seen. | +| `RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core` | passes, with and without `--features media-desktop`. | +| The acceptance of section 10 | The `rg` is empty from the repository root (`--glob '!**/ts/**'`) and from `crates/voelin-core/src` (`--glob '!ts/**'`), with the four exceptions; `session.rs` names none of `tsclientlib`, `tsproto`, `voelin_query`, `ts_bookkeeping`; the grep of `pub` items outside `ts/` is empty; the rustdoc JSON of `voelin-core` (nightly, `--features media-desktop`; every item of the crate, 5,292 of them, whose type references name `tsclientlib`, `tsproto*`, `ts_bookkeeping`, `voelin_query` or `voelin_observer`) has 11 items with such references, all in `voelin_core::ts` (`to_blob`, `from_blob`, `export`, `write_export`, `improve_level`, `Found::identity`, `resolve`, `native_version`, `KnownVersion::to_version` and the two setters), none elsewhere; `voelin_core::stream` keeps its re-exports; `cargo tree -p voelin-core -e normal` still lists `tsclientlib` and `tsproto*`. | +| `scripts/notices.sh --check` (cargo-about 0.9.2, built under the scratch directory) | up to date at the merge and at the head; `Cargo.lock` did not change after the merge. | +| `scripts/it-smoke.sh ts3 ts6` | Before (`6a08147`, the head of slice 3) and after (`f1df886`): fresh compose stacks (`down -v`, `up -d`, project `voelin-seam-merge`, state directory under the scratch directory) and the same result: every per-server scenario passes, the TeamSpeak session module stage 12 passed and 2 ignored (16.34 s before, 16.39 s after), the engine stage 5 passed and 1 failed at `live.rs:396` (`ts6_banners`, the baseline's failure, 17.5). The two outputs, 99 lines each (the compose lines left out), are equal line by line with digits, base64 runs and uuids masked, but for the random uid of the streamer in the stream-directory line and the name of the state directory in two paths. | +| The live binaries by hand, serially, `--features media-desktop`, on the same servers | Before and after alike: `ts_session::live_tests --include-ignored` 14 of 14 (46.42 s, 46.43 s), `live` 6 of 6 (73.40 s, 73.39 s), `media_live` 2, `stream_live` 3, `voice_features` 3, `voelin-stream`'s `live_ts6` 1. | + +The last bullet of 17.6 (documents that still name the old paths) is closed by +`76a884a`; the others stand. diff --git a/docs/ui.md b/docs/ui.md index 58c7dd9..4805822 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -793,7 +793,7 @@ scaled down (an animation to its first frame). SVG uses Slint's vector loader and the existing vector-cache cost. Avatars and server, channel, client and group icons use the same image cache. -The focused checks are the `voelin-core`, `voelin-model`, `voelin-observer`, +The focused checks are the `voelin-core`, `voelin-observer`, `voelin-store` and `voelin-ui` library tests. They cover offline icon restoration, bookmark compatibility, cache misses and old-address event rejection. The live `ts6_banners` test checks disabled diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index fa6054f..466ae84 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -533,6 +533,9 @@ for svc in "${SERVERS[@]}"; do fi done +log "TeamSpeak session (voelin-core ts_session) against both servers: link conformance subset, chat, refused moves, poke, voice, files" +VOELIN_LIVE=1 cargo test --quiet -p voelin-core --lib ts_session::live_tests -- --test-threads=1 2>&1 | grep -E "test result|panicked|timed out" || fail "TeamSpeak session tests failed" + log "engine (voelin-core) against both servers, media pipeline through TS6" VOELIN_LIVE=1 cargo test --quiet -p voelin-core --features media-desktop --test live --test stream_live --test media_live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed" diff --git a/tools/voelinctl/Cargo.toml b/tools/voelinctl/Cargo.toml index 6e9cfc5..6bf12aa 100644 --- a/tools/voelinctl/Cargo.toml +++ b/tools/voelinctl/Cargo.toml @@ -24,7 +24,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } tsclientlib = { path = "../../crates/proto/tsclientlib", features = ["unstable"] } tsproto = { path = "../../crates/proto/tsproto" } tsproto-packets = { path = "../../crates/proto/tsproto-packets" } -voelin-model = { path = "../../crates/voelin-model" } +voelin-model = { workspace = true } voelin-query = { path = "../../crates/voelin-query" } voelin-observer = { path = "../../crates/voelin-observer" } # The client database (`identity import`/`export`) and where it lives. diff --git a/tools/voelinctl/src/client.rs b/tools/voelinctl/src/client.rs index 5a4990c..d6af2e0 100644 --- a/tools/voelinctl/src/client.rs +++ b/tools/voelinctl/src/client.rs @@ -254,7 +254,7 @@ pub async fn run(args: EngineArgs) -> Result<()> { let mut options = VoiceOptions::new(&args.address, &args.nick); if let Some(path) = &args.identity { - options.identity = Some(crate::identity::load(path)?); + options.identity = Some(voelin_core::ts::identity::to_blob(&crate::identity::load(path)?)); } engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs index a6ef5ae..d2d20fe 100644 --- a/tools/voelinctl/src/engine.rs +++ b/tools/voelinctl/src/engine.rs @@ -100,11 +100,11 @@ pub async fn run(args: GatewayArgs) -> Result<()> { engine.send(Command::ObserveGateway { session: SESSION, urls: vec![args.url.clone()], - identity: Box::new(identity.clone()), + identity: Box::new(voelin_core::ts::identity::to_blob(&identity)), }); if let Some(addr) = &args.voice { let mut options = VoiceOptions::new(addr, &args.nick); - options.identity = Some(identity); + options.identity = Some(voelin_core::ts::identity::to_blob(&identity)); if args.loopback { options.stream_peer = PeerConfig::loopback(); } diff --git a/tools/voelinctl/src/identity.rs b/tools/voelinctl/src/identity.rs index 366739e..1ba1fff 100644 --- a/tools/voelinctl/src/identity.rs +++ b/tools/voelinctl/src/identity.rs @@ -1,12 +1,12 @@ //! Load, create and store client identities as JSON files, and move them in -//! and out of the client database (`voelin_core::identity`). +//! and out of the client database (`voelin_core::ts::identity`). use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use tsclientlib::Identity; -use voelin_core::identity::{self as ident, Found, Imported}; +use voelin_core::ts::identity::{self as ident, Found, Imported}; use voelin_store::Store; pub fn default_path() -> PathBuf { diff --git a/tools/voelinctl/src/versions.rs b/tools/voelinctl/src/versions.rs index 8353b24..c76d3c9 100644 --- a/tools/voelinctl/src/versions.rs +++ b/tools/voelinctl/src/versions.rs @@ -1,3 +1,3 @@ //! Shared signed client versions and CLI argument resolution. -pub use voelin_core::versions::{client_metadata, known_versions, native_version, resolve}; +pub use voelin_core::ts::versions::{client_metadata, known_versions, native_version, resolve};