diff --git a/crates/proto/tsproto-structs/declarations/Book.toml b/crates/proto/tsproto-structs/declarations/Book.toml index e84e844..3e9fd88 100644 --- a/crates/proto/tsproto-structs/declarations/Book.toml +++ b/crates/proto/tsproto-structs/declarations/Book.toml @@ -192,6 +192,7 @@ properties = [ { name="InheritedChannelGroupFromChannel", type="ChannelId" }, { name="Badges", type="str" }, { name="UserTag", type="str", opt=true }, + { name="MyTeamSpeakAvatar", type="str", opt=true, doc="`,;…` of the myTeamSpeak avatar (TeamSpeak 6)" }, { name="PermissionHints", type="ClientPermissionHint", opt=true }, { name="OptionalData", type="OptionalClientData", opt=true }, { name="ConnectionData", type="ConnectionClientData", opt=true }, diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index 83c65d3..ba94a82 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -3,7 +3,7 @@ use tsclientlib::{ClientType, MaxClients, data}; use voelin_model::{ BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode, - Presence, ServerDetails, parse_badges, + Presence, ServerDetails, myts_avatar_url, parse_badges, }; fn group_info( @@ -147,6 +147,7 @@ pub(crate) fn presence_from_book( server_groups, country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()), + myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url), description: Some(c.description.clone()).filter(|d| !d.is_empty()), talk_power: c.talk_power, talker: c.talk_power_granted, @@ -177,10 +178,8 @@ mod tests { 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() { + /// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`. + fn ts6_book() -> data::Connection { let InMessage::InitServer(init) = message(concat!( "initserver virtualserver_name=Test virtualserver_welcomemessage ", "virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ", @@ -200,20 +199,29 @@ mod tests { )) 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" - ) - }; + data::Connection::new(EccKeyPrivP256::create().to_pub(), &init) + } + + /// A `channellist` entry as TeamSpeak 6 sends it. + fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String { + 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" + ) + } + + /// 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 mut book = ts6_book(); let list = format!( "channellist {}|{}", channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), @@ -266,4 +274,50 @@ mod tests { assert_eq!(p.server.banner_mode, BannerMode::KeepAspect); assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust); } + + /// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it: + /// when the client enters and when it changes. + #[test] + fn myts_avatars() { + let mut book = ts6_book(); + book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", "")))) + .unwrap(); + let enter = |clid: u16, avatar: &str| { + format!( + "notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \ + client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \ + client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \ + client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \ + client_output_hardware=1 client_meta_data client_is_recording=0 \ + client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \ + client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \ + client_talk_request=0 client_talk_request_msg client_is_talker=0 \ + client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \ + client_needed_serverquery_view_power=75 client_is_channel_commander=0 \ + client_country=RU client_badges client_myteamspeak_id=m{clid} \ + client_integrations{avatar}" + ) + }; + for text in [ + enter( + 5, + r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png", + ), + // A TeamSpeak 3 server, or a client without one. + enter(6, ""), + enter(7, " client_myteamspeak_avatar"), + ] { + book.handle_command(&message(&text)).unwrap(); + } + let p = presence_from_book(&book, None, |_| false); + let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone(); + assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png")); + assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None)); + book.handle_command(&message( + r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png", + )) + .unwrap(); + let p = presence_from_book(&book, None, |_| false); + assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png")); + } } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 376548b..3d0e23e 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -125,7 +125,15 @@ enum SourceEvent { /// Identity of a wanted image, independent of its transport. #[derive(Clone, Debug, PartialEq, Eq, Hash)] enum ImageRequest { - Avatar { uid: String, hash: String }, + Avatar { + uid: String, + hash: String, + }, + /// A client's myTeamSpeak avatar (TeamSpeak 6), on the web. + MytsAvatar { + uid: String, + url: String, + }, Icon(u32), Picture(String), } @@ -164,6 +172,13 @@ struct ImageRetry { due: Option, } +/// Whether an explicitly requested image belongs to the voice connection +/// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the +/// web. +fn voice_bound(request: &ImageRequest) -> bool { + !matches!(request, ImageRequest::MytsAvatar { .. }) +} + /// Our live stream, for the gateway's directory. struct OwnStream { id: String, @@ -222,6 +237,12 @@ struct Session { contacts_rx: Option>, /// Avatars reported per client unique id (their hash), voice only. avatars: HashMap, + /// myTeamSpeak avatars wanted per client unique id (their link), any + /// presence: where the server's avatar is not shown. + myts_avatars: HashMap, + /// Clients whose server avatar could not be downloaded (retries used + /// up): their myTeamSpeak avatar is shown instead. + server_avatars_failed: HashSet, /// Icons reported or being fetched, voice only. icons: HashSet, /// Pictures on the web (banners) reported or being fetched, by address. @@ -259,6 +280,8 @@ impl Session { contacts, contacts_rx, avatars: HashMap::new(), + myts_avatars: HashMap::new(), + server_avatars_failed: HashSet::new(), icons: HashSet::new(), pictures: HashSet::new(), image_epoch: 0, @@ -673,9 +696,13 @@ impl Session { .voice_presence .as_ref() .and_then(|p| p.client_by_uid(&client_uid)) - .and_then(|c| c.avatar.clone()); - if let Some(hash) = hash { + .and_then(|c| c.avatar.clone()) + .filter(|_| !self.server_avatars_failed.contains(&client_uid)); + let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone()); + if let Some(hash) = hash.filter(|_| self.voice.is_some()) { self.fetch_avatar(&client_uid, &hash, true); + } else if let Some(url) = myts { + self.fetch_myts_avatar(&client_uid, &url, true); } } Command::ListOfflineMessages { request, .. } => { @@ -828,6 +855,8 @@ impl Session { self.image_epoch += 1; self.image_retries.clear(); self.avatars.clear(); + self.myts_avatars.clear(); + self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); self.contact_audio.clear(); @@ -866,7 +895,7 @@ impl Session { } fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter { - let epoch = if requested { + let epoch = if requested && voice_bound(&request) { self.voice.as_ref().map_or(0, |(generation, _)| *generation) } else { self.image_epoch @@ -884,6 +913,45 @@ impl Session { self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter); } + /// The myTeamSpeak avatars of the presence shown (any source) where the + /// server's avatar is not shown: none set, no voice connection to + /// download it over, or its download gave up. As the official client: + /// the server's avatar first. + fn fetch_myts_avatars(&mut self, p: &Presence) { + if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + return; + } + let mut wanted = HashMap::with_capacity(self.myts_avatars.len()); + for c in p.clients.values() { + let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue }; + let server_avatar = c.avatar.is_some() + && self.voice.is_some() + && !self.server_avatars_failed.contains(uid); + if server_avatar { + continue; + } + if self.myts_avatars.get(uid) != Some(url) { + self.fetch_myts_avatar(uid, url, false); + } + wanted.insert(uid.clone(), url.clone()); + } + self.myts_avatars = wanted; + } + + fn fetch_myts_avatar(&self, uid: &str, url: &str, requested: bool) { + let request = ImageRequest::MytsAvatar { uid: uid.into(), url: url.into() }; + let waiter = self.image_waiter(request, requested); + web::fetch_avatar(self.cache.current(), url, max_cache_bytes(&self.settings), waiter); + } + + /// The client shown (any presence) with this unique id. + fn shown_client(&self, uid: &str) -> Option<&voelin_model::ClientInfo> { + [&self.voice_presence, &self.gateway_presence, &self.query_presence] + .into_iter() + .find_map(|p| p.as_ref()) + .and_then(|p| p.client_by_uid(uid)) + } + fn fetch_icon(&self, icon: u32) { let waiter = self.image_waiter(ImageRequest::Icon(icon), false); self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter); @@ -894,6 +962,7 @@ impl Session { ImageRequest::Avatar { uid, hash } => { self.voice.is_some() && self.avatars.get(uid) == Some(hash) } + ImageRequest::MytsAvatar { uid, url } => self.myts_avatars.get(uid) == Some(url), ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id), ImageRequest::Picture(url) => self.pictures.contains(url), } @@ -907,13 +976,25 @@ impl Session { result: Result, ) { let wanted = if requested { - matches!(&request, ImageRequest::Avatar { uid, hash } - if self.voice.is_some() && self.voice_presence.as_ref() - .and_then(|p| p.client_by_uid(uid)).and_then(|c| c.avatar.as_ref()) == Some(hash)) + match &request { + ImageRequest::Avatar { uid, hash } => { + self.voice.is_some() + && self + .voice_presence + .as_ref() + .and_then(|p| p.client_by_uid(uid)) + .and_then(|c| c.avatar.as_ref()) + == Some(hash) + } + ImageRequest::MytsAvatar { uid, url } => { + self.shown_client(uid).and_then(|c| c.myts_avatar.as_ref()) == Some(url) + } + _ => false, + } } else { self.wants_image(&request) }; - let current = if requested { + let current = if requested && voice_bound(&request) { self.is_current(Source::Voice, epoch) } else { epoch == self.image_epoch @@ -932,12 +1013,21 @@ impl Session { ImageRequest::Avatar { uid: client_uid, hash } => { Event::AvatarReady { session, client_uid, hash, path } } + // The address in place of a hash: it changes with the + // picture. + ImageRequest::MytsAvatar { uid: client_uid, url } => { + Event::AvatarReady { session, client_uid, hash: url, path } + } ImageRequest::Icon(icon) => Event::IconReady { session, icon, path }, ImageRequest::Picture(url) => Event::PictureReady { session, url, path }, }); } Err(error) => { debug!(?request, %error, "image download failed"); + let avatar_of = match &request { + ImageRequest::Avatar { uid, .. } => Some(uid.clone()), + _ => None, + }; let retry = self .image_retries .entry(request) @@ -949,6 +1039,14 @@ impl Session { } _ => None, }; + // The server's avatar gave up (its files unreachable): the + // myTeamSpeak one, if the client has one. + if let (None, Some(uid)) = (retry.due, avatar_of) + && self.server_avatars_failed.insert(uid) + && let Some(presence) = self.voice_presence.clone() + { + self.fetch_myts_avatars(&presence); + } } } } @@ -959,6 +1057,7 @@ impl Session { self.images_enabled = enabled; self.image_epoch += 1; self.avatars.clear(); + self.myts_avatars.clear(); self.icons.clear(); self.pictures.clear(); self.image_retries.clear(); @@ -996,6 +1095,7 @@ impl Session { for request in ready { match request { ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false), + ImageRequest::MytsAvatar { uid, url } => self.fetch_myts_avatar(&uid, &url, false), ImageRequest::Icon(icon) => self.fetch_icon(icon), ImageRequest::Picture(url) => self.fetch_picture(&url, true), } @@ -1927,6 +2027,7 @@ impl Session { self.emit_state(); } self.fetch_pictures(&presence); + self.fetch_myts_avatars(&presence); let presence = Arc::new(presence); self.contacts.presence(self.id, presence.clone()); self.emit(Event::Presence { session: self.id, presence }); @@ -2219,6 +2320,76 @@ mod banner_tests { std::fs::remove_dir_all(cache.dir()).unwrap(); } + /// myTeamSpeak avatars (TeamSpeak 6) come from the web where the + /// server's avatar is not shown: none set, no voice connection to get it + /// over (observing), or its download gave up. + #[tokio::test] + async fn myts_avatars_where_the_servers_is_not_shown() { + let (mut session, mut events) = session("myts-avatar"); + let cache = session.cache.current(); + let client = |id, uid: &str, avatar: Option<&str>, myts: &str| voelin_model::ClientInfo { + id, + uid: Some(uid.into()), + avatar: avatar.map(Into::into), + myts_avatar: Some(myts.into()), + ..Default::default() + }; + let (a, b) = ("https://a.example.test/a.png", "https://a.example.test/b.png"); + let hash = "0123456789abcdef0123456789abcdef"; + let mut presence = Presence::default(); + presence.clients.insert(1, client(1, "A=", None, a)); + presence.clients.insert(2, client(2, "B=", Some(hash), b)); + // Owned here, so nothing goes to the network. + let temps: Vec<_> = [a, b] + .iter() + .map(|url| { + let key = cache::picture_key(url).unwrap(); + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("first download"); + }; + (key, temp) + }) + .collect(); + // Observing: both, even the one with a server avatar. + session.gateway_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.len(), 2); + for (key, temp) in &temps { + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(temp, b"\x89PNG\r\n\x1a\npicture").unwrap(); + cache.finish(key, temp, Ok(()), 0); + let done = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(done); + } + let mut ready = Vec::new(); + while let Ok(event) = events.try_recv() { + if let Event::AvatarReady { client_uid, hash, .. } = event { + ready.push((client_uid, hash)); + } + } + ready.sort(); + assert_eq!(ready, [("A=".to_owned(), a.to_owned()), ("B=".to_owned(), b.to_owned())]); + // With voice the server's avatar is shown where there is one. + let (tx, _rx) = mpsc::unbounded_channel(); + session.voice = Some((1, tx)); + session.voice_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.keys().collect::>(), ["A="]); + // Until its download gives up (the server's files unreachable). + let request = ImageRequest::Avatar { uid: "B=".into(), hash: hash.into() }; + session.avatars.insert("B=".into(), hash.into()); + for _ in 0..4 { + session.image_finished( + false, + session.image_epoch, + request.clone(), + Err("refused".into()), + ); + } + assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b)); + std::fs::remove_dir_all(cache.dir()).unwrap(); + } + #[tokio::test] async fn enabling_images_replays_current_presence_without_server_updates() { let (mut session, mut events) = session("policy-enable"); diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index 9af4ddf..5373a4f 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -54,6 +54,23 @@ static CLIENT: LazyLock> = LazyLock::new(|| { /// 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) { + fetch_within(cache, url, fresh, max_cache_bytes, &LIMITS, waiter); +} + +/// [`fetch`] a myTeamSpeak avatar: a picture of at most +/// [`AVATAR_LIMITS`]'s size, once (its link changes with it). +pub(crate) fn fetch_avatar(cache: Cache, url: &str, max_cache_bytes: u64, waiter: Waiter) { + fetch_within(cache, url, false, max_cache_bytes, &AVATAR_LIMITS, waiter); +} + +fn fetch_within( + cache: Cache, + url: &str, + fresh: bool, + max_cache_bytes: u64, + limits: &'static Limits, + waiter: Waiter, +) { let Some(key) = cache::picture_key(url) else { waiter(Err("not an http or https address".into())); return; @@ -62,7 +79,7 @@ pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, let url = url.to_owned(); tokio::spawn(async move { let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open"); - let result = download(&url, &temp, &LIMITS).await; + let result = download(&url, &temp, limits).await; cache.finish(&key, &temp, result, max_cache_bytes); }); } @@ -77,6 +94,8 @@ struct Limits { const LIMITS: Limits = Limits { max_bytes: cache::MAX_PICTURE_BYTES, grace: GRACE, min_rate: cache::MIN_PICTURE_RATE }; +/// Avatars are small pictures (as myTeamSpeak's own, 4 MiB at most). +const AVATAR_LIMITS: Limits = Limits { max_bytes: 4 << 20, ..LIMITS }; /// Download the picture at `url` into `to` within `limits`, and only if it /// is a picture (what arrived stays in `to` on failure; the cache removes it). diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index 95acfa9..8ba52df 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -11,7 +11,7 @@ mod tree; pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; pub use presence::{ ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, - Presence, PresenceDelta, PresenceSnapshot, parse_badges, + Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, }; pub use server::{ BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, diff --git a/crates/voelin-model/src/presence.rs b/crates/voelin-model/src/presence.rs index 7776838..b9b2b6f 100644 --- a/crates/voelin-model/src/presence.rs +++ b/crates/voelin-model/src/presence.rs @@ -98,6 +98,11 @@ pub struct ClientInfo { /// no avatar. A new hash means a new avatar. #[serde(default, skip_serializing_if = "Option::is_none")] pub avatar: Option, + /// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from + /// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the + /// server has no avatar for the client. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub myts_avatar: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, #[serde(default, skip_serializing_if = "is_zero_i32")] @@ -136,6 +141,34 @@ pub fn parse_badges(value: &str) -> Vec { .collect() } +/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak +/// 6): `,;,…`, states as myTeamSpeak's +/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the +/// official client reads it: an entry that is not `,` (an +/// empty one too, from a trailing `;`) makes the whole value no avatar; +/// the "online" picture is shown whatever the client's state (an unknown +/// state counts as online), else away, do not disturb, offline, the first +/// of a kind. Only an HTTPS link of at most 4 KiB. +pub fn myts_avatar_url(value: &str) -> Option { + let mut best: Option<(u8, &str)> = None; + for entry in value.split(';') { + let mut parts = entry.split(','); + let state: u32 = parts.next()?.trim().parse().ok()?; + let url = parts.next()?.trim(); + let rank = match state { + 3 => 1, + 1 => 2, + 4 => 3, + _ => 0, + }; + if best.is_none_or(|(r, _)| rank < r) { + best = Some((rank, url)); + } + } + let url = best?.1; + (url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned()) +} + /// How a group's name is shown next to its members. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -348,6 +381,38 @@ mod tests { assert!(new.diff(&new).is_empty()); } + #[test] + fn myts_avatars_as_the_official_client_reads_them() { + let on = "https://a.example.test/on.png"; + assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on)); + // Away before do not disturb before offline; the first of a kind. + assert_eq!( + myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b") + .as_deref(), + Some("https://a/away") + ); + assert_eq!( + myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(), + Some("https://a/dnd") + ); + // An unknown state counts as online. + assert_eq!( + myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(), + Some("https://a/x") + ); + // One bad entry spoils the value. + for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] { + assert_eq!(myts_avatar_url(bad), None, "{bad:?}"); + } + // Only HTTPS, and not endless. + assert_eq!(myts_avatar_url("2,http://a/on"), None); + assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None); + // Older JSON without the field still loads. + let client: ClientInfo = + serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap(); + assert_eq!(client.myts_avatar, None); + } + #[test] fn badges_and_groups() { assert_eq!( diff --git a/crates/voelin-observer/src/convert.rs b/crates/voelin-observer/src/convert.rs index a174f40..6b630fe 100644 --- a/crates/voelin-observer/src/convert.rs +++ b/crates/voelin-observer/src/convert.rs @@ -89,6 +89,7 @@ pub fn client_from_row(row: &Row) -> Option { // What the row carries (`notifycliententerview` all of it, // `clientlist -voice -groups -icon` some). avatar: row.get("client_flag_avatar").filter(|a| !a.is_empty()).map(str::to_string), + myts_avatar: row.get("client_myteamspeak_avatar").and_then(voelin_model::myts_avatar_url), description: row.get("client_description").filter(|d| !d.is_empty()).map(str::to_string), talk_power: row.parse("client_talk_power").unwrap_or(0), talker: row.flag("client_is_talker").unwrap_or(false),