//! The voice connection's book (tsclientlib) as model types. use tsclientlib::{ClientType, MaxClients, data}; use voelin_model::{ BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode, Presence, ServerDetails, myts_avatar_url, shown_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.trim().to_owned(), banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64, banner_mode: match server.hostbanner_mode { 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(), 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, // `as` saturates (and turns NaN into 0); the mixer clamps it. priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32, 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), banner_gfx_url: c .banner_gfx_url .as_deref() .map(str::trim) .filter(|u| !u.is_empty()) .map(str::to_owned), // A number the book keeps as text. banner_mode: c .banner_mode .as_deref() .map_or(BannerMode::NoAdjust, BannerMode::from_wire), }, ) }) .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()), 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, channel_group: Some(c.channel_group.0), badges: shown_badges( &c.badges, c.signed_badges.as_deref().unwrap_or_default(), ), 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(), } } #[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() } /// 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 ", "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"); }; 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"), 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); assert_eq!(p.server.priority_speaker_dimm_db, -18); } /// 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")); } // ---- across the session seam --------------------------------------------- /// A presence made into the entities the TeamSpeak session writes /// (`ts_session::entities`), pushed the way a host syncs them, and /// projected back by the engine (`link::project`): what the UI is shown /// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1). fn through_the_seam(presence: &Presence, ts6: bool, own: Option) -> Presence { use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId}; use voelin_proto::link::Features; use voelin_proto::v1::{self, push::Body}; use crate::link::media::TalkTracker; use crate::link::project::{View, presence as project}; use crate::ts_session::entities::build; let built = build(presence, ts6, own); let mut replica = Replica::new(SCHEMA_GENERATION); for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)] { replica.subscribe(scope); let pushes = [ Body::SyncBegin(v1::SyncBegin { scope: Some(scope.to_proto()), mode: v1::SyncMode::Full as i32, epoch: 1, }), Body::Change(v1::Change { scope: Some(scope.to_proto()), rev: 1, put: layer.values().cloned().collect(), del: Vec::new(), }), Body::SyncEnd(v1::SyncEnd { scope: Some(scope.to_proto()), cursor: Some(v1::Cursor { epoch: 1, rev: 1 }), gap: false, }), ]; for body in pushes { replica.apply_push(&v1::Push { body: Some(body) }); } } let features = Features::new(["voice"]); let talking = TalkTracker::default(); project(&View { replica: &replica, server: 1, teamspeak: true, version: "", features: &features, streams: ts6, talking: &talking, }) } /// A TeamSpeak 6 server and some clients with what the book holds of them. fn ts6_presence() -> Presence { let mut book = ts6_book(); let list = format!( "channellist {}|{}|{}", channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), channel( 12, 1, "Raid", r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2" ), channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"), ); book.handle_command(&message(&list)).unwrap(); let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| { format!( "notifycliententerview reasonid=0 ctid={channel} clid={clid} \ client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \ client_unique_identifier=u{clid}= client_flag_avatar=abcdef \ client_description=about\\sme client_icon_id=777 client_input_muted=1 \ client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \ client_output_hardware=1 client_meta_data client_is_recording=1 \ client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \ client_servergroups={groups} client_away={} client_away_message={away} \ client_talk_power=75 client_talk_request=0 client_talk_request_msg \ client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \ client_nickname_phonetic client_needed_serverquery_view_power=75 \ client_is_channel_commander=1 client_country=RU client_badges \ client_myteamspeak_id=m{clid} client_integrations{avatar}", 100 + u64::from(clid), u8::from(!away.is_empty()), ) }; for text in [ enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"), enter(6, 12, "8,9", "gone\\sfishing", ""), enter(7, 12, "", "", " client_myteamspeak_avatar"), ] { book.handle_command(&message(&text)).unwrap(); } presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false) } #[test] fn a_book_is_what_the_ui_is_shown_across_the_seam() { let p = ts6_presence(); assert_eq!(p.clients.len(), 3, "the fixture has clients"); assert!(p.clients.values().any(|c| c.away.is_some()), "one is away"); // A TeamSpeak 6 client the book has no streaming flag of (it was not // sent) is not streaming: v1 has no "unknown" for it. let mut expected = p.clone(); for client in expected.clients.values_mut() { client.streaming = Some(client.streaming.unwrap_or(false)); } assert_eq!(through_the_seam(&p, true, Some(5)), expected); // The same server as a TeamSpeak 3 one has no streams to tell of. let mut ts3 = p.clone(); for client in ts3.clients.values_mut() { client.streaming = None; } assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3); } /// A deterministic stream of numbers for the generated presences. struct Numbers(u64); impl Numbers { fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; self.0 } fn below(&mut self, n: u64) -> u64 { self.next() % n } fn flag(&mut self) -> bool { self.below(2) == 0 } fn text(&mut self, prefix: &str) -> String { format!("{prefix}{}", self.below(1000)) } } /// A presence of the shape a TeamSpeak link reports: sibling channels in an /// order chain, every client with a database id, unique ids that are base64 /// (TeamSpeak 3 and 6) or login names, groups of both kinds. fn generated(seed: u64, ts6: bool) -> Presence { use base64::Engine as _; use voelin_model::{ BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode, }; let mut n = Numbers(seed | 1); let mut p = Presence::default(); let name = n.text("Server "); p.server_name = name.clone(); p.server = voelin_model::ServerDetails { name, uid: Some(n.text("uid")), welcome_message: n.text("welcome "), host_message: n.text("host "), host_message_mode: [ HostMessageMode::None, HostMessageMode::Log, HostMessageMode::Modal, ][n.below(3) as usize], banner_url: if n.flag() { n.text("https://b/") } else { String::new() }, banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() }, banner_gfx_interval_s: n.below(100), banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect] [n.below(3) as usize], host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() }, host_button_url: String::new(), host_button_gfx_url: String::new(), icon: n.below(5) as u32 * 1000, platform: "Linux".into(), version: n.text("6.0."), max_clients: n.below(500) as u16, priority_speaker_dimm_db: -(n.below(30) as i32), default_server_group: Some(1 + n.below(9)), default_channel_group: Some(1 + n.below(9)), }; // Groups. for id in 1..=(2 + n.below(4)) { let group = |id: u64, n: &mut Numbers| GroupInfo { id, name: n.text("group "), icon: n.below(3) as u32 * 100, sort_id: n.below(1000) as i32 - 500, naming_mode: [ GroupNamingMode::None, GroupNamingMode::Before, GroupNamingMode::After, ][n.below(3) as usize], group_type: [GroupType::Regular, GroupType::Template, GroupType::Query] [n.below(3) as usize], }; p.server_groups.insert(id, group(id, &mut n)); p.channel_groups.insert(id, group(id, &mut n)); } // Channels: a tree whose siblings follow each other. let mut parents = vec![0u64]; for id in 1..=(3 + n.below(8)) { let parent = parents[n.below(parents.len() as u64) as usize]; let order = p .channels .values() .filter(|c| c.parent == parent) .map(|c| c.id) .next_back() .unwrap_or(0); parents.push(id); p.channels.insert( id, ChannelInfo { id, parent, order, name: n.text("channel "), topic: n.flag().then(|| n.text("topic ")), has_password: n.flag(), max_clients: match n.below(3) { 0 => None, 1 => Some(0), _ => Some(1 + n.below(50) as i32), }, needed_subscribe_power: n.below(3) as i32 * 10, needed_talk_power: n.below(3) as i32 * 25, is_default: id == 1, icon: n.below(3) as u32 * 500, banner_gfx_url: n.flag().then(|| n.text("https://c/")), banner_mode: [ BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect, ][n.below(3) as usize], }, ); } // Clients. let channels: Vec = p.channels.keys().copied().collect(); for id in 1..=(1 + n.below(12)) { let id = id as u16; let uid = match n.below(4) { 0 => None, 1 => Some(n.text("login")), _ => { let bytes: Vec = (0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect(); Some(base64::engine::general_purpose::STANDARD.encode(bytes)) } }; let channel = channels[n.below(channels.len() as u64) as usize]; p.clients.insert( id, ClientInfo { id, uid, nickname: n.text("nick "), channel, is_query: n.below(5) == 0, away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }), input_muted: n.flag(), output_muted: n.flag(), talking: Some(false), streaming: ts6.then(|| n.flag()), server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(), country: n.flag().then(|| "DE".into()), avatar: n.flag().then(|| n.text("hash")), myts_avatar: n.flag().then(|| n.text("https://a/")), description: n.flag().then(|| n.text("about ")), talk_power: n.below(100) as i32, talker: n.flag(), channel_group: n.flag().then(|| 1 + n.below(9)), badges: (0..n.below(3)).map(|_| n.text("badge")).collect(), icon: n.below(3) as u32 * 111, recording: n.flag(), priority_speaker: n.flag(), channel_commander: n.flag(), database_id: Some(1_000 + u64::from(id)), }, ); } p } #[test] fn generated_presences_survive_the_seam() { for seed in 1..=200u64 { for ts6 in [false, true] { let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6); let own = p.clients.keys().next().copied(); assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}"); } } } }