diff --git a/Cargo.lock b/Cargo.lock index fce5534..ac486af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9095,7 +9095,9 @@ name = "voelin-core" version = "0.1.0" dependencies = [ "anyhow", + "base64 0.22.1", "futures", + "md5", "serde", "serde_json", "thiserror 2.0.21", @@ -9105,11 +9107,13 @@ dependencies = [ "tracing", "tsclientlib", "tsproto-packets", + "tsproto-types", "voelin-audio", "voelin-gateway-proto", "voelin-media", "voelin-model", "voelin-observer", + "voelin-platform", "voelin-query", "voelin-store", "voelin-stream", @@ -9308,6 +9312,7 @@ dependencies = [ "dirs", "futures", "futures-util", + "md5", "png", "serde_json", "tokio", diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index cd3ca85..c6dfab0 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -67,3 +67,14 @@ against or offered back to upstream. required `reason`; `notifyjoinstreamrequest` carries `is_remove`, `notifystreamstopped` and `notifystreamclientleft` carry `reason`, the latter also `return_code`. +8. **File transfer fixes** (`tsclientlib/src/lib.rs`, marked "Voelin patch"). + A server that refuses `ftinitdownload`/`ftinitupload` (file not found, no + permission, quota) answers with an `error` for the command's return code, which + came out as a `MessageResult` the caller cannot match to its + `FiletransferHandle`; it now fails the transfer (`FiletransferFailed`). A + transfer address of `0.0.0.0`/`::` means the server's own address. The return + code and transfer id counters wrap instead of overflowing. +9. **TeamSpeak 6 times in milliseconds** (`ts-bookkeeping/build/message_parser.rs`, + "Voelin patch"). TeamSpeak 6 sends some times, e.g. `datetime` of `notifyfilelist`, + in milliseconds, which failed to parse and dropped the whole message (empty file + lists). Values from 10^11 on (year 5138 in seconds) are taken as milliseconds. diff --git a/crates/proto/ts-bookkeeping/build/message_parser.rs b/crates/proto/ts-bookkeeping/build/message_parser.rs index f1fc849..fb74f34 100644 --- a/crates/proto/ts-bookkeeping/build/message_parser.rs +++ b/crates/proto/ts-bookkeeping/build/message_parser.rs @@ -181,13 +181,18 @@ pub fn single_value_deserializer(field: &Field, rust_type: &str) -> String { panic!("Unknown original time type {} found.", field.type_s); } } + // Voelin patch: TeamSpeak 6 sends some times (e.g. `datetime` of + // `notifyfilelist`) in milliseconds; seconds past 10^11 (year 5138) + // are taken as milliseconds. "OffsetDateTime" => format!( - "OffsetDateTime::from_unix_timestamp( - val.parse().map_err(|e| ParseError::ParseInt {{ + "OffsetDateTime::from_unix_timestamp({{ + let t: i64 = val.parse().map_err(|e| ParseError::ParseInt {{ arg: \"{}\", value: val.to_string(), source: e, - }})?).map_err(|e| ParseError::ParseDate {{ + }})?; + if t.unsigned_abs() >= 100_000_000_000 {{ t / 1000 }} else {{ t }} + }}).map_err(|e| ParseError::ParseDate {{ arg: \"{}\", value: val.to_string(), source: e, diff --git a/crates/proto/tsclientlib/src/lib.rs b/crates/proto/tsclientlib/src/lib.rs index d41b601..e01a16e 100644 --- a/crates/proto/tsclientlib/src/lib.rs +++ b/crates/proto/tsclientlib/src/lib.rs @@ -14,7 +14,7 @@ #![recursion_limit = "128"] use std::borrow::Cow; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::convert::TryInto; use std::iter; use std::mem; @@ -271,6 +271,12 @@ struct ConnectedConnection { client: client::Client, cur_return_code: u16, cur_filetransfer_id: u16, + /// Voelin patch: `ftinitdownload`/`ftinitupload` commands waiting for + /// their answer, by return code. The server refuses a transfer (file not + /// found, no permission, quota) with an `error` for the command, which + /// must fail the transfer: the caller only knows its + /// [`FiletransferHandle`]. + filetransfer_commands: HashMap, /// If we are subscribed to the server. This will automatically subscribe to new channels. subscribed: bool, /// If a file stream can be opened, it gets put in here until the tcp @@ -1149,6 +1155,7 @@ impl Connection { client, cur_return_code: 0, cur_filetransfer_id: 0, + filetransfer_commands: HashMap::new(), subscribed: false, filetransfers: Default::default(), connection_time: OffsetDateTime::now_utc(), @@ -1362,6 +1369,14 @@ impl ConnectedConnection { missing_permission: msg.missing_permission_id, }) }; + // Voelin patch: a refused file transfer fails its handle. + if let Some(ft) = self.filetransfer_commands.remove(&ret_code) { + if let Err(e) = res { + stream_items + .push_back(Ok(StreamItem::FiletransferFailed(ft, e.into()))); + } + continue; + } stream_items .push_back(Ok(StreamItem::MessageResult(MessageHandle(ret_code), res))); } else { @@ -1371,7 +1386,8 @@ impl ConnectedConnection { } else if let InMessage::FileDownload(msg) = &msg { for msg in msg.iter() { let ft_id = FiletransferHandle(msg.client_filetransfer_id); - let ip = msg.ip.unwrap_or_else(|| self.client.address.ip()); + // Voelin patch: servers listening on all interfaces announce 0.0.0.0. + let ip = msg.ip.filter(|ip| !ip.is_unspecified()).unwrap_or_else(|| self.client.address.ip()); let addr = SocketAddr::new(ip, msg.port); let key = msg.filetransfer_key.clone(); let size = msg.size; @@ -1397,7 +1413,8 @@ impl ConnectedConnection { } else if let InMessage::FileUpload(msg) = &msg { for msg in msg.iter() { let ft_id = FiletransferHandle(msg.client_filetransfer_id); - let ip = msg.ip.unwrap_or_else(|| self.client.address.ip()); + // Voelin patch: servers listening on all interfaces announce 0.0.0.0. + let ip = msg.ip.filter(|ip| !ip.is_unspecified()).unwrap_or_else(|| self.client.address.ip()); let addr = SocketAddr::new(ip, msg.port); let key = msg.filetransfer_key.clone(); let seek_position = msg.seek_position; @@ -1617,7 +1634,7 @@ impl ConnectedConnection { fn send_command_with_result(&mut self, mut packet: OutCommand) -> Result { let code = self.cur_return_code; - self.cur_return_code += 1; + self.cur_return_code = self.cur_return_code.wrapping_add(1); packet.write_arg("return_code", &code); self.send_command(packet).map(|_| MessageHandle(code)) @@ -1632,7 +1649,7 @@ impl ConnectedConnection { seek_position: Option, ) -> Result { let ft_id = self.cur_filetransfer_id; - self.cur_filetransfer_id += 1; + self.cur_filetransfer_id = self.cur_filetransfer_id.wrapping_add(1); let pass = channel_password .map(|p| tsproto_types::crypto::encode_password(p.as_bytes())) .unwrap_or_default(); @@ -1645,7 +1662,9 @@ impl ConnectedConnection { protocol: 1, })); - self.send_command_with_result(packet).map(|_| FiletransferHandle(ft_id)) + let handle = self.send_command_with_result(packet)?; + self.filetransfer_commands.insert(handle.0, FiletransferHandle(ft_id)); + Ok(FiletransferHandle(ft_id)) } fn upload_file( @@ -1653,7 +1672,7 @@ impl ConnectedConnection { overwrite: bool, resume: bool, ) -> Result { let ft_id = self.cur_filetransfer_id; - self.cur_filetransfer_id += 1; + self.cur_filetransfer_id = self.cur_filetransfer_id.wrapping_add(1); let pass = channel_password .map(|p| tsproto_types::crypto::encode_password(p.as_bytes())) @@ -1669,7 +1688,9 @@ impl ConnectedConnection { protocol: 1, })); - self.send_command_with_result(packet).map(|_| FiletransferHandle(ft_id)) + let handle = self.send_command_with_result(packet)?; + self.filetransfer_commands.insert(handle.0, FiletransferHandle(ft_id)); + Ok(FiletransferHandle(ft_id)) } } diff --git a/crates/voelin-android/src/host.rs b/crates/voelin-android/src/host.rs index d773d99..973d730 100644 --- a/crates/voelin-android/src/host.rs +++ b/crates/voelin-android/src/host.rs @@ -223,6 +223,7 @@ mod tests { text: text.into(), ts_ms: 0, via_relay: false, + blocked: false, }, } } diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 886cf3c..8ef9568 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -23,11 +23,13 @@ media-desktop = ["media", "voelin-media/default"] [dependencies] anyhow = "1" +base64 = "0.22" futures = "0.3" +md5 = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } +tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } tokio-tungstenite = "0.30" toml = "1.1.6" tracing = "0.1" @@ -36,11 +38,14 @@ voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true } voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } +# Paths only (the cache directory). +voelin-platform = { path = "../voelin-platform", default-features = false } voelin-query = { path = "../voelin-query" } voelin-store = { path = "../voelin-store" } voelin-stream = { path = "../voelin-stream" } tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } +tsproto-types = { path = "../proto/tsproto-types" } [dev-dependencies] tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] } diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs new file mode 100644 index 0000000..cf20f97 --- /dev/null +++ b/crates/voelin-core/src/book.rs @@ -0,0 +1,159 @@ +//! The voice connection's book (tsclientlib) as model types. + +use tsclientlib::{ClientType, MaxClients, data}; +use voelin_model::{ + ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostBannerMode, + HostMessageMode, Presence, ServerDetails, parse_badges, +}; + +fn group_info( + id: u64, + name: &str, + icon: tsclientlib::IconId, + sort_id: i32, + naming_mode: tsclientlib::GroupNamingMode, + group_type: tsclientlib::GroupType, +) -> GroupInfo { + GroupInfo { + id, + name: name.to_owned(), + icon: icon.0, + sort_id, + naming_mode: match naming_mode { + tsclientlib::GroupNamingMode::None => GroupNamingMode::None, + tsclientlib::GroupNamingMode::Before => GroupNamingMode::Before, + tsclientlib::GroupNamingMode::After => GroupNamingMode::After, + }, + group_type: match group_type { + tsclientlib::GroupType::Template => GroupType::Template, + tsclientlib::GroupType::Regular => GroupType::Regular, + tsclientlib::GroupType::Query => GroupType::Query, + }, + } +} + +/// What the server tells about itself; `uid` as the voice source computed it. +fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails { + ServerDetails { + name: server.name.clone(), + uid: uid.map(str::to_owned), + welcome_message: server.welcome_message.clone(), + host_message: server.hostmessage.clone(), + host_message_mode: match server.hostmessage_mode { + tsclientlib::HostMessageMode::None => HostMessageMode::None, + tsclientlib::HostMessageMode::Log => HostMessageMode::Log, + tsclientlib::HostMessageMode::Modal => HostMessageMode::Modal, + tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit, + }, + banner_url: server.hostbanner_url.clone(), + banner_gfx_url: server.hostbanner_gfx_url.clone(), + banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64, + banner_mode: match server.hostbanner_mode { + tsclientlib::HostBannerMode::NoAdjust => HostBannerMode::NoAdjust, + tsclientlib::HostBannerMode::AdjustIgnoreAspect => HostBannerMode::IgnoreAspect, + tsclientlib::HostBannerMode::AdjustKeepAspect => HostBannerMode::KeepAspect, + }, + host_button_tooltip: server.hostbutton_tooltip.clone(), + host_button_url: server.hostbutton_url.clone(), + host_button_gfx_url: server.hostbutton_gfx_url.clone(), + icon: server.icon.0, + platform: server.platform.clone(), + version: server.version.clone(), + max_clients: server.max_clients, + default_server_group: Some(server.default_server_group.0), + default_channel_group: Some(server.default_channel_group.0), + } +} + +/// The presence visible through a voice connection; `server_uid` as +/// the voice source computed it, `talking` the clients talking now. +pub(crate) fn presence_from_book( + book: &data::Connection, + server_uid: Option<&str>, + talking: impl Fn(u16) -> bool, +) -> Presence { + let limit = |m: &Option| match m { + Some(MaxClients::Limited(n)) => Some(*n as i32), + _ => None, + }; + Presence { + server_name: book.server.name.clone(), + server: server_details(&book.server, server_uid), + server_groups: book + .server_groups + .values() + .map(|g| { + let info = + group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type); + (g.id.0, info) + }) + .collect(), + channel_groups: book + .channel_groups + .values() + .map(|g| { + let info = + group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type); + (g.id.0, info) + }) + .collect(), + channels: book + .channels + .values() + .map(|c| { + ( + c.id.0, + ChannelInfo { + id: c.id.0, + parent: c.parent.0, + order: c.order.0, + name: c.name.clone(), + topic: c.topic.clone().filter(|t| !t.is_empty()), + has_password: c.has_password.unwrap_or(false), + max_clients: limit(&c.max_clients), + needed_subscribe_power: 0, + needed_talk_power: c.needed_talk_power.unwrap_or(0), + is_default: c.is_default.unwrap_or(false), + icon: c.icon.map_or(0, |i| i.0), + }, + ) + }) + .collect(), + clients: book + .clients + .values() + .map(|c| { + let mut server_groups: Vec = c.server_groups.iter().map(|g| g.0).collect(); + server_groups.sort_unstable(); + ( + c.id.0, + ClientInfo { + id: c.id.0, + uid: c.uid.as_ref().map(|u| u.as_ref().to_string()), + nickname: c.name.clone(), + channel: c.channel.0, + is_query: matches!(c.client_type, ClientType::Query { .. }), + away: c.away_message.clone(), + input_muted: c.input_muted, + output_muted: c.output_muted, + talking: Some(talking(c.id.0)), + streaming: c.is_streaming, + server_groups, + country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), + avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()), + description: Some(c.description.clone()).filter(|d| !d.is_empty()), + talk_power: c.talk_power, + talker: c.talk_power_granted, + channel_group: Some(c.channel_group.0), + badges: parse_badges(&c.badges), + icon: c.icon.0, + recording: c.is_recording, + priority_speaker: c.is_priority_speaker, + channel_commander: c.is_channel_commander, + database_id: Some(c.database_id.0), + }, + ) + }) + .collect(), + } +} diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs new file mode 100644 index 0000000..cf27d4f --- /dev/null +++ b/crates/voelin-core/src/cache.rs @@ -0,0 +1,387 @@ +//! The avatar and icon cache: files on disk named by their content. +//! +//! An avatar's name is its MD5 hash (`client_flag_avatar`), an icon's its +//! 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. Keys are relative paths (`avatars/`, +//! `icons/`). +//! +//! 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 +//! download (into a temporary path), later askers wait for the same +//! download ([`Cache::finish`] answers them all). + +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError, RwLock}; +use std::time::SystemTime; + +use tracing::debug; + +/// Called with the cached file's path, or why it could not be fetched. +pub(crate) type Waiter = Box) + Send>; + +/// What [`Cache::fetch`] decided. +pub(crate) enum Fetch { + /// In the cache; the waiter was answered. + Cached, + /// Another download is running; the waiter is answered when it ends. + Waiting, + /// Download into this path, then call [`Cache::finish`]. + Download(PathBuf), +} + +struct Entry { + size: u64, + tick: u64, +} + +#[derive(Default)] +struct Index { + scanned: bool, + entries: HashMap, + /// Use order: oldest first. + lru: BTreeMap, + total: u64, + next_tick: u64, + in_flight: HashMap>, + temp_serial: u64, +} + +/// See the [module docs](self). Cheap to clone. +#[derive(Clone)] +pub struct Cache { + dir: Arc, + index: Arc>, +} + +impl std::fmt::Debug for Cache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Cache").field("dir", &self.dir).finish() + } +} + +/// The cache key of an avatar (its MD5 hash, hex). +pub(crate) fn avatar_key(hash: &str) -> Option { + let valid = + !hash.is_empty() && hash.len() <= 128 && hash.bytes().all(|b| b.is_ascii_hexdigit()); + valid.then(|| format!("avatars/{}", hash.to_ascii_lowercase())) +} + +/// The cache key of an icon. +pub(crate) fn icon_key(id: u32) -> String { + format!("icons/{id}") +} + +impl Cache { + /// A cache in `dir` (created when the first file arrives). + pub fn new(dir: impl Into) -> Self { + Self { dir: Arc::new(dir.into()), index: Arc::default() } + } + + /// The platform's cache directory (`/voelin/images`). + pub fn default_dir() -> PathBuf { + voelin_platform::paths::cache_dir().join("images") + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Index> { + let mut index = self.index.lock().unwrap_or_else(PoisonError::into_inner); + if !index.scanned { + index.scanned = true; + scan(&self.dir, &mut index); + } + index + } + + /// The file of `key` if it is cached (marked as used). + pub fn get(&self, key: &str) -> Option { + let mut index = self.lock(); + self.touch(&mut index, key) + } + + fn touch(&self, index: &mut Index, key: &str) -> Option { + let path = self.dir.join(key); + let tick = index.entries.get(key)?.tick; + if !path.is_file() { + // Deleted behind our back. + let entry = index.entries.remove(key)?; + index.lru.remove(&entry.tick); + index.total = index.total.saturating_sub(entry.size); + return None; + } + index.lru.remove(&tick); + let tick = index.next_tick; + index.next_tick += 1; + index.lru.insert(tick, key.to_owned()); + if let Some(e) = index.entries.get_mut(key) { + e.tick = tick; + } + // The use time for the next run (best effort). + if let Ok(file) = std::fs::File::options().append(true).open(&path) { + let _ = file.set_modified(SystemTime::now()); + } + Some(path) + } + + /// Get `key`, downloading it once however many ask (see [`Fetch`]). + pub(crate) fn fetch(&self, key: &str, waiter: Waiter) -> Fetch { + let mut index = self.lock(); + if let Some(path) = self.touch(&mut index, key) { + drop(index); + waiter(Ok(path)); + return Fetch::Cached; + } + if let Some(waiters) = index.in_flight.get_mut(key) { + waiters.push(waiter); + return Fetch::Waiting; + } + index.in_flight.insert(key.to_owned(), vec![waiter]); + index.temp_serial += 1; + let temp = self.dir.join("tmp").join(format!( + "{}-{}-{}.part", + key.replace('/', "_"), + std::process::id(), + index.temp_serial + )); + Fetch::Download(temp) + } + + /// The download of `key` into `temp` ended; keep at most `max_bytes` + /// (0: no limit) and answer everyone waiting. + pub(crate) fn finish( + &self, + key: &str, + temp: &Path, + result: Result<(), String>, + max_bytes: u64, + ) { + let result = result.and_then(|()| self.insert_file(key, temp, max_bytes)); + let _ = std::fs::remove_file(temp); + let waiters = self.lock().in_flight.remove(key).unwrap_or_default(); + for waiter in waiters { + waiter(result.clone()); + } + } + + /// Put a file we have (e.g. our own avatar) into the cache. + pub(crate) fn insert_copy( + &self, + key: &str, + from: &Path, + max_bytes: u64, + ) -> Result { + let temp = self.dir.join("tmp").join(format!("{}.copy", key.replace('/', "_"))); + std::fs::create_dir_all(temp.parent().expect("tmp dir")).map_err(|e| e.to_string())?; + std::fs::copy(from, &temp).map_err(|e| e.to_string())?; + let result = self.insert_file(key, &temp, max_bytes); + let _ = std::fs::remove_file(&temp); + result + } + + fn insert_file(&self, key: &str, temp: &Path, max_bytes: u64) -> Result { + let path = self.dir.join(key); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("cache: {e}"))?; + } + let size = std::fs::metadata(temp).map_err(|e| format!("cache: {e}"))?.len(); + std::fs::rename(temp, &path).map_err(|e| format!("cache: {e}"))?; + let mut index = self.lock(); + if let Some(old) = index.entries.remove(key) { + index.lru.remove(&old.tick); + index.total = index.total.saturating_sub(old.size); + } + let tick = index.next_tick; + index.next_tick += 1; + index.entries.insert(key.to_owned(), Entry { size, tick }); + index.lru.insert(tick, key.to_owned()); + index.total += size; + self.evict(&mut index, max_bytes, key); + Ok(path) + } + + /// Remove least recently used files until the cache fits `max_bytes` + /// (never `keep`, the file just added). + fn evict(&self, index: &mut Index, max_bytes: u64, keep: &str) { + if max_bytes == 0 { + return; + } + while index.total > max_bytes { + let Some((&tick, key)) = index.lru.iter().find(|(_, k)| k.as_str() != keep) else { + break; + }; + let key = key.clone(); + index.lru.remove(&tick); + if let Some(entry) = index.entries.remove(&key) { + index.total = index.total.saturating_sub(entry.size); + } + if let Err(e) = std::fs::remove_file(self.dir.join(&key)) { + debug!("cache: cannot remove {key}: {e}"); + } + } + } + + /// Bytes in the cache. + pub fn size(&self) -> u64 { + self.lock().total + } +} + +/// Index what is on disk, oldest use first; leftover temporary files go. +fn scan(dir: &Path, index: &mut Index) { + let _ = std::fs::remove_dir_all(dir.join("tmp")); + let mut found = Vec::new(); + for sub in ["avatars", "icons"] { + let Ok(entries) = std::fs::read_dir(dir.join(sub)) else { continue }; + for entry in entries.flatten() { + let Ok(meta) = entry.metadata() else { continue }; + if !meta.is_file() { + continue; + } + let used = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); + let key = format!("{sub}/{}", entry.file_name().to_string_lossy()); + found.push((used, key, meta.len())); + } + } + found.sort(); + for (_, key, size) in found { + let tick = index.next_tick; + index.next_tick += 1; + index.total += size; + index.lru.insert(tick, key.clone()); + index.entries.insert(key, Entry { size, tick }); + } +} + +/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`] +/// can replace, shared by the sessions. +#[derive(Clone, Debug)] +pub(crate) struct SharedCache(Arc>); + +impl SharedCache { + pub fn new(cache: Cache) -> Self { + Self(Arc::new(RwLock::new(cache))) + } + + pub fn current(&self) -> Cache { + self.0.read().unwrap_or_else(PoisonError::into_inner).clone() + } + + pub fn replace(&self, cache: Cache) { + *self.0.write().unwrap_or_else(PoisonError::into_inner) = cache; + } +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use super::*; + + fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "voelin-cache-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + /// Fetch `key` and write `bytes` as its download. + fn put(cache: &Cache, key: &str, bytes: usize, max: u64) -> PathBuf { + let (tx, rx) = mpsc::channel(); + let Fetch::Download(temp) = cache.fetch(key, Box::new(move |r| tx.send(r).unwrap())) else { + panic!("{key} should download"); + }; + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, vec![0u8; bytes]).unwrap(); + cache.finish(key, &temp, Ok(()), max); + rx.recv().unwrap().unwrap() + } + + #[test] + fn fetch_once_then_hit() { + let dir = temp_dir("fetch"); + let cache = Cache::new(&dir); + let (tx, rx) = mpsc::channel(); + let waiter = |tx: mpsc::Sender<_>| -> Waiter { Box::new(move |r| tx.send(r).unwrap()) }; + let key = avatar_key("ABCDEF0123").unwrap(); + assert_eq!(key, "avatars/abcdef0123"); + let Fetch::Download(temp) = cache.fetch(&key, waiter(tx.clone())) else { panic!() }; + // A second asker waits for the same download. + assert!(matches!(cache.fetch(&key, waiter(tx.clone())), Fetch::Waiting)); + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, b"png").unwrap(); + cache.finish(&key, &temp, Ok(()), 0); + let a = rx.recv().unwrap().unwrap(); + let b = rx.recv().unwrap().unwrap(); + assert_eq!(a, b); + assert_eq!(std::fs::read(&a).unwrap(), b"png"); + assert!(!temp.exists()); + assert!(matches!(cache.fetch(&key, waiter(tx)), Fetch::Cached)); + assert_eq!(rx.recv().unwrap().unwrap(), a); + assert_eq!(cache.get(&key), Some(a)); + assert_eq!(cache.size(), 3); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn failed_download_answers_everyone_and_retries() { + let dir = temp_dir("fail"); + let cache = Cache::new(&dir); + let (tx, rx) = mpsc::channel(); + let tx2 = tx.clone(); + let Fetch::Download(temp) = cache.fetch("icons/7", Box::new(move |r| tx.send(r).unwrap())) + else { + panic!() + }; + assert!(matches!( + cache.fetch("icons/7", Box::new(move |r| tx2.send(r).unwrap())), + Fetch::Waiting + )); + cache.finish("icons/7", &temp, Err("file not found".into()), 0); + assert_eq!(rx.recv().unwrap(), Err("file not found".into())); + assert_eq!(rx.recv().unwrap(), Err("file not found".into())); + assert!(cache.get("icons/7").is_none()); + assert!(matches!(cache.fetch("icons/7", Box::new(|_| {})), Fetch::Download(_))); + } + + #[test] + fn evicts_least_recently_used_and_survives_restart() { + let dir = temp_dir("lru"); + let cache = Cache::new(&dir); + let a = put(&cache, "icons/1", 400, 1000); + let b = put(&cache, "icons/2", 400, 1000); + // `a` is used again: `b` is now the oldest. + assert_eq!(cache.get("icons/1"), Some(a.clone())); + let c = put(&cache, "icons/3", 400, 1000); + assert!(a.exists() && c.exists()); + assert!(!b.exists(), "the least recently used file goes"); + assert_eq!(cache.size(), 800); + // No limit: nothing goes. + put(&cache, "icons/4", 5000, 0); + assert_eq!(cache.size(), 5800); + // A new instance finds the files. + let again = Cache::new(&dir); + assert_eq!(again.size(), 5800); + assert_eq!(again.get("icons/3"), Some(c)); + // A file bigger than the limit stays until the next one comes. + put(&again, "icons/5", 3000, 1000); + assert_eq!(again.size(), 3000); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn keys() { + assert!(avatar_key("").is_none()); + assert!(avatar_key("../x").is_none()); + assert_eq!(icon_key(4_294_967_295), "icons/4294967295"); + } +} diff --git a/crates/voelin-core/src/contacts.rs b/crates/voelin-core/src/contacts.rs new file mode 100644 index 0000000..fd51969 --- /dev/null +++ b/crates/voelin-core/src/contacts.rs @@ -0,0 +1,427 @@ +//! Contacts: friends, blocked people and per-person settings, by unique id, +//! across all sessions. +//! +//! # Contract for the UI +//! +//! - [`crate::Command::SetContact`] adds or changes a contact (all fields; +//! `added_ms` 0 is set to now; `last_seen_*` and an empty nickname keep the stored +//! one), [`crate::Command::RemoveContact`] removes it. Both, and loading +//! the contacts of a newly attached database, emit +//! [`crate::Event::ContactsChanged`] with the full list; +//! [`crate::Engine::contacts`] reads it any time. +//! - [`crate::Event::FriendPresence`] tells where a friend is: every +//! session whose presence (voice, gateway or query) shows them, with +//! client, channel, away and streaming state; an empty list when they +//! left the last one. It comes when that changes, and for every friend +//! when the contacts change. +//! - Blocked contacts: their server and channel messages are reported with +//! [`voelin_model::ChatMessage::blocked`] set (live and from history); +//! their private messages and pokes are dropped or flagged per +//! `privacy.block_mode`. +//! - A contact's `muted` and `volume` apply to their voice in every session +//! (as [`crate::Command::SetClientMuted`] / `SetClientVolume` would). +//! - `stream.permissions = friends` accepts friends' requests to watch our +//! stream and asks for everyone else. +//! +//! Contacts live in the client database ([`crate::History`]'s, table +//! `contacts`), in memory for lookups. When a contact appears on or leaves a +//! server, `last_seen_ms` / `last_server` are updated (in one write per +//! presence change). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::{Arc, Mutex, PoisonError}; + +use serde::Serialize; +use tokio::sync::{broadcast, watch}; +use tracing::warn; +use voelin_model::{ChannelId, Presence}; +use voelin_store::ContactSeen; +pub use voelin_store::{Contact, Relation}; + +use crate::history::{self, SharedHistory}; +use crate::{Event, SessionId}; + +/// Where a friend is in one session. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct FriendSpot { + pub session: SessionId, + /// The server's name as the session sees it. + pub server_name: String, + pub client: u16, + pub nickname: String, + pub channel: ChannelId, + pub channel_name: String, + /// Away, with the message (empty without one). + pub away: Option, + pub streaming: bool, +} + +#[derive(Default)] +struct Inner { + contacts: HashMap, + /// Last presence per session. + sessions: BTreeMap>, + /// Contacts present per session (for sightings). + present: HashMap>, + /// Friends' spots as last reported (friends seen somewhere only). + reported: HashMap>, +} + +/// See the [module docs](self). Cheap to clone. +#[derive(Clone)] +pub(crate) struct Contacts { + inner: Arc>, + events: broadcast::Sender, + history: SharedHistory, + /// Bumped on every change of the contacts, for sessions. + revision: watch::Sender, +} + +impl Contacts { + pub fn new(events: broadcast::Sender, history: SharedHistory) -> Self { + Self { inner: Arc::default(), events, history, revision: watch::Sender::new(0) } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Told on every change of the contacts. + pub fn watch(&self) -> watch::Receiver { + self.revision.subscribe() + } + + pub fn list(&self) -> Vec { + let mut list: Vec<_> = self.lock().contacts.values().cloned().collect(); + list.sort_by(|a, b| a.uid.cmp(&b.uid)); + list + } + + pub fn get(&self, uid: &str) -> Option { + self.lock().contacts.get(uid).cloned() + } + + pub fn relation(&self, uid: &str) -> Relation { + self.lock().contacts.get(uid).map_or(Relation::Neutral, |c| c.relation) + } + + pub fn is_blocked(&self, uid: Option<&str>) -> bool { + uid.is_some_and(|uid| self.relation(uid) == Relation::Blocked) + } + + /// Read the contacts of the current database (after it was attached). + pub fn load(&self) { + let this = self.clone(); + self.history.current().run_then( + false, + |s| s.contacts(), + move |result| match result { + Ok(list) => { + this.lock().contacts = list.into_iter().map(|c| (c.uid.clone(), c)).collect(); + this.changed(); + } + Err(e) => warn!("cannot read contacts: {e}"), + }, + ); + } + + /// Add or change a contact. + pub fn set(&self, mut contact: Contact) { + { + let mut inner = self.lock(); + if let Some(old) = inner.contacts.get(&contact.uid) { + if contact.added_ms == 0 { + contact.added_ms = old.added_ms; + } + if contact.nickname.is_empty() { + contact.nickname = old.nickname.clone(); + } + contact.last_seen_ms = contact.last_seen_ms.max(old.last_seen_ms); + if contact.last_server.is_none() { + contact.last_server = old.last_server.clone(); + } + } + if contact.added_ms == 0 { + contact.added_ms = history::now_ms(); + } + inner.contacts.insert(contact.uid.clone(), contact.clone()); + } + self.history.current().run_then( + false, + move |s| s.put_contact(&contact), + |r| { + if let Err(e) = r { + warn!("cannot store a contact: {e}"); + } + }, + ); + self.changed(); + } + + pub fn remove(&self, uid: &str) { + if self.lock().contacts.remove(uid).is_none() { + return; + } + let uid = uid.to_owned(); + self.history.current().run_then( + false, + move |s| s.delete_contact(&uid), + |r| { + if let Err(e) = r { + warn!("cannot remove a contact: {e}"); + } + }, + ); + self.changed(); + } + + /// The contacts changed: tell the UI and the sessions, update friends. + fn changed(&self) { + self.revision.send_modify(|r| *r += 1); + let _ = self.events.send(Event::ContactsChanged { contacts: Arc::new(self.list()) }); + self.update_friends(true); + } + + /// A session published presence (empty when it has none). + pub fn presence(&self, session: SessionId, presence: Arc) { + let now = history::now_ms(); + let server = Some(presence.server_name.clone()).filter(|n| !n.is_empty()); + let seen = { + let mut inner = self.lock(); + let here: HashMap<&str, &str> = presence + .clients + .values() + .filter_map(|c| { + let uid = c.uid.as_deref()?; + inner.contacts.contains_key(uid).then_some((uid, c.nickname.as_str())) + }) + .collect(); + let before = inner.present.remove(&session).unwrap_or_default(); + // Sightings: contacts that came or went. + let mut seen: Vec = Vec::new(); + for (uid, nick) in &here { + if !before.contains(*uid) { + seen.push(ContactSeen { + uid: (*uid).to_owned(), + nickname: (*nick).to_owned(), + ts_ms: now, + server: server.clone(), + }); + } + } + for uid in before.iter().filter(|u| !here.contains_key(u.as_str())) { + seen.push(ContactSeen { + uid: uid.clone(), + nickname: String::new(), + ts_ms: now, + server: server.clone(), + }); + } + for s in &seen { + if let Some(c) = inner.contacts.get_mut(&s.uid) { + c.last_seen_ms = c.last_seen_ms.max(now); + if server.is_some() { + c.last_server = server.clone(); + } + if !s.nickname.is_empty() { + c.nickname = s.nickname.clone(); + } + } + } + let present = here.keys().map(|u| (*u).to_owned()).collect(); + inner.present.insert(session, present); + inner.sessions.insert(session, presence); + seen + }; + if !seen.is_empty() { + self.history.current().run_then( + false, + move |s| s.touch_contacts(&seen), + |r| { + if let Err(e) = r { + warn!("cannot store when contacts were seen: {e}"); + } + }, + ); + } + self.update_friends(false); + } + + /// A session ended: its friends are gone from it. + pub fn session_closed(&self, session: SessionId) { + self.presence(session, Arc::new(Presence::default())); + { + let mut inner = self.lock(); + inner.sessions.remove(&session); + inner.present.remove(&session); + } + self.update_friends(false); + } + + /// Report friends whose spots changed (every friend with `all`). + fn update_friends(&self, all: bool) { + let mut out: Vec<(String, Vec)> = Vec::new(); + { + let inner = &mut *self.lock(); + let friends: HashSet = inner + .contacts + .values() + .filter(|c| c.relation == Relation::Friend) + .map(|c| c.uid.clone()) + .collect(); + let mut now: HashMap> = HashMap::new(); + for (session, presence) in &inner.sessions { + for (uid, spot) in spots_in(*session, presence, &friends) { + now.entry(uid).or_default().push(spot); + } + } + let mut uids: HashSet = now.keys().cloned().collect(); + uids.extend(inner.reported.keys().cloned()); + if all { + uids.extend(friends.iter().cloned()); + } + for uid in uids { + let spots = now.remove(&uid).unwrap_or_default(); + let before = inner.reported.get(&uid); + if !all && before.map_or(spots.is_empty(), |b| *b == spots) { + continue; + } + if spots.is_empty() { + inner.reported.remove(&uid); + } else { + inner.reported.insert(uid.clone(), spots.clone()); + } + out.push((uid, spots)); + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + for (uid, sessions) in out { + let _ = self.events.send(Event::FriendPresence { uid, sessions }); + } + } +} + +/// Friends' spots in one session's presence. +fn spots_in( + session: SessionId, + presence: &Presence, + friends: &HashSet, +) -> HashMap { + let mut spots = HashMap::new(); + for c in presence.clients.values() { + let Some(uid) = c.uid.as_ref().filter(|u| friends.contains(*u)) else { continue }; + // Several connections of one identity: the first. + spots.entry(uid.clone()).or_insert_with(|| FriendSpot { + session, + server_name: presence.server_name.clone(), + client: c.id, + nickname: c.nickname.clone(), + channel: c.channel, + channel_name: presence + .channels + .get(&c.channel) + .map(|ch| ch.name.clone()) + .unwrap_or_default(), + away: c.away.clone(), + streaming: c.streaming.unwrap_or(false), + }); + } + spots +} + +#[cfg(test)] +mod tests { + use voelin_model::{ChannelInfo, ClientInfo}; + + use super::*; + use crate::History; + + fn presence(server: &str, clients: &[(u16, &str, &str)]) -> Arc { + let mut p = Presence { server_name: server.into(), ..Presence::default() }; + p.channels.insert(1, ChannelInfo { id: 1, name: "Lobby".into(), ..Default::default() }); + for (id, uid, nick) in clients { + let c = ClientInfo { + id: *id, + uid: Some((*uid).into()), + nickname: (*nick).into(), + channel: 1, + ..Default::default() + }; + p.clients.insert(*id, c); + } + Arc::new(p) + } + + fn friend(uid: &str) -> Contact { + Contact { relation: Relation::Friend, ..Contact::new(uid) } + } + + type Spots = Vec<(SessionId, u16)>; + + /// The friend events so far: uid and (session, client) per spot. + fn friend_events(rx: &mut broadcast::Receiver) -> Vec<(String, Spots)> { + let mut out = Vec::new(); + while let Ok(e) = rx.try_recv() { + if let Event::FriendPresence { uid, sessions } = e { + out.push((uid, sessions.iter().map(|s| (s.session, s.client)).collect())); + } + } + out + } + + #[tokio::test] + async fn friends_across_sessions() { + let (events, mut rx) = broadcast::channel(64); + let history = SharedHistory::new(History::in_memory()); + let contacts = Contacts::new(events, history.clone()); + contacts.set(friend("f=")); + contacts.set(Contact { relation: Relation::Blocked, ..Contact::new("b=") }); + assert_eq!(contacts.relation("b="), Relation::Blocked); + assert!(contacts.is_blocked(Some("b="))); + assert!(!contacts.is_blocked(Some("f=")) && !contacts.is_blocked(None)); + // Changing the contacts reports every friend (offline here). + assert!(friend_events(&mut rx).contains(&("f=".into(), vec![]))); + + contacts.presence(1, presence("A", &[(5, "f=", "Fred"), (6, "x=", "X")])); + assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(1, 5)])]); + // Nothing new: nothing reported. + contacts.presence(1, presence("A", &[(5, "f=", "Fred"), (7, "y=", "Y")])); + assert!(friend_events(&mut rx).is_empty()); + contacts.presence(2, presence("B", &[(9, "f=", "Fred")])); + assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(1, 5), (2, 9)])]); + contacts.session_closed(1); + assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(2, 9)])]); + // No friend any more: reported gone. + contacts.set(Contact::new("f=")); + assert!(friend_events(&mut rx).contains(&("f=".into(), vec![]))); + + // Sightings reach the database. + history.current().flush(); + let stored = history.current().run(false, |s| s.contact("f=")).await.unwrap().unwrap(); + assert_eq!(stored.last_server.as_deref(), Some("B")); + assert_eq!(stored.nickname, "Fred"); + assert!(stored.last_seen_ms > 0 && stored.added_ms > 0); + } + + #[tokio::test] + async fn load_and_remove() { + let (events, mut rx) = broadcast::channel(64); + let history = SharedHistory::new(History::in_memory()); + history.current().run(false, |s| s.put_contact(&friend("a="))).await.unwrap(); + let contacts = Contacts::new(events, history.clone()); + let mut revision = contacts.watch(); + contacts.load(); + let loaded = loop { + if let Event::ContactsChanged { contacts } = rx.recv().await.unwrap() { + break contacts; + } + }; + assert_eq!(loaded.len(), 1); + assert!(revision.has_changed().unwrap()); + revision.mark_unchanged(); + contacts.remove("a="); + assert!(revision.has_changed().unwrap()); + assert!(contacts.list().is_empty()); + assert!(history.current().run(false, |s| s.contacts()).await.unwrap().is_empty()); + } +} diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs new file mode 100644 index 0000000..95a95ef --- /dev/null +++ b/crates/voelin-core/src/files.rs @@ -0,0 +1,482 @@ +//! Files in channels, avatars and icons (voice connection, TeamSpeak 3 and 6). +//! +//! # Contract for the UI +//! +//! File browser requests carry a [`RequestId`] the caller picks, transfers +//! a [`TransferId`]; answers carry them back: +//! +//! - [`crate::Command::ListFiles`] → [`crate::Event::FileList`] (an empty +//! directory is an empty list, not an error). +//! - [`crate::Command::DeleteFiles`], [`crate::Command::RenameFile`], +//! [`crate::Command::CreateDirectory`] → [`crate::Event::RequestDone`]. +//! - [`crate::Command::DownloadFile`], [`crate::Command::DownloadChatFile`] +//! (a file linked in chat, [`voelin_model::FileRef`]), +//! [`crate::Command::UploadFile`] → [`crate::Event::Transfer`]: +//! `Requested`, `Started`, `Progress` (every `files.progress_interval_ms`), +//! then `Done`, `Failed` or `Cancelled` ([`crate::Command::CancelTransfer`]). +//! +//! Downloads stream to disk: into `.part`, renamed to `` when +//! complete (with `resume`, an existing `.part` is continued). Downloads +//! into memory ([`DownloadTo::Memory`]) come back in `Done`. Uploads read +//! the file as they send it. There is no size limit besides the server's +//! quotas. +//! +//! Paths on the server start with `/` (`/docs/report.pdf`); channel 0 holds +//! the server's avatars and icons. +//! +//! Avatars and icons are fetched by themselves (setting +//! `cache.fetch_images`) into the engine's cache ([`crate::cache`]): +//! [`crate::Event::AvatarReady`] when a client's avatar is there (again when +//! its hash changes), [`crate::Event::IconReady`] for every icon a server, +//! group, channel or client uses (ids below 1000 are built into clients and +//! never downloaded). [`crate::Command::SetAvatar`] uploads our own. + +use std::fmt; +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; + +/// Picked by the caller; the answer carries it back. +pub type RequestId = u64; +/// Picked by the caller; the transfer's events carry it. +pub type TransferId = u64; + +/// One entry of a directory listing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct FileEntry { + pub name: String, + /// Bytes (0 for directories). + pub size: u64, + /// Unix seconds of the last change. + pub modified_s: i64, + pub is_dir: bool, +} + +/// Bytes of a download into memory. +#[derive(Clone, PartialEq, Eq)] +pub struct Bytes(pub Arc<[u8]>); + +impl fmt::Debug for Bytes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Bytes({} bytes)", self.0.len()) + } +} + +/// Where a download goes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DownloadTo { + /// A file (written as `.part` until complete). `resume`: continue + /// an existing `.part`. + Path { path: PathBuf, resume: bool }, + /// Memory: the bytes come in [`TransferState::Done`]. + Memory, +} + +/// A transfer's progress. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TransferState { + /// Asked the server. + Requested, + /// Data flows; `offset` bytes were there before (resume). + Started { + size: u64, + offset: u64, + }, + Progress { + done: u64, + size: u64, + }, + Done { + size: u64, + path: Option, + data: Option, + }, + Failed(String), + Cancelled, +} + +impl TransferState { + pub fn is_final(&self) -> bool { + matches!(self, Self::Done { .. } | Self::Failed(_) | Self::Cancelled) + } +} + +/// Reports a transfer's states. +pub(crate) type Report = Arc; + +/// Where a running download writes. +#[derive(Clone, Debug)] +pub(crate) enum Sink { + /// Write `part` (appending with `append`), then rename it to `dest`. + File { + part: PathBuf, + dest: PathBuf, + append: bool, + }, + Memory, +} + +impl Sink { + pub fn from_target(to: &DownloadTo) -> Self { + match to { + DownloadTo::Path { path, resume } => { + let mut part = path.clone().into_os_string(); + part.push(".part"); + Sink::File { part: part.into(), dest: path.clone(), append: *resume } + } + DownloadTo::Memory => Sink::Memory, + } + } + + /// Bytes already there to resume from. + pub fn offset(&self) -> u64 { + match self { + Sink::File { part, append: true, .. } => std::fs::metadata(part).map_or(0, |m| m.len()), + _ => 0, + } + } + + /// The partial file to remove when a transfer is cancelled. + pub fn part(&self) -> Option<&Path> { + match self { + Sink::File { part, .. } => Some(part), + Sink::Memory => None, + } + } +} + +/// Rate limit for progress reports. +struct Progress<'a> { + report: &'a Report, + every: Duration, + last: Instant, +} + +impl Progress<'_> { + fn update(&mut self, done: u64, size: u64) { + if self.last.elapsed() >= self.every { + self.last = Instant::now(); + (self.report)(TransferState::Progress { done, size }); + } + } +} + +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, + size: u64, + offset: u64, + sink: Sink, + progress_every: Duration, + report: Report, +) { + report(TransferState::Started { size, offset }); + let result = receive(&mut stream, size, offset, &sink, progress_every, &report).await; + report(match result { + Ok(done) => done, + Err(e) => TransferState::Failed(e), + }); +} + +async fn receive( + stream: &mut TcpStream, + size: u64, + offset: u64, + sink: &Sink, + progress_every: Duration, + report: &Report, +) -> Result { + let mut progress = Progress { report, every: progress_every, last: Instant::now() }; + let mut buf = vec![0u8; CHUNK]; + let mut done = offset; + match sink { + Sink::File { part, dest, append } => { + if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) { + tokio::fs::create_dir_all(dir) + .await + .map_err(|e| format!("{}: {e}", dir.display()))?; + } + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .write(true) + .append(*append) + .truncate(!*append) + .open(part) + .await + .map_err(|e| format!("{}: {e}", part.display()))?; + let received = async { + while done < size { + let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?; + if n == 0 { + return Err(format!("connection closed after {done} of {size} bytes")); + } + let data = &buf[..n]; + file.write_all(data).await.map_err(|e| format!("{}: {e}", part.display()))?; + done += n as u64; + progress.update(done, size); + } + Ok(()) + } + .await; + // What arrived stays in the part (to resume), also after an error. + let flushed = file.flush().await.map_err(|e| e.to_string()); + drop(file); + received?; + flushed?; + if part != dest { + tokio::fs::rename(part, dest) + .await + .map_err(|e| format!("{}: {e}", dest.display()))?; + } + Ok(TransferState::Done { size, path: Some(dest.clone()), data: None }) + } + Sink::Memory => { + let mut data = Vec::with_capacity(usize::try_from(size).unwrap_or(0).min(1 << 24)); + while done < size { + let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?; + if n == 0 { + return Err(format!("connection closed after {done} of {size} bytes")); + } + data.extend_from_slice(&buf[..n]); + done += n as u64; + progress.update(done, size); + } + Ok(TransferState::Done { size, path: None, data: Some(Bytes(data.into())) }) + } + } +} + +/// Send `file` from `offset` (`size` bytes in total). Reports `Started`, +/// `Progress` and the final state. +pub(crate) async fn upload( + mut stream: TcpStream, + file: PathBuf, + size: u64, + offset: u64, + progress_every: Duration, + report: Report, +) { + report(TransferState::Started { size, offset }); + let result = send(&mut stream, &file, size, offset, progress_every, &report).await; + report(match result { + Ok(()) => TransferState::Done { size, path: Some(file), data: None }, + Err(e) => TransferState::Failed(e), + }); +} + +async fn send( + stream: &mut TcpStream, + path: &Path, + size: u64, + offset: u64, + progress_every: Duration, + report: &Report, +) -> Result<(), String> { + let mut progress = Progress { report, every: progress_every, last: Instant::now() }; + let mut file = + tokio::fs::File::open(path).await.map_err(|e| format!("{}: {e}", path.display()))?; + if offset > 0 { + file.seek(std::io::SeekFrom::Start(offset)).await.map_err(|e| e.to_string())?; + } + let mut buf = vec![0u8; CHUNK]; + let mut done = offset; + while done < size { + let want = usize::try_from(size - done).unwrap_or(CHUNK).min(CHUNK); + let n = + file.read(&mut buf[..want]).await.map_err(|e| format!("{}: {e}", path.display()))?; + if n == 0 { + return Err(format!("{} shrank while uploading", path.display())); + } + stream.write_all(&buf[..n]).await.map_err(|e| e.to_string())?; + done += n as u64; + progress.update(done, size); + } + 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(()) +} + +/// A file's MD5 (hex), as `client_flag_avatar` names an avatar. +pub(crate) fn md5_file(path: &Path) -> std::io::Result { + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut ctx = md5::Context::new(); + let mut buf = vec![0u8; CHUNK]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + ctx.consume(&buf[..n]); + } + Ok(format!("{:x}", ctx.finalize())) +} + +/// The avatar file of a client on the server: `/avatar_` and the unique +/// id's bytes as letters `a` to `p` (one per nibble), as TeamSpeak 3 and 6 +/// servers store them (verified against 3.13.8 and 6.0.0-beta13.1). +pub fn avatar_path(uid: &str) -> Option { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD.decode(uid.trim()).ok()?; + let mut path = String::with_capacity(8 + bytes.len() * 2); + path.push_str("/avatar_"); + for b in bytes { + path.push(char::from(b'a' + (b >> 4))); + path.push(char::from(b'a' + (b & 0x0f))); + } + Some(path) +} + +/// The file of an icon on the server. +pub fn icon_path(id: u32) -> String { + format!("/icon_{id}") +} + +/// Icons below this id are built into clients (group icons 100 to 600). +pub const FIRST_DOWNLOADABLE_ICON: u32 = 1000; + +/// `dir` and `name` joined as a server path (`/dir/name`). +pub fn join_path(dir: &str, name: &str) -> String { + let dir = dir.trim_end_matches('/'); + let name = name.trim_start_matches('/'); + format!("{dir}/{name}") +} + +/// A server path in the form the server echoes (`/` for the root, no +/// trailing slash otherwise). +pub(crate) fn normalize_dir(path: &str) -> String { + let trimmed = path.trim_end_matches('/'); + if trimmed.is_empty() { + "/".into() + } else if trimmed.starts_with('/') { + trimmed.into() + } else { + format!("/{trimmed}") + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use tokio::net::TcpListener; + + use super::*; + + #[test] + fn avatar_paths() { + // Two bytes 0x01 0xfe: "ab" "po". + assert_eq!(avatar_path("Af4=").as_deref(), Some("/avatar_abpo")); + assert_eq!(avatar_path("not base64!"), None); + assert_eq!(icon_path(123456), "/icon_123456"); + } + + #[test] + fn paths() { + assert_eq!(join_path("/", "a.txt"), "/a.txt"); + assert_eq!(join_path("/docs/", "/a.txt"), "/docs/a.txt"); + assert_eq!(normalize_dir(""), "/"); + assert_eq!(normalize_dir("/docs/"), "/docs"); + assert_eq!(normalize_dir("docs"), "/docs"); + } + + fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-files-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn recorder() -> (Report, Arc>>) { + let states = Arc::new(Mutex::new(Vec::new())); + let s = states.clone(); + (Arc::new(move |state| s.lock().unwrap().push(state)), states) + } + + /// A server that sends `data` on the first connection. + async fn serve(data: Vec) -> std::net::SocketAddr { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let (mut s, _) = listener.accept().await.unwrap(); + s.write_all(&data).await.unwrap(); + }); + addr + } + + #[tokio::test] + async fn downloads_to_disk_and_resumes() { + let dir = temp("download"); + let dest = dir.join("sub/file.bin"); + let data: Vec = (0..200_000u32).map(|i| i as u8).collect(); + // First half: the connection ends early; the part stays. + let addr = serve(data[..100_000].to_vec()).await; + let (report, states) = recorder(); + let target = DownloadTo::Path { path: dest.clone(), resume: false }; + let sink = Sink::from_target(&target); + let stream = TcpStream::connect(addr).await.unwrap(); + download(stream, data.len() as u64, 0, sink, Duration::ZERO, report).await; + let last = states.lock().unwrap().last().cloned().unwrap(); + assert!(matches!(last, TransferState::Failed(ref e) if e.contains("100000 of 200000"))); + assert!(!dest.exists()); + // Resume: the rest. + let target = DownloadTo::Path { path: dest.clone(), resume: true }; + let sink = Sink::from_target(&target); + assert_eq!(sink.offset(), 100_000); + let addr = serve(data[100_000..].to_vec()).await; + let (report, states) = recorder(); + let stream = TcpStream::connect(addr).await.unwrap(); + download(stream, data.len() as u64, 100_000, sink, Duration::ZERO, report).await; + let states = states.lock().unwrap().clone(); + assert_eq!(states[0], TransferState::Started { size: 200_000, offset: 100_000 }); + assert!(states.iter().any(|s| matches!(s, TransferState::Progress { .. }))); + assert_eq!( + states.last().unwrap(), + &TransferState::Done { size: 200_000, path: Some(dest.clone()), data: None } + ); + assert_eq!(std::fs::read(&dest).unwrap(), data); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn downloads_to_memory() { + let addr = serve(b"hello".to_vec()).await; + let (report, states) = recorder(); + let stream = TcpStream::connect(addr).await.unwrap(); + download(stream, 5, 0, Sink::Memory, Duration::from_secs(60), report).await; + let last = states.lock().unwrap().last().cloned().unwrap(); + let TransferState::Done { data: Some(Bytes(data)), .. } = last else { panic!("{last:?}") }; + assert_eq!(&*data, b"hello"); + } + + #[tokio::test] + async fn uploads_from_offset() { + let dir = temp("upload"); + let file = dir.join("up.bin"); + std::fs::write(&file, b"0123456789").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut s, _) = listener.accept().await.unwrap(); + let mut got = Vec::new(); + s.read_to_end(&mut got).await.unwrap(); + got + }); + let (report, states) = recorder(); + let stream = TcpStream::connect(addr).await.unwrap(); + upload(stream, 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"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index f35e14a..2d4a9c3 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -65,7 +65,7 @@ pub(crate) enum GatewayCmd { pub(crate) enum GatewayEvent { /// Logged in; requests go through `client`. Connected(GatewayClient), - Presence(Presence), + Presence(Box), /// A push other than presence. Push(Box), Disconnected(Option), @@ -132,11 +132,11 @@ async fn run_inner( Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason), Some(Push::PresenceSnapshot(snapshot)) => { presence = Presence::from_snapshot(snapshot); - let _ = events.send(GatewayEvent::Presence(presence.clone())); + let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone()))); } Some(Push::PresenceDelta(delta)) => { presence.apply(&delta); - let _ = events.send(GatewayEvent::Presence(presence.clone())); + let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone()))); } // Answers to requests sent without waiting. Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {} diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs index a9d0397..0543467 100644 --- a/crates/voelin-core/src/history.rs +++ b/crates/voelin-core/src/history.rs @@ -62,6 +62,7 @@ pub use voelin_store::MessageSource; use voelin_store::{ChatCursor, WriteOutcome}; use voelin_store::{NewMessage, PageQuery, Reaction, RemoteInfo, Store, StoredMessage, Written}; +use crate::contacts::Contacts; use crate::gateway::{GatewayClient, GatewayUpdate}; use crate::settings::{CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_STORE_HISTORY, Settings}; use crate::{Event, SessionId}; @@ -125,6 +126,7 @@ impl From for HistoryMessage { text: m.text, ts_ms: m.ts_ms, via_relay: m.via_relay, + blocked: false, }, source: m.source, remote_id: m.remote_id, @@ -471,6 +473,8 @@ pub(crate) struct ChatCtx { pub settings: Settings, /// The key of the server's history. pub server_uid: String, + /// Messages of blocked contacts are flagged. + pub contacts: Contacts, } impl ChatCtx { @@ -499,6 +503,10 @@ impl ChatCtx { source: HistorySource, complete: bool, ) { + let mut messages = messages; + for m in &mut messages { + m.message.blocked = self.contacts.is_blocked(m.message.author_uid.as_deref()); + } self.emit(Event::ChatHistory { session: self.session, target: target.clone(), @@ -523,12 +531,15 @@ impl ChatCtx { /// [`HistorySource::Live`] from the writer thread. pub fn store_live(&self, messages: Vec) { let (session, events) = (self.session, self.events.clone()); + let contacts = self.contacts.clone(); self.history.write(self.memory(), messages, self.tolerance_ms(), move |result| { for w in result.unwrap_or_default() { if w.outcome == WriteOutcome::Unchanged { continue; } - let message = HistoryMessage::from(w.message); + let mut message = HistoryMessage::from(w.message); + message.message.blocked = + contacts.is_blocked(message.message.author_uid.as_deref()); let _ = events.send(Event::ChatHistory { session, target: message.message.target.clone(), @@ -757,6 +768,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, }; new_message("srv", &msg, MessageSource::Voice) } diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index d3ceb1b..c2de11e 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -32,12 +32,24 @@ //! (pins, reactions, topics, events, stream directory, activity, //! administration) are [`Command::Gateway`] requests and //! [`Event::Gateway`] updates ([`gateway`]). +//! +//! The voice connection also carries pokes ([`Command::Poke`], +//! [`Event::Poke`]), private messages to any client (a +//! [`ChatTarget::Private`] chat, stored under the peer's unique id), the +//! channels' file browsers, avatars and icons ([`files`], cached in +//! [`cache`]) and offline messages ([`offline`]). Contacts (friends, +//! blocked people, per-person volume) are engine-wide ([`contacts`]). mod audio; +mod book; +pub mod cache; +pub mod contacts; +pub mod files; pub mod gateway; pub mod history; #[cfg(feature = "media")] pub mod media; +pub mod offline; mod query; mod route; mod session; @@ -46,17 +58,27 @@ pub mod stream; mod voice; use std::collections::HashMap; +use std::path::PathBuf; use std::sync::Arc; use tokio::sync::{broadcast, mpsc}; pub use voelin_audio::settings::TransmitMode; pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings}; -use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; +use voelin_model::{ + Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails, + ServerFlavor, +}; use crate::audio::{AudioEvent, AudioHandle, AudioIn}; +pub use cache::Cache; +use cache::SharedCache; +use contacts::Contacts; +pub use contacts::{Contact, FriendSpot, Relation}; +pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferState}; pub use gateway::{GatewayRequest, GatewayUpdate}; use history::SharedHistory; pub use history::{History, HistoryMessage, HistorySource}; +pub use offline::{OfflineMessage, OfflineMessageInfo}; pub use route::{ChatRoute, Dedup, route_chat}; use settings::{SettingChange, Settings, SharedSettings}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; @@ -223,10 +245,141 @@ pub enum Command { stream_id: String, volume: f32, }, + /// Poke a client (voice): the server shows it a notification with + /// `message`. Failures come as [`Event::Error`]. + Poke { + session: SessionId, + client: u16, + message: String, + }, + /// List a directory of a channel's files (voice; `path` `/` for the + /// root), answered with [`Event::FileList`]. See [`files`]. + ListFiles { + session: SessionId, + request: RequestId, + channel: ChannelId, + password: Option, + path: String, + }, + /// Download a channel's file (`path` like `/dir/name`); progress as + /// [`Event::Transfer`]. + DownloadFile { + session: SessionId, + transfer: TransferId, + channel: ChannelId, + password: Option, + path: String, + to: DownloadTo, + }, + /// Download a file linked in chat ([`ChatMessage::file_refs`]); fails if + /// the link names another server. + DownloadChatFile { + session: SessionId, + transfer: TransferId, + file: FileRef, + password: Option, + to: DownloadTo, + }, + /// Upload a local file as `path` in a channel; progress as + /// [`Event::Transfer`]. `resume` continues a partial upload. + UploadFile { + session: SessionId, + transfer: TransferId, + channel: ChannelId, + password: Option, + path: String, + from: PathBuf, + overwrite: bool, + resume: bool, + }, + /// Stop a transfer ([`TransferState::Cancelled`]); a partial download is + /// deleted. + CancelTransfer { + session: SessionId, + transfer: TransferId, + }, + /// Delete files or directories of a channel ([`Event::RequestDone`]). + DeleteFiles { + session: SessionId, + request: RequestId, + channel: ChannelId, + password: Option, + paths: Vec, + }, + /// Rename or move a file, also into another channel + /// (`to_channel`: channel and its password) ([`Event::RequestDone`]). + RenameFile { + session: SessionId, + request: RequestId, + channel: ChannelId, + password: Option, + from: String, + to: String, + to_channel: Option<(ChannelId, Option)>, + }, + CreateDirectory { + session: SessionId, + request: RequestId, + channel: ChannelId, + password: Option, + path: String, + }, + /// Our avatar (voice): upload `image` and announce it, or remove it + /// (`None`) ([`Event::RequestDone`]). + SetAvatar { + session: SessionId, + request: RequestId, + image: Option, + }, + /// Report a client's avatar again ([`Event::AvatarReady`]), fetching it + /// if needed (avatars are also fetched by themselves, setting + /// `cache.fetch_images`). + FetchAvatar { + session: SessionId, + client_uid: String, + }, + /// Our offline messages ([`Event::OfflineMessages`]); see [`offline`]. + ListOfflineMessages { + session: SessionId, + request: RequestId, + }, + GetOfflineMessage { + session: SessionId, + request: RequestId, + id: u32, + }, + SendOfflineMessage { + session: SessionId, + request: RequestId, + to_uid: String, + subject: String, + text: String, + }, + DeleteOfflineMessage { + session: SessionId, + request: RequestId, + id: u32, + }, + SetOfflineMessageRead { + session: SessionId, + request: RequestId, + id: u32, + read: bool, + }, /// Close everything of a session. CloseSession { session: SessionId, }, + /// Add or change a contact (engine-wide; see [`contacts`]). + SetContact { + contact: Box, + }, + RemoveContact { + uid: String, + }, + /// Keep avatars and icons in this directory from now on (default: + /// [`Cache::default_dir`]). + AttachCache(PathBuf), /// Set a setting's runtime value (see [`settings`]); invalid values are /// reported as [`Event::SettingRejected`]. SetSetting { @@ -404,6 +557,87 @@ pub enum Event { key: String, message: String, }, + /// The server's details changed (also in [`Presence::server`]; voice). + ServerDetails { + session: SessionId, + details: Arc, + }, + /// The server or channel groups changed (also in the presence; voice), + /// in display order. + Groups { + session: SessionId, + server_groups: Arc>, + channel_groups: Arc>, + }, + /// Someone poked us. With `blocked` (their contact is blocked, + /// `privacy.block_mode = flag`); with `hide` it never comes. + Poke { + session: SessionId, + from: u16, + from_uid: Option, + from_name: String, + message: String, + blocked: bool, + }, + /// Answer to [`Command::ListFiles`]. + FileList { + session: SessionId, + request: RequestId, + channel: ChannelId, + /// The listed directory (`/` or `/dir`, no trailing slash). + path: String, + result: Result, String>, + }, + /// A transfer's progress ([`Command::DownloadFile`], `UploadFile`, …). + Transfer { + session: SessionId, + transfer: TransferId, + state: TransferState, + }, + /// Answer to a request without data (file operations, avatar, offline + /// messages). + RequestDone { + session: SessionId, + request: RequestId, + result: Result<(), String>, + }, + /// A client's avatar is in the cache: `path`, its MD5 `hash` + /// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears + /// with an avatar and when it changes. + AvatarReady { + session: SessionId, + client_uid: String, + path: PathBuf, + hash: String, + }, + /// An icon (server, group, channel or client) is in the cache. + IconReady { + session: SessionId, + icon: u32, + path: PathBuf, + }, + /// Answer to [`Command::ListOfflineMessages`]. + OfflineMessages { + session: SessionId, + request: RequestId, + result: Result, String>, + }, + /// Answer to [`Command::GetOfflineMessage`]. + OfflineMessage { + session: SessionId, + request: RequestId, + result: Result, + }, + /// All contacts, after every change. + ContactsChanged { + contacts: Arc>, + }, + /// Where a friend is now: one spot per session that sees them (empty: + /// nowhere). + FriendPresence { + uid: String, + sessions: Vec, + }, } /// Handle to the engine. Cheap to clone; all methods are non-blocking. @@ -413,8 +647,7 @@ pub struct Engine { events: broadcast::Sender, frames: broadcast::Sender, runtime: tokio::runtime::Handle, - settings: SharedSettings, - history: SharedHistory, + shared: Shared, } impl Engine { @@ -436,29 +669,37 @@ impl Engine { let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. let (frames, _) = broadcast::channel(4096); - let settings = SharedSettings::new(settings); let history = SharedHistory::new(history); - let shared = Shared { settings: settings.clone(), history: history.clone() }; - tokio::spawn(run(rx, events.clone(), frames.clone(), shared)); - Self { - commands, - events, - frames, - runtime: tokio::runtime::Handle::current(), - settings, + let shared = Shared { + settings: SharedSettings::new(settings), + contacts: Contacts::new(events.clone(), history.clone()), history, - } + cache: SharedCache::new(Cache::new(Cache::default_dir())), + }; + shared.contacts.load(); + tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone())); + Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared } } /// The chat history the engine uses. pub fn history(&self) -> History { - self.history.current() + self.shared.history.current() } /// The settings the engine uses (read, watch or change them directly; /// changes are reported as [`Event::SettingChanged`] all the same). pub fn settings(&self) -> Settings { - self.settings.current() + self.shared.settings.current() + } + + /// All contacts (as the last [`Event::ContactsChanged`] told). + pub fn contacts(&self) -> Vec { + self.shared.contacts.list() + } + + /// The avatar and icon cache the engine uses. + pub fn cache(&self) -> Cache { + self.shared.cache.current() } /// The runtime the engine runs on, for helpers started from other @@ -492,9 +733,12 @@ enum Input { } /// What the engine and its sessions share and commands can replace. -struct Shared { - settings: SharedSettings, - history: SharedHistory, +#[derive(Clone)] +pub(crate) struct Shared { + pub settings: SharedSettings, + pub history: SharedHistory, + pub cache: SharedCache, + pub contacts: Contacts, } /// Delete chat history past `chat.retention_days` (0: keep everything). @@ -516,9 +760,9 @@ async fn run( mut commands: mpsc::UnboundedReceiver, events: broadcast::Sender, frames: broadcast::Sender, - shared: Shared, + engine: Shared, ) { - let Shared { settings: shared, history } = shared; + let Shared { settings: shared, history, cache, contacts } = engine.clone(); let mut sessions: HashMap = HashMap::new(); let mut current = shared.current(); // Pruning: at start, then hourly (and when the setting changes). @@ -606,6 +850,20 @@ async fn run( Command::AttachHistory(new) => { history.replace(new.clone()); prune_history(¤t, &new); + // The contacts live in the same database. + contacts.load(); + continue; + } + Command::AttachCache(dir) => { + cache.replace(Cache::new(dir)); + continue; + } + Command::SetContact { contact } => { + contacts.set(*contact); + continue; + } + Command::RemoveContact { uid } => { + contacts.remove(&uid); continue; } ref command => command_session(command), @@ -624,8 +882,7 @@ async fn run( events.clone(), frames.clone(), settings.clone(), - shared.clone(), - history.clone(), + engine.clone(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -684,6 +941,22 @@ fn command_session(command: &Command) -> SessionId { | Command::SetStreamVolume { session, .. } | Command::SetClientVolume { session, .. } | Command::SetClientMuted { session, .. } + | Command::Poke { session, .. } + | Command::ListFiles { session, .. } + | Command::DownloadFile { session, .. } + | Command::DownloadChatFile { session, .. } + | Command::UploadFile { session, .. } + | Command::CancelTransfer { session, .. } + | Command::DeleteFiles { session, .. } + | Command::RenameFile { session, .. } + | Command::CreateDirectory { session, .. } + | Command::SetAvatar { session, .. } + | Command::FetchAvatar { session, .. } + | Command::ListOfflineMessages { session, .. } + | Command::GetOfflineMessage { session, .. } + | Command::SendOfflineMessage { session, .. } + | Command::DeleteOfflineMessage { session, .. } + | Command::SetOfflineMessageRead { session, .. } | Command::CloseSession { session } => *session, Command::SetAudioSettings(_) | Command::SetSrtpProfiles(_) @@ -691,7 +964,10 @@ fn command_session(command: &Command) -> SessionId { | Command::SetSetting { .. } | Command::ResetSetting { .. } | Command::AttachSettings(_) - | Command::AttachHistory(_) => { + | Command::AttachHistory(_) + | Command::AttachCache(_) + | Command::SetContact { .. } + | Command::RemoveContact { .. } => { unreachable!("engine-wide commands have no session") } } diff --git a/crates/voelin-core/src/offline.rs b/crates/voelin-core/src/offline.rs new file mode 100644 index 0000000..e767ab6 --- /dev/null +++ b/crates/voelin-core/src/offline.rs @@ -0,0 +1,39 @@ +//! Offline messages: mail the server keeps for a unique id until its owner +//! reads it (voice connection; TeamSpeak 3 and 6, capability +//! `offline_messages`). +//! +//! # Contract for the UI +//! +//! - [`crate::Command::ListOfflineMessages`] → [`crate::Event::OfflineMessages`] +//! (our inbox, without texts; empty is an empty list). +//! - [`crate::Command::GetOfflineMessage`] → [`crate::Event::OfflineMessage`] +//! (with the text; the server marks it read). +//! - [`crate::Command::SendOfflineMessage`], [`crate::Command::DeleteOfflineMessage`], +//! [`crate::Command::SetOfflineMessageRead`] → [`crate::Event::RequestDone`]. +//! +//! Servers do not announce new offline messages while we are connected; +//! list them after connecting and when the user opens the inbox. + +use serde::Serialize; + +/// An offline message in the inbox list. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct OfflineMessageInfo { + pub id: u32, + /// The sender's unique id. + pub from_uid: String, + pub subject: String, + /// Unix seconds when it was sent. + pub ts_s: i64, + pub read: bool, +} + +/// An offline message with its text. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct OfflineMessage { + pub id: u32, + pub from_uid: String, + pub subject: String, + pub text: String, + pub ts_s: i64, +} diff --git a/crates/voelin-core/src/query.rs b/crates/voelin-core/src/query.rs index 8b66d98..b048bfb 100644 --- a/crates/voelin-core/src/query.rs +++ b/crates/voelin-core/src/query.rs @@ -14,7 +14,7 @@ pub(crate) enum QueryCmd { } pub(crate) enum QueryEvent { - Presence(Presence), + Presence(Box), Chat(ChatMessage), Error(String), Disconnected, @@ -35,7 +35,7 @@ pub(crate) async fn run( e = observed.recv() => match e { Ok(ObserverEvent::Snapshot(_)) | Ok(ObserverEvent::Delta(_)) | Err(broadcast::error::RecvError::Lagged(_)) => { let presence = observer.presence().read().unwrap().clone(); - let _ = events.send(QueryEvent::Presence(presence)); + let _ = events.send(QueryEvent::Presence(Box::new(presence))); } Ok(ObserverEvent::Chat(msg)) => { if open.contains(&msg.target) { diff --git a/crates/voelin-core/src/route.rs b/crates/voelin-core/src/route.rs index 27ae3aa..8185dd5 100644 --- a/crates/voelin-core/src/route.rs +++ b/crates/voelin-core/src/route.rs @@ -26,7 +26,10 @@ pub fn route_chat( match target { ChatTarget::Server | ChatTarget::Private(_) if voice_channel.is_some() => ChatRoute::Voice, ChatTarget::Channel(cid) if voice_channel == Some(*cid) => ChatRoute::Voice, - ChatTarget::Private(_) => ChatRoute::Unavailable("private chat needs a voice connection"), + ChatTarget::Private(_) => ChatRoute::Unavailable( + "private messages need a voice connection (gateways and query relays cannot send them \ + as you; an offline message reaches clients who are away)", + ), _ if gateway => ChatRoute::Gateway, _ if query => ChatRoute::Query, ChatTarget::Channel(_) => ChatRoute::Unavailable( @@ -106,6 +109,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, } } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index fcbbb50..87d0d52 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -6,18 +6,22 @@ //! the address (`voice:
`, `gateway:`). The gateway's features //! are driven through its client ([`crate::gateway`]). -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::PathBuf; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc}; +use tokio::sync::{broadcast, mpsc, watch}; use tracing::debug; use tsclientlib::ClientId; use voelin_audio::AudioSettings; use voelin_gateway_proto::{HistoryEntry, StreamEntry, StreamSpec, feature}; -use voelin_model::{ChatMessage, ChatTarget, Presence}; +use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails}; use voelin_stream::ClientState; use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; +use crate::cache::{self, Fetch, SharedCache, Waiter}; +use crate::contacts::{Contacts, Relation}; +use crate::files::{self, DownloadTo, Report, RequestId, Sink, TransferId, TransferState}; use crate::gateway::{ self, ClientError, GatewayClient, GatewayCmd, GatewayEvent, GatewayRequest, GatewayUpdate, Push, ReactionPush, @@ -25,13 +29,25 @@ use crate::gateway::{ use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; -use crate::settings::SharedSettings; +use crate::settings::{ + BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, PRIVACY_BLOCK_MODE, SharedSettings, +}; use crate::stream::{ LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo, StreamInput, StreamKind, kind_name, parse_kind, }; -use crate::voice::{self, VoiceCmd, VoiceEvent}; -use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState}; +use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink}; +use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState}; + +const NO_VOICE: &str = "not connected with voice"; + +/// Server and channel groups in display order. +type Groups = (Arc>, Arc>); + +/// `cache.max_mb` in bytes (0: no limit). +fn max_cache_bytes(settings: &SharedSettings) -> u64 { + settings.current().get(&CACHE_MAX_MB).saturating_mul(1024 * 1024) +} pub(crate) struct SessionHandle { tx: mpsc::UnboundedSender, @@ -43,11 +59,10 @@ impl SessionHandle { events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, - settings: SharedSettings, - history: SharedHistory, + shared: Shared, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn(Session::new(id, events, frames, audio_settings, settings, history).run(rx)); + tokio::spawn(Session::new(id, events, frames, audio_settings, shared).run(rx)); Self { tx } } @@ -70,6 +85,8 @@ enum SourceEvent { Directory(u64, Result, ClientError>), /// The server's unique id the database remembers for an address. KnownServer(String), + /// Our avatar file is uploaded (its MD5) or failed: announce it. + AvatarUploaded(u64, RequestId, Result), } /// Our live stream, for the gateway's directory. @@ -123,6 +140,20 @@ struct Session { dedup: Dedup, sources_tx: mpsc::UnboundedSender, sources_rx: Option>, + cache: SharedCache, + contacts: Contacts, + contacts_rx: Option>, + /// Avatars reported per client unique id (their hash), voice only. + avatars: HashMap, + /// Icons reported or being fetched, voice only. + icons: HashSet, + /// Contact volume and mute applied per client. + contact_audio: HashMap, + /// Friends' client ids, as last told to the streams. + stream_friends: BTreeSet, + /// The server's details and groups as last reported. + details: Option>, + groups: Option, } impl Session { @@ -131,11 +162,21 @@ impl Session { events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, - settings: SharedSettings, - history: SharedHistory, + shared: Shared, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); + let Shared { settings, history, cache, contacts } = shared; + let contacts_rx = Some(contacts.watch()); Self { + cache, + contacts, + contacts_rx, + avatars: HashMap::new(), + icons: HashSet::new(), + contact_audio: HashMap::new(), + stream_friends: BTreeSet::new(), + details: None, + groups: None, id, events, state: SessionState::default(), @@ -187,6 +228,7 @@ impl Session { async fn run(mut self, mut commands: mpsc::UnboundedReceiver) { let mut sources = self.sources_rx.take().expect("receiver"); + let mut contacts = self.contacts_rx.take().expect("contacts"); loop { tokio::select! { cmd = commands.recv() => match cmd { @@ -194,9 +236,11 @@ impl Session { Some(cmd) => self.command(cmd), }, Some(event) = sources.recv() => self.source_event(event), + Ok(()) = contacts.changed() => self.contacts_changed(), } } self.stop_all(); + self.contacts.session_closed(self.id); } fn next_generation(&mut self) -> u64 { @@ -244,8 +288,14 @@ impl Session { self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p)); self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e)); } - tokio::spawn(voice::run(*options, cmd_rx, ev_tx)); + let link = VoiceLink { + session: self.id, + events: self.events.clone(), + settings: self.settings.clone(), + }; + tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx)); self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); + self.forget_images(); self.voice = Some((generation, cmd_tx)); self.state.voice = VoiceState::Connecting; self.emit_state(); @@ -427,16 +477,398 @@ impl Session { s.send(StreamInput::SrtpProfiles(profiles)); } } + Command::Poke { client, message, .. } => { + self.voice_cmd(VoiceCmd::Poke { client, message }); + } + Command::ListFiles { request, channel, password, path, .. } => { + if self.voice.is_none() { + let result = Err(NO_VOICE.into()); + let path = files::normalize_dir(&path); + self.emit(Event::FileList { session: self.id, request, channel, path, result }); + return; + } + let dir = Remote { channel, password, path }; + self.voice_cmd(VoiceCmd::ListFiles { request, dir }); + } + Command::DownloadFile { transfer, channel, password, path, to, .. } => { + self.download(transfer, Remote { channel, password, path }, &to); + } + Command::DownloadChatFile { transfer, file, password, to, .. } => { + let elsewhere = file + .server_uid + .as_ref() + .zip(self.state.server_uid.as_ref()) + .is_some_and(|(theirs, ours)| theirs != ours); + if elsewhere { + self.transfer_state( + transfer, + TransferState::Failed("the file is on another server".into()), + ); + return; + } + let path = file.full_path(); + self.download(transfer, Remote { channel: file.channel, password, path }, &to); + } + Command::UploadFile { + transfer, + channel, + password, + path, + from, + overwrite, + resume, + .. + } => { + if self.voice.is_none() { + self.transfer_state(transfer, TransferState::Failed(NO_VOICE.into())); + return; + } + let report = self.transfer_report(transfer); + let file = Remote { channel, password, path }; + let transfer = Some(transfer); + self.voice_cmd(VoiceCmd::Upload { + transfer, + file, + from, + overwrite, + resume, + report, + }); + } + Command::CancelTransfer { transfer, .. } => { + self.voice_cmd(VoiceCmd::CancelTransfer(transfer)); + } + Command::DeleteFiles { request, channel, password, paths, .. } => { + let request = Some(request); + self.voice_request( + request, + VoiceCmd::DeleteFiles { request, channel, password, paths }, + ); + } + Command::RenameFile { request, channel, password, from, to, to_channel, .. } => { + let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone())); + let from = Remote { channel, password, path: from }; + let to = Remote { channel: to_channel, password: to_password, path: to }; + self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to }); + } + Command::CreateDirectory { request, channel, password, path, .. } => { + let dir = Remote { channel, password, path }; + self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir }); + } + Command::SetAvatar { request, image, .. } => self.set_avatar(request, image), + Command::FetchAvatar { client_uid, .. } => { + let hash = self + .voice_presence + .as_ref() + .and_then(|p| p.client_by_uid(&client_uid)) + .and_then(|c| c.avatar.clone()); + if let Some(hash) = hash { + self.fetch_avatar(&client_uid, &hash); + } + } + Command::ListOfflineMessages { request, .. } => { + if self.voice.is_none() { + let result = Err(NO_VOICE.into()); + self.emit(Event::OfflineMessages { session: self.id, request, result }); + return; + } + self.voice_cmd(VoiceCmd::OfflineList { request }); + } + Command::GetOfflineMessage { request, id, .. } => { + if self.voice.is_none() { + let result = Err(NO_VOICE.into()); + self.emit(Event::OfflineMessage { session: self.id, request, result }); + return; + } + self.voice_cmd(VoiceCmd::OfflineGet { request, id }); + } + Command::SendOfflineMessage { request, to_uid, subject, text, .. } => { + let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text }; + self.voice_request(Some(request), cmd); + } + Command::DeleteOfflineMessage { request, id, .. } => { + self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id }); + } + Command::SetOfflineMessageRead { request, id, read, .. } => { + self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read }); + } // Engine-wide. Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } | Command::ResetSetting { .. } | Command::AttachSettings(_) - | Command::AttachHistory(_) => {} + | Command::AttachHistory(_) + | Command::AttachCache(_) + | Command::SetContact { .. } + | Command::RemoveContact { .. } => {} } } + // Files, avatars, icons + + /// A request to the voice connection; without one it fails at once. + fn voice_request(&self, request: Option, cmd: VoiceCmd) { + match (&self.voice, request) { + (Some(_), _) => self.voice_cmd(cmd), + (None, Some(request)) => self.emit(Event::RequestDone { + session: self.id, + request, + result: Err(NO_VOICE.into()), + }), + (None, None) => {} + } + } + + fn transfer_state(&self, transfer: TransferId, state: TransferState) { + self.emit(Event::Transfer { session: self.id, transfer, state }); + } + + /// Reports a user's transfer as [`Event::Transfer`]. + fn transfer_report(&self, transfer: TransferId) -> Report { + let (session, events) = (self.id, self.events.clone()); + Arc::new(move |state| { + let _ = events.send(Event::Transfer { session, transfer, state }); + }) + } + + fn download(&self, transfer: TransferId, file: Remote, to: &DownloadTo) { + if self.voice.is_none() { + self.transfer_state(transfer, TransferState::Failed(NO_VOICE.into())); + return; + } + let report = self.transfer_report(transfer); + let sink = Sink::from_target(to); + self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report }); + } + + /// Upload our avatar and announce its hash, or remove it. + fn set_avatar(&mut self, request: RequestId, image: Option) { + let Some((generation, tx)) = self.voice.clone() else { + let result = Err(NO_VOICE.into()); + self.emit(Event::RequestDone { session: self.id, request, result }); + return; + }; + let Some(image) = image else { + // The file too (best effort), then no hash. + if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) { + let cmd = VoiceCmd::DeleteFiles { + request: None, + channel: 0, + password: None, + paths: vec![path], + }; + self.voice_cmd(cmd); + } + let hash = String::new(); + self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash }); + return; + }; + let (sources, cache, settings) = + (self.sources_tx.clone(), self.cache.current(), self.settings.clone()); + tokio::spawn(async move { + let hashed = image.clone(); + let hash = match tokio::task::spawn_blocking(move || files::md5_file(&hashed)).await { + Ok(Ok(hash)) => hash, + Ok(Err(e)) => { + let e = format!("{}: {e}", image.display()); + let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, Err(e))); + return; + } + Err(e) => { + let e = e.to_string(); + let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, Err(e))); + return; + } + }; + // Ours is shown without a download. + if let Some(key) = cache::avatar_key(&hash) + && let Err(e) = cache.insert_copy(&key, &image, max_cache_bytes(&settings)) + { + debug!("cannot cache our avatar: {e}"); + } + let report: Report = Arc::new(move |state| { + let result = match state { + TransferState::Done { .. } => Ok(hash.clone()), + TransferState::Failed(e) => Err(e), + TransferState::Cancelled => Err("cancelled".into()), + _ => return, + }; + let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result)); + }); + let file = Remote { channel: 0, password: None, path: "/avatar".into() }; + let upload = VoiceCmd::Upload { + transfer: None, + file, + from: image, + overwrite: true, + resume: false, + report, + }; + let _ = tx.send(upload); + }); + } + + /// Forget what was reported about avatars and icons (a new connection + /// reports them again). + fn forget_images(&mut self) { + self.avatars.clear(); + self.icons.clear(); + self.contact_audio.clear(); + self.stream_friends.clear(); + self.details = None; + self.groups = None; + } + + /// Fetch the avatars and icons of the voice presence that are new. + fn fetch_images(&mut self, p: &Presence) { + if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + return; + } + let mut avatars = HashMap::with_capacity(self.avatars.len()); + for c in p.clients.values() { + let (Some(uid), Some(hash)) = (&c.uid, &c.avatar) else { continue }; + if self.avatars.get(uid) != Some(hash) { + self.fetch_avatar(uid, hash); + } + avatars.insert(uid.clone(), hash.clone()); + } + self.avatars = avatars; + let icons = std::iter::once(p.server.icon) + .chain(p.server_groups.values().map(|g| g.icon)) + .chain(p.channel_groups.values().map(|g| g.icon)) + .chain(p.channels.values().map(|c| c.icon)) + .chain(p.clients.values().map(|c| c.icon)) + .filter(|id| *id >= files::FIRST_DOWNLOADABLE_ICON) + .collect::>(); + for id in icons { + if self.icons.insert(id) { + self.fetch_icon(id); + } + } + } + + fn fetch_avatar(&self, uid: &str, hash: &str) { + let Some(key) = cache::avatar_key(hash) else { return }; + let (session, events) = (self.id, self.events.clone()); + let (client_uid, hash) = (uid.to_owned(), hash.to_owned()); + let waiter: Waiter = Box::new(move |result| match result { + Ok(path) => { + let _ = events.send(Event::AvatarReady { session, client_uid, path, hash }); + } + Err(e) => debug!(%client_uid, "no avatar: {e}"), + }); + self.fetch_image(key, files::avatar_path(uid), waiter); + } + + fn fetch_icon(&self, icon: u32) { + let (session, events) = (self.id, self.events.clone()); + let waiter: Waiter = Box::new(move |result| match result { + Ok(path) => { + let _ = events.send(Event::IconReady { session, icon, path }); + } + Err(e) => debug!(icon, "no icon: {e}"), + }); + self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), waiter); + } + + /// Get `key` from the cache, downloading `path` of channel 0 once. + fn fetch_image(&self, key: String, path: Option, waiter: Waiter) { + let cache = self.cache.current(); + let Fetch::Download(temp) = cache.fetch(&key, waiter) else { return }; + let settings = self.settings.clone(); + let (Some(path), Some(_)) = (path, &self.voice) else { + cache.finish(&key, &temp, Err(NO_VOICE.into()), max_cache_bytes(&settings)); + return; + }; + let finish = { + let temp = temp.clone(); + move |result: Result<(), String>| { + cache.finish(&key, &temp, result, max_cache_bytes(&settings)); + } + }; + let report: Report = Arc::new(move |state| match state { + TransferState::Done { .. } => finish(Ok(())), + TransferState::Failed(e) => finish(Err(e)), + TransferState::Cancelled => finish(Err("cancelled".into())), + _ => {} + }); + let sink = Sink::File { part: temp.clone(), dest: temp, append: false }; + let file = Remote { channel: 0, password: None, path }; + self.voice_cmd(VoiceCmd::Download { transfer: None, file, sink, report }); + } + + // Contacts + + /// The contacts changed: apply volumes and friends again. + fn contacts_changed(&mut self) { + if let Some(p) = self.voice_presence.clone() { + self.apply_contacts(&p); + } + } + + /// Contacts' volumes and mutes for their clients, friends for the + /// streams (voice presence). + fn apply_contacts(&mut self, p: &Presence) { + let mut friends = BTreeSet::new(); + let mut wanted: HashMap = HashMap::new(); + for c in p.clients.values() { + let Some(contact) = c.uid.as_deref().and_then(|uid| self.contacts.get(uid)) else { + continue; + }; + if contact.relation == Relation::Friend { + friends.insert(c.id); + } + if contact.muted || contact.volume != 1.0 { + wanted.insert(c.id, (contact.volume, contact.muted)); + } + } + if let Some(a) = &self.audio { + for (client, (volume, muted)) in &wanted { + if self.contact_audio.get(client) != Some(&(*volume, *muted)) { + a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume }); + a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted }); + } + } + // No contact setting any more: back to normal. + for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) { + if p.clients.contains_key(client) { + a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 }); + a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false }); + } + } + self.contact_audio = wanted; + } + if friends != self.stream_friends { + self.stream_friends = friends.clone(); + if let Some(s) = &self.streams { + s.send(StreamInput::Friends(friends)); + } + } + } + + /// Report the server's details and groups when they changed. + fn report_details(&mut self, p: &Presence) { + if self.details.as_deref() != Some(&p.server) { + let details = Arc::new(p.server.clone()); + self.details = Some(details.clone()); + self.emit(Event::ServerDetails { session: self.id, details }); + } + let sorted = |groups| -> Arc> { + Arc::new(Presence::sorted_groups(groups).into_iter().cloned().collect()) + }; + let groups = (sorted(&p.server_groups), sorted(&p.channel_groups)); + if self.groups.as_ref() != Some(&groups) { + self.groups = Some(groups.clone()); + let (server_groups, channel_groups) = groups; + self.emit(Event::Groups { session: self.id, server_groups, channel_groups }); + } + } + + fn block_mode(&self) -> BlockMode { + self.settings.current().get(&PRIVACY_BLOCK_MODE) + } + fn stream_input(&self, input: StreamInput) { match &self.streams { Some(s) => s.send(input), @@ -509,6 +941,7 @@ impl Session { history: self.history.current(), settings: self.settings.current(), server_uid: self.state.server_uid.clone()?, + contacts: self.contacts.clone(), }) } @@ -592,6 +1025,7 @@ impl Session { text: text.to_owned(), ts_ms: history::now_ms(), via_relay: *route != ChatRoute::Voice, + blocked: false, }; ctx.store_live(vec![history::new_message(&ctx.server_uid, &msg, MessageSource::Local)]); } @@ -819,6 +1253,20 @@ impl Session { self.open_histories(); } } + SourceEvent::AvatarUploaded(g, request, result) => match result { + Ok(hash) if self.is_current(Source::Voice, g) => { + self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash }); + } + Ok(_) => self.emit(Event::RequestDone { + session: self.id, + request, + result: Err("the voice connection changed".into()), + }), + Err(e) => { + let result = Err(format!("avatar upload: {e}")); + self.emit(Event::RequestDone { session: self.id, request, result }); + } + }, _ => debug!("event from a replaced source ignored"), } } @@ -879,9 +1327,22 @@ impl Session { s.send(StreamInput::Clients(clients)); } } - self.voice_presence = Some(p); + self.report_details(&p); + self.fetch_images(&p); + self.apply_contacts(&p); + self.voice_presence = Some(*p); self.publish_presence(); } + VoiceEvent::Poke { from, from_uid, from_name, message } => { + let blocked = self.contacts.is_blocked(from_uid.as_deref()); + if blocked && self.block_mode() == BlockMode::Hide { + debug!(?from_uid, "poke of a blocked contact hidden"); + return; + } + let session = self.id; + self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked }); + } + VoiceEvent::Error(message) => self.error(message), VoiceEvent::Stream(n) => { if let Some(s) = &self.streams { s.send(StreamInput::Notification(n)); @@ -912,6 +1373,7 @@ impl Session { self.voice = None; self.voice_presence = None; self.audio = None; + self.forget_images(); self.state.voice = VoiceState::Disconnected; self.state.own_channel = None; self.state.own_client = None; @@ -947,7 +1409,7 @@ impl Session { self.open_histories(); } GatewayEvent::Presence(p) => { - self.gateway_presence = Some(p); + self.gateway_presence = Some(*p); self.publish_presence(); } GatewayEvent::Push(push) => self.gateway_push(*push), @@ -1044,7 +1506,7 @@ impl Session { self.state.observe = ObserveState::Observing; self.emit_state(); } - self.query_presence = Some(p); + self.query_presence = Some(*p); self.publish_presence(); } QueryEvent::Chat(msg) => self.chat(msg, MessageSource::Query, None), @@ -1060,7 +1522,9 @@ impl Session { } /// A live message: reported, and stored (merged with other copies). - fn chat(&mut self, msg: ChatMessage, source: MessageSource, entry: Option) { + /// Messages of blocked contacts are flagged; their private messages + /// dropped with `privacy.block_mode = hide`. + fn chat(&mut self, mut msg: ChatMessage, source: MessageSource, entry: Option) { let wanted = match &msg.target { ChatTarget::Server | ChatTarget::Private(_) => true, target => self.open_chats.contains(target) || !msg.via_relay, @@ -1068,6 +1532,14 @@ impl Session { if !wanted { return; } + msg.blocked = self.contacts.is_blocked(msg.author_uid.as_deref()); + if msg.blocked + && matches!(msg.target, ChatTarget::Private(_)) + && self.block_mode() == BlockMode::Hide + { + debug!(author = ?msg.author_uid, "private message of a blocked contact hidden"); + return; + } if let Some(ctx) = self.chat_ctx() { let stored = match &entry { Some(entry) => history::gateway_message(&ctx.server_uid, entry), @@ -1095,6 +1567,8 @@ impl Session { self.state.presence_source = source; self.emit_state(); } - self.emit(Event::Presence { session: self.id, presence: Arc::new(presence) }); + let presence = Arc::new(presence); + self.contacts.presence(self.id, presence.clone()); + self.emit(Event::Presence { session: self.id, presence }); } } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 025d35e..635c232 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1044,8 +1044,8 @@ pub static STREAM_HARDWARE_ACCELERATION: Key = Key::new( pub enum StreamPermissions { /// Every join request is accepted. Everyone, - /// Friends are accepted. Until there are contacts, every request is - /// shown to the user ([`crate::Event::StreamViewerRequest`]). + /// Friends (contacts marked friend) are accepted; others are shown to + /// the user ([`crate::Event::StreamViewerRequest`]). Friends, /// Clients in our channel are accepted, others denied. #[default] @@ -1096,6 +1096,51 @@ pub static CHAT_RETENTION_DAYS: Key = Key::new( || 0, ); +/// Size of the avatar and icon cache in MiB; the least recently used files +/// go first. 0: no limit. +pub static CACHE_MAX_MB: Key = Key::new( + "cache.max_mb", + Kind::UInt { min: 0 }, + "Size of the avatar and icon cache in MiB (0: no limit).", + || 256, +); + +/// Download the avatars and icons of servers we are on by themselves. +pub static CACHE_FETCH_IMAGES: Key = Key::new( + "cache.fetch_images", + Kind::Bool, + "Download avatars and icons of the servers we are on.", + || true, +); + +/// How often a file transfer reports its progress (ms); 0: after every +/// piece received or sent. +pub static FILES_PROGRESS_MS: Key = Key::new( + "files.progress_interval_ms", + Kind::UInt { min: 0 }, + "How often a file transfer reports its progress, in ms (0: continuously).", + || 250, +); + +/// What happens to private messages and pokes of blocked contacts (their +/// channel and server messages are always shown, flagged). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BlockMode { + /// Dropped: neither reported nor stored. + #[default] + Hide, + /// Reported and stored with `blocked` set. + Flag, +} + +pub static PRIVACY_BLOCK_MODE: Key = Key::new( + "privacy.block_mode", + Kind::Choice(&["hide", "flag"]), + "Private messages and pokes of blocked contacts: hide them, or show them flagged.", + BlockMode::default, +); + /// What an audio source of our stream captures, as stored; see /// [`AudioSourceSetting`]. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -1180,7 +1225,7 @@ pub static STREAM_AUDIO_SOURCES: Key> = Key::new( .validated(valid_audio_sources); /// The keys every [`Settings`] knows from the start. -pub fn builtin_keys() -> [&'static dyn Setting; 16] { +pub fn builtin_keys() -> [&'static dyn Setting; 20] { [ &CRASH_REPORTS, &AUDIO, @@ -1198,6 +1243,10 @@ pub fn builtin_keys() -> [&'static dyn Setting; 16] { &CHAT_DEDUPE_TOLERANCE_MS, &CHAT_RETENTION_DAYS, &STREAM_AUDIO_SOURCES, + &CACHE_MAX_MB, + &CACHE_FETCH_IMAGES, + &FILES_PROGRESS_MS, + &PRIVACY_BLOCK_MODE, ] } diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 4373cf1..e51dbe3 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -12,7 +12,7 @@ //! cannot. Our own stream's life (live, viewers, ended) goes back to the //! session ([`OwnStreamEvent`]), which keeps its directory entry. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; @@ -153,6 +153,8 @@ pub(crate) enum StreamInput { RequestFailed(Request, String), /// Clients on the server: channel and `client_is_streaming`. Clients(BTreeMap), + /// Clients that are friends (contacts), for `stream.permissions`. + Friends(BTreeSet), /// The registered streams of the gateway's directory (full list). Directory(Vec), /// The voice connection is gone. @@ -256,6 +258,7 @@ impl StreamHandle { live: None, viewers: 0, clients: BTreeMap::new(), + friends: BTreeSet::new(), gateway, }; tokio::spawn(task.run(rx)); @@ -293,6 +296,8 @@ struct StreamTask { viewers: u32, /// The clients as of the last update. clients: BTreeMap, + /// Friends' client ids (`stream.permissions = friends`). + friends: BTreeSet, gateway: Arc>, } @@ -368,6 +373,10 @@ impl StreamTask { self.streams.request_failed(&request, &error); Ok(()) } + StreamInput::Friends(friends) => { + self.friends = friends; + Ok(()) + } StreamInput::Clients(clients) => { // Streams of clients that left, stopped streaming or are not // in our channel are gone; unannounced ones are looked up. @@ -525,8 +534,8 @@ impl StreamTask { match *self.settings.current().get_arc(&STREAM_PERMISSIONS) { StreamPermissions::Everyone => Some(true), StreamPermissions::Nobody => Some(false), - // No contacts yet: ask for everyone. - StreamPermissions::Friends => None, + // Friends are let in; others: ask. + StreamPermissions::Friends => self.friends.contains(&viewer.0).then_some(true), StreamPermissions::Channel => { let discovery = self.streams.discovery(); let own = discovery.own_channel(); @@ -989,7 +998,7 @@ mod tests { assert_eq!(parse_kind("game"), StreamKind::Screen); } - /// `stream.permissions` answers join requests unless it is `friends`. + /// `stream.permissions` answers join requests (`friends`: friends only, others are asked). #[tokio::test(flavor = "multi_thread")] async fn permissions_answer_join_requests() { let in_channels = |streamer: u64, viewer: u64| { @@ -998,12 +1007,13 @@ mod tests { (CLIENTS[1], ClientState { channel: viewer, streaming: Some(false) }), ])) }; - for (permissions, viewer_channel, expected) in [ - (StreamPermissions::Everyone, 2, Some(true)), - (StreamPermissions::Channel, 1, Some(true)), - (StreamPermissions::Channel, 2, Some(false)), - (StreamPermissions::Nobody, 1, Some(false)), - (StreamPermissions::Friends, 1, None), + for (permissions, viewer_channel, friend, expected) in [ + (StreamPermissions::Everyone, 2, false, Some(true)), + (StreamPermissions::Channel, 1, false, Some(true)), + (StreamPermissions::Channel, 2, false, Some(false)), + (StreamPermissions::Nobody, 1, false, Some(false)), + (StreamPermissions::Friends, 1, false, None), + (StreamPermissions::Friends, 2, true, Some(true)), ] { let settings = Settings::in_memory(); settings.set(&STREAM_PERMISSIONS, permissions).unwrap(); @@ -1011,6 +1021,9 @@ mod tests { for h in handles.iter() { h.send(in_channels(1, viewer_channel)); } + if friend { + handles[0].send(StreamInput::Friends(BTreeSet::from([CLIENTS[1]]))); + } let setup = StreamSetup { name: "p".into(), ..Default::default() }; handles[0].send(StreamInput::Start { setup, auto_accept: false }); let (mut live, mut listed) = (false, false); diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index 6e9a5f8..e53ce02 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -1,25 +1,38 @@ //! The voice source: a normal client connection. +//! +//! Besides presence, chat, voice and stream signalling it carries what only +//! a client connection can do: pokes, file transfer (channel files, +//! avatars, icons) and offline messages. Their answers go straight to the +//! engine's event bus ([`VoiceLink`]); what the session must see first +//! (chat, pokes: blocking) comes as [`VoiceEvent`]s. use std::collections::HashMap; +use std::path::PathBuf; use std::time::Duration; +use base64::Engine as _; use futures::prelude::*; -use tokio::sync::mpsc; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::AbortHandle; use tokio::time::{Instant, timeout}; -use tracing::{info, warn}; -use tsclientlib::data; +use tracing::{debug, info, warn}; use tsclientlib::events::Event as BookEvent; +use tsclientlib::messages::c2s; use tsclientlib::prelude::*; use tsclientlib::{ - ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle, MessageTarget, - StreamItem, Version, -}; -use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; -use voelin_model::{ - ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor, + Connection, DisconnectOptions, FiletransferHandle, Identity, InMessage, MessageHandle, + MessageTarget, StreamItem, TsError, Version, }; +use tsproto_packets::packets::{AudioData, InAudioBuf, OutCommand, OutPacket}; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; use voelin_stream::{PeerConfig, Request, StreamNotification}; +use crate::book::presence_from_book; +use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; +use crate::offline::{OfflineMessage, OfflineMessageInfo}; +use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; +use crate::{Event, SessionId}; + #[derive(Clone, Debug)] pub struct VoiceOptions { pub address: String, @@ -51,6 +64,45 @@ impl VoiceOptions { } } +/// Where a voice connection reports answers the session does not need to see. +#[derive(Clone)] +pub(crate) struct VoiceLink { + pub session: SessionId, + pub events: broadcast::Sender, + pub settings: SharedSettings, +} + +impl VoiceLink { + fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + fn done(&self, request: RequestId, result: Result<(), String>) { + self.emit(Event::RequestDone { session: self.session, request, result }); + } +} + +/// A file on the server: channel, its password, path. +#[derive(Clone, Debug)] +pub(crate) struct Remote { + pub channel: ChannelId, + pub password: Option, + pub path: String, +} + +impl Remote { + fn cpw(&self) -> String { + encode_password(self.password.as_deref()) + } +} + +fn encode_password(password: Option<&str>) -> String { + password + .filter(|p| !p.is_empty()) + .map(|p| tsproto_types::crypto::encode_password(p.as_bytes())) + .unwrap_or_default() +} + pub(crate) enum VoiceCmd { SendChat(ChatTarget, String), Move(ChannelId, Option), @@ -60,6 +112,73 @@ pub(crate) enum VoiceCmd { Audio(OutPacket), /// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`]. Stream(Request), + Poke { + client: u16, + message: String, + }, + ListFiles { + request: RequestId, + dir: Remote, + }, + /// Download `file`; `transfer` if the user can cancel it. + Download { + transfer: Option, + file: Remote, + sink: Sink, + report: Report, + }, + Upload { + transfer: Option, + file: Remote, + from: PathBuf, + overwrite: bool, + resume: bool, + report: Report, + }, + CancelTransfer(TransferId), + DeleteFiles { + /// `None`: best effort, nobody waits for the answer. + request: Option, + channel: ChannelId, + password: Option, + paths: Vec, + }, + RenameFile { + request: RequestId, + from: Remote, + to: Remote, + }, + CreateDirectory { + request: RequestId, + dir: Remote, + }, + /// `clientupdate client_flag_avatar` (empty: no avatar). + SetAvatarHash { + request: Option, + hash: String, + }, + OfflineList { + request: RequestId, + }, + OfflineGet { + request: RequestId, + id: u32, + }, + OfflineAdd { + request: RequestId, + to_uid: String, + subject: String, + text: String, + }, + OfflineDelete { + request: RequestId, + id: u32, + }, + OfflineFlag { + request: RequestId, + id: u32, + read: bool, + }, Disconnect, } @@ -74,9 +193,15 @@ pub(crate) enum VoiceEvent { /// Our unique id as the server knows it. own_uid: Option, }, - Presence(Presence), + Presence(Box), OwnChannel(ChannelId), Chat(ChatMessage), + Poke { + from: u16, + from_uid: Option, + from_name: String, + message: String, + }, /// Incoming voice for the audio thread, and who is talking. Audio(InAudioBuf), Talking { @@ -85,64 +210,11 @@ pub(crate) enum VoiceEvent { }, Stream(StreamNotification), StreamRequestFailed(Request, String), + /// A command failed (the connection stays). + Error(String), Disconnected(Option), } -/// The presence visible through a voice connection. -pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { - let limit = |m: &Option| match m { - Some(MaxClients::Limited(n)) => Some(*n as i32), - _ => None, - }; - Presence { - server_name: book.server.name.clone(), - channels: book - .channels - .values() - .map(|c| { - ( - c.id.0, - ChannelInfo { - id: c.id.0, - parent: c.parent.0, - order: c.order.0, - name: c.name.clone(), - topic: c.topic.clone().filter(|t| !t.is_empty()), - has_password: c.has_password.unwrap_or(false), - max_clients: limit(&c.max_clients), - needed_subscribe_power: 0, - needed_talk_power: c.needed_talk_power.unwrap_or(0), - is_default: c.is_default.unwrap_or(false), - }, - ) - }) - .collect(), - clients: book - .clients - .values() - .map(|c| { - ( - c.id.0, - ClientInfo { - id: c.id.0, - uid: c.uid.as_ref().map(|u| u.as_ref().to_string()), - nickname: c.name.clone(), - channel: c.channel.0, - is_query: matches!(c.client_type, ClientType::Query { .. }), - away: c.away_message.clone(), - input_muted: c.input_muted, - output_muted: c.output_muted, - talking: None, - streaming: c.is_streaming, - server_groups: c.server_groups.iter().map(|g| g.0).collect(), - country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), - }, - ) - }) - .collect(), - } -} - fn now_ms() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -156,21 +228,87 @@ enum Input { Tick, } +/// A command waiting for the server's answer. +enum Pending { + Stream(Request), + FileList { + request: RequestId, + channel: ChannelId, + path: String, + entries: Vec, + }, + Done(RequestId), + OfflineList { + request: RequestId, + messages: Vec, + }, + OfflineGet { + request: RequestId, + id: u32, + message: Option, + }, + /// Failures are reported as [`VoiceEvent::Error`] with this label. + Report(&'static str), + /// Best effort: the answer does not matter. + Quiet, +} + +/// A transfer the server has not opened yet. +enum Job { + Download { transfer: Option, offset: u64, sink: Sink, report: Report }, + Upload { transfer: Option, from: PathBuf, size: u64, report: Report }, +} + +impl Job { + fn report(&self) -> &Report { + match self { + Job::Download { report, .. } | Job::Upload { report, .. } => report, + } + } + + fn transfer(&self) -> Option { + match self { + Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer, + } + } +} + +/// A user's transfer, for cancelling. +enum Slot { + Waiting(FiletransferHandle), + Running { task: AbortHandle, part: Option, report: Report }, +} + /// Run a voice connection until it ends or is told to disconnect. pub(crate) async fn run( options: VoiceOptions, + link: VoiceLink, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - let reason = match run_inner(&options, &mut commands, &events).await { + let reason = match run_inner(&options, link, &mut commands, &events).await { Ok(()) => None, Err(e) => Some(e.to_string()), }; let _ = events.send(VoiceEvent::Disconnected(reason)); } +/// The state of a connected voice source. +struct Voice { + con: Connection, + link: VoiceLink, + events: mpsc::UnboundedSender, + server_uid: String, + /// Who is talking: last voice packet per client. + talking: HashMap, + pending: HashMap, + jobs: HashMap, + transfers: HashMap, +} + async fn run_inner( options: &VoiceOptions, + link: VoiceLink, commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { @@ -203,7 +341,7 @@ async fn run_inner( Some(Err(e)) => return Err(e.into()), None => anyhow::bail!("connection closed"), } - { + let server_uid = { let state = con.get_state()?; let flavor = ServerFlavor::from_version_string(&state.server.version); let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts()); @@ -218,24 +356,30 @@ async fn run_inner( name: state.server.name.clone(), flavor, own_client: state.own_client.0, - server_uid, + server_uid: server_uid.clone(), own_uid, }); - } + server_uid + }; // Subscribe to all channels to see everyone. let cmd = con.get_state()?.server.set_subscribed(true); cmd.send(&mut con)?; - publish_state(&con, events)?; + let mut voice = Voice { + con, + link, + events: events.clone(), + server_uid, + talking: HashMap::new(), + pending: HashMap::new(), + jobs: HashMap::new(), + transfers: HashMap::new(), + }; + voice.publish_state()?; - // Who is talking: last voice packet per client. - let mut talking: std::collections::HashMap = Default::default(); let mut tick = tokio::time::interval(Duration::from_millis(250)); - // Stream commands waiting for the server's answer. - let mut stream_requests: HashMap = HashMap::new(); - - loop { + let result = loop { let input = { - let mut stream = con.events(); + let mut stream = voice.con.events(); tokio::select! { item = stream.next() => Input::Item(item), cmd = commands.recv() => Input::Cmd(cmd), @@ -243,164 +387,539 @@ async fn run_inner( } }; match input { - Input::Item(None) => anyhow::bail!("connection closed"), - Input::Item(Some(Err(e))) => return Err(e.into()), - Input::Item(Some(Ok(item))) => match item { - StreamItem::BookEvents(book_events) => { - for e in &book_events { - if let BookEvent::Message { target, invoker, message } = e { - let own_channel = own_channel(&con); - let target = match target { - MessageTarget::Server => ChatTarget::Server, - MessageTarget::Channel => { - ChatTarget::Channel(own_channel.unwrap_or(0)) - } - // Our own private message comes back to us: it - // belongs to the chat with its receiver. - MessageTarget::Client(to) - if Some(invoker.id) == own_client(&con) => - { - ChatTarget::Private(client_uid(&con, to).unwrap_or_default()) - } - MessageTarget::Client(_) | MessageTarget::Poke(_) => { - ChatTarget::Private( - invoker - .uid - .as_ref() - .map(|u| u.as_ref().to_string()) - .unwrap_or_default(), - ) - } - }; - let _ = events.send(VoiceEvent::Chat(ChatMessage { - target, - author_name: invoker.name.clone(), - author_uid: invoker.uid.as_ref().map(|u| u.as_ref().to_string()), - author_id: Some(invoker.id.0), - text: message.clone(), - ts_ms: now_ms(), - via_relay: false, - })); - } - } - publish_state(&con, events)?; + Input::Item(None) => break Err(anyhow::anyhow!("connection closed")), + Input::Item(Some(Err(e))) => break Err(e.into()), + Input::Item(Some(Ok(item))) => { + if let Err(e) = voice.item(item) { + break Err(e); } - StreamItem::Audio(packet) => { - let from = match packet.data().data() { - AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, - _ => continue, - }; - if talking.insert(from, Instant::now()).is_none() { - let _ = events.send(VoiceEvent::Talking { client: from, talking: true }); - } - let _ = events.send(VoiceEvent::Audio(packet)); - } - StreamItem::MessageEvent(msg) => { - for n in StreamNotification::from_message(&msg) { - let _ = events.send(VoiceEvent::Stream(n)); - } - } - StreamItem::MessageResult(handle, result) => { - if let (Some(request), Err(e)) = (stream_requests.remove(&handle), result) { - let _ = - events.send(VoiceEvent::StreamRequestFailed(request, e.to_string())); - } - } - StreamItem::DisconnectedTemporarily(reason) => { - warn!(?reason, "voice connection interrupted, reconnecting"); - } - _ => {} - }, - Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break, - Input::Cmd(Some(VoiceCmd::Stream(request))) => { - let handle = request.to_command().send_with_result(&mut con)?; - stream_requests.insert(handle, request); } - Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?, - Input::Tick => { - talking.retain(|client, last| { - let active = last.elapsed() < Duration::from_millis(400); - if !active { - let _ = - events.send(VoiceEvent::Talking { client: *client, talking: false }); + Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break Ok(()), + Input::Cmd(Some(cmd)) => { + if let Err(e) = voice.command(cmd) { + let _ = voice.events.send(VoiceEvent::Error(e.to_string())); + } + } + Input::Tick => voice.tick(), + } + }; + // Transfers the server never opened fail; running ones go on. + for (_, job) in voice.jobs.drain() { + job.report()(TransferState::Failed("disconnected".into())); + } + result?; + voice.con.disconnect(DisconnectOptions::new())?; + let _ = + timeout(Duration::from_secs(3), voice.con.events().for_each(|_| future::ready(()))).await; + Ok(()) +} + +impl Voice { + fn publish_state(&self) -> anyhow::Result<()> { + let state = self.con.get_state()?; + let talking = |id| self.talking.contains_key(&id); + let presence = presence_from_book(state, Some(&self.server_uid), talking); + let _ = self.events.send(VoiceEvent::Presence(Box::new(presence))); + if let Some(own) = state.clients.get(&state.own_client) { + let _ = self.events.send(VoiceEvent::OwnChannel(own.channel.0)); + } + Ok(()) + } + + fn tick(&mut self) { + let events = &self.events; + self.talking.retain(|client, last| { + let active = last.elapsed() < Duration::from_millis(400); + if !active { + let _ = events.send(VoiceEvent::Talking { client: *client, talking: false }); + } + active + }); + } + + 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) => { + for e in &book_events { + if let BookEvent::Message { target, invoker, message } = e { + self.message(target, invoker, message); } - active + } + self.publish_state()?; + } + StreamItem::Audio(packet) => { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => return Ok(()), + }; + if self.talking.insert(from, Instant::now()).is_none() { + let _ = self.events.send(VoiceEvent::Talking { client: from, talking: true }); + } + let _ = self.events.send(VoiceEvent::Audio(packet)); + } + StreamItem::MessageEvent(msg) => self.message_event(&msg), + StreamItem::MessageResult(handle, result) => { + if let Some(pending) = self.pending.remove(&handle) { + self.answered(pending, result.map_err(|e| e.error)); + } + } + StreamItem::FileDownload(handle, download) => { + if let Some(Job::Download { transfer, offset, sink, report }) = + self.jobs.remove(&handle) + { + let part = sink.part().map(ToOwned::to_owned); + let task = tokio::spawn(files::download( + download.stream, + download.size, + offset, + sink, + self.progress_every(), + report.clone(), + )); + self.running(transfer, task.abort_handle(), part, report); + } + } + StreamItem::FileUpload(handle, upload) => { + if let Some(Job::Upload { transfer, from, size, report }) = + 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); + } + } + 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))); + } + } + StreamItem::DisconnectedTemporarily(reason) => { + warn!(?reason, "voice connection interrupted, reconnecting"); + } + _ => {} + } + Ok(()) + } + + fn running( + &mut self, + transfer: Option, + task: AbortHandle, + part: Option, + report: Report, + ) { + self.transfers.retain(|_, slot| match slot { + Slot::Running { task, .. } => !task.is_finished(), + Slot::Waiting(_) => true, + }); + if let Some(id) = transfer { + self.transfers.insert(id, Slot::Running { task, part, report }); + } + } + + /// A chat message or poke from the book. + fn message(&self, target: &MessageTarget, invoker: &tsclientlib::Invoker, text: &str) { + let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string()); + let target = match target { + MessageTarget::Poke(_) => { + let _ = self.events.send(VoiceEvent::Poke { + from: invoker.id.0, + from_uid: uid, + from_name: invoker.name.to_string(), + message: text.to_owned(), }); + return; } - } + MessageTarget::Server => ChatTarget::Server, + MessageTarget::Channel => ChatTarget::Channel(self.own_channel().unwrap_or(0)), + // Our own private message comes back to us: it belongs to the + // chat with its receiver. + MessageTarget::Client(to) if Some(invoker.id) == self.own_client() => { + ChatTarget::Private(self.client_uid(to).unwrap_or_default()) + } + MessageTarget::Client(_) => ChatTarget::Private(uid.clone().unwrap_or_default()), + }; + let _ = self.events.send(VoiceEvent::Chat(ChatMessage { + target, + author_name: invoker.name.to_string(), + author_uid: uid, + author_id: Some(invoker.id.0), + text: text.to_owned(), + ts_ms: now_ms(), + via_relay: false, + blocked: false, + })); } - con.disconnect(DisconnectOptions::new())?; - let _ = timeout(Duration::from_secs(3), con.events().for_each(|_| future::ready(()))).await; - Ok(()) -} - -fn own_client(con: &Connection) -> Option { - con.get_state().ok().map(|state| state.own_client) -} - -fn client_uid(con: &Connection, client: &tsclientlib::ClientId) -> Option { - let state = con.get_state().ok()?; - state.clients.get(client)?.uid.as_ref().map(|u| u.as_ref().to_string()) -} - -fn own_channel(con: &Connection) -> Option { - let state = con.get_state().ok()?; - state.clients.get(&state.own_client).map(|c| c.channel.0) -} - -fn publish_state( - con: &Connection, - events: &mpsc::UnboundedSender, -) -> anyhow::Result<()> { - let state = con.get_state()?; - let _ = events.send(VoiceEvent::Presence(presence_from_book(state))); - if let Some(own) = state.clients.get(&state.own_client) { - let _ = events.send(VoiceEvent::OwnChannel(own.channel.0)); - } - Ok(()) -} - -fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> { - match cmd { - VoiceCmd::SendChat(target, text) => { - let state = con.get_state()?; - let out = match target { - ChatTarget::Server => state.server.send_textmessage(&text), - ChatTarget::Channel(_) => state.send_message(MessageTarget::Channel, &text), - ChatTarget::Private(uid) => { - let client = state - .clients - .values() - .find(|c| c.uid.as_ref().is_some_and(|u| u.as_ref().to_string() == uid)) - .ok_or_else(|| anyhow::anyhow!("client is not on the server"))?; - state.send_message(MessageTarget::Client(client.id), &text) + /// Messages the book does not handle: stream signalling, file lists, + /// offline messages. + fn message_event(&mut self, msg: &InMessage) { + match msg { + InMessage::FileList(list) => { + for part in list.iter() { + let path = files::normalize_dir(&part.path); + let entry = FileEntry { + name: part.name.clone(), + size: part.size, + modified_s: part.date_time.unix_timestamp(), + is_dir: !part.is_file, + }; + let channel = part.channel_id.0; + if let Some(Pending::FileList { entries, .. }) = self.first_pending(|p| { + matches!(p, Pending::FileList { channel: c, path: p, .. } + if *c == channel && *p == path) + }) { + entries.push(entry); + } + } + } + InMessage::OfflineMessageList(list) => { + for part in list.iter() { + let info = OfflineMessageInfo { + id: part.message_id, + from_uid: part.client_uid.as_ref().to_string(), + subject: part.subject.clone(), + ts_s: part.timestamp.unix_timestamp(), + read: part.is_read, + }; + if let Some(Pending::OfflineList { messages, .. }) = + self.first_pending(|p| matches!(p, Pending::OfflineList { .. })) + { + messages.push(info); + } + } + } + InMessage::OfflineMessage(list) => { + for part in list.iter() { + let m = OfflineMessage { + id: part.message_id, + from_uid: part.client_uid.as_ref().to_string(), + subject: part.subject.clone(), + text: part.message.clone(), + ts_s: part.timestamp.unix_timestamp(), + }; + let id = part.message_id; + if let Some(Pending::OfflineGet { message, .. }) = self.first_pending( + |p| matches!(p, Pending::OfflineGet { id: i, .. } if *i == id), + ) { + *message = Some(m); + } + } + } + _ => { + for n in StreamNotification::from_message(msg) { + let _ = self.events.send(VoiceEvent::Stream(n)); } - }; - out.send(con)?; - } - VoiceCmd::Move(channel, password) => { - let state = con.get_state()?; - let own = &state.clients[&state.own_client]; - let mut part = own.client_move(tsclientlib::ChannelId(channel)); - if let Some(pw) = &password { - part = part.set_password(pw); } - part.send(con)?; } - VoiceCmd::SetInputMuted(muted) => { - con.get_state()?.client_update().set_input_muted(muted).send(con)?; - } - VoiceCmd::SetOutputMuted(muted) => { - con.get_state()?.client_update().set_output_muted(muted).send(con)?; - } - VoiceCmd::Audio(packet) => { - con.send_audio(packet)?; - } - VoiceCmd::Stream(request) => { - request.to_command().send(con)?; - } - VoiceCmd::Disconnect => {} } - Ok(()) + + /// The oldest pending command matching `f` (answers come in order). + fn first_pending(&mut self, f: impl Fn(&Pending) -> bool) -> Option<&mut Pending> { + let key = self.pending.iter().filter(|(_, p)| f(p)).map(|(h, _)| *h).min_by_key(|h| h.0)?; + self.pending.get_mut(&key) + } + + /// The server answered a command. + fn answered(&mut self, pending: Pending, result: Result<(), TsError>) { + let session = self.link.session; + // An empty list is an empty result, not an error. + let listed = match result { + Ok(()) | Err(TsError::DatabaseEmptyResult) => Ok(()), + Err(e) => Err(e), + }; + match pending { + Pending::Stream(request) => { + if let Err(e) = result { + let _ = + self.events.send(VoiceEvent::StreamRequestFailed(request, e.to_string())); + } + } + Pending::FileList { request, channel, path, entries } => { + let result = listed.map(|()| entries).map_err(|e| e.to_string()); + self.link.emit(Event::FileList { session, request, channel, path, result }); + } + Pending::Done(request) => self.link.done(request, result.map_err(|e| e.to_string())), + Pending::OfflineList { request, messages } => { + let result = listed.map(|()| messages).map_err(|e| e.to_string()); + self.link.emit(Event::OfflineMessages { session, request, result }); + } + Pending::OfflineGet { request, id, message } => { + let result = match (result, message) { + (Ok(()), Some(m)) => Ok(m), + (Ok(()), None) => Err(format!("offline message {id} not found")), + (Err(e), _) => Err(e.to_string()), + }; + self.link.emit(Event::OfflineMessage { session, request, result }); + } + Pending::Quiet => {} + Pending::Report(what) => { + if let Err(e) = result { + let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}"))); + } + } + } + } + + fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> { + let handle = cmd.send_with_result(&mut self.con)?; + self.pending.insert(handle, pending); + Ok(()) + } + + fn command(&mut self, cmd: VoiceCmd) -> anyhow::Result<()> { + match cmd { + VoiceCmd::SendChat(target, text) => { + let state = self.con.get_state()?; + let out = match target { + ChatTarget::Server => state.server.send_textmessage(&text), + ChatTarget::Channel(_) => state.send_message(MessageTarget::Channel, &text), + ChatTarget::Private(uid) => { + let client = state + .clients + .values() + .find(|c| c.uid.as_ref().is_some_and(|u| u.as_ref().to_string() == uid)) + .ok_or_else(|| { + anyhow::anyhow!( + "private message: the client is not on the server \ + (send an offline message instead)" + ) + })?; + state.send_message(MessageTarget::Client(client.id), &text) + } + }; + self.send(out, Pending::Report("message"))?; + } + VoiceCmd::Move(channel, password) => { + let state = self.con.get_state()?; + let own = &state.clients[&state.own_client]; + let mut part = own.client_move(tsclientlib::ChannelId(channel)); + if let Some(pw) = &password { + part = part.set_password(pw); + } + part.send(&mut self.con)?; + } + VoiceCmd::SetInputMuted(muted) => { + self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?; + } + VoiceCmd::SetOutputMuted(muted) => { + let update = self.con.get_state()?.client_update().set_output_muted(muted); + update.send(&mut self.con)?; + } + VoiceCmd::Audio(packet) => self.con.send_audio(packet)?, + VoiceCmd::Stream(request) => { + let cmd = request.to_command(); + self.send(cmd, Pending::Stream(request))?; + } + VoiceCmd::Poke { client, message } => { + let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once( + c2s::OutClientPokeRequestPart { + client_id: tsclientlib::ClientId(client), + message: message.as_str().into(), + }, + )); + self.send(cmd, Pending::Report("poke"))?; + } + VoiceCmd::ListFiles { request, dir } => { + let path = files::normalize_dir(&dir.path); + let cpw = dir.cpw(); + let cmd = c2s::OutFileListRequestMessage::new(&mut std::iter::once( + c2s::OutFileListRequestPart { + channel_id: tsclientlib::ChannelId(dir.channel), + channel_password: cpw.as_str().into(), + path: path.as_str().into(), + }, + )); + let pending = + Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() }; + self.send(cmd, pending)?; + } + VoiceCmd::Download { transfer, file, sink, report } => { + let offset = sink.offset(); + 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, + Err(e) => { + report(TransferState::Failed(e.to_string())); + return Ok(()); + } + }; + report(TransferState::Requested); + self.jobs.insert(handle, Job::Download { transfer, offset, sink, report }); + if let Some(id) = transfer { + self.transfers.insert(id, Slot::Waiting(handle)); + } + } + VoiceCmd::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(()); + } + }; + 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, + Err(e) => { + report(TransferState::Failed(e.to_string())); + return Ok(()); + } + }; + 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)); + } + } + VoiceCmd::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?)"), + }, + VoiceCmd::DeleteFiles { request, channel, password, paths } => { + let cpw = encode_password(password.as_deref()); + let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart { + channel_id: tsclientlib::ChannelId(channel), + channel_password: cpw.as_str().into(), + name: p.as_str().into(), + }); + let cmd = c2s::OutDeleteFileMessage::new(&mut parts); + self.send(cmd, request.map_or(Pending::Quiet, Pending::Done))?; + } + VoiceCmd::RenameFile { request, from, to } => { + let (cpw, tcpw) = (from.cpw(), to.cpw()); + let other = to.channel != from.channel; + let cmd = + c2s::OutRenameFileMessage::new(&mut std::iter::once(c2s::OutRenameFilePart { + channel_id: tsclientlib::ChannelId(from.channel), + channel_password: cpw.as_str().into(), + target_channel_id: other.then_some(tsclientlib::ChannelId(to.channel)), + target_channel_password: other.then_some(tcpw.as_str().into()), + old_name: from.path.as_str().into(), + new_name: to.path.as_str().into(), + })); + self.send(cmd, Pending::Done(request))?; + } + VoiceCmd::CreateDirectory { request, dir } => { + let cpw = dir.cpw(); + let cmd = c2s::OutCreateDirectoryMessage::new(&mut std::iter::once( + c2s::OutCreateDirectoryPart { + channel_id: tsclientlib::ChannelId(dir.channel), + channel_password: cpw.as_str().into(), + directory_name: dir.path.as_str().into(), + }, + )); + self.send(cmd, Pending::Done(request))?; + } + VoiceCmd::SetAvatarHash { request, hash } => { + let update = self.con.get_state()?.client_update().set_avatar_hash(&hash); + let cmd = c2s::OutClientUpdateMessage::new(&mut std::iter::once(update)); + let pending = request.map_or(Pending::Report("avatar"), Pending::Done); + self.send(cmd, pending)?; + } + VoiceCmd::OfflineList { request } => { + let cmd = c2s::OutOfflineMessageListRequestMessage::new(); + self.send(cmd, Pending::OfflineList { request, messages: Vec::new() })?; + } + VoiceCmd::OfflineGet { request, id } => { + let cmd = c2s::OutOfflineMessageGetMessage::new(&mut std::iter::once( + c2s::OutOfflineMessageGetPart { message_id: id }, + )); + self.send(cmd, Pending::OfflineGet { request, id, message: None })?; + } + VoiceCmd::OfflineAdd { request, to_uid, subject, text } => { + // The command carries the unique id's bytes (base64 on the wire). + let bytes = base64::engine::general_purpose::STANDARD + .decode(to_uid.trim()) + .map_err(|_| anyhow::anyhow!("offline message: invalid unique id {to_uid:?}")); + let uid = match bytes { + Ok(bytes) => tsclientlib::UidBuf(bytes), + Err(e) => { + self.link.done(request, Err(e.to_string())); + return Ok(()); + } + }; + let cmd = c2s::OutOfflineMessageAddMessage::new(&mut std::iter::once( + c2s::OutOfflineMessageAddPart { + client_uid: std::borrow::Cow::Borrowed(uid.as_ref()), + subject: subject.as_str().into(), + message: text.as_str().into(), + }, + )); + self.send(cmd, Pending::Done(request))?; + } + VoiceCmd::OfflineDelete { request, id } => { + let cmd = c2s::OutOfflineMessageDelMessage::new(&mut std::iter::once( + c2s::OutOfflineMessageDelPart { message_id: id }, + )); + self.send(cmd, Pending::Done(request))?; + } + VoiceCmd::OfflineFlag { request, id, read } => { + let cmd = c2s::OutOfflineMessageUpdateFlagMessage::new(&mut std::iter::once( + c2s::OutOfflineMessageUpdateFlagPart { message_id: id, is_read: read }, + )); + self.send(cmd, Pending::Done(request))?; + } + VoiceCmd::Disconnect => {} + } + Ok(()) + } + + fn own_client(&self) -> Option { + self.con.get_state().ok().map(|state| state.own_client) + } + + fn client_uid(&self, client: &tsclientlib::ClientId) -> Option { + let state = self.con.get_state().ok()?; + state.clients.get(client)?.uid.as_ref().map(|u| u.as_ref().to_string()) + } + + fn own_channel(&self) -> Option { + let state = self.con.get_state().ok()?; + state.clients.get(&state.own_client).map(|c| c.channel.0) + } +} + +/// A failed transfer, for the user. +fn transfer_error(error: &tsclientlib::Error) -> String { + match error { + tsclientlib::Error::CommandError(e) if e.error == TsError::FileNotFound => { + "file not found".into() + } + e => e.to_string(), + } } diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs index 9fb294f..4dcf7ed 100644 --- a/crates/voelin-core/tests/gateway.rs +++ b/crates/voelin-core/tests/gateway.rs @@ -77,6 +77,7 @@ impl State { text: text.into(), ts_ms, via_relay: true, + blocked: false, }; let entry = HistoryEntry { rev, ..HistoryEntry::new(self.messages.len() as i64 + 1, message) }; @@ -275,6 +276,7 @@ fn answer( text, ts_ms: now_ms(), via_relay: true, + blocked: false, }; let entry = HistoryEntry { rev, diff --git a/crates/voelin-core/tests/voice_features.rs b/crates/voelin-core/tests/voice_features.rs new file mode 100644 index 0000000..6b4cfb8 --- /dev/null +++ b/crates/voelin-core/tests/voice_features.rs @@ -0,0 +1,179 @@ +//! The engine's contacts and voice feature commands through its public API +//! (without a server: answers without a voice connection, contacts kept +//! in the client database). The round trips against real servers are in +//! `scripts/it-smoke.sh` (`voelinctl engine`). + +use std::time::Duration; + +use tokio::sync::broadcast; +use voelin_core::settings::Settings; +use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState}; +use voelin_model::FileRef; + +async fn next(rx: &mut broadcast::Receiver, mut f: impl FnMut(Event) -> Option) -> T { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some(t) = f(rx.recv().await.expect("engine events")) { + return t; + } + } + }) + .await + .expect("event in time") +} + +#[tokio::test(flavor = "multi_thread")] +async fn requests_without_voice_fail_with_their_ids() { + let engine = Engine::start(); + let mut rx = engine.subscribe(); + engine.send(Command::ListFiles { + session: 1, + request: 11, + channel: 1, + password: None, + path: "/docs/".into(), + }); + let (path, result) = next(&mut rx, |e| match e { + Event::FileList { request: 11, path, result, .. } => Some((path, result)), + _ => None, + }) + .await; + assert_eq!(path, "/docs"); + assert!(result.unwrap_err().contains("voice")); + + engine.send(Command::DownloadFile { + session: 1, + transfer: 12, + channel: 1, + password: None, + path: "/a".into(), + to: DownloadTo::Memory, + }); + let state = next(&mut rx, |e| match e { + Event::Transfer { transfer: 12, state, .. } => Some(state), + _ => None, + }) + .await; + assert!(matches!(state, TransferState::Failed(_))); + + for (request, command) in [ + ( + 13, + Command::SendOfflineMessage { + session: 1, + request: 13, + to_uid: "u=".into(), + subject: "s".into(), + text: "t".into(), + }, + ), + ( + 14, + Command::DeleteFiles { + session: 1, + request: 14, + channel: 1, + password: None, + paths: vec!["/a".into()], + }, + ), + (15, Command::SetAvatar { session: 1, request: 15, image: None }), + ] { + engine.send(command); + let result = next(&mut rx, |e| match e { + Event::RequestDone { request: r, result, .. } if r == request => Some(result), + _ => None, + }) + .await; + assert!(result.is_err(), "request {request}"); + } + engine.send(Command::ListOfflineMessages { session: 1, request: 16 }); + let result = next(&mut rx, |e| match e { + Event::OfflineMessages { request: 16, result, .. } => Some(result), + _ => None, + }) + .await; + assert!(result.is_err()); +} + +/// A file linked in chat is fetched through the voice connection. +#[tokio::test(flavor = "multi_thread")] +async fn chat_file_needs_voice() { + let engine = Engine::start(); + let mut rx = engine.subscribe(); + let file = FileRef { + server_uid: Some("other=".into()), + channel: 1, + path: "/".into(), + name: "a".into(), + ..Default::default() + }; + // Without a server id of our own the link cannot be checked: it is + // tried (and fails without voice). + engine.send(Command::DownloadChatFile { + session: 1, + transfer: 1, + file, + password: None, + to: DownloadTo::Memory, + }); + let state = next(&mut rx, |e| match e { + Event::Transfer { transfer: 1, state, .. } => Some(state), + _ => None, + }) + .await; + assert!(matches!(state, TransferState::Failed(e) if e.contains("voice"))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn contacts_are_kept_in_the_database() { + let dir = std::env::temp_dir().join(format!("voelin-contacts-engine-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("client.db"); + { + let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap()); + let mut rx = engine.subscribe(); + let friend = Contact { + nickname: "Alice".into(), + relation: Relation::Friend, + volume: 0.5, + ..Contact::new("alice=") + }; + engine.send(Command::SetContact { contact: Box::new(friend) }); + engine.send(Command::SetContact { + contact: Box::new(Contact { relation: Relation::Blocked, ..Contact::new("troll=") }), + }); + engine.send(Command::RemoveContact { uid: "troll=".into() }); + let contacts = next(&mut rx, |e| match e { + Event::ContactsChanged { contacts } + if contacts.len() == 1 && contacts[0].uid == "alice=" => + { + Some(contacts) + } + _ => None, + }) + .await; + assert_eq!(contacts[0].volume, 0.5); + assert!(contacts[0].added_ms > 0); + // Friends offline everywhere are reported so. + let (uid, sessions) = next(&mut rx, |e| match e { + Event::FriendPresence { uid, sessions } => Some((uid, sessions)), + _ => None, + }) + .await; + assert_eq!((uid.as_str(), sessions.len()), ("alice=", 0)); + engine.history().flush(); + } + // A new engine attaches the database later: the contacts come back. + let engine = Engine::start(); + let mut rx = engine.subscribe(); + engine.send(Command::AttachHistory(History::open(&path).unwrap())); + next(&mut rx, |e| match e { + Event::ContactsChanged { contacts } if contacts.len() == 1 => Some(()), + _ => None, + }) + .await; + assert_eq!(engine.contacts()[0].nickname, "Alice"); + drop(engine); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/voelin-gateway-proto/src/messages/tests.rs b/crates/voelin-gateway-proto/src/messages/tests.rs index abcb46e..1a18c94 100644 --- a/crates/voelin-gateway-proto/src/messages/tests.rs +++ b/crates/voelin-gateway-proto/src/messages/tests.rs @@ -12,6 +12,7 @@ fn chat(text: &str) -> ChatMessage { text: text.into(), ts_ms: 1_700_000_000_123, via_relay: true, + blocked: false, } } diff --git a/crates/voelin-gateway/src/db/chat.rs b/crates/voelin-gateway/src/db/chat.rs index c2ec70e..12aee2a 100644 --- a/crates/voelin-gateway/src/db/chat.rs +++ b/crates/voelin-gateway/src/db/chat.rs @@ -25,6 +25,7 @@ fn entry_from_row(r: &Row) -> rusqlite::Result { author_id: None, text: r.get(5)?, via_relay: true, + blocked: false, }, topic_id: r.get(6)?, rev: r.get(7)?, diff --git a/crates/voelin-gateway/src/db/tests.rs b/crates/voelin-gateway/src/db/tests.rs index 7cc643f..ffb06e9 100644 --- a/crates/voelin-gateway/src/db/tests.rs +++ b/crates/voelin-gateway/src/db/tests.rs @@ -15,6 +15,7 @@ fn msg(target: ChatTarget, text: &str, ts_ms: i64) -> ChatMessage { text: text.into(), ts_ms, via_relay: true, + blocked: false, } } diff --git a/crates/voelin-gateway/src/hub.rs b/crates/voelin-gateway/src/hub.rs index 70f9ea2..d9d9539 100644 --- a/crates/voelin-gateway/src/hub.rs +++ b/crates/voelin-gateway/src/hub.rs @@ -657,7 +657,7 @@ impl Hub { .filter(|(_, c)| !c.is_query && channels.contains_key(&c.channel)) .map(|(id, c)| (*id, c.clone())) .collect(); - Presence { server_name: p.server_name.clone(), channels, clients } + Presence { server_name: p.server_name.clone(), channels, clients, ..Presence::default() } } // Chat @@ -783,6 +783,7 @@ impl Hub { text: text.to_string(), ts_ms: now_ms(), via_relay: true, + blocked: false, }, topic, )) diff --git a/crates/voelin-model/src/chat.rs b/crates/voelin-model/src/chat.rs index 6380006..e429fc8 100644 --- a/crates/voelin-model/src/chat.rs +++ b/crates/voelin-model/src/chat.rs @@ -1,9 +1,18 @@ //! 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::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 { @@ -28,6 +37,157 @@ pub struct ChatMessage { /// Carried by a gateway or query relay rather than our own connection. #[serde(default)] pub via_relay: bool, + /// The author is blocked in our contacts (set by the engine when it + /// reports the message; never sent over the wire). + #[serde(default, skip_serializing_if = "is_false")] + pub blocked: bool, +} + +impl ChatMessage { + /// The file links in the text, in order of appearance, each once. + pub fn file_refs(&self) -> Vec { + parse_file_links(&self.text) + } +} + +/// A file in a channel's file browser, as a chat message links it. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct FileRef { + /// The server's unique id (`serverUID`), when the link tells it: a link + /// from another server cannot be downloaded here. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub server_uid: Option, + pub channel: ChannelId, + /// The directory, `/` for the channel's root. + pub path: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(default, skip_serializing_if = "is_false")] + pub is_dir: bool, + /// Unix seconds of the last change, when the link tells it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified_s: Option, + /// The link as it appeared. + pub url: String, +} + +/// URL schemes of file links (`ts3file`; later clients may use others of +/// the same form). +const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"]; + +impl FileRef { + /// The file's path in the channel: [`Self::path`] joined with [`Self::name`]. + pub fn full_path(&self) -> String { + let dir = self.path.trim_end_matches('/'); + format!("{dir}/{}", self.name) + } + + /// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`). + pub fn parse(url: &str) -> Option { + let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase(); + let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?; + let rest = &url[scheme.len()..]; + let (host, query) = rest.split_once('?').unwrap_or((rest, "")); + let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() }; + let mut channel = None; + for pair in query.split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let value = percent_decode(value); + match key.to_ascii_lowercase().as_str() { + "serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()), + "channel" | "cid" => channel = value.parse().ok(), + "path" => file.path = if value.is_empty() { "/".into() } else { value }, + "filename" | "name" => file.name = value, + "isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"), + "size" => file.size = value.parse().ok(), + "filedatetime" => file.modified_s = value.parse().ok(), + _ => {} + } + } + if file.name.is_empty() { + file.name = percent_decode(host.trim_end_matches('/')); + } + file.channel = channel?; + (!file.name.is_empty()).then_some(file) + } + + /// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`. + pub fn to_bbcode(&self) -> String { + let mut url = format!("ts3file://{}?", percent_encode(&self.name)); + if let Some(uid) = &self.server_uid { + url.push_str(&format!("serverUID={}&", percent_encode(uid))); + } + url.push_str(&format!( + "channel={}&path={}&filename={}&isDir={}", + self.channel, + percent_encode(&self.path), + percent_encode(&self.name), + u8::from(self.is_dir) + )); + if let Some(size) = self.size { + url.push_str(&format!("&size={size}")); + } + if let Some(t) = self.modified_s { + url.push_str(&format!("&fileDateTime={t}")); + } + format!("[URL={url}]{}[/URL]", self.name) + } +} + +/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown +/// `[name](…)` or bare), in order, each once. +pub fn parse_file_links(text: &str) -> Vec { + let lower = text.to_ascii_lowercase(); + let mut found: Vec = Vec::new(); + let mut at = 0; + while at < text.len() { + let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min(); + let Some(start) = next else { break }; + let end = text[start..] + .find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>')) + .map_or(text.len(), |i| start + i); + if let Some(file) = FileRef::parse(&text[start..end]) + && !found.iter().any(|f| f.url == file.url) + { + found.push(file); + } + at = end.max(start + 1); + } + found +} + +/// `%XX` escapes to bytes (a `+` stays: file names keep theirs). +fn percent_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() +} + +fn percent_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 } /// Format of messages a relay posts on behalf of a user. @@ -70,6 +230,80 @@ mod tests { 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!( diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index 1bf5275..e8024e0 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -8,9 +8,12 @@ mod presence; mod server; mod tree; -pub use chat::{ChatMessage, ChatTarget, relay_text, split_message}; +pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; pub use presence::{ - ChannelId, ChannelInfo, ClientId, ClientInfo, Presence, PresenceDelta, PresenceSnapshot, + ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, + Presence, PresenceDelta, PresenceSnapshot, parse_badges, +}; +pub use server::{ + Capabilities, HostBannerMode, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, }; -pub use server::{Capabilities, ServerFlavor, ServerVersion}; pub use tree::{TreeRow, order_siblings, tree_rows}; diff --git a/crates/voelin-model/src/presence.rs b/crates/voelin-model/src/presence.rs index ec4c2c0..d0adf59 100644 --- a/crates/voelin-model/src/presence.rs +++ b/crates/voelin-model/src/presence.rs @@ -3,13 +3,34 @@ //! 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::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 +} #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ChannelInfo { @@ -32,6 +53,9 @@ pub struct ChannelInfo { 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, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -44,6 +68,7 @@ pub struct ClientInfo { /// ServerQuery clients (bots, our own relays). UIs normally hide them. #[serde(default)] pub is_query: bool, + /// Away, with the away message (empty without one); `None`: not away. #[serde(default, skip_serializing_if = "Option::is_none")] pub away: Option, #[serde(default)] @@ -56,9 +81,89 @@ pub struct ClientInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub streaming: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub server_groups: Vec, + pub server_groups: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub country: Option, + /// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`: + /// no avatar. A new hash means a new avatar. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub avatar: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "is_zero_i32")] + pub talk_power: i32, + /// Allowed to talk regardless of talk power (`client_is_talker`). + #[serde(default, skip_serializing_if = "is_false")] + pub talker: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel_group: Option, + /// Badge GUIDs (`client_badges`), in display order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub badges: Vec, + /// Icon id (`client_icon_id`); 0: none. + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub icon: u32, + #[serde(default, skip_serializing_if = "is_false")] + pub recording: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub priority_speaker: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub channel_commander: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub database_id: Option, +} + +/// Badge GUIDs of a `client_badges` value +/// (`Overwolf=0:badges=,`). +pub fn parse_badges(value: &str) -> Vec { + value + .split(':') + .filter_map(|part| part.strip_prefix("badges=")) + .flat_map(|list| list.split(',')) + .map(str::trim) + .filter(|g| !g.is_empty()) + .map(str::to_owned) + .collect() +} + +/// 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)] @@ -87,6 +192,11 @@ pub struct Presence { pub server_name: String, pub channels: BTreeMap, pub clients: BTreeMap, + /// What the source knows about the server (a voice connection: all of + /// it; other sources: nothing). + pub server: ServerDetails, + pub server_groups: BTreeMap, + pub channel_groups: BTreeMap, } impl Presence { @@ -95,9 +205,23 @@ impl Presence { server_name: s.server_name, channels: s.channels.into_iter().map(|c| (c.id, c)).collect(), clients: s.clients.into_iter().map(|c| (c.id, c)).collect(), + ..Self::default() } } + /// The client with this unique id, if present (the first of several + /// connections with the same identity). + pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> { + self.clients.values().find(|c| c.uid.as_deref() == Some(uid)) + } + + /// Groups in display order (sort id, then id). + pub fn sorted_groups(groups: &BTreeMap) -> Vec<&GroupInfo> { + let mut sorted: Vec<_> = groups.values().collect(); + sorted.sort_by_key(|g| (g.sort_id, g.id)); + sorted + } + pub fn snapshot(&self) -> PresenceSnapshot { PresenceSnapshot { server_name: self.server_name.clone(), @@ -214,6 +338,40 @@ mod tests { assert!(new.diff(&new).is_empty()); } + #[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()); + 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); diff --git a/crates/voelin-model/src/server.rs b/crates/voelin-model/src/server.rs index d13e763..20925f7 100644 --- a/crates/voelin-model/src/server.rs +++ b/crates/voelin-model/src/server.rs @@ -78,17 +78,105 @@ impl ServerFlavor { pub fn capabilities(&self) -> Capabilities { match self { - ServerFlavor::Ts3(_) => { - Capabilities { streams: false, raw_query: true, ssh_query: true, http_query: false } - } - ServerFlavor::Ts6(_) => { - Capabilities { streams: true, raw_query: false, ssh_query: true, http_query: true } - } + 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 the host banner image is scaled. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HostBannerMode { + /// As it is. + #[default] + NoAdjust, + /// Stretched to the banner area. + IgnoreAspect, + /// Scaled to fit, keeping its aspect ratio. + KeepAspect, +} + +/// What a server tells its (voice) clients about itself. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerDetails { + pub name: String, + /// `virtualserver_unique_identifier` (the key of its chat history). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub uid: Option, + #[serde(default)] + pub welcome_message: String, + #[serde(default)] + pub host_message: String, + #[serde(default)] + pub host_message_mode: HostMessageMode, + /// Where a click on the banner leads. + #[serde(default)] + pub banner_url: String, + /// The banner image. + #[serde(default)] + pub banner_gfx_url: String, + /// Reload the banner image this often (seconds); 0: never. + #[serde(default)] + pub banner_gfx_interval_s: u64, + #[serde(default)] + pub banner_mode: HostBannerMode, + #[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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_server_group: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_channel_group: Option, +} + /// Features that depend on the server software. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Capabilities { @@ -100,6 +188,12 @@ pub struct Capabilities { 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)] diff --git a/crates/voelin-observer/src/convert.rs b/crates/voelin-observer/src/convert.rs index d1cb412..288750d 100644 --- a/crates/voelin-observer/src/convert.rs +++ b/crates/voelin-observer/src/convert.rs @@ -17,6 +17,7 @@ pub fn channel_from_row(row: &Row) -> Option { needed_subscribe_power: row.parse("channel_needed_subscribe_power").unwrap_or(0), needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0), is_default: row.flag("channel_flag_default").unwrap_or(false), + icon: row.parse::("channel_icon_id").map_or(0, |i| i as u32), }) } @@ -69,6 +70,19 @@ pub fn client_from_row(row: &Row) -> Option { .map(|g| g.split(',').filter_map(|g| g.parse().ok()).collect()) .unwrap_or_default(), country: row.get("client_country").filter(|c| !c.is_empty()).map(str::to_string), + // What the row carries (`notifycliententerview` all of it, + // `clientlist -voice -groups -icon` some). + avatar: row.get("client_flag_avatar").filter(|a| !a.is_empty()).map(str::to_string), + description: row.get("client_description").filter(|d| !d.is_empty()).map(str::to_string), + talk_power: row.parse("client_talk_power").unwrap_or(0), + talker: row.flag("client_is_talker").unwrap_or(false), + channel_group: row.parse("client_channel_group_id"), + badges: row.get("client_badges").map(voelin_model::parse_badges).unwrap_or_default(), + icon: row.parse::("client_icon_id").map_or(0, |i| i as u32), + recording: row.flag("client_is_recording").unwrap_or(false), + priority_speaker: row.flag("client_is_priority_speaker").unwrap_or(false), + channel_commander: row.flag("client_is_channel_commander").unwrap_or(false), + database_id: row.parse("client_database_id"), }) } @@ -130,6 +144,7 @@ pub fn is_text_message(n: &Notification, now_ms: i64) -> Option { text: row.get("msg").unwrap_or_default().to_string(), ts_ms: now_ms, via_relay: true, + blocked: false, }) } diff --git a/crates/voelin-store/src/contacts.rs b/crates/voelin-store/src/contacts.rs new file mode 100644 index 0000000..54099ac --- /dev/null +++ b/crates/voelin-store/src/contacts.rs @@ -0,0 +1,299 @@ +//! Contacts: people the user marked, by their unique id (the same on every +//! server). +//! +//! A contact is a friend, blocked, or neutral (only a note, a volume or a +//! mute). Its nickname is a hint (the last one seen); `last_seen_ms` and +//! `last_server` say when and where the engine saw the contact last. + +use rusqlite::{OptionalExtension, Row, params}; +use serde::{Deserialize, Serialize}; + +use crate::{Result, Store}; + +/// What the user thinks of a contact. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Relation { + Friend, + Blocked, + #[default] + Neutral, +} + +impl Relation { + pub fn as_str(self) -> &'static str { + match self { + Relation::Friend => "friend", + Relation::Blocked => "blocked", + Relation::Neutral => "neutral", + } + } + + /// Parse [`Self::as_str`]; anything else is neutral. + pub fn parse(s: &str) -> Self { + match s { + "friend" => Relation::Friend, + "blocked" => Relation::Blocked, + _ => Relation::Neutral, + } + } +} + +fn default_volume() -> f32 { + 1.0 +} + +/// A contact. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Contact { + /// The client's unique id. + pub uid: String, + /// The nickname last seen (or given by the user). + #[serde(default)] + pub nickname: String, + #[serde(default)] + pub relation: Relation, + #[serde(default)] + pub note: String, + /// Do not play the contact's voice. + #[serde(default)] + pub muted: bool, + /// Playback volume, linear (1 = unchanged). + #[serde(default = "default_volume")] + pub volume: f32, + /// Unix milliseconds when the contact was added. + #[serde(default)] + pub added_ms: i64, + /// Unix milliseconds when the contact was last seen on a server (0: never). + #[serde(default)] + pub last_seen_ms: i64, + /// The server (its name, else its unique id) the contact was last seen on. + #[serde(default)] + pub last_server: Option, +} + +impl Contact { + /// A neutral contact with the default volume. + pub fn new(uid: impl Into) -> Self { + Self { + uid: uid.into(), + nickname: String::new(), + relation: Relation::Neutral, + note: String::new(), + muted: false, + volume: 1.0, + added_ms: 0, + last_seen_ms: 0, + last_server: None, + } + } +} + +/// Version 3: contacts. +pub(crate) const SCHEMA_3: &str = r#" + CREATE TABLE contacts ( + uid TEXT PRIMARY KEY, + nickname TEXT NOT NULL DEFAULT '', + relation TEXT NOT NULL DEFAULT 'neutral', + note TEXT NOT NULL DEFAULT '', + mute INTEGER NOT NULL DEFAULT 0, + volume REAL NOT NULL DEFAULT 1.0, + added_ms INTEGER NOT NULL DEFAULT 0, + last_seen_ms INTEGER NOT NULL DEFAULT 0, + last_server TEXT + ) WITHOUT ROWID; +"#; + +const COLUMNS: &str = + "uid, nickname, relation, note, mute, volume, added_ms, last_seen_ms, last_server"; + +fn contact_from_row(r: &Row) -> rusqlite::Result { + let relation: String = r.get(2)?; + Ok(Contact { + uid: r.get(0)?, + nickname: r.get(1)?, + relation: Relation::parse(&relation), + note: r.get(3)?, + muted: r.get(4)?, + volume: r.get::<_, f64>(5)? as f32, + added_ms: r.get(6)?, + last_seen_ms: r.get(7)?, + last_server: r.get(8)?, + }) +} + +/// When and where a contact was seen, for [`Store::touch_contacts`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ContactSeen { + pub uid: String, + pub nickname: String, + pub ts_ms: i64, + pub server: Option, +} + +impl Store { + /// All contacts, by unique id. + pub fn contacts(&self) -> Result> { + let mut stmt = + self.db.prepare_cached(&format!("SELECT {COLUMNS} FROM contacts ORDER BY uid"))?; + let rows = stmt.query_map([], contact_from_row)?; + Ok(rows.collect::>()?) + } + + pub fn contact(&self, uid: &str) -> Result> { + Ok(self + .db + .prepare_cached(&format!("SELECT {COLUMNS} FROM contacts WHERE uid = ?1"))? + .query_row([uid], contact_from_row) + .optional()?) + } + + /// Store a contact (insert or replace all of it). + pub fn put_contact(&self, c: &Contact) -> Result<()> { + self.db + .prepare_cached(&format!( + "INSERT OR REPLACE INTO contacts ({COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)" + ))? + .execute(params![ + c.uid, + c.nickname, + c.relation.as_str(), + c.note, + c.muted, + f64::from(c.volume), + c.added_ms, + c.last_seen_ms, + c.last_server + ])?; + Ok(()) + } + + /// Remove a contact; `true` if it existed. + pub fn delete_contact(&self, uid: &str) -> Result { + Ok(self.db.prepare_cached("DELETE FROM contacts WHERE uid = ?1")?.execute([uid])? > 0) + } + + /// Record sightings of contacts in one transaction (newer ones win; + /// unknown unique ids are ignored). The nickname hint follows the + /// sighting. + pub fn touch_contacts(&mut self, seen: &[ContactSeen]) -> Result<()> { + let tx = self.db.transaction()?; + { + let mut update = tx.prepare_cached( + "UPDATE contacts SET last_seen_ms = ?2, last_server = COALESCE(?3, last_server), + nickname = CASE WHEN ?4 = '' THEN nickname ELSE ?4 END + WHERE uid = ?1 AND last_seen_ms <= ?2", + )?; + for s in seen { + update.execute(params![s.uid, s.ts_ms, s.server, s.nickname])?; + } + } + tx.commit()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn friend(uid: &str) -> Contact { + Contact { + nickname: "Alice".into(), + relation: Relation::Friend, + note: "from school".into(), + volume: 1.5, + added_ms: 10, + ..Contact::new(uid) + } + } + + #[test] + fn put_get_delete() { + let store = Store::open_in_memory().unwrap(); + assert!(store.contacts().unwrap().is_empty()); + let a = friend("a="); + store.put_contact(&a).unwrap(); + let mut b = Contact::new("b="); + b.relation = Relation::Blocked; + b.muted = true; + store.put_contact(&b).unwrap(); + assert_eq!(store.contacts().unwrap(), [a.clone(), b.clone()]); + assert_eq!(store.contact("a=").unwrap(), Some(a.clone())); + let changed = Contact { relation: Relation::Neutral, ..a.clone() }; + store.put_contact(&changed).unwrap(); + assert_eq!(store.contact("a=").unwrap().unwrap().relation, Relation::Neutral); + assert!(store.delete_contact("a=").unwrap()); + assert!(!store.delete_contact("a=").unwrap()); + assert_eq!(store.contacts().unwrap(), [b]); + } + + #[test] + fn sightings_update_known_contacts_only() { + let mut store = Store::open_in_memory().unwrap(); + store.put_contact(&friend("a=")).unwrap(); + let seen = |uid: &str, ts_ms, server: Option<&str>, nick: &str| ContactSeen { + uid: uid.into(), + nickname: nick.into(), + ts_ms, + server: server.map(str::to_owned), + }; + store + .touch_contacts(&[ + seen("a=", 100, Some("Home"), "Alice2"), + seen("x=", 100, Some("Home"), "X"), + ]) + .unwrap(); + let a = store.contact("a=").unwrap().unwrap(); + assert_eq!((a.last_seen_ms, a.last_server.as_deref()), (100, Some("Home"))); + assert_eq!(a.nickname, "Alice2"); + assert!(store.contact("x=").unwrap().is_none()); + // An older sighting does not win; no server keeps the last one. + store.touch_contacts(&[seen("a=", 50, Some("Other"), "")]).unwrap(); + store.touch_contacts(&[seen("a=", 200, None, "")]).unwrap(); + let a = store.contact("a=").unwrap().unwrap(); + assert_eq!((a.last_seen_ms, a.last_server.as_deref()), (200, Some("Home"))); + assert_eq!(a.nickname, "Alice2"); + } + + /// A database of version 2 (chat history, no contacts) gains the table + /// and keeps its data. + #[test] + fn migrates_version_2() { + let dir = std::env::temp_dir().join(format!("voelin-contacts-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("client.db"); + { + let mut db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch(crate::store::SCHEMA_1).unwrap(); + let tx = db.transaction().unwrap(); + crate::chat::migrate_2(&tx).unwrap(); + tx.commit().unwrap(); + db.pragma_update(None, "user_version", 2).unwrap(); + db.execute_batch("INSERT INTO settings (key, value) VALUES ('k', '1');").unwrap(); + } + let store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), 3); + assert_eq!(Store::SCHEMA_VERSION, 3); + assert_eq!(store.setting::("k").unwrap(), Some(1)); + store.put_contact(&friend("a=")).unwrap(); + drop(store); + let store = Store::open(&path).unwrap(); + assert_eq!(store.contacts().unwrap(), [friend("a=")]); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn relation_names() { + for r in [Relation::Friend, Relation::Blocked, Relation::Neutral] { + assert_eq!(Relation::parse(r.as_str()), r); + } + assert_eq!(Relation::parse("x"), Relation::Neutral); + let json = serde_json::to_string(&friend("a=")).unwrap(); + assert!(json.contains(r#""relation":"friend""#)); + let back: Contact = serde_json::from_str(r#"{"uid":"u"}"#).unwrap(); + assert_eq!(back, Contact::new("u")); + } +} diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index fc9a07c..58a672d 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -1,14 +1,15 @@ //! Local persistence for the client. //! -//! One SQLite database holds identities, bookmarks, settings and the chat -//! history ([`chat`]). Passwords and query credentials never go into the -//! database; they live in a [`Secrets`] store (the OS keyring with the -//! `keyring` feature). +//! One SQLite database holds identities, bookmarks, settings, contacts +//! ([`contacts`]) and the chat history ([`chat`]). Passwords and query +//! credentials never go into the database; they live in a [`Secrets`] store +//! (the OS keyring with the `keyring` feature). //! //! The schema is versioned (`PRAGMA user_version`): opening a database runs //! the migrations it has not seen, each in one transaction, keeping the data. pub mod chat; +pub mod contacts; mod secrets; mod store; @@ -16,6 +17,7 @@ pub use chat::{ ChatCursor, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo, StoredMessage, SyncState, WriteOutcome, Written, }; +pub use contacts::{Contact, ContactSeen, Relation}; #[cfg(feature = "keyring")] pub use secrets::KeyringSecrets; pub use secrets::{MemorySecrets, Secrets}; diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index 5e84339..d782bba 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -18,8 +18,11 @@ enum Migration { /// Schema migrations; entry `i` upgrades from version `i` to `i + 1` /// (`PRAGMA user_version`). Add new ones at the end; never change one that /// shipped. -const MIGRATIONS: &[Migration] = - &[Migration::Sql(SCHEMA_1), Migration::Code(crate::chat::migrate_2)]; +const MIGRATIONS: &[Migration] = &[ + Migration::Sql(SCHEMA_1), + Migration::Code(crate::chat::migrate_2), + Migration::Sql(crate::contacts::SCHEMA_3), +]; /// Version 1: identities, bookmarks, settings and a first chat cache. pub(crate) const SCHEMA_1: &str = r#" diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 18eff60..578b06d 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -358,6 +358,11 @@ pub fn run(options: RunOptions) -> Result<()> { // VOELIN_DATA_DIR isolates the database; the other development // switches are in dev.rs. + // A host that names the data directory (Android) has no platform cache + // directory either: avatars and icons go next to the database. + if let Some(dir) = &options.data_dir { + engine.send(Command::AttachCache(dir.join("images"))); + } let dir: PathBuf = match (options.data_dir, std::env::var_os("VOELIN_DATA_DIR")) { (Some(dir), _) => dir, (None, Some(dir)) => dir.into(), diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index cc52a53..af1832e 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -331,6 +331,7 @@ fn demo_ui(app: &mut App) { text: text.into(), ts_ms: now - (60 - minute) * 60_000, via_relay: relay, + blocked: false, }; app.add_message(id, message); } diff --git a/crates/voelin-ui/src/vm/chat.rs b/crates/voelin-ui/src/vm/chat.rs index da4b097..d4268be 100644 --- a/crates/voelin-ui/src/vm/chat.rs +++ b/crates/voelin-ui/src/vm/chat.rs @@ -86,6 +86,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, } } diff --git a/dev/docker-compose.yml b/dev/docker-compose.yml index 514d88b..c607b58 100644 --- a/dev/docker-compose.yml +++ b/dev/docker-compose.yml @@ -46,11 +46,14 @@ services: TSSERVER_QUERY_SSH_ENABLED: 1 TSSERVER_QUERY_HTTP_ENABLED: 1 TSSERVER_QUERY_ALLOW_LIST: /etc/tsserver/query_ip_allowlist.txt + # Clients connect to the port the server announces, so it must be the + # published one (30033 is the TS3 server's). + TSSERVER_FILE_TRANSFER_PORT: 30034 ports: - "9988:9987/udp" # voice (mapped to 9988 so both servers can run) - "10022:10022" # SSH ServerQuery - "10080:10080" # HTTP WebQuery - - "30034:30033" # file transfer + - "30034:30034" # file transfer: the server announces its own port volumes: - ts6-data:/var/tsserver - ./query_ip_allowlist.txt:/etc/tsserver/query_ip_allowlist.txt:ro diff --git a/docs/architecture.md b/docs/architecture.md index 271c46c..1747d17 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,6 +47,9 @@ the admin grants them to the guest query group. | Voice | tsproto UDP transport, Opus (`opus2`), echo cancellation / noise suppression (sonora), own jitter buffer, cpal / AAudio | | Invisible presence | Gateway presence stream (snapshot + deltas from query events) or direct query; `channelsubscribeall` when voice-connected | | Screen share with sound | TS6 stream signalling (`voelin-stream`), str0m WebRTC, per-platform capture and codecs (`voelin-media`) | +| Channel files, avatars, icons | Voice connection: `ftgetfilelist`, `ftinitdownload`/`ftinitupload` + TCP transfer, `ftdeletefile`/`ftrenamefile`/`ftcreatedir`; images cached on disk by content | +| Pokes, private messages, offline messages | Voice connection: `clientpoke`, `sendtextmessage targetmode=1`, `messagelist`/`messageget`/`messageadd`/`messagedel`/`messageupdateflag` | +| Friends, blocking | Contacts by unique id in the client database; presence of every session | ## Workspace layout @@ -62,14 +65,14 @@ fuzz/ cargo-fuzz targets | Crate | Responsibility | State | |---|---|---| -| `voelin-model` | UI-facing domain model (servers, channels, clients, chat, capabilities), no IO | done | +| `voelin-model` | UI-facing domain model (servers and their details, channels, clients, server and channel groups, chat and its file links, capabilities), no IO | done | | `voelin-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery | done | | `voelin-observer` | Presence tracker + chat relay pool over `voelin-query` | done | | `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | -| `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors), secrets (keyring / Android Keystore); versioned schema | done | +| `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors), contacts, secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) | | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport | -| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6; `media` module (capture → encoder → stream, stream → decoder) | done | +| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder) | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) | | `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders planned; MediaCodec not run on a device yet) | | `voelin-platform` | Global hotkeys, notifications, paths, crash reports, notices | done | @@ -145,6 +148,83 @@ local ids. The contract is in the module docs of `voelin_core::gateway` and `voelin_core::history`; `voelinctl gateway --engine` drives it from the command line. +## Server details, groups and client details + +The voice connection's book has everything the server tells its clients; +`voelin-model` carries it: per client the avatar hash (`client_flag_avatar`), +description, talk power, channel group, server groups, badges, icon, away +message, mute, talk, recording and stream flags; per server +(`Presence::server`, `ServerDetails`) the welcome and host message, host +banner (link, image, reload interval, scaling), host button, icon, unique id, +platform and version; the server and channel groups (name, icon, sort id, +naming mode, type). `Event::Presence` carries all of it; `Event::ServerDetails` +and `Event::Groups` come when those parts change. Gateway and query presence +fill what their rows have. The new fields are optional in JSON, so gateways +and clients of different versions still understand each other. + +## Files, avatars and icons + +Channel file browsers, avatars and icons go over the voice connection (TS3 +and TS6 alike, verified against 3.13.8 and 6.0.0-beta13.1). `ftgetfilelist` +lists a directory; `ftinitdownload`/`ftinitupload` open a transfer, which +then runs over its own TCP connection to the port the server announces (the +dev TS6 server announces 30034, its published port). The engine +(`voelin_core::files`) streams transfers in 64 KiB pieces: downloads into +`.part`, renamed when complete (resumable), or into memory; uploads +read the file as they send it. Progress is reported every +`files.progress_interval_ms`; transfers can be cancelled. Nothing limits +sizes besides the server's quotas. Requests and transfers carry ids the +caller picks (`RequestId`, `TransferId`). + +Chat messages link files as `[URL=ts3file://name?serverUID=…&channel=…&path=…&filename=…&size=…]`; +`ChatMessage::file_refs` finds them (`FileRef`) for file cards and +`Command::DownloadChatFile` fetches one (refused if the link names another +server). `FileRef::to_bbcode` writes a link. + +Avatars live in channel 0 as `/avatar_` (one letter +per nibble; the same on TS6 with its longer unique ids); `client_flag_avatar` +is the file's MD5. Icons are `/icon_`, the id being the CRC32 of the +image (below 1000: built into clients). The engine fetches every avatar and +icon of the servers it is on (`cache.fetch_images`) into a content-addressed +disk cache (`voelin_core::cache`, `/voelin/images/{avatars,icons}`): +a lookup is a map access, a download of the same file for several sessions +runs once, and the least recently used files go when the cache exceeds +`cache.max_mb` (0: no limit). `Event::AvatarReady` / `Event::IconReady` +report the files. `Command::SetAvatar` uploads ours to `/avatar` and +announces its hash (`clientupdate client_flag_avatar`), or removes it. + +## Pokes, private and offline messages + +`Command::Poke` sends `clientpoke`; incoming pokes are `Event::Poke` (they +used to be stored as private messages). Private messages to any client on +the server are a `ChatTarget::Private(unique id)` chat over the voice +connection, stored in the chat history under the peer's unique id, so the +conversation survives reconnects and new client ids. Gateways and query +relays cannot send private messages as the user; without voice the engine +says so. A voice command that fails (e.g. a private message to a client who +left) is an error event; the connection stays. + +Offline messages (`voelin_core::offline`, capability `offline_messages`, +TS3 and TS6) are listed, read, sent to a unique id (on TS6 the one that +server generation derives, see `voelinctl identity show`), deleted and +marked read. Guests may not send them by default. + +## Contacts + +Contacts (`voelin_store::contacts`, table `contacts` since schema version 3) +are people by unique id: friend, blocked or neutral, with a note, a mute and +a volume, when they were added, and when and on which server they were last +seen. The engine (`voelin_core::contacts`) keeps them in memory for lookups, +takes `Command::SetContact` / `RemoveContact`, and reports +`Event::ContactsChanged`. From the presence of every session (voice, +gateway or query) it reports where each friend is (`Event::FriendPresence`) +for Home's friends list, and records sightings in one write per change. A +contact's mute and volume apply to their voice in every session. Messages of +blocked contacts are flagged (`ChatMessage::blocked`, live and in history); +their private messages and pokes are dropped or flagged per +`privacy.block_mode`. `stream.permissions = friends` lets friends watch our +stream without asking and asks for everyone else. + ## Streams `voelin-stream::Streams` holds the stream state of one TS6 connection without @@ -230,7 +310,8 @@ key); writes notify subscribers and go to SQLite on a writer thread. The engine holds one (`Engine::settings`, `Command::AttachSettings`), takes `Command::SetSetting` / `ResetSetting` and reports `Event::SettingChanged`. The UI opens it on its database and registers its own keys (`ui`, -`client_playback`); the stream keys (`stream.*`) and chat keys (`chat.*`) +`client_playback`); the stream (`stream.*`), chat (`chat.*`), cache (`cache.*`), +file transfer (`files.*`) and privacy (`privacy.*`) keys are defined in the core, which reads them on every use. ## Milestones diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 2441f4a..2fde60b 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -23,6 +23,12 @@ # 11. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream # 12. late stream (TeamSpeak 6 only): a viewer that connects after the stream # started finds it (requeststreaminfo) and watches it +# 13. the engine's voice features (voelinctl engine): upload a file and +# post its link in chat, another client lists the channel's files and +# downloads the linked file (compared byte for byte), the file is +# deleted; an avatar set by one client is fetched by another (MD5 +# checked); poke, private message and offline message round trips; a +# friend is seen online; a blocked contact's poke arrives flagged # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: VOELINCTL=path/to/voelinctl, TSGW=path/to/tsgw (default: builds both @@ -352,6 +358,114 @@ directory_check() { grep -E "^watching|^received" "$viewer_out" } +# A voice session through the engine: voelinctl engine . +eng() { + local addr=$1 + shift + "$VOELINCTL" engine "$addr" "$@" +} + +# The unique id the server knows an identity by (TeamSpeak 6: another hash). +server_uid() { + local svc=$1 id=$2 field=uid + [[ $svc == ts6 ]] && field=uid6 + "$VOELINCTL" identity show --identity "$id" | awk -v f="$field:" '$1 == f { print $2 }' +} + +# Run a background listener, then the action; both must succeed. +roundtrip() { + local what=$1 listen_log=$2 listener_cmd=$3 action_cmd=$4 + eval "$listener_cmd" >"$listen_log" 2>&1 & + local listener=$! + sleep 3 + if ! eval "$action_cmd" >"$STATE_DIR/action.log" 2>&1; then + cat "$STATE_DIR/action.log" "$listen_log" + fail "$what: the action failed" + fi + if ! wait "$listener"; then + cat "$listen_log" "$STATE_DIR/action.log" + fail "$what: not received" + fi +} + +# Files, avatars, pokes, private and offline messages, contacts through the +# engine (voelinctl engine). +engine_voice_check() { + local svc=$1 addr=$2 admin_id="$STATE_DIR/$svc-admin.json" + local user="$STATE_DIR/voice-user.json" other="$STATE_DIR/voice-other.json" + [[ -f "$user" ]] || "$VOELINCTL" identity new --out "$user" >/dev/null + [[ -f "$other" ]] || "$VOELINCTL" identity new --out "$other" >/dev/null + local t="$$-$RANDOM" dir="$STATE_DIR/files-$svc" + rm -rf "$dir" && mkdir -p "$dir/in" + + # Files: the admin uploads (guests may not) and links the file in chat; + # a reader downloads it from the link; a guest lists it; it is deleted. + head -c 1500000 /dev/urandom >"$dir/smoke-$t.bin" + roundtrip "file link" "$dir/reader.log" \ + "eng $addr --nick file-reader --seconds 25 listen --fetch-links $dir/in" \ + "eng $addr --identity $admin_id --nick file-sharer --seconds 20 files upload $dir/smoke-$t.bin --share --overwrite" + cmp "$dir/smoke-$t.bin" "$dir/in/smoke-$t.bin" || fail "the downloaded file differs" + grep -E "^file link|^transfer 7 done" "$dir/reader.log" + if ! eng "$addr" --nick file-lister --seconds 20 files ls --channel 1 --path / \ + --expect "smoke-$t.bin" >"$dir/ls.log" 2>&1; then + cat "$dir/ls.log" + fail "the file is not listed" + fi + grep "smoke-$t.bin" "$dir/ls.log" + eng "$addr" --identity "$admin_id" --nick file-sharer --seconds 20 files rm --channel 1 \ + "/smoke-$t.bin" >/dev/null || fail "could not delete the file" + + # Avatar: set by one client (kept by the server), fetched by another. + printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' | + base64 -d >"$dir/avatar.png" + local md5 + md5=$(md5sum "$dir/avatar.png" | cut -d' ' -f1) + eng "$addr" --identity "$user" --nick avatar-owner-$t --seconds 20 avatar set "$dir/avatar.png" \ + >"$dir/avatar-set.log" 2>&1 || { cat "$dir/avatar-set.log"; fail "could not set the avatar"; } + roundtrip "avatar" "$dir/avatar-owner.log" \ + "eng $addr --identity $user --nick avatar-owner-$t --seconds 10 listen --expect never-$t || true" \ + "eng $addr --nick avatar-fetcher --seconds 12 avatar wait --nick avatar-owner-$t --md5 $md5" + grep "^avatar avatar-owner-$t" "$STATE_DIR/action.log" + + # Poke and private message from one guest to another. + roundtrip "poke" "$dir/poke.log" \ + "eng $addr --identity $user --nick poke-target-$t --seconds 15 listen --expect poke-$t" \ + "eng $addr --nick poker --seconds 10 poke --to poke-target-$t --message poke-$t" + grep "^poke from" "$dir/poke.log" + roundtrip "private message" "$dir/dm.log" \ + "eng $addr --identity $user --nick dm-target-$t --seconds 15 listen --expect dm-$t" \ + "eng $addr --nick dm-sender --seconds 10 dm --to dm-target-$t --message dm-$t" + grep "^chat private" "$dir/dm.log" + + # Offline message: the admin writes (guests may not), the user reads + # and deletes it. + local uid + uid=$(server_uid "$svc" "$user") + eng "$addr" --identity "$admin_id" --nick mailer --seconds 15 offline send --to-uid "$uid" \ + --subject "smoke $t" --message "offline-$t" >"$dir/offline-send.log" 2>&1 || + { cat "$dir/offline-send.log"; fail "could not send the offline message"; } + if ! eng "$addr" --identity "$user" --nick mail-reader --seconds 15 offline read \ + --expect "offline-$t" --delete >"$dir/offline-read.log" 2>&1; then + cat "$dir/offline-read.log" + fail "the offline message did not arrive" + fi + grep "offline-$t" "$dir/offline-read.log" + + # Contacts: a friend seen online; a blocked contact's poke flagged. + local db="$dir/contacts.db" + eng "$addr" --db "$db" contacts set "$uid" --relation friend --nickname friend >/dev/null + eng "$addr" --db "$db" contacts set "$(server_uid "$svc" "$other")" --relation blocked >/dev/null + roundtrip "friend presence" "$dir/friend.log" \ + "eng $addr --identity $user --nick friend-$t --seconds 10 listen --expect never-$t || true" \ + "eng $addr --db $db --nick friend-watcher --seconds 10 contacts ls --expect-online $uid" + grep "^friend" "$STATE_DIR/action.log" | tail -1 + roundtrip "blocked poke" "$dir/blocked.log" \ + "eng $addr --db $db --set privacy.block_mode=flag --nick blocker-$t --seconds 15 listen --expect '(blocked)'" \ + "eng $addr --identity $other --nick blocked-poker --seconds 10 poke --to blocker-$t --message blocked-$t" + grep "^poke from" "$dir/blocked.log" + rm -rf "$dir" +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" @@ -370,6 +484,7 @@ for svc in "${SERVERS[@]}"; do presence_check "$addr" "${QUERY[$svc]}" relay_check "$addr" "${QUERY[$svc]}" gateway_check "$svc" "$addr" + engine_voice_check "$svc" "$addr" if [[ $svc == ts6 ]]; then stream_check "$addr" stream_late_check "$addr" diff --git a/tools/voelinctl/Cargo.toml b/tools/voelinctl/Cargo.toml index 3ed9ccc..df0ab3f 100644 --- a/tools/voelinctl/Cargo.toml +++ b/tools/voelinctl/Cargo.toml @@ -14,6 +14,7 @@ base64 = "0.22" clap = { version = "4", features = ["derive", "env"] } dirs = "6" futures = "0.3" +md5 = "0.8" png = "0.18" serde_json = "1" tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "signal", "time"] } diff --git a/tools/voelinctl/src/client.rs b/tools/voelinctl/src/client.rs new file mode 100644 index 0000000..c629c03 --- /dev/null +++ b/tools/voelinctl/src/client.rs @@ -0,0 +1,792 @@ +//! `voelinctl engine`: a voice session through the client engine +//! (voelin-core), for what the app does with a voice connection: files, +//! avatars and icons, pokes, private and offline messages, contacts. +//! +//! Prints one line per interesting event (`files ...`, `transfer ...`, +//! `poke ...`, `chat ...`, `avatar ...`, `icon ...`, `offline ...`, +//! `friend ...`, `contacts ...`, `done ...`, `error: ...`). The action +//! decides when the run succeeded; `--seconds` bounds it. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use clap::{Args, Subcommand}; +use tokio::sync::broadcast::error::RecvError; +use tokio::time::{Instant, timeout_at}; +use voelin_core::settings::Settings; +use voelin_core::{ + Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState, VoiceOptions, + VoiceState, +}; +use voelin_model::{ChatTarget, Presence}; + +use crate::gateway::target_name; + +const SESSION: u64 = 1; + +#[derive(Args, Debug)] +pub struct EngineArgs { + /// Server address (host:port). + pub address: String, + /// Identity file (default: a new identity). + #[arg(long, env = "VOELINCTL_IDENTITY")] + pub identity: Option, + #[arg(long, default_value = "voelinctl")] + pub nick: String, + /// Client database: chat history and contacts (default: in memory). + #[arg(long)] + pub db: Option, + /// Avatar and icon cache directory (default: a new temporary one). + #[arg(long)] + pub cache: Option, + /// Give up after this many seconds. + #[arg(long, default_value_t = 30)] + pub seconds: u64, + /// An engine setting, e.g. `privacy.block_mode=flag`. Repeatable. + #[arg(long = "set", value_name = "KEY=VALUE")] + pub set: Vec, + #[command(subcommand)] + pub action: EngineAction, +} + +#[derive(Subcommand, Debug)] +pub enum EngineAction { + /// A channel's file browser. + Files { + #[command(subcommand)] + command: FilesCommand, + }, + /// Our avatar, or wait for someone else's. + Avatar { + #[command(subcommand)] + command: AvatarCommand, + }, + /// Poke the client with this nickname. + Poke { + #[arg(long)] + to: String, + #[arg(long)] + message: String, + }, + /// Send a private message to the client with this nickname. + Dm { + #[arg(long)] + to: String, + #[arg(long)] + message: String, + }, + /// Offline messages. + Offline { + #[command(subcommand)] + command: OfflineCommand, + }, + /// Contacts in `--db`. + Contacts { + #[command(subcommand)] + command: ContactsCommand, + }, + /// Print events; with `--expect`, succeed once a line contains it. + Listen { + #[arg(long)] + expect: Option, + /// Download the first file linked in chat into this directory + /// (succeeds when it is there). + #[arg(long)] + fetch_links: Option, + }, +} + +#[derive(Subcommand, Debug)] +pub enum FilesCommand { + /// List a directory. + Ls { + #[arg(long, default_value_t = 1)] + channel: u64, + #[arg(long, default_value = "/")] + path: String, + /// Succeed only if an entry of this name is listed. + #[arg(long)] + expect: Option, + }, + /// Upload a local file. + Upload { + file: PathBuf, + #[arg(long, default_value_t = 1)] + channel: u64, + /// Remote path (default: `/`). + #[arg(long)] + path: Option, + #[arg(long)] + overwrite: bool, + /// Then post a link to it in our channel's chat. + #[arg(long)] + share: bool, + }, + /// Download a file. + Download { + #[arg(long, default_value_t = 1)] + channel: u64, + #[arg(long)] + path: String, + #[arg(long)] + out: PathBuf, + #[arg(long)] + resume: bool, + }, + /// Delete files or directories. + Rm { + #[arg(long, default_value_t = 1)] + channel: u64, + paths: Vec, + }, + Mkdir { + #[arg(long, default_value_t = 1)] + channel: u64, + path: String, + }, + Mv { + #[arg(long, default_value_t = 1)] + channel: u64, + from: String, + to: String, + }, +} + +#[derive(Subcommand, Debug)] +pub enum AvatarCommand { + /// Upload an image as our avatar. + Set { image: PathBuf }, + /// Remove our avatar. + Clear, + /// Wait until the avatar of the client with this nickname is fetched. + Wait { + #[arg(long)] + nick: String, + /// Fail unless the file's MD5 is this. + #[arg(long)] + md5: Option, + }, +} + +#[derive(Subcommand, Debug)] +pub enum OfflineCommand { + /// Send to a unique id. + Send { + #[arg(long)] + to_uid: String, + #[arg(long)] + subject: String, + #[arg(long)] + message: String, + }, + /// List the inbox and read every message; with `--expect`, succeed if a + /// text contains it; with `--delete`, delete what was read. + Read { + #[arg(long)] + expect: Option, + #[arg(long)] + delete: bool, + }, +} + +#[derive(Subcommand, Debug)] +pub enum ContactsCommand { + /// Add or change a contact. + Set { + uid: String, + #[arg(long, value_parser = ["friend", "blocked", "neutral"], default_value = "neutral")] + relation: String, + #[arg(long, default_value = "")] + nickname: String, + #[arg(long, default_value = "")] + note: String, + }, + Rm { + uid: String, + }, + /// Connect, print the contacts and friends' presence. + Ls { + /// Succeed once this friend (unique id) is seen online. + #[arg(long)] + expect_online: Option, + }, +} + +/// What the action waits for. +#[derive(Default)] +struct Wait { + /// Answers still missing, by request or transfer id. + requests: usize, + done: bool, +} + +pub async fn run(args: EngineArgs) -> Result<()> { + let settings = Settings::in_memory(); + if let Some(e) = settings.apply_overrides(args.set.iter().map(String::as_str)).first() { + bail!("--set: {e}"); + } + let history = match &args.db { + Some(path) => { + History::open(path).with_context(|| format!("database {}", path.display()))? + } + None => History::in_memory(), + }; + let engine = Engine::start_with(settings, history); + let mut events = engine.subscribe(); + let temp_cache = args.cache.is_none(); + let cache = args.cache.clone().unwrap_or_else(|| { + std::env::temp_dir().join(format!("voelinctl-cache-{}", std::process::id())) + }); + engine.send(Command::AttachCache(cache.clone())); + let deadline = Instant::now() + Duration::from_secs(args.seconds); + + // Contacts need no server. + if let EngineAction::Contacts { command } = &args.action + && !matches!(command, ContactsCommand::Ls { .. }) + { + let result = contacts(&engine, command, &mut events, deadline).await; + engine.history().flush(); + return result; + } + + let mut options = VoiceOptions::new(&args.address, &args.nick); + if let Some(path) = &args.identity { + options.identity = Some(crate::identity::load(path)?); + } + engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + + let mut run = Runner { + engine: engine.clone(), + args: &args, + presence: Arc::new(Presence::default()), + server_uid: None, + connected: false, + started: false, + wait: Wait::default(), + read: BTreeMap::new(), + matched: false, + fetched_link: false, + finish_at: None, + }; + let result = loop { + let wake = run.finish_at.map_or(deadline, |f| f.min(deadline)); + let event = match timeout_at(wake, events.recv()).await { + Ok(Ok(e)) => e, + Ok(Err(RecvError::Lagged(_))) => continue, + Ok(Err(RecvError::Closed)) => break Err(anyhow::anyhow!("engine stopped")), + Err(_) if run.finish_at.is_some_and(|f| Instant::now() >= f) => break Ok(()), + Err(_) => break Err(anyhow::anyhow!("timed out")), + }; + match run.event(event) { + Ok(true) => break Ok(()), + Ok(false) => {} + Err(e) => break Err(e), + } + }; + engine.send(Command::DisconnectVoice { session: SESSION }); + engine.history().flush(); + // Let the disconnect go out. + tokio::time::sleep(Duration::from_millis(300)).await; + if temp_cache { + let _ = std::fs::remove_dir_all(&cache); + } + result +} + +struct Runner<'a> { + engine: Engine, + args: &'a EngineArgs, + presence: Arc, + server_uid: Option, + connected: bool, + started: bool, + wait: Wait, + /// Offline messages being read: id → subject. + read: BTreeMap, + /// An offline message had the expected text. + matched: bool, + fetched_link: bool, + /// Succeed at this time unless an error comes first (commands that + /// have no answer on success). + finish_at: Option, +} + +impl Runner<'_> { + fn send(&self, command: Command) { + self.engine.send(command); + } + + fn client_id(&self, nick: &str) -> Result { + self.presence + .clients + .values() + .find(|c| c.nickname == nick) + .map(|c| c.id) + .with_context(|| format!("no client {nick:?} on the server")) + } + + /// Handle one event; `Ok(true)`: the action succeeded. + fn event(&mut self, event: Event) -> Result { + match event { + Event::State { session: SESSION, state } => { + if state.voice == VoiceState::Connected { + self.connected = true; + } + if state.server_uid.is_some() { + self.server_uid = state.server_uid; + } + } + Event::Presence { session: SESSION, presence } => { + self.presence = presence; + if self.connected && !self.started && !self.presence.clients.is_empty() { + self.started = true; + println!("connected: {} clients", self.presence.clients.len()); + return self.start(); + } + } + Event::Error { session: SESSION, message } => { + println!("error: {message}"); + if !matches!(self.args.action, EngineAction::Listen { .. }) { + bail!("{message}"); + } + } + Event::FileList { request, channel, path, result, .. } => match result { + Ok(entries) => { + for e in &entries { + let kind = if e.is_dir { "dir" } else { "file" }; + println!("files {channel}:{path} {kind} {} {} bytes", e.name, e.size); + } + println!("files {channel}:{path} n={} (request {request})", entries.len()); + if let EngineAction::Files { command: FilesCommand::Ls { expect, .. } } = + &self.args.action + { + if let Some(name) = expect + && !entries.iter().any(|e| &e.name == name) + { + bail!("{name} is not listed"); + } + return Ok(true); + } + } + Err(e) => bail!("listing {channel}:{path}: {e}"), + }, + Event::Transfer { transfer, state, .. } => { + match &state { + TransferState::Progress { .. } => {} + TransferState::Done { size, path, .. } => { + let path = path.as_ref().map(|p| p.display().to_string()); + println!( + "transfer {transfer} done {size} bytes {}", + path.unwrap_or_default() + ); + } + state => println!("transfer {transfer} {state:?}"), + } + match state { + TransferState::Failed(e) => bail!("transfer {transfer}: {e}"), + TransferState::Cancelled => bail!("transfer {transfer} cancelled"), + TransferState::Done { size, .. } => return self.transfer_done(size), + _ => {} + } + } + Event::RequestDone { request, result, .. } => { + match &result { + Ok(()) => println!("done {request}"), + Err(e) => println!("done {request} failed: {e}"), + } + result.map_err(|e| anyhow::anyhow!("request {request}: {e}"))?; + self.wait.requests = self.wait.requests.saturating_sub(1); + if self.wait.requests == 0 && self.wait.done { + return Ok(true); + } + } + Event::Poke { from_name, message, blocked, .. } => { + let line = format!( + "poke from {from_name}: {message}{}", + if blocked { " (blocked)" } else { "" } + ); + println!("{line}"); + return Ok(self.expected(&line)); + } + Event::Chat { session: SESSION, message } => { + println!( + "chat {} {}{}: {}", + target_name(&message.target), + message.author_name, + if message.blocked { " (blocked)" } else { "" }, + message.text + ); + for file in message.file_refs() { + println!( + "file link {}:{} ({:?} bytes, server {:?})", + file.channel, + file.full_path(), + file.size, + file.server_uid + ); + if let EngineAction::Listen { fetch_links: Some(dir), .. } = &self.args.action + && !self.fetched_link + { + self.fetched_link = true; + let to = DownloadTo::Path { path: dir.join(&file.name), resume: false }; + self.send(Command::DownloadChatFile { + session: SESSION, + transfer: 7, + file, + password: None, + to, + }); + } + } + let private = matches!(message.target, ChatTarget::Private(_)); + // Our own message comes back once the server delivered it. + if let EngineAction::Dm { message: sent, .. } = &self.args.action { + return Ok(private && message.text == *sent); + } + return Ok(self.expected(&message.text)); + } + Event::AvatarReady { client_uid, path, hash, .. } => { + let nick = self + .presence + .client_by_uid(&client_uid) + .map_or("?", |c| c.nickname.as_str()) + .to_owned(); + println!("avatar {nick} {client_uid} {hash} {}", path.display()); + if let EngineAction::Avatar { command: AvatarCommand::Wait { nick: want, md5 } } = + &self.args.action + && *want == nick + { + let data = std::fs::read(&path)?; + let actual = format!("{:x}", md5_of(&data)); + if actual != hash { + bail!("avatar file hash {actual} is not the announced {hash}"); + } + if let Some(md5) = md5 + && *md5 != actual + { + bail!("avatar hash {actual}, expected {md5}"); + } + return Ok(true); + } + } + Event::IconReady { icon, path, .. } => { + println!("icon {icon} {}", path.display()); + return Ok(self.expected(&format!("icon {icon}"))); + } + Event::OfflineMessages { result, .. } => { + let list = result.map_err(|e| anyhow::anyhow!("messagelist: {e}"))?; + println!("offline inbox n={}", list.len()); + if list.is_empty() { + bail!("no offline messages"); + } + for (i, m) in list.iter().enumerate() { + println!( + "offline {} from {} {:?} read={}", + m.id, m.from_uid, m.subject, m.read + ); + self.read.insert(m.id, m.subject.clone()); + self.send(Command::GetOfflineMessage { + session: SESSION, + request: 100 + i as u64, + id: m.id, + }); + } + } + Event::OfflineMessage { result, .. } => { + let m = result.map_err(|e| anyhow::anyhow!("messageget: {e}"))?; + println!("offline {} from {} {:?}: {}", m.id, m.from_uid, m.subject, m.text); + self.read.remove(&m.id); + self.matched |= self.expected(&m.text); + if let EngineAction::Offline { + command: OfflineCommand::Read { delete: true, .. }, + } = &self.args.action + { + self.wait.requests += 1; + let request = 1000 + u64::from(m.id); + self.send(Command::DeleteOfflineMessage { + session: SESSION, + request, + id: m.id, + }); + } + if self.read.is_empty() { + let expecting = matches!( + &self.args.action, + EngineAction::Offline { + command: OfflineCommand::Read { expect: Some(_), .. } + } + ); + if expecting && !self.matched { + bail!("no offline message contains the expected text"); + } + self.wait.done = true; + return Ok(self.wait.requests == 0); + } + } + Event::FriendPresence { uid, sessions } => { + let spots: Vec = sessions + .iter() + .map(|s| format!("{} as {} in {}", s.server_name, s.nickname, s.channel_name)) + .collect(); + println!("friend {uid}: [{}]", spots.join(", ")); + if let EngineAction::Contacts { + command: ContactsCommand::Ls { expect_online: Some(want) }, + } = &self.args.action + { + return Ok(*want == uid && !sessions.is_empty()); + } + } + Event::ServerDetails { details, .. } => { + println!( + "server {:?} {} {} icon={} banner={:?}", + details.name, + details.platform, + details.version, + details.icon, + details.banner_gfx_url + ); + } + Event::Groups { server_groups, channel_groups, .. } => { + println!( + "groups: {} server, {} channel", + server_groups.len(), + channel_groups.len() + ); + } + _ => {} + } + Ok(false) + } + + /// `--expect` of listen / offline read. + fn expected(&self, text: &str) -> bool { + let expect = match &self.args.action { + EngineAction::Listen { expect, .. } => expect, + EngineAction::Offline { command: OfflineCommand::Read { expect, .. } } => expect, + _ => return false, + }; + expect.as_ref().is_some_and(|e| text.contains(e.as_str())) + } + + /// Voice is up: do the action. + fn start(&mut self) -> Result { + let session = SESSION; + match &self.args.action { + EngineAction::Files { command } => match command { + FilesCommand::Ls { channel, path, .. } => self.send(Command::ListFiles { + session, + request: 1, + channel: *channel, + password: None, + path: path.clone(), + }), + FilesCommand::Upload { file, channel, path, overwrite, .. } => { + let name = file.file_name().context("file name")?.to_string_lossy(); + let path = path.clone().unwrap_or_else(|| format!("/{name}")); + self.send(Command::UploadFile { + session, + transfer: 1, + channel: *channel, + password: None, + path, + from: file.clone(), + overwrite: *overwrite, + resume: false, + }); + } + FilesCommand::Download { channel, path, out, resume } => { + self.send(Command::DownloadFile { + session, + transfer: 1, + channel: *channel, + password: None, + path: path.clone(), + to: DownloadTo::Path { path: out.clone(), resume: *resume }, + }); + } + FilesCommand::Rm { channel, paths } => { + self.wait = Wait { requests: 1, done: true }; + self.send(Command::DeleteFiles { + session, + request: 1, + channel: *channel, + password: None, + paths: paths.clone(), + }); + } + FilesCommand::Mkdir { channel, path } => { + self.wait = Wait { requests: 1, done: true }; + self.send(Command::CreateDirectory { + session, + request: 1, + channel: *channel, + password: None, + path: path.clone(), + }); + } + FilesCommand::Mv { channel, from, to } => { + self.wait = Wait { requests: 1, done: true }; + self.send(Command::RenameFile { + session, + request: 1, + channel: *channel, + password: None, + from: from.clone(), + to: to.clone(), + to_channel: None, + }); + } + }, + EngineAction::Avatar { command } => match command { + AvatarCommand::Set { image } => { + self.wait = Wait { requests: 1, done: true }; + let image = Some(image.clone()); + self.send(Command::SetAvatar { session, request: 1, image }); + } + AvatarCommand::Clear => { + self.wait = Wait { requests: 1, done: true }; + self.send(Command::SetAvatar { session, request: 1, image: None }); + } + AvatarCommand::Wait { nick, .. } => { + // Also when it was fetched before this run looked. + if let Some(uid) = self + .presence + .clients + .values() + .find(|c| c.nickname == *nick) + .and_then(|c| c.uid.clone()) + { + self.send(Command::FetchAvatar { session, client_uid: uid }); + } + } + }, + EngineAction::Poke { to, message } => { + let client = self.client_id(to)?; + self.send(Command::Poke { session, client, message: message.clone() }); + // No answer on success: an error would come quickly. + self.finish_at = Some(Instant::now() + Duration::from_secs(1)); + } + EngineAction::Dm { to, message } => { + let uid = self + .presence + .clients + .values() + .find(|c| c.nickname == *to) + .and_then(|c| c.uid.clone()) + .with_context(|| format!("no client {to:?} with a unique id"))?; + let target = ChatTarget::Private(uid); + self.send(Command::OpenChat { session, target: target.clone() }); + self.send(Command::SendChat { session, target, text: message.clone() }); + } + EngineAction::Offline { command } => match command { + OfflineCommand::Send { to_uid, subject, message } => { + self.wait = Wait { requests: 1, done: true }; + self.send(Command::SendOfflineMessage { + session, + request: 1, + to_uid: to_uid.clone(), + subject: subject.clone(), + text: message.clone(), + }); + } + OfflineCommand::Read { .. } => { + self.send(Command::ListOfflineMessages { session, request: 1 }); + } + }, + EngineAction::Contacts { command } => { + for c in self.engine.contacts() { + println!("contact {} {:?} {:?}", c.uid, c.relation, c.nickname); + } + if matches!(command, ContactsCommand::Ls { expect_online: None }) { + self.finish_at = Some(Instant::now() + Duration::from_secs(2)); + } + } + EngineAction::Listen { .. } => {} + } + Ok(false) + } + + /// Our echo of a private message proves it was sent. + fn transfer_done(&mut self, size: u64) -> Result { + if let EngineAction::Files { + command: FilesCommand::Upload { file, channel, path, share: true, .. }, + } = &self.args.action + { + let name = file.file_name().context("file name")?.to_string_lossy().into_owned(); + let path = path.clone().unwrap_or_else(|| format!("/{name}")); + let (dir, name) = match path.rsplit_once('/') { + Some((dir, name)) => (if dir.is_empty() { "/" } else { dir }, name), + None => ("/", path.as_str()), + }; + let link = voelin_model::FileRef { + server_uid: self.server_uid.clone(), + channel: *channel, + path: dir.to_owned(), + name: name.to_owned(), + size: Some(size), + ..Default::default() + }; + let target = ChatTarget::Channel(*channel); + let text = link.to_bbcode(); + println!("share {text}"); + self.send(Command::SendChat { session: SESSION, target, text }); + self.finish_at = Some(Instant::now() + Duration::from_secs(1)); + return Ok(false); + } + Ok(true) + } +} + +async fn contacts( + engine: &Engine, + command: &ContactsCommand, + events: &mut tokio::sync::broadcast::Receiver, + deadline: Instant, +) -> Result<()> { + // The stored contacts are loaded first (on the database thread). + let history = engine.history(); + tokio::task::spawn_blocking(move || history.flush()).await?; + while events.try_recv().is_ok() {} + match command { + ContactsCommand::Set { uid, relation, nickname, note } => { + let relation = match relation.as_str() { + "friend" => Relation::Friend, + "blocked" => Relation::Blocked, + _ => Relation::Neutral, + }; + let contact = Contact { + nickname: nickname.clone(), + relation, + note: note.clone(), + ..Contact::new(uid.clone()) + }; + engine.send(Command::SetContact { contact: Box::new(contact) }); + } + ContactsCommand::Rm { uid } => engine.send(Command::RemoveContact { uid: uid.clone() }), + ContactsCommand::Ls { .. } => {} + } + let changed = timeout_at(deadline, async { + while let Ok(e) = events.recv().await { + if let Event::ContactsChanged { contacts } = e { + return Some(contacts); + } + } + None + }) + .await + .ok() + .flatten() + .context("no contacts update")?; + println!("contacts n={}", changed.len()); + for c in changed.iter() { + println!("contact {} {:?} {:?} {:?}", c.uid, c.relation, c.nickname, c.note); + } + Ok(()) +} + +fn md5_of(data: &[u8]) -> md5::Digest { + md5::compute(data) +} diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index b631171..8156c45 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -2,6 +2,7 @@ mod alloc; mod bench; +mod client; mod engine; mod gateway; mod identity; @@ -56,6 +57,9 @@ enum Command { /// `--engine` through the client engine (chat history sync, pins, /// reactions, topics, events, stream directory, administration). Gateway(gateway::GatewayArgs), + /// A voice session through the client engine: files, avatars, pokes, + /// private and offline messages, contacts. + Engine(client::EngineArgs), /// TeamSpeak 6: probe how a client that arrives after a stream started /// can learn about it; prints every command both clients exchange. ProbeStream(probe::ProbeStreamArgs), @@ -223,6 +227,7 @@ fn main() -> Result<()> { Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)), Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::run(args)), + Command::Engine(args) => tokio::runtime::Runtime::new()?.block_on(client::run(args)), Command::ProbeStream(args) => tokio::runtime::Runtime::new()?.block_on(probe::run(args)), Command::Stream(args) => bench::run(args), } @@ -247,7 +252,11 @@ fn run_identity(command: IdentityCommand) -> Result<()> { let id = identity::load(&path)?; println!("uid: {}", identity::uid(&id)); println!("level: {}", id.level()); - println!("omega: {}", id.key().to_pub().to_ts()); + let omega = id.key().to_pub().to_ts(); + // TeamSpeak 6 servers know the identity by another unique id. + let ids = voelin_gateway_proto::UniqueIds::from_omega(&omega); + println!("uid6: {}", ids.ts6); + println!("omega: {omega}"); Ok(()) } }