From f24da42aabdec926f4f25b8642dfd63c3fb277db Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 19:50:39 +0000 Subject: [PATCH] voelin-core: files, avatars, icons, pokes, offline messages, contacts The new UI needs a channel file browser, avatars and icons, pokes, direct messages to anyone, the offline message inbox and a friends list. The voice connection can do all of it; the engine did not offer it. Files (module files): ListFiles, DownloadFile (to disk as .part, renamed when complete, resumable, or into memory), DownloadChatFile for a FileRef from a chat message, UploadFile, CancelTransfer, DeleteFiles, RenameFile, CreateDirectory. Transfers stream in 64 KiB pieces and report Requested/Started/Progress (files.progress_interval_ms)/Done/ Failed/Cancelled; requests and transfers carry an id the caller picks. Avatars and icons are fetched by themselves (cache.fetch_images) into a content-addressed disk cache (module cache: avatars by MD5, icons by id, LRU bounded by cache.max_mb, 0 = no limit, use times kept as file times, concurrent downloads of one file deduplicated across sessions) and reported as AvatarReady / IconReady. SetAvatar uploads ours and announces its hash, or removes it. Pokes are a command and a distinct event (they were stored as private messages before). A failing voice command (e.g. a private message to a client who left) is now an error event instead of ending the connection. Offline messages (module offline) list, read, send, delete and mark. Contacts (module contacts) are engine-wide and stored in the client database: SetContact / RemoveContact, ContactsChanged, FriendPresence across all sessions, last seen time and server, per-person volume and mute applied in every session, blocked authors flagged in chat and their pokes and private messages hidden or flagged (privacy.block_mode), and stream.permissions = friends lets friends watch without asking. ServerDetails and Groups events report the server's details and groups when they change. The book mapping moved to its own module. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 4 + crates/voelin-core/Cargo.toml | 7 +- crates/voelin-core/src/book.rs | 159 +++++ crates/voelin-core/src/cache.rs | 387 ++++++++++ crates/voelin-core/src/contacts.rs | 427 +++++++++++ crates/voelin-core/src/files.rs | 482 +++++++++++++ crates/voelin-core/src/gateway.rs | 6 +- crates/voelin-core/src/history.rs | 12 +- crates/voelin-core/src/lib.rs | 322 ++++++++- crates/voelin-core/src/offline.rs | 39 + crates/voelin-core/src/query.rs | 4 +- crates/voelin-core/src/route.rs | 5 +- crates/voelin-core/src/session.rs | 509 +++++++++++++- crates/voelin-core/src/settings.rs | 55 +- crates/voelin-core/src/stream.rs | 33 +- crates/voelin-core/src/voice.rs | 1056 +++++++++++++++++++--------- 16 files changed, 3119 insertions(+), 388 deletions(-) create mode 100644 crates/voelin-core/src/book.rs create mode 100644 crates/voelin-core/src/cache.rs create mode 100644 crates/voelin-core/src/contacts.rs create mode 100644 crates/voelin-core/src/files.rs create mode 100644 crates/voelin-core/src/offline.rs diff --git a/Cargo.lock b/Cargo.lock index 515ee26..975020d 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", 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 5de7989..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}; @@ -472,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 { @@ -500,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(), @@ -524,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(), 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 7936471..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( diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 2006c32..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(), }) } @@ -820,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"), } } @@ -880,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)); @@ -913,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; @@ -948,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), @@ -1045,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), @@ -1061,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, @@ -1069,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), @@ -1096,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 f888c18..b2fe138 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,8 +1096,53 @@ 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, +); + /// The keys every [`Settings`] knows from the start. -pub fn builtin_keys() -> [&'static dyn Setting; 15] { +pub fn builtin_keys() -> [&'static dyn Setting; 19] { [ &CRASH_REPORTS, &AUDIO, @@ -1114,6 +1159,10 @@ pub fn builtin_keys() -> [&'static dyn Setting; 15] { &CHAT_HISTORY_PAGE, &CHAT_DEDUPE_TOLERANCE_MS, &CHAT_RETENTION_DAYS, + &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 6e131c7..d10e0fb 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -1,27 +1,37 @@ //! 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 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, GroupInfo, GroupNamingMode, - GroupType, HostBannerMode, HostMessageMode, Presence, ServerDetails, ServerFlavor, - parse_badges, + 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, @@ -53,6 +63,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), @@ -62,6 +111,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, } @@ -76,9 +192,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 { @@ -87,161 +209,11 @@ pub(crate) enum VoiceEvent { }, Stream(StreamNotification), StreamRequestFailed(Request, String), + /// A command failed (the connection stays). + Error(String), Disconnected(Option), } -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 -/// [`VoiceEvent::Connected`] told 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(), - } -} - fn now_ms() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -255,21 +227,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<()> { @@ -325,17 +363,22 @@ async fn run_inner( // Subscribe to all channels to see everyone. let cmd = con.get_state()?.server.set_subscribed(true); cmd.send(&mut con)?; - // Who is talking: last voice packet per client. - let mut talking: HashMap = HashMap::new(); - publish_state(&con, &server_uid, &talking, 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()?; 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), @@ -343,168 +386,529 @@ 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, - blocked: false, - })); - } - } - publish_state(&con, &server_uid, &talking, 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, - server_uid: &str, - talking: &HashMap, - events: &mpsc::UnboundedSender, -) -> anyhow::Result<()> { - let state = con.get_state()?; - let presence = presence_from_book(state, Some(server_uid), |id| talking.contains_key(&id)); - let _ = events.send(VoiceEvent::Presence(presence)); - 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 } => { + let uid = tsclientlib::UidBuf(to_uid.into_bytes()); + 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(), + } }