diff --git a/Cargo.lock b/Cargo.lock index 8d8e7e8..e346c37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9480,6 +9480,7 @@ dependencies = [ "futures", "hickory-resolver", "md5", + "reqwest", "rusqlite", "serde", "serde_json", diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index f9a7792..eb0261a 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -106,3 +106,14 @@ against or offered back to upstream. handed those fewer than 32 bytes to `from_short`, which refused them: one identity in 256 (the official client's ones included) could not be imported. The scalar is padded to 32 bytes now; a test round-trips such keys. +13. **Channel banners** (`tsproto-structs/declarations/Messages.toml`, `Book.toml`). + TeamSpeak 6 channels have a banner picture, `channel_banner_gfx_url` and + `channel_banner_mode`, which its server sends in `channellist`, + `notifychannelcreated` and `notifychanneledited` (verified against + 6.0.0-beta13.1; upstream declared them for `channellist` only, so creating + or editing a channel logged "Unknown argument" and lost them). The book's + `Channel` keeps them as `banner_gfx_url` and `banner_mode`. The mode stays + a string, as upstream declared it, so a value the parser does not know + cannot drop the whole channel list; its numbers are those of + `HostBannerMode` (the server's `channeledit` documentation: 0 as it is, + 1 stretched, 2 scaled keeping the aspect ratio). diff --git a/crates/proto/tsproto-structs/declarations/Book.toml b/crates/proto/tsproto-structs/declarations/Book.toml index cd8d5ba..e84e844 100644 --- a/crates/proto/tsproto-structs/declarations/Book.toml +++ b/crates/proto/tsproto-structs/declarations/Book.toml @@ -76,6 +76,8 @@ properties = [ { name="Icon", type="IconId", opt=true }, { name="IsPrivate", type="bool", opt=true }, { name="StorageQuota", type="u32", opt=true }, + { name="BannerGfxUrl", type="str", opt=true, doc="TeamSpeak 6: the address of the channel's banner picture" }, + { name="BannerMode", type="str", opt=true, doc="TeamSpeak 6: how the banner is scaled, the values of `HostBannerMode`" }, { name="Subscribed", type="bool" }, { name="PermissionHints", type="ChannelPermissionHint", opt=true }, { name="OptionalData", type="OptionalChannelData", opt=true }, diff --git a/crates/proto/tsproto-structs/declarations/Messages.toml b/crates/proto/tsproto-structs/declarations/Messages.toml index d9921b1..b4495aa 100644 --- a/crates/proto/tsproto-structs/declarations/Messages.toml +++ b/crates/proto/tsproto-structs/declarations/Messages.toml @@ -24,7 +24,7 @@ fields = [ { map="cgi", ts="cgi", pretty="ChannelGroupIndex", type="ChannelGroupId" }, { map="cgid", ts="cgid", pretty="ChannelGroup", type="ChannelGroupId" }, # TODO: Consider name 'ChannelGroup' for consistency { map="channel_banner_gfx_url", ts="channel_banner_gfx_url", pretty="BannerGfxUrl", type="str" }, - { map="channel_banner_mode", ts="channel_banner_mode", pretty="BannerMode", type="str" }, # ?? Same as HostBannerMode maybe? There's no ui for this setting + { map="channel_banner_mode", ts="channel_banner_mode", pretty="BannerMode", type="str" }, # Like HostBannerMode: 0 as it is, 1 stretched, 2 scaled keeping the aspect ratio (TeamSpeak 6 channeledit docs). A string, so an unknown mode cannot drop the channel list { map="channel_codec", ts="channel_codec", pretty="Codec", type="Codec" }, { map="channel_codec_is_unencrypted", ts="channel_codec_is_unencrypted", pretty="IsUnencrypted", type="bool" }, { map="channel_codec_latency_factor", ts="channel_codec_latency_factor", pretty="CodecLatencyFactor", type="i32" }, @@ -606,10 +606,10 @@ default = { s2c=true, c2s=false, response=true, low=false, np=false } msg = [ { name="BanList", notify="notifybanlist", attributes=["banid", "ip", "name", "uid", "mytsid?", "lastnickname", "created", "duration@time", "invokercldbid", "invokername", "invokeruid?", "reason", "enforcements"] }, { name="ChannelClientPermList", notify="notifychannelclientpermlist", attributes=["cid", "cldbid", "permid?", "permsid?", "permvalue", "permnegated", "permskip"] }, - { name="ChannelCreated", notify="notifychannelcreated", attributes=["cid", "invokerid", "invokername", "invokeruid?", "channel_order", "channel_name", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_unique_identifier?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "channel_storage_quota?", "cpid"] }, + { name="ChannelCreated", notify="notifychannelcreated", attributes=["cid", "invokerid", "invokername", "invokeruid?", "channel_order", "channel_name", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_unique_identifier?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "channel_storage_quota?", "cpid", "channel_banner_gfx_url?", "channel_banner_mode?"] }, { name="ChannelDeleted", notify="notifychanneldeleted", attributes=["cid", "invokerid", "invokername", "invokeruid?"] }, # Has no invoker when we requested the description with: channelgetdescription cid=1 - { name="ChannelEdited", notify="notifychanneledited", attributes=["cid", "invokerid?", "invokername?", "invokeruid?", "reasonid", "channel_order?", "channel_name?", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "cpid?", "channel_description?"] }, + { name="ChannelEdited", notify="notifychanneledited", attributes=["cid", "invokerid?", "invokername?", "invokeruid?", "reasonid", "channel_order?", "channel_name?", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "cpid?", "channel_description?", "channel_banner_gfx_url?", "channel_banner_mode?"] }, { name="ChannelGroupClientList", notify="notifychannelgroupclientlist", attributes=["cid", "cldbid", "cgid"] }, { name="ChannelGroupList", notify="notifychannelgrouplist", attributes=["cgid", "name", "type@group", "iconid", "savedb", "sortid", "namemode", "n_modifyp", "n_member_addp", "n_member_removep?"] }, { name="ChannelGroupPermList", notify="notifychannelgrouppermlist", attributes=["cgid", "permid?", "permsid?", "permvalue", "permnegated", "permskip"] }, diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 44fb3fd..c4dba41 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -29,6 +29,8 @@ futures = "0.3" # Finding a server's gateway in DNS (the voice resolver's version). hickory-resolver = "0.26" md5 = "0.8" +# Banners on the web; the client the workspace has (voelin-query, voelin-media). +reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] } # Reading the official clients' settings.db when importing identities. rusqlite = { version = "0.40.2", features = ["bundled"] } serde = { version = "1", features = ["derive"] } diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index cf20f97..83c65d3 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -2,8 +2,8 @@ use tsclientlib::{ClientType, MaxClients, data}; use voelin_model::{ - ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostBannerMode, - HostMessageMode, Presence, ServerDetails, parse_badges, + BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode, + Presence, ServerDetails, parse_badges, }; fn group_info( @@ -49,9 +49,9 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails { 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, + tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust, + tsclientlib::HostBannerMode::AdjustIgnoreAspect => BannerMode::IgnoreAspect, + tsclientlib::HostBannerMode::AdjustKeepAspect => BannerMode::KeepAspect, }, host_button_tooltip: server.hostbutton_tooltip.clone(), host_button_url: server.hostbutton_url.clone(), @@ -115,6 +115,12 @@ pub(crate) fn presence_from_book( 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), + banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()), + // A number the book keeps as text. + banner_mode: c + .banner_mode + .as_deref() + .map_or(BannerMode::NoAdjust, BannerMode::from_wire), }, ) }) @@ -157,3 +163,107 @@ pub(crate) fn presence_from_book( .collect(), } } + +#[cfg(test)] +mod tests { + use tsclientlib::InMessage; + use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType}; + use tsproto_types::crypto::EccKeyPrivP256; + + use super::*; + + fn message(text: &str) -> InMessage { + let packet = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command); + InMessage::new(&packet.header(), text.as_bytes()).unwrap() + } + + /// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them: + /// in the channel list, when a channel is created and when it is edited. + #[test] + fn channel_banners() { + let InMessage::InitServer(init) = message(concat!( + "initserver virtualserver_name=Test virtualserver_welcomemessage ", + "virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ", + "virtualserver_maxclients=32 virtualserver_created=0 ", + "virtualserver_codec_encryption_mode=0 virtualserver_hostmessage ", + "virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 ", + "virtualserver_default_channel_group=8 virtualserver_hostbanner_url ", + r"virtualserver_hostbanner_gfx_url=https:\/\/example.com\/banner.png ", + "virtualserver_hostbanner_gfx_interval=60 ", + "virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 ", + "virtualserver_ask_for_privilegekey=0 ", + "virtualserver_hostbutton_tooltip virtualserver_hostbutton_url ", + "virtualserver_hostbutton_gfx_url virtualserver_name_phonetic ", + "virtualserver_icon_id=0 virtualserver_hostbanner_mode=2 ", + "virtualserver_channel_temp_delete_delay_default=0 acn=t aclid=2 pv=7 ", + "client_talk_power=75 client_needed_serverquery_view_power=75", + )) else { + panic!("not an initserver"); + }; + let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init); + let channel = |cid: u64, order: u64, name: &str, banner: &str| { + format!( + "cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \ + channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \ + channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \ + channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \ + channel_codec_is_unencrypted=1 channel_delete_delay=0 \ + channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \ + channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \ + channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \ + channel_storage_quota=4294967295" + ) + }; + let list = format!( + "channellist {}|{}", + channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), + channel( + 12, + 1, + "Raid", + r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2" + ), + ); + for text in [ + list.as_str(), + concat!( + "notifychannelcreated cid=13 cpid=0 invokerid=1 invokername=serveradmin ", + "invokeruid=serveradmin channel_name=New channel_order=12 ", + r"channel_flag_permanent=1 channel_banner_gfx_url=https:\/\/example.com\/new.jpg ", + "channel_banner_mode=1", + ), + concat!( + "notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=serveradmin ", + "invokeruid=serveradmin channel_banner_mode=1", + ), + ] { + book.handle_command(&message(text)).unwrap(); + } + let p = presence_from_book(&book, None, |_| false); + let banner = |p: &Presence, cid| { + let c = &p.channels[&cid]; + (c.banner_gfx_url.clone(), c.banner_mode) + }; + assert_eq!(banner(&p, 1), (None, BannerMode::NoAdjust)); + assert_eq!( + banner(&p, 12), + (Some("http://127.0.0.1:1/d.png".into()), BannerMode::IgnoreAspect) + ); + assert_eq!( + banner(&p, 13), + (Some("https://example.com/new.jpg".into()), BannerMode::IgnoreAspect) + ); + // Removing the banner sends an empty address. + book.handle_command(&message( + "notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=x channel_banner_gfx_url", + )) + .unwrap(); + let p = presence_from_book(&book, None, |_| false); + assert_eq!(p.channels[&12].banner_gfx_url, None); + // The host banner, for comparison. + assert_eq!(p.server.banner_gfx_url, "https://example.com/banner.png"); + assert_eq!(p.server.banner_gfx_interval_s, 60); + assert_eq!(p.server.banner_mode, BannerMode::KeepAspect); + assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust); + } +} diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index cf27d4f..6eaf2ef 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -3,8 +3,9 @@ //! 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/`). +//! several clients is one file. Pictures from the web (banners, +//! [`crate::web`]) are named by the MD5 hash of their address. Keys are +//! relative paths (`avatars/`, `icons/`, `pictures/`). //! //! The cache is bounded by `cache.max_mb` (read on every insert; 0: no //! limit): the least recently used files go first. Use times survive @@ -76,6 +77,14 @@ pub(crate) fn icon_key(id: u32) -> String { format!("icons/{id}") } +/// The cache key of a picture on the web: only `http` and `https` +/// addresses. +pub(crate) fn picture_key(url: &str) -> Option { + let (scheme, rest) = url.split_once("://")?; + let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"); + (web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url))) +} + impl Cache { /// A cache in `dir` (created when the first file arrives). pub fn new(dir: impl Into) -> Self { @@ -131,9 +140,11 @@ impl Cache { } /// Get `key`, downloading it once however many ask (see [`Fetch`]). - pub(crate) fn fetch(&self, key: &str, waiter: Waiter) -> Fetch { + /// With `fresh`, download it again even if it is cached (a picture that + /// changes at its address); the new file replaces the old one. + pub(crate) fn fetch(&self, key: &str, fresh: bool, waiter: Waiter) -> Fetch { let mut index = self.lock(); - if let Some(path) = self.touch(&mut index, key) { + if !fresh && let Some(path) = self.touch(&mut index, key) { drop(index); waiter(Ok(path)); return Fetch::Cached; @@ -237,7 +248,7 @@ impl Cache { 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"] { + for sub in ["avatars", "icons", "pictures"] { let Ok(entries) = std::fs::read_dir(dir.join(sub)) else { continue }; for entry in entries.flatten() { let Ok(meta) = entry.metadata() else { continue }; @@ -297,7 +308,8 @@ mod tests { /// 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 { + let Fetch::Download(temp) = cache.fetch(key, false, Box::new(move |r| tx.send(r).unwrap())) + else { panic!("{key} should download"); }; std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); @@ -314,9 +326,9 @@ mod tests { 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!() }; + let Fetch::Download(temp) = cache.fetch(&key, false, waiter(tx.clone())) else { panic!() }; // A second asker waits for the same download. - assert!(matches!(cache.fetch(&key, waiter(tx.clone())), Fetch::Waiting)); + assert!(matches!(cache.fetch(&key, false, 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); @@ -325,10 +337,18 @@ mod tests { 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!(matches!(cache.fetch(&key, false, waiter(tx.clone())), Fetch::Cached)); assert_eq!(rx.recv().unwrap().unwrap(), a); - assert_eq!(cache.get(&key), Some(a)); + assert_eq!(cache.get(&key), Some(a.clone())); assert_eq!(cache.size(), 3); + // Fresh: downloaded again, the new file replaces the old one. + let Fetch::Download(temp) = cache.fetch(&key, true, waiter(tx)) else { panic!() }; + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, b"newer").unwrap(); + cache.finish(&key, &temp, Ok(()), 0); + assert_eq!(rx.recv().unwrap().unwrap(), a); + assert_eq!(std::fs::read(&a).unwrap(), b"newer"); + assert_eq!(cache.size(), 5); std::fs::remove_dir_all(dir).unwrap(); } @@ -338,19 +358,20 @@ mod tests { 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())) + let Fetch::Download(temp) = + cache.fetch("icons/7", false, Box::new(move |r| tx.send(r).unwrap())) else { panic!() }; assert!(matches!( - cache.fetch("icons/7", Box::new(move |r| tx2.send(r).unwrap())), + cache.fetch("icons/7", false, 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(_))); + assert!(matches!(cache.fetch("icons/7", false, Box::new(|_| {})), Fetch::Download(_))); } #[test] @@ -383,5 +404,25 @@ mod tests { assert!(avatar_key("").is_none()); assert!(avatar_key("../x").is_none()); assert_eq!(icon_key(4_294_967_295), "icons/4294967295"); + let url = "https://example.com/banner.png"; + assert_eq!(picture_key(url).unwrap(), format!("pictures/{:x}", md5::compute(url))); + assert_ne!(picture_key(url), picture_key("http://example.com/banner.png")); + assert!(picture_key("HTTP://example.com/b.gif").is_some()); + for not_web in ["", "file:///etc/passwd", "ftp://h/b.png", "https://", "example.com/b.png"] + { + assert!(picture_key(not_web).is_none(), "{not_web}"); + } + } + + /// Pictures are cached files like the others (counted after a restart). + #[test] + fn pictures_survive_restart() { + let dir = temp_dir("pictures"); + let key = picture_key("https://example.com/b.png").unwrap(); + let path = put(&Cache::new(&dir), &key, 10, 0); + let again = Cache::new(&dir); + assert_eq!(again.size(), 10); + assert_eq!(again.get(&key), Some(path)); + std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 3163b08..32fac11 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -39,8 +39,10 @@ //! [`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`]). +//! [`cache`]) and offline messages ([`offline`]). The host banner and +//! channel banners are pictures on the web, fetched into the same cache +//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person +//! volume) are engine-wide ([`contacts`]). mod audio; mod book; @@ -62,6 +64,7 @@ pub mod stream; #[cfg(feature = "media")] pub mod studio; mod voice; +mod web; use std::collections::HashMap; use std::path::PathBuf; @@ -646,6 +649,17 @@ pub enum Event { icon: u32, path: PathBuf, }, + /// A picture on the web is in the cache: the host banner + /// ([`ServerDetails::banner_gfx_url`]) or a channel's + /// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting + /// `cache.fetch_images`). Comes again when the host banner was reloaded + /// (`banner_gfx_interval_s`, at least a minute): the file at `path` + /// changed. + PictureReady { + session: SessionId, + url: String, + path: PathBuf, + }, /// Answer to [`Command::ListOfflineMessages`]. OfflineMessages { session: SessionId, diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 8a76b19..34e949c 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -38,6 +38,7 @@ use crate::stream::{ StreamInput, StreamKind, kind_name, parse_kind, }; use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink}; +use crate::web; use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState}; const NO_VOICE: &str = "not connected with voice"; @@ -108,6 +109,8 @@ enum SourceEvent { KnownServer(String), /// Our avatar file is uploaded (its MD5) or failed: announce it. AvatarUploaded(u64, RequestId, Result), + /// Time to fetch the host banner again (`banner_gfx_interval_s`). + ReloadBanner, } /// Our live stream, for the gateway's directory. @@ -168,6 +171,11 @@ struct Session { avatars: HashMap, /// Icons reported or being fetched, voice only. icons: HashSet, + /// Pictures on the web (banners) reported or being fetched, by address. + pictures: HashSet, + /// The host banner's address and reload interval (seconds) while it has + /// one, and the timer that asks for the reloads. + banner_reload: Option<(String, u64, tokio::task::AbortHandle)>, /// Contact volume and mute applied per client. contact_audio: HashMap, /// Friends' client ids, as last told to the streams. @@ -194,6 +202,8 @@ impl Session { contacts_rx, avatars: HashMap::new(), icons: HashSet::new(), + pictures: HashSet::new(), + banner_reload: None, contact_audio: HashMap::new(), stream_friends: BTreeSet::new(), details: None, @@ -741,6 +751,7 @@ impl Session { fn forget_images(&mut self) { self.avatars.clear(); self.icons.clear(); + self.pictures.clear(); self.contact_audio.clear(); self.stream_friends.clear(); self.details = None; @@ -799,10 +810,60 @@ impl Session { self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), waiter); } + /// Fetch the banners of the presence shown (any source) that are new, + /// and have the host banner reloaded as often as the server asks. + fn fetch_pictures(&mut self, p: &Presence) { + let reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s)) + .filter(|(url, every)| !url.is_empty() && *every > 0); + if self.banner_reload.as_ref().map(|(url, every, _)| (url, *every)) != reload { + if let Some((.., timer)) = self.banner_reload.take() { + timer.abort(); + } + if let Some((url, every_s)) = reload { + let every = std::time::Duration::from_secs(every_s).max(web::MIN_RELOAD); + let tx = self.sources_tx.clone(); + // Ends with the session (nobody receives). + let timer = tokio::spawn(async move { + let start = tokio::time::Instant::now() + every; + let mut tick = tokio::time::interval_at(start, every); + loop { + tick.tick().await; + if tx.send(SourceEvent::ReloadBanner).is_err() { + break; + } + } + }); + self.banner_reload = Some((url.clone(), every_s, timer.abort_handle())); + } + } + if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + return; + } + let urls = std::iter::once(&p.server.banner_gfx_url) + .chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref())); + for url in urls.filter(|u| !u.is_empty()) { + if self.pictures.insert(url.clone()) { + self.fetch_picture(url, false); + } + } + } + + /// Get the picture at `url` into the cache (again with `fresh`). + fn fetch_picture(&self, url: &str, fresh: bool) { + let (session, events, address) = (self.id, self.events.clone(), url.to_owned()); + let waiter: Waiter = Box::new(move |result| match result { + Ok(path) => { + let _ = events.send(Event::PictureReady { session, url: address, path }); + } + Err(e) => debug!(url = %address, "no picture: {e}"), + }); + web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), 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 Fetch::Download(temp) = cache.fetch(&key, false, 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)); @@ -1302,6 +1363,13 @@ impl Session { self.emit(Event::RequestDone { session: self.id, request, result }); } }, + SourceEvent::ReloadBanner => { + if let Some((url, ..)) = &self.banner_reload + && self.settings.current().get(&CACHE_FETCH_IMAGES) + { + self.fetch_picture(url, true); + } + } _ => debug!("event from a replaced source ignored"), } } @@ -1613,6 +1681,7 @@ impl Session { self.state.presence_source = source; self.emit_state(); } + self.fetch_pictures(&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/web.rs b/crates/voelin-core/src/web.rs new file mode 100644 index 0000000..a8fad91 --- /dev/null +++ b/crates/voelin-core/src/web.rs @@ -0,0 +1,215 @@ +//! Pictures from the web: the host banner and TeamSpeak 6 channel banners, +//! which servers give as `http(s)` addresses on any host. +//! +//! They go into the engine's cache ([`crate::cache`], named by the MD5 hash +//! of the address) like avatars and icons, and only with +//! `cache.fetch_images`: fetching one contacts a host the server chose, as +//! the official client does. A picture is at most [`MAX_BYTES`], arrives +//! within [`TIMEOUT`] (connected within [`CONNECT_TIMEOUT`]) and is kept +//! only if its content is a picture the UI shows (PNG, JPEG, GIF, WebP, +//! SVG), whatever its address or the server say. The client is the +//! workspace's reqwest with rustls: system proxies (`HTTPS_PROXY`, +//! `NO_PROXY`, …) and the platform's certificate store. + +use std::path::Path; +use std::sync::LazyLock; +use std::time::Duration; + +use crate::cache::{self, Cache, Fetch, Waiter}; + +/// Larger pictures are refused; banners are rarely above a few hundred KiB. +pub(crate) const MAX_BYTES: u64 = 4 << 20; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const TIMEOUT: Duration = Duration::from_secs(30); +/// The host banner is reloaded at most this often, whatever the server +/// asks (TeamSpeak 3 and 6 servers refuse intervals below a minute). +pub(crate) const MIN_RELOAD: Duration = Duration::from_secs(60); + +static CLIENT: LazyLock> = LazyLock::new(|| { + reqwest::Client::builder() + .connect_timeout(CONNECT_TIMEOUT) + .timeout(TIMEOUT) + .user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION"))) + .build() + .map_err(|e| e.to_string()) +}); + +/// Get the picture at `url` into `cache`, downloading it once however many +/// ask (again with `fresh`: it changes at its address); `waiter` is told +/// where it is. `max_cache_bytes`: `cache.max_mb` in bytes. +pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, waiter: Waiter) { + let Some(key) = cache::picture_key(url) else { + waiter(Err("not an http or https address".into())); + return; + }; + let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return }; + let url = url.to_owned(); + tokio::spawn(async move { + let result = download(&url, &temp, MAX_BYTES).await; + cache.finish(&key, &temp, result, max_cache_bytes); + }); +} + +/// Download the picture at `url` into `to`: at most `max_bytes`, and only +/// if it is a picture. +async fn download(url: &str, to: &Path, max_bytes: u64) -> Result<(), String> { + let client = CLIENT.as_ref().map_err(Clone::clone)?; + let too_big = || format!("larger than {} KiB", max_bytes >> 10); + let mut response = client + .get(url) + .send() + .await + .and_then(reqwest::Response::error_for_status) + .map_err(|e| e.to_string())?; + if response.content_length().is_some_and(|n| n > max_bytes) { + return Err(too_big()); + } + let mut data = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? { + if (data.len() + chunk.len()) as u64 > max_bytes { + return Err(too_big()); + } + data.extend_from_slice(&chunk); + } + if !is_picture(&data) { + return Err("not a picture".into()); + } + if let Some(dir) = to.parent() { + tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?; + } + tokio::fs::write(to, &data).await.map_err(|e| e.to_string()) +} + +/// Whether `data` is a picture the UI decodes, told by its content as the +/// UI tells it (SVG by its start, without leading blanks). +fn is_picture(data: &[u8]) -> bool { + const STARTS: [&[u8]; 6] = + [b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP") +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + use super::*; + + const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0\x1f\x15\xc4\x89\0\0\0\rIDATx\xdac\xf8\xcf\xc0\xf0\x1f\0\x05\0\x01\xff\x89\x99=\x1d\0\0\0\0IEND\xaeB`\x82"; + + /// An HTTP server on 127.0.0.1 with a few answers; returns its address. + async fn server() -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { return }; + tokio::spawn(async move { + let mut request = Vec::new(); + let mut buf = [0u8; 1024]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + match socket.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => request.extend_from_slice(&buf[..n]), + } + } + let path = String::from_utf8_lossy(&request) + .split_whitespace() + .nth(1) + .unwrap_or("/") + .to_owned(); + let (status, length, body): (&str, bool, Vec) = match path.as_str() { + "/banner" => ("200 OK", true, PNG.to_vec()), + "/svg" => { + ("200 OK", true, b"".to_vec()) + } + // Too big, as announced or as it comes. + "/big" => ("200 OK", true, [PNG, &[0; 4000]].concat()), + "/big-unannounced" => ("200 OK", false, [PNG, &[0; 4000]].concat()), + "/page" => ("200 OK", true, b"".to_vec()), + _ => ("404 Not Found", true, b"no".to_vec()), + }; + let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n"); + if length { + head += &format!("Content-Length: {}\r\n", body.len()); + } + head += "\r\n"; + let _ = socket.write_all(head.as_bytes()).await; + let _ = socket.write_all(&body).await; + }); + } + }); + format!("http://{addr}") + } + + fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[tokio::test] + async fn downloads_pictures_only() { + let base = server().await; + let dir = temp_dir("download"); + let to = dir.join("tmp/x.part"); + download(&format!("{base}/banner"), &to, 1000).await.unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), PNG); + download(&format!("{base}/svg"), &to, 1000).await.unwrap(); + for (path, error) in [ + ("/big", "larger than"), + ("/big-unannounced", "larger than"), + ("/page", "not a picture"), + ("/missing", "404"), + ] { + let e = download(&format!("{base}{path}"), &to, 1000).await.unwrap_err(); + assert!(e.contains(error), "{path}: {e}"); + } + // Nothing listens there. + let port = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port(); + assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, 1000).await.is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test(flavor = "multi_thread")] + async fn fetch_into_the_cache() { + let base = server().await; + let dir = temp_dir("fetch"); + let cache = Cache::new(&dir); + let (tx, rx) = mpsc::channel(); + let waiter = |tx: &mpsc::Sender<_>| -> Waiter { + let tx = tx.clone(); + Box::new(move |r| tx.send(r).unwrap()) + }; + let url = format!("{base}/banner"); + fetch(cache.clone(), &url, false, 0, waiter(&tx)); + let path = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap().unwrap(); + assert_eq!(path, dir.join(cache::picture_key(&url).unwrap())); + assert_eq!(std::fs::read(&path).unwrap(), PNG); + // Not on the web: refused at once, nothing cached. + let (tx, rx) = mpsc::channel(); + fetch(cache.clone(), "file:///etc/hostname", false, 0, waiter(&tx)); + assert!(rx.recv().unwrap().unwrap_err().contains("http")); + // A failed download is reported and leaves nothing behind. + fetch(cache.clone(), &format!("{base}/page"), false, 0, waiter(&tx)); + let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap(); + assert_eq!(failed, Err("not a picture".into())); + assert_eq!(cache.size(), PNG.len() as u64); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn pictures_by_content() { + assert!(is_picture(PNG)); + assert!(is_picture(b"\xff\xd8\xff\xe0\0\x10JFIF")); + assert!(is_picture(b"GIF89a\x01\0\x01\0")); + assert!(is_picture(b"RIFF\x24\0\0\0WEBPVP8 ")); + assert!(is_picture(b"")); + assert!(!is_picture(b"")); + assert!(!is_picture(b"RIFF\x24\0\0\0WAVEfmt ")); + assert!(!is_picture(b"")); + } +} diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index c4c5276..2579c72 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -122,3 +122,127 @@ async fn ts3_engine() { engine_roundtrip("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")) .await; } + +/// A 1×1 PNG. +const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + +/// An HTTP server on 127.0.0.1 that answers every request with `body`; +/// returns its address. The engine fetches banners itself (the server only +/// passes their addresses on), so it reaches this one. +async fn serve(body: Vec) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let body = body.clone(); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut buf = [0u8; 1024]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + match socket.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => request.extend_from_slice(&buf[..n]), + } + } + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = socket.write_all(head.as_bytes()).await; + let _ = socket.write_all(&body).await; + }); + } + }); + format!("http://{addr}") +} + +/// The host banner and a channel banner set through ServerQuery reach the +/// engine's cache (`Event::PictureReady`); the server is put back after. +#[tokio::test(flavor = "multi_thread")] +async fn ts6_banners() { + use base64::Engine as _; + use voelin_model::BannerMode; + use voelin_query::{Command as Query, QueryClient}; + if !live() { + return; + } + let png = base64::prelude::BASE64_STANDARD.decode(PNG).unwrap(); + let base = serve(png.clone()).await; + let (host_url, channel_url) = (format!("{base}/host.png"), format!("{base}/channel.png")); + let (admin, _) = QueryClient::connect(&query(voelin_query::Transport::Ssh, "127.0.0.1:10022")) + .await + .unwrap(); + let info = admin.send(&Query::new("serverinfo")).await.unwrap().remove(0); + let before = |key: &str| info.get(key).unwrap_or_default().to_owned(); + let (old_url, old_mode) = + (before("virtualserver_hostbanner_gfx_url"), before("virtualserver_hostbanner_mode")); + let edit = Query::new("serveredit") + .arg("virtualserver_hostbanner_gfx_url", &host_url) + .arg("virtualserver_hostbanner_mode", 2); + admin.send(&edit).await.unwrap(); + let created = admin + .send( + &Query::new("channelcreate") + .arg("channel_name", format!("banner-{}", std::process::id())) + .arg("channel_banner_gfx_url", &channel_url) + .arg("channel_banner_mode", 1), + ) + .await; + + let check = { + let (host_url, channel_url) = (host_url.clone(), channel_url.clone()); + tokio::spawn(async move { + let engine = Engine::start(); + let dir = + std::env::temp_dir().join(format!("voelin-live-banners-{}", std::process::id())); + engine.send(Command::AttachCache(dir.clone())); + let mut events = engine.subscribe(); + engine.send(Command::ConnectVoice { + session: 1, + options: Box::new(VoiceOptions::new("127.0.0.1:9988", "banner-check")), + }); + let mut seen = std::collections::HashMap::new(); + let mut channel_mode = None; + wait_for(&mut events, "both banners", |e| { + match e { + Event::PictureReady { url, path, .. } => { + seen.insert(url.clone(), std::fs::read(path).unwrap()); + } + Event::Presence { presence, .. } => { + channel_mode = presence + .channels + .values() + .find(|c| c.banner_gfx_url.as_deref() == Some(channel_url.as_str())) + .map(|c| c.banner_mode); + assert_eq!(presence.server.banner_mode, BannerMode::KeepAspect); + } + _ => {} + } + seen.contains_key(&host_url) && seen.contains_key(&channel_url) + }) + .await; + assert_eq!(channel_mode, Some(BannerMode::IgnoreAspect)); + assert!(seen.values().all(|bytes| *bytes == png)); + engine.send(Command::CloseSession { session: 1 }); + tokio::time::sleep(Duration::from_millis(500)).await; + let _ = std::fs::remove_dir_all(dir); + }) + }; + let result = check.await; + + if let Ok(rows) = &created + && let Some(cid) = rows.first().and_then(|r| r.get("cid")) + { + let delete = Query::new("channeldelete").arg("cid", cid).arg("force", 1); + admin.send(&delete).await.unwrap(); + } + let restore = Query::new("serveredit") + .arg("virtualserver_hostbanner_gfx_url", old_url) + .arg("virtualserver_hostbanner_mode", old_mode); + admin.send(&restore).await.unwrap(); + created.unwrap(); + if let Err(e) = result { + std::panic::resume_unwind(e.into_panic()); + } +} diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index e8024e0..95acfa9 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -14,6 +14,6 @@ pub use presence::{ Presence, PresenceDelta, PresenceSnapshot, parse_badges, }; pub use server::{ - Capabilities, HostBannerMode, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, + BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, }; pub use tree::{TreeRow, order_siblings, tree_rows}; diff --git a/crates/voelin-model/src/presence.rs b/crates/voelin-model/src/presence.rs index d0adf59..7776838 100644 --- a/crates/voelin-model/src/presence.rs +++ b/crates/voelin-model/src/presence.rs @@ -13,7 +13,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::server::ServerDetails; +use crate::server::{BannerMode, ServerDetails}; pub type ChannelId = u64; pub type ClientId = u16; @@ -32,6 +32,10 @@ fn is_false(b: &bool) -> bool { !*b } +fn is_default(v: &T) -> bool { + *v == T::default() +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ChannelInfo { pub id: ChannelId, @@ -56,6 +60,12 @@ pub struct ChannelInfo { /// Icon id (`channel_icon_id`); 0: none. #[serde(default, skip_serializing_if = "is_zero_u32")] pub icon: u32, + /// The address of the channel's banner picture (TeamSpeak 6, + /// `channel_banner_gfx_url`), drawn behind the channel. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub banner_gfx_url: Option, + #[serde(default, skip_serializing_if = "is_default")] + pub banner_mode: BannerMode, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/voelin-model/src/server.rs b/crates/voelin-model/src/server.rs index 20925f7..20f0333 100644 --- a/crates/voelin-model/src/server.rs +++ b/crates/voelin-model/src/server.rs @@ -116,10 +116,11 @@ pub enum HostMessageMode { ModalQuit, } -/// How the host banner image is scaled. +/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is +/// scaled to its area: `0`, `1` and `2` on the wire. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] -pub enum HostBannerMode { +pub enum BannerMode { /// As it is. #[default] NoAdjust, @@ -129,6 +130,18 @@ pub enum HostBannerMode { KeepAspect, } +impl BannerMode { + /// From its number on the wire; an unknown one shows the picture as it + /// is. + pub fn from_wire(value: &str) -> Self { + match value.trim() { + "1" => Self::IgnoreAspect, + "2" => Self::KeepAspect, + _ => Self::NoAdjust, + } + } +} + /// What a server tells its (voice) clients about itself. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ServerDetails { @@ -152,7 +165,7 @@ pub struct ServerDetails { #[serde(default)] pub banner_gfx_interval_s: u64, #[serde(default)] - pub banner_mode: HostBannerMode, + pub banner_mode: BannerMode, #[serde(default)] pub host_button_tooltip: String, #[serde(default)] diff --git a/crates/voelin-observer/src/convert.rs b/crates/voelin-observer/src/convert.rs index 288750d..a174f40 100644 --- a/crates/voelin-observer/src/convert.rs +++ b/crates/voelin-observer/src/convert.rs @@ -1,10 +1,10 @@ //! Query rows and events to model types. -use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta}; +use voelin_model::{BannerMode, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta}; use voelin_query::{Notification, Row}; -/// From a `channellist -topic -flags -voice -limits` row, or the fields of -/// `notifychannelcreated`. +/// From a `channellist -topic -flags -voice -limits -icon -banners` row, or +/// the fields of `notifychannelcreated`. pub fn channel_from_row(row: &Row) -> Option { Some(ChannelInfo { id: row.parse("cid")?, @@ -18,6 +18,13 @@ pub fn channel_from_row(row: &Row) -> Option { needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0), is_default: row.flag("channel_flag_default").unwrap_or(false), icon: row.parse::("channel_icon_id").map_or(0, |i| i as u32), + banner_gfx_url: row + .get("channel_banner_gfx_url") + .filter(|u| !u.is_empty()) + .map(str::to_string), + banner_mode: row + .get("channel_banner_mode") + .map_or(BannerMode::NoAdjust, BannerMode::from_wire), }) } @@ -48,6 +55,15 @@ pub fn update_channel(channel: &mut ChannelInfo, row: &Row) { if let Some(d) = row.flag("channel_flag_default") { channel.is_default = d; } + if let Some(i) = row.parse::("channel_icon_id") { + channel.icon = i as u32; + } + if let Some(url) = row.get("channel_banner_gfx_url") { + channel.banner_gfx_url = Some(url.to_string()).filter(|u| !u.is_empty()); + } + if let Some(mode) = row.get("channel_banner_mode") { + channel.banner_mode = BannerMode::from_wire(mode); + } } /// From a `clientlist -uid -away -voice -groups -country` row or a @@ -186,11 +202,24 @@ mod tests { channel_flag_default=1 channel_flag_password=0 channel_maxclients=-1 \ channel_needed_subscribe_power=0 channel_needed_talk_power=5", )[0]; - let c = channel_from_row(row).unwrap(); + let mut c = channel_from_row(row).unwrap(); assert_eq!(c.name, "Default Channel"); assert!(c.is_default && !c.has_password); assert_eq!(c.max_clients, None); assert_eq!(c.needed_talk_power, 5); + assert_eq!((c.banner_gfx_url.as_deref(), c.banner_mode), (None, BannerMode::NoAdjust)); + // `-banners` (TeamSpeak 6 and 3.13), and the edit that changes them. + let row = &voelin_query::parse_rows( + "cid=2 pid=0 channel_name=Raid channel_banner_gfx_url=https:\\/\\/e.com\\/b.png \ + channel_banner_mode=2", + )[0]; + let banner = |c: &ChannelInfo| (c.banner_gfx_url.clone(), c.banner_mode); + let raid = channel_from_row(row).unwrap(); + assert_eq!(banner(&raid), (Some("https://e.com/b.png".into()), BannerMode::KeepAspect)); + update_channel(&mut c, row); + assert_eq!(banner(&c), banner(&raid)); + update_channel(&mut c, &voelin_query::parse_rows("cid=1 channel_banner_gfx_url")[0]); + assert_eq!(banner(&c), (None, BannerMode::KeepAspect)); } #[test] diff --git a/crates/voelin-observer/src/observer.rs b/crates/voelin-observer/src/observer.rs index 2dcb7c7..2d3b785 100644 --- a/crates/voelin-observer/src/observer.rs +++ b/crates/voelin-observer/src/observer.rs @@ -105,7 +105,15 @@ async fn run( async fn load(client: &QueryClient) -> voelin_query::Result { let info = client.send(&Command::new("serverinfo")).await?; let channels = client - .send(&Command::new("channellist").flag("topic").flag("flags").flag("voice").flag("limits")) + .send( + &Command::new("channellist") + .flag("topic") + .flag("flags") + .flag("voice") + .flag("limits") + .flag("icon") + .flag("banners"), + ) .await?; let clients = client .send( diff --git a/tools/voelinctl/src/client.rs b/tools/voelinctl/src/client.rs index c629c03..f58cb28 100644 --- a/tools/voelinctl/src/client.rs +++ b/tools/voelinctl/src/client.rs @@ -476,6 +476,10 @@ impl Runner<'_> { println!("icon {icon} {}", path.display()); return Ok(self.expected(&format!("icon {icon}"))); } + Event::PictureReady { url, path, .. } => { + println!("picture {url} {}", path.display()); + return Ok(self.expected(&format!("picture {url}"))); + } Event::OfflineMessages { result, .. } => { let list = result.map_err(|e| anyhow::anyhow!("messagelist: {e}"))?; println!("offline inbox n={}", list.len());