//! [`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"]); } }