Merge main (c60acf9, the session seam) into phase5/ui-vm-2

The engine of main runs on voelin_proto::link::Session; this branch had split
the Slint controllers into <area>/logic.rs (voelin-ui-vm) and <area>/bind.rs
(voelin-ui) before that merge and was never reviewed. One conflict, the one
the Opus gate of the seam merge predicted:

- crates/voelin-ui/src/servers.rs (modify/delete): this branch had split the
  file into servers/bind.rs and voelin-ui-vm's servers/logic.rs; main had
  changed the file for the seam (docs/session-seam.md 17.3). The file stays
  deleted and the changes of main are made where the code now is:
  servers/bind.rs sends ts::identity::to_blob(&identity) in ConnectVoice and in
  both ObserveGateway sends, builds voelin_core::QueryLogin {address,
  allowlisted: false} with voelin_core::QueryTransport for ObserveQuery, names
  ts::identity::DEFAULT_NICKNAME, and its tests import ts::identity::{Found,
  LaunchImport}; servers/logic.rs imports ts::identity::LaunchImport (and
  links ts::identity::import_new), and voice_options keeps the eager
  ts::versions::resolve for the message and assigns Some(spec.clone()) to
  VoiceOptions::client_version (the engine resolves the spec when it
  connects).

Cargo.lock merged without a conflict and differs from main's only by the edge
of voelin-ui-vm to roxmltree, which this branch added (d9de95b).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 14:18:43 +03:00
commit 371e4d77c8
77 files changed
+15310 -3433

No files matched your search

+1 -1
View File
@@ -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"
+13 -3
View File
@@ -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
+25 -5
View File
@@ -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/<md5>`, `icons/<id>`, `pictures/<md5>`).
//!
//! 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/<md5>`: 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<String> {
@@ -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}-{}-{:?}",
+27 -19
View File
@@ -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<R: AsyncRead + Unpin>(
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<R: AsyncRead + Unpin>(
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<W, F>(
mut writer: W,
stored: F,
file: PathBuf,
size: u64,
offset: u64,
progress_every: Duration,
report: Report,
) {
) where
W: AsyncWrite + Unpin,
F: Future<Output = Result<(), String>>,
{
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<W: AsyncWrite + Unpin>(
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<String> {
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");
+44 -19
View File
@@ -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<String>),
}
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
/// with it.
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
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<Push>), 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<String>,
identity: tsclientlib::Identity,
identity: IdentityBlob,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// 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)));
+27 -64
View File
@@ -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<Arc<tsproto::myts::Identity>>),
/// 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<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -136,12 +126,15 @@ pub enum Command {
ObserveGateway {
session: SessionId,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
/// 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<IdentityBlob>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
ObserveQuery {
session: SessionId,
connect: Box<voelin_query::Connect>,
connect: Box<QueryLogin>,
},
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<dyn ServerLink>,
) -> 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<Event>,
frames: broadcast::Sender<StreamFrame>,
engine: Shared,
link: Arc<dyn ServerLink>,
link: Arc<link::SessionLink>,
) {
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<SessionId, session::SessionHandle> = 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 { .. }
-330
View File
@@ -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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// 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<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// 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<String>, nickname: impl Into<String>) -> 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<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
/// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]).
pub(crate) myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
pub(crate) myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
}
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<String>,
pub path: String,
}
/// What the session asks of a connection.
pub enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
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<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
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<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
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<String>),
}
+261
View File
@@ -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<dyn Fn(StreamCmd) + Send + Sync>,
/// What the stream task reports.
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
}
impl StreamPort {
/// A port whose commands go to `send`.
pub(crate) fn new(
send: impl Fn(StreamCmd) + Send + Sync + 'static,
events: mpsc::UnboundedReceiver<StreamEvent>,
) -> 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<StreamPort>,
}
/// 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<Result<LocalConnected, SessionError>>;
}
/// 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<Arc<dyn LocalConnector>>,
account: Option<Arc<dyn AccountAgent>>,
/// The connections' trust in hosts that are neither valid nor pinned.
trust: Option<Arc<dyn HostTrust>>,
}
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<dyn Connector>) {
self.connectors.register(connector);
}
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
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<Arc<dyn AccountAgent>>) {
self.account = agent;
}
/// The account agent, if one was set ([`Backends::set_account`]).
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
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<Arc<dyn HostTrust>>) {
self.trust = trust;
}
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
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<Result<LocalConnected, SessionError>> {
let scheme = Self::scheme(&params.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(&params.address) else {
let shown = without_query(&params.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<bool> {
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");
}
}
+261
View File
@@ -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<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
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<Credential, SessionError> {
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<String, SessionError> {
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<voelin_model::ServerLink, SessionError> {
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::<u16>().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<ConnectParams, SessionError> {
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));
}
}
@@ -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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
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<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
_options: ConnectOptions,
_ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
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<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
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<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> 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");
}
+322
View File
@@ -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<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// 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<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> 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
);
}
+310
View File
@@ -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<MediaPacket> {
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<u8>,
}
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<Incoming> {
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<u16, Instant>,
hinted: HashSet<u16>,
}
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<u16> {
let mut silent: Vec<u16> = 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));
}
}
+322
View File
@@ -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<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `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<String>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// 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<String>, nickname: impl Into<String>) -> 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<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
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<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
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<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
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<Result<(u64, BoxRead), String>>,
},
/// 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<Result<(u64, BoxDuplex), String>>,
},
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
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<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
/// 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<String>,
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<String>),
}
+214
View File
@@ -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<serde_json::Value> {
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
serde_json::from_slice::<serde_json::Value>(&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<u64, &v1::Channel> = 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<u64, GroupInfo> = BTreeMap::new();
let mut channel_groups: BTreeMap<u64, GroupInfo> = 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<ChatMessage> {
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(""), "");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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,
}
+141 -1
View File
@@ -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<String>,
/// Select the virtual server by its voice port...
pub server_port: Option<u16>,
/// ...or by id (the first server when neither is given).
pub server_id: Option<u32>,
/// 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<QueryCmd>,
events: mpsc::UnboundedSender<QueryEvent>,
) {
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}");
}
}
+11 -40
View File
@@ -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<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> 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<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
id: SessionId,
events: broadcast::Sender<Event>,
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<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> 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)
}
+1 -1
View File
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = 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<bool> = Key::new(
"identity.import_from_teamspeak",
Kind::Bool,
+1 -1
View File
@@ -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 {
@@ -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<u16>) -> 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<u64> = 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<u8> =
(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}");
}
}
}
}
@@ -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<LaunchImport, Iden
Ok(report)
}
/// A TeamSpeak identity as the API takes it
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
/// the store writes.
pub fn to_blob(identity: &Identity) -> 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<Identity, IdentityError> {
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();
+30
View File
@@ -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;
+256
View File
@@ -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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// 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<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// 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<String>, nickname: impl Into<String>) -> 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<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
}
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<Arc<tsproto::myts::Identity>>) {
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<Arc<tsclientlib::MytsData>>) {
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<Self>) -> 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<Option<Arc<tsproto::myts::Identity>>>,
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
_keep: Option<Arc<Account>>,
}
impl Watches {
/// Watches of senders that someone else keeps (a test's).
#[cfg(test)]
pub(super) fn of(
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> 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<Account>,
}
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<Account> {
&self.account
}
}
impl ServerLink for TsLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
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<tsproto::myts::Identity> {
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");
}
}
File diff suppressed because it is too large. Load diff
@@ -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<Key, Entity>;
/// 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<v1::User>,
/// Clients by unique id: their user id and participant id.
pub by_uid: HashMap<String, (u64, u32)>,
}
/// 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<v1::Image> {
(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<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = 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<ChannelId> = 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<u16>) -> 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<u64> = 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<String> {
let kept = user
.foreign
.as_ref()
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&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<Entity>, Vec<Entity>) {
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, ""));
}
}
+115
View File
@@ -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<Vec<u8>> {
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);
}
}
@@ -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<T>(what: &str, future: impl Future<Output = T>) -> 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<dyn Session>, mpsc::Receiver<v1::Push>, 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<dyn Session>,
pushes: mpsc::Receiver<v1::Push>,
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<u32, v1::VoiceState>,
}
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<Answer, SessionError> {
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<v1::VoiceState, SessionError> {
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<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> 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::<u64>("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::<u64>("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<v1::VoiceState, SessionError>| 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::<u64>("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<u8> = (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::<String>()
.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;
}
}
@@ -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<u16, Talker>,
}
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<MediaPacket> {
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<MediaPacket> {
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<EncodedVoice> {
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());
}
}
+855
View File
@@ -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<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
_ => {
// Without the query: a channel password rides in it.
let shown = crate::link::without_query(&params.address);
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
}
};
let identity = match &params.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(&params.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
identity,
client_version,
server_password: nonempty(&params.hello.password).or(link.password.clone()),
channel: link.channel.clone(),
channel_password: link.channel_password.clone(),
token: nonempty(&params.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<Cmd>,
closed: watch::Receiver<Option<CloseReason>>,
/// The media slot of our client; the driver changes it when we are another
/// client after TeamSpeak's own reconnect.
own_slot: Arc<AtomicU32>,
}
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> 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<Result<Answer, SessionError>> {
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<Result<Download, SessionError>> {
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<Result<Upload, SessionError>> {
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<Sent, MediaError> {
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<CloseReason> {
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<BoxDuplex>,
ended: Option<oneshot::Sender<()>>,
}
impl AsyncWrite for UploadBody {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
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<Result<v1::Entities, SessionError>> = 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<dyn ServerLink>,
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<dyn ServerLink>, 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<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
}
impl Connector for LinkConnector {
fn schemes(&self) -> &'static [&'static str] {
self.schemes
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
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<Result<LocalConnected, SessionError>> {
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<TsLink>,
}
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<Arc<tsproto::myts::Identity>>) {
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<Arc<tsclientlib::MytsData>>) {
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<Result<Connected, SessionError>> {
self.connector.connect(params)
}
}
impl LocalConnector for TsConnector {
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
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<String>,
}
fn ended_error(reason: Option<String>) -> 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<LinkEvent>,
) -> Result<Joined, SessionError> {
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<dyn ServerLink>,
params: ConnectParams,
ctx: LocalCtx,
) -> Result<LocalConnected, SessionError> {
let options = inner_options(&params, &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<LinkEvent> = 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(&params(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<String> {
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()
);
}
}
@@ -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]";
@@ -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<TransferId>,
offset: u64,
sink: Sink,
report: Report,
started: Instant,
},
Upload {
transfer: Option<TransferId>,
from: PathBuf,
size: u64,
report: Report,
},
/// [`LinkCmd::OpenRead`].
OpenRead(oneshot::Sender<Result<(u64, BoxRead), String>>),
/// [`LinkCmd::OpenWrite`].
OpenWrite(oneshot::Sender<Result<(u64, BoxDuplex), String>>),
}
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<TransferId> {
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<FiletransferHandle, Job>, 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<PathBuf>, 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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
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<LinkEvent>,
server_uid: String,
/// Who is talking: last voice packet per client.
talking: HashMap<u16, Instant>,
pending: HashMap<MessageHandle, Pending>,
jobs: HashMap<FiletransferHandle, Job>,
transfers: HashMap<TransferId, Slot>,
/// `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<LinkCmd>,
events: &mpsc::UnboundedSender<LinkEvent>,
) -> 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<TransferId>,
task: AbortHandle,
part: Option<PathBuf>,
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,
));
-34
View File
@@ -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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
tokio::spawn(voice::run(options, ctx, cmds, events));
}
}
+45 -5
View File
@@ -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.
-570
View File
@@ -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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
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<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
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<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
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<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> 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<HistoryMessage> {
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");
}
+23 -2
View File
@@ -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,
@@ -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<T>(
events: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> 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");
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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]
+1 -1
View File
@@ -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" }
-18
View File
@@ -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
-94
View File
@@ -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,
1 uid name description filename codes
2 4b27be5a-b92a-4b30-8b2d-14b59653f427 20th Anniversary Celebrating 20 Years of TeamSpeak 20_years
3 f81ad44d-e931-47d1-a3ef-5fd160217cf8 4Netplayers 4Netplayers customer 4netplayers
4 b78a0f3e-8758-4572-b102-42a79b4a0342 ???? Reads between the line hat
5 2bf80270-8efe-46dc-a472-3280a0479145 Alpha Tester Helped to test our software. THANK YOU! Alpha
6 05114019-6b46-4b13-b5a1-e5179ef69fb5 April Fools! Roses are red, gaming is fun, you are carrying too much to be able to run :( rpg
7 1a518885-520c-4f54-9f49-8b1acb674771 Braindance I’m chippin’ in Braindance P4TEKZ80PZ
8 cbf5aafd-2554-4053-80bb-0cf82ec0a430 Bright Idea TeamSpeak took my idea on board FeatureBadge_Lightbulb
9 d6062d9c-42a3-49c9-91dd-8c43a5a46805 Bug Catcher I found a bug! BugBadge_Splat
10 dfc70674-0fd0-431e-b3a1-edc32d7b09b2 Challenge Accepted Unlocked at SCILL Play — Challenges, tournaments and more! scill
11 afed63f4-82f1-4479-ab02-0ef053f55723 Communities Early Adopter Thank you for your Support! communities_early_adopter
12 54be472d-3163-4076-9059-7f46128d937e Communities Purchase Purchased a TeamSpeak Community communities_purchase
13 f85f7e21-753a-4566-b26a-4e3e9155d2ef Cyberpunk We have a city to burn Cyberpunk
14 c028298c-84ff-4e22-be4e-b8c17552b4bb Digi Digi joined your channel #DIGWIN digi
15 56df5ce2-6c5a-4a24-90e2-29e497e26170 Drone Champions League I follow the Drone Champions League DCL_Badge DRONECHAMP
16 935e5a2a-954a-44ca-aa7a-55c79285b601 E3 2018 - Winner Discovered at E3 2018 E3-2018
17 61723e54-3da2-4f19-a33f-fcdc8ef5eaa0 Father's Day 2022 Not all heroes wear capes fathersday2022
18 b9c7d6ad-5b99-40fb-988c-1d02ab6cc130 Found Tim Speak Found Tim Speak at Gamescom 2018 met_tim XJN4WJZEJN
19 809bdd5a-2601-4152-82ff-a21d23d8fd46 G2 Esports Aged 20 years being a G2 fan G2_Esports
20 62444179-0d99-42ba-a45c-c6b1557d079a Gamescom 2014 Registered at Gamescom 2014 gamescom_2014
21 50bbdbc8-0f2a-46eb-9808-602225b49627 Gamescom 2016 Registered during Gamescom 2016 gamescom_2016
22 534c9582-ab02-4267-aec6-2d94361daa2a Gamescom 2017 Visited TeamSpeak at Gamescom 2017 gamescom_2017 DK9JGRJH1Q
23 4eef1ecf-a0ea-423d-bfd0-496543a00305 Gamescom 2018 Visited TeamSpeak at Gamescom 2018 gamescom_2018 8CXB49KPJ4
24 b82a45a5-b235-4926-be77-de102222e5eb Gamescom 2019 Visited TeamSpeak at Gamescom 2019 Gamescom19 PNKCB76VZ8
25 34dbfa8f-bd27-494c-aa08-a312fc0bb240 Gamescom Hero 2017 Gaming Hero at Gamescom 2017 hero_2017
26 24512806-f886-4440-b579-9e26e4219ef6 Gamescom Hero 2018 Gamescom Exclusive Gaming Hero 2018 gamescom_2018_played BJCFQBU53C
27 d49fd07e-99fb-41de-8d7b-c98064713171 GommeHD.net Your #1 Minecraft Network for over 10 years GMHD
28 c565972a-3912-457b-826f-84820c1ba6ca Halloween 2021 Happy Halloween 2021 halloween21
29 133595e7-950f-4ef2-b113-f91a68b5770d Halloween 2021 Special Earned by participating in our Halloween 2021 special stream halloween21_special
30 fb154277-5fe7-428a-85a4-43c0bdcdda3d Halloween 2022 Spooky_Scary_Skeletons.mp4 halloween22
31 e6679ce2-d458-493c-8ffb-5660e47ac99f Happy Hanami Enjoy the view hanami2023
32 de7bd960-eb02-47e1-9ce2-a44f6e255d8f Happy Holidays 2019 Happy holidays from everyone at TeamSpeak! Happy_Holidays
33 d4ea0251-ba46-4c1a-83b7-59db3f89e52c Happy New Year 2021 Survived the great toilet paper crisis of 2020 firework_2020
34 1519e001-06a0-458c-9195-a8a6d0ec87fc Happy New Year 2023 Aw man, here we go again 2023_NewYear
35 834d4cc1-cd80-48d6-96c4-23d131d78649 Happy Summer 2023 heat death of the universe happy_summer_2023
36 c68bcc52-7aeb-4868-b4d2-e7b20716f9ba Heatwave 2022 I'm melting... help summer_icecream
37 94242c4e-6742-4540-8b66-ce951ed57159 Helping Hand \ pushed some buttons *beep* *bop* ~ thanks! homebase
38 288a56c6-4da3-48de-9c9f-bd9eede5d832 Immortal Roleplay This is your life. Immortal_Roleplay
39 69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d International Peace Day United we stand, divided we fall peaceday2022
40 9ea23c77-8755-4d82-b30c-92f4aac109ef International Women's Day 2021 To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day! wft
41 7d9fa2b1-b6fa-47ad-9838-c239a4ddd116 MIFCOM MIFCOM | Entered Performance mifcom
42 ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776 Merry Christmas 2019 It’s the most wonderful ‘Tim’ of the Year Christmas
43 c6480fe2-ee25-4ee8-9853-243652c8ec54 Merry Christmas 2020 Let it snow, let it snow, let it snow! Christmas2020
44 0581aa0f-8c2d-4681-bb9f-8492fec49977 Merry Christmas 2021 Look what Santa's left under the server tree! christmas2021
45 d4875b30-9908-43cb-a1eb-1a958e226078 Merry Christmas 2022 There's snow place like home christmas2022
46 87ccf9ea-67c9-45e5-adbc-77e210e6128a Met Tim Met Tim Speak IRL tim_irl
47 0d98391c-ecdf-4f26-931a-49bfd669cda7 Mind Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_MindEgg
48 2fdda3c6-20e0-48f1-9c12-f39239a2ed02 Mother's Day 2022 Thanks for bearing with us rose
49 c3f823eb-5d5c-40f9-9dbd-3437d59a539d Official TeamSpeak Gamer New myTeamSpeak member TS-2018
50 8dfa37ac-b40d-4466-b393-ff2184a9adf3 Overwatch League I follow the Overwatch League OWL_Badge
51 4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac PGL Antwerp 2022 Watched the PGL CS:GO Major PGLant
52 fa3ece28-64df-431f-b1b3-90844bfdd2d9 Paris Games Week 2014 Registered at Paris Games Week 2014 paris_gamesweek_2014
53 d95f9901-c42d-4bac-8849-7164fd9e2310 Paris Games Week 2016 Registered during Paris Games Week 2016 paris_gamesweek_2016
54 0005232e-538e-4cb2-93b6-d7d83e873829 PietSmiet Werde Snob auf PietSmiet.de ;) PietSmiet
55 be932556-dfa9-4dc6-afd0-98de0ab25777 PolTeamgeist WooOOHoohOOHooo PolTeamgeist
56 5f6d49e4-35c8-4809-8c81-6e71f7f749e9 Power Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_PowerEgg
57 ceee2445-4fbf-4f06-9421-286f0f4e875a Pride Never be afraid to show your colors. pride
58 1aa375e8-7207-45bf-8b80-556bafafc834 Reality Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_RealityEgg
59 f22c22f1-8e2d-4d99-8de9-f352dc26ac5b Rocket Beans TV Rocket Beans TV Community rbtv RWGE2NURJZ
60 2c9698c1-1fec-4baa-a28f-4845f045f42f Soul Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SoulEgg
61 641a4d85-2351-482c-97a1-02fc3b6abbb5 Space Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SpaceEgg
62 63261116-4359-4842-873e-56820afbe068 SpartaTheOriginal Olaf Toast @ twitch.tv/SpartaTheOriginal Toast
63 ef567ec5-f46e-4520-be07-6021023cf6bd Sponsorship License Sponsored by TeamSpeak Sponsorship
64 7a627d47-5496-4d68-83b5-2c4eafff9b30 Stay Home, Stay Safe Playing Apart, Staying Connected StaySafeStayHome
65 7262a528-c7df-4369-bc2c-d34bf5853d7b TS Chat Alpha Tester Helped us test our new mobile app, thanks! slim_golden
66 6eee759e-b1e9-4937-b023-07fc778532a2 TS Gameday Participant At least i tried... silvered
67 e1447b99-53b0-448a-98b7-ee7bad8bd268 TS Gameday Winner As shiny as the golden frying pan goldenjoystick
68 1cb07348-34a4-4741-b50f-c41e584370f7 TeamSpeak Addon Author Creator of TeamSpeak Addons addon_author
69 450f81c1-ab41-4211-a338-222fa94ed157 TeamSpeak Addon Developer (Bronze) Creator of at least 1 TeamSpeak Addon addon_author_bronze
70 94ec66de-5940-4e38-b002-970df0cf6c94 TeamSpeak Addon Developer (Gold) Creator of at least 5 TeamSpeak Addons addon_author_gold
71 c9e97536-5a2d-4c8e-a135-af404587a472 TeamSpeak Addon Developer (Silver) Creator of at least 3 TeamSpeak Addons addon_author_silver
72 9cd152a7-bf65-4ece-aeba-62d27678f79a TeamSpeak Competition Winner Badge TeamSpeak Competition Winner CompWinnerBadge
73 64221fd1-706c-4bb2-ba55-996c39effa79 TeamSpeak Jedi myTeamSpeak early adopter TS-OG
74 6b187e83-873b-46b0-b2c2-a31af15e76a4 TeamSpeak Merch Badge TeamSpeak Merch Owner - 1st Edition cap_red
75 22b9ec39-7694-453e-864c-dfc7b1b0d7c7 TeamSpeak Merch Badge 2.0 TeamSpeak Merch Owner - 2nd Edition topper
76 205916f3-a953-4754-8905-bc15069b1f91 TeamSpeak Merch Badge 3.0 TeamSpeak Merch Owner — 3rd Edition Merch3
77 8d843dfa-c51a-407f-87b3-94cfc8f03e96 TeamSpeak Staff Official Staff Member teamspeak_staff
78 c2368518-3728-4260-bcd1-8b85e9f8984c Test Testing, Testing. Testing
79 4086a249-a503-4f31-9e83-8a0a8e3089bd Tim-o'-Lantern Mwuhaahaahaahaahaa Tim-O-Lantern JQGCTAQWHT
80 089c7295-3aa2-48b0-b2f1-2dd1bec12caf Time Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_TimeEgg
81 904e232c-f369-44db-87f7-5142e15620cc Time Machine Worked like a machine to update addons in super-quick time. time_machine
82 4c61af66-22ef-4897-b0bb-25fcef2acf60 Undead Nightmare I'm the last of my kind undead_nightmare
83 b0a36aea-3e46-4e83-a455-6e92ae1b9d94 Undead Nightmare I'm the last of my kind undead_nightmare
84 0cd924ed-c5ea-459e-b60a-4f1bc0b65f07 Up, Up and Away! Find me on Mount Chiliad up,_up_and_away!
85 4b0fd4f5-d456-4294-973d-853a1db5c7d8 Valentim's Day 2019 Valentim's Day 2019 Valentines_Badge
86 92801833-e721-4b7e-84d4-6c02dbb332b9 Valentim's Day 2020 Valentim's Day 2020 Valentim2020
87 958f904b-8260-48a4-a961-f786cbd39411 Valentine's Day 2023 Love you like my Tamagotchi ValentinesDay23
88 a676c708-da67-4784-ba7f-3fb7e8d2e865 Valentines Day 2021 Roses are red, TS is blue, Servers are Sweet and so are you. valentine21
89 c54a9f92-07f7-4214-90f3-eafeea8005da World Backup Day Don't be an April Fool. Back up your data! backupday_2023
90 448a6d13-4e08-46a1-aafa-b4ff6d6c2d06 World Bonsai Day harmony, balance, patience bonsai_day
91 0f976a27-ddf5-447c-b79c-0644a8e8a297 Year of the Dragon 2024 Arise, Shenron! year_of_the_dragon_2024
92 8c22fe26-30ac-4231-8b31-67d8a75c808a Year of the Ox 2021 Only listen to the fortune cookie; disregard all other fortune telling units. ox21
93 970c70e6-00a1-41c1-ac5c-81c89a06c7a6 Year of the Rabbit 2023 Do a barrel roll! chineseNY2023
94 92356386-0451-4a97-87d9-10ff4f43260c Year of the Tiger 2022 Rocky sends his regards tiger
-144
View File
@@ -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<HashMap<String, BadgeInfo>> = 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<String> {
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<Vec<String>> {
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());
}
}
-283
View File
@@ -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<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_id: Option<ClientId>,
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<FileRef> {
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<String>,
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<u64>,
#[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<i64>,
/// 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<Self> {
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<FileRef> {
let lower = text.to_ascii_lowercase();
let mut found: Vec<FileRef> = 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<String> {
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"}"#);
}
}
-23
View File
@@ -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};
-420
View File
@@ -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/<code>`,
/// `teamspeak://invite=<code>`): 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<u16>,
pub nickname: Option<String>,
/// The server's password.
pub password: Option<String>,
/// The channel to join: its names from the top, separated by `/` (a `/`
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key: it puts its user in a server or channel group.
pub token: Option<String>,
}
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://<host>?<query>` 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/<host>?<query>` (also `/s=<host>`), and the
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
/// for anything else.
pub fn parse(text: &str) -> Option<Link> {
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://<host>?port=…`,
/// then what is set of nickname, password, channel (or `cid` for
/// `/<id>`), 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<String>| {
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<String> =
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
format!("channel={}", names.join("/"))
}
}
});
let query: Vec<String> = [
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<String> {
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<str>]) -> String {
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
}
/// The channel id of a path `/<id>` (what `cid=` gives).
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
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://`: `<host>[:port][/]?<query>`, or
/// `invite=<code>`.
fn parse_server(rest: &str) -> Option<Link> {
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<String> = raw.split('/').map(percent::decode).collect();
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
}
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().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/<host>?…` (or `/s=`), with or without `https://`, goes where
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
/// invite code.
fn parse_short(text: &str, lower: &str) -> Option<Link> {
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<u16>) {
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<u16> {
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<u16>) -> 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);
}
}
}
}
-54
View File
@@ -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%");
}
}
-493
View File
@@ -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<T: Default + PartialEq>(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<String>,
#[serde(default)]
pub has_password: bool,
/// `None` means unlimited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_clients: Option<i32>,
#[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<String>,
#[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<String>,
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<String>,
#[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<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub streaming: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub server_groups: Vec<GroupId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
/// 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<String>,
/// 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<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[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<GroupId>,
/// Badge GUIDs, in display order ([`shown_badges`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub badges: Vec<String>,
/// 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<u64>,
}
/// Badge GUIDs of a `client_badges` value
/// (`Overwolf=0:badges=<guid>,<guid>`).
pub fn parse_badges(value: &str) -> Vec<String> {
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<String> {
let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned);
let mut shown: Vec<String> = 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): `<state>,<url>;<state>,<url>…`, 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 `<number>,<url>` (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<String> {
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<ChannelInfo>,
pub clients: Vec<ClientInfo>,
}
#[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<ChannelId, ChannelInfo>,
pub clients: BTreeMap<ClientId, ClientInfo>,
/// What the source knows about the server (a voice connection: all of
/// it; other sources: nothing).
pub server: ServerDetails,
pub server_groups: BTreeMap<GroupId, GroupInfo>,
pub channel_groups: BTreeMap<GroupId, GroupInfo>,
}
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<GroupId, GroupInfo>) -> 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<PresenceDelta> {
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<Item = &ClientInfo> {
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<ChannelInfo>, clients: Vec<ClientInfo>) -> 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 });
}
}
-250
View File
@@ -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<String>,
/// Build timestamp (seconds since the Unix epoch).
pub build: Option<u64>,
}
impl ServerVersion {
pub fn parse(s: &str) -> Option<Self> {
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::<u32>());
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<String>,
#[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<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_channel_group: Option<u64>,
}
/// 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);
}
}
-192
View File
@@ -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<ChannelId, &ChannelInfo> = 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<TreeRow<'a>> {
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<TreeRow<'a>>,
) {
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<Spacer>) {
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<TreeRow>| -> Vec<String> {
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));
}
}
+1 -1
View File
@@ -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]
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -34,7 +34,7 @@ png = "0.18"
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" }
[lints]
+7 -5
View File
@@ -5,7 +5,7 @@
//! [`Cx`](crate::host::Cx)'s update what to draw and send; the store, the
//! secrets, the identity and the sockets are the front end's.
use voelin_core::identity::LaunchImport;
use voelin_core::ts::identity::LaunchImport;
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::{Bookmark, QueryConfig};
@@ -21,7 +21,7 @@ use crate::state::{AppState, Lines, SessionView};
pub 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 fn imported_status(report: &LaunchImport) -> Option<String> {
let n = report.added.len();
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
@@ -96,10 +96,12 @@ pub fn voice_options(
) -> Result<VoiceOptions, String> {
let mut options = VoiceOptions::new(&bookmark.address, &bookmark.nickname);
if let Some(spec) = &bookmark.client_version {
match voelin_core::versions::resolve(spec) {
Ok(version) => options.client_version = version,
Err(error) => return Err(format!("Invalid client compatibility version: {error}")),
// 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) {
return Err(format!("Invalid client compatibility version: {error}"));
}
options.client_version = Some(spec.clone());
}
options.channel = channel;
options.channel_password = channel_password;
@@ -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};
+1 -1
View File
@@ -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" }
+1 -1
View File
@@ -376,7 +376,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()
+1 -1
View File
@@ -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;
+15 -11
View File
@@ -49,7 +49,7 @@ impl App {
return false;
}
};
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.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
@@ -69,7 +69,7 @@ impl App {
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![logic::CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME]
![logic::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())
@@ -143,7 +143,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;
}
@@ -152,7 +154,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)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
@@ -160,18 +164,18 @@ impl App {
ObservePlan::Query(q) => {
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) });
}
@@ -420,7 +424,7 @@ impl App {
#[cfg(test)]
mod tests {
use voelin_core::identity::{Found, LaunchImport};
use voelin_core::ts::identity::{Found, LaunchImport};
use super::*;
+6 -6
View File
@@ -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."));
}