//! The engine's view of a session's replica, in the client's older model //! (`docs/session-seam.md` section 5.3). //! //! The UI and `session.rs` still speak `Presence`, `ChannelInfo`, //! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and //! [`chat_message`] project the replica into them with //! `voelin_model::replica::convert`, and fix up where that says less than the //! older model does (F1 to F10 of the design). The fix-ups apply the //! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the //! ids it has; they go when the UI reads the replica. use std::collections::BTreeMap; use voelin_model::replica::{Replica, convert}; use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails}; use voelin_proto::link::Features; use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope}; use super::media::TalkTracker; use crate::ts::ts_session::entities::user_uid; use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM}; /// What the projection needs to know besides the replica. pub(crate) struct View<'a> { pub(crate) replica: &'a Replica, /// The server of the session. pub(crate) server: u64, /// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules /// (channel groups) are undone. pub(crate) teamspeak: bool, /// The version the host said (`Welcome.host.backend.version`). pub(crate) version: &'a str, pub(crate) features: &'a Features, /// Whether the connection has streams (a port, not just the feature). pub(crate) streams: bool, pub(crate) talking: &'a TalkTracker, } /// What a `Foreign` of TeamSpeak holds under `key`. fn foreign_value( foreign: Option<&v1::Foreign>, kind: &str, key: &str, ) -> Option { let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?; serde_json::from_slice::(&foreign.json).ok()?.get(key).cloned() } /// The server's unique id as the client keys its history and aliases by it: /// the host's without the `ts:` of protocol section 11.2 (F3). pub(crate) fn server_key(uid: &str) -> String { uid.strip_prefix("ts:").unwrap_or(uid).to_owned() } /// The client's older model of the server (what `LinkEvent::Presence` holds). pub(crate) fn presence(view: &View<'_>) -> Presence { let replica = view.replica; let server = view.server; // F1: only what the older model calls channels. let channels: Vec<&v1::Channel> = replica .channels(server) .filter(|channel| { !matches!( ChannelKind::try_from(channel.kind), Ok(ChannelKind::ServerChat | ChannelKind::Dm | ChannelKind::GroupDm | ChannelKind::Thread) ) }) .collect(); let by_id: BTreeMap = channels.iter().map(|c| (c.id, *c)).collect(); let channel_infos = convert::channel_infos(&channels) .into_iter() .map(|mut info| { // F7: a limit of 0 is a limit, not "unlimited". let zero = by_id .get(&info.id) .and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients")); if zero.and_then(|v| v.as_i64()) == Some(0) { info.max_clients = Some(0); } (info.id, info) }) .collect(); let clients = replica .voice_states(server) .filter_map(|voice| { let user = replica.user(voice.user_id); let member = replica.member(server, voice.user_id); let mut client = convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?; // F10: a unique id that is no base64 rides in `Foreign`. client.uid = user.and_then(user_uid); // F2: the client's channel group is TeamSpeak's own number. if view.teamspeak { client.channel_group = client.channel_group.map(ids::channel_group); } // F6: the client's icon. client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon") .and_then(|v| v.as_u64()) .and_then(|v| u32::try_from(v).ok()) .unwrap_or(0); // F8: who is talking comes from the media. client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id)); // F9: the stream flag only where there are streams. if !view.streams { client.streaming = None; } Some((client.id, client)) }) .collect(); let mut server_groups: BTreeMap = BTreeMap::new(); let mut channel_groups: BTreeMap = BTreeMap::new(); for role in replica.roles(server) { let mut info = convert::group_info(role); if role.scope == RoleScope::Channel as i32 { if view.teamspeak { info.id = ids::channel_group(info.id); } channel_groups.insert(info.id, info); } else { server_groups.insert(info.id, info); } } let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default(); Presence { server_name: details.name.clone(), channels: channel_infos, clients, server: details, server_groups, channel_groups, } } /// `convert::server_details` with F2 to F5. fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails { let mut details = convert::server_details(server); // F3: the unique id as the client keys it. details.uid = details.uid.as_deref().map(server_key); let foreign = server.foreign.as_ref(); // F4: the version the server sent, else the one the host reports. details.version = foreign_value(foreign, "server", "version") .and_then(|v| v.as_str().map(str::to_owned)) .filter(|v| !v.is_empty()) .unwrap_or_else(|| view.version.to_owned()); // F5: the server's platform. details.platform = foreign_value(foreign, "server", "platform") .and_then(|v| v.as_str().map(str::to_owned)) .unwrap_or_default(); // F2: the default channel group is TeamSpeak's own number. if view.teamspeak { details.default_channel_group = details.default_channel_group.map(ids::channel_group); } details } /// Where the older model files the messages of a channel (the replica's /// `chat_target`, with the unique id of F10). fn chat_target(replica: &Replica, channel: u64) -> ChatTarget { let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) }; match ChannelKind::try_from(info.kind) { Ok(ChannelKind::ServerChat) => ChatTarget::Server, Ok(ChannelKind::Dm | ChannelKind::GroupDm) => { let own = replica.own_user(); info.recipients .iter() .copied() .find(|id| *id != own) .and_then(|id| replica.user(id)) .and_then(user_uid) .map_or(ChatTarget::Channel(channel), ChatTarget::Private) } _ => ChatTarget::Channel(channel), } } /// A message of the replica as the older model has it. pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option { let message = replica.message(channel, id)?; let author = replica.user(message.author_id); let name = Some(message.author_name.as_str()) .filter(|name| !name.is_empty()) .or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty())) .unwrap_or_default(); Some(ChatMessage { target: chat_target(replica, channel), author_name: name.to_owned(), author_uid: author.and_then(user_uid), author_id: (message.author_participant != 0) .then(|| u16::try_from(message.author_participant).ok()) .flatten(), text: message.text.clone(), ts_ms: message.ts_ms, via_relay: message.flags & MessageFlag::Relayed as u32 != 0, blocked: false, }) } #[cfg(test)] mod tests { use super::*; #[test] fn the_ts_prefix_of_a_server_uid_goes() { assert_eq!(server_key("ts:abc="), "abc="); assert_eq!(server_key("abc="), "abc="); assert_eq!(server_key(""), ""); } }