diff --git a/crates/voelin-android/src/host.rs b/crates/voelin-android/src/host.rs index d773d99..973d730 100644 --- a/crates/voelin-android/src/host.rs +++ b/crates/voelin-android/src/host.rs @@ -223,6 +223,7 @@ mod tests { text: text.into(), ts_ms: 0, via_relay: false, + blocked: false, }, } } diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs index a9d0397..5de7989 100644 --- a/crates/voelin-core/src/history.rs +++ b/crates/voelin-core/src/history.rs @@ -125,6 +125,7 @@ impl From for HistoryMessage { text: m.text, ts_ms: m.ts_ms, via_relay: m.via_relay, + blocked: false, }, source: m.source, remote_id: m.remote_id, @@ -757,6 +758,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, }; new_message("srv", &msg, MessageSource::Voice) } diff --git a/crates/voelin-core/src/route.rs b/crates/voelin-core/src/route.rs index 27ae3aa..7936471 100644 --- a/crates/voelin-core/src/route.rs +++ b/crates/voelin-core/src/route.rs @@ -106,6 +106,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, } } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index fcbbb50..2006c32 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -592,6 +592,7 @@ impl Session { text: text.to_owned(), ts_ms: history::now_ms(), via_relay: *route != ChatRoute::Voice, + blocked: false, }; ctx.store_live(vec![history::new_message(&ctx.server_uid, &msg, MessageSource::Local)]); } diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index 6e9a5f8..6e131c7 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -16,7 +16,9 @@ use tsclientlib::{ }; use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; use voelin_model::{ - ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor, + ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, GroupNamingMode, + GroupType, HostBannerMode, HostMessageMode, Presence, ServerDetails, ServerFlavor, + parse_badges, }; use voelin_stream::{PeerConfig, Request, StreamNotification}; @@ -88,14 +90,97 @@ pub(crate) enum VoiceEvent { Disconnected(Option), } -/// The presence visible through a voice connection. -pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { +fn group_info( + id: u64, + name: &str, + icon: tsclientlib::IconId, + sort_id: i32, + naming_mode: tsclientlib::GroupNamingMode, + group_type: tsclientlib::GroupType, +) -> GroupInfo { + GroupInfo { + id, + name: name.to_owned(), + icon: icon.0, + sort_id, + naming_mode: match naming_mode { + tsclientlib::GroupNamingMode::None => GroupNamingMode::None, + tsclientlib::GroupNamingMode::Before => GroupNamingMode::Before, + tsclientlib::GroupNamingMode::After => GroupNamingMode::After, + }, + group_type: match group_type { + tsclientlib::GroupType::Template => GroupType::Template, + tsclientlib::GroupType::Regular => GroupType::Regular, + tsclientlib::GroupType::Query => GroupType::Query, + }, + } +} + +/// What the server tells about itself; `uid` as the voice source computed it. +fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails { + ServerDetails { + name: server.name.clone(), + uid: uid.map(str::to_owned), + welcome_message: server.welcome_message.clone(), + host_message: server.hostmessage.clone(), + host_message_mode: match server.hostmessage_mode { + tsclientlib::HostMessageMode::None => HostMessageMode::None, + tsclientlib::HostMessageMode::Log => HostMessageMode::Log, + tsclientlib::HostMessageMode::Modal => HostMessageMode::Modal, + tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit, + }, + banner_url: server.hostbanner_url.clone(), + banner_gfx_url: server.hostbanner_gfx_url.clone(), + banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64, + banner_mode: match server.hostbanner_mode { + tsclientlib::HostBannerMode::NoAdjust => HostBannerMode::NoAdjust, + tsclientlib::HostBannerMode::AdjustIgnoreAspect => HostBannerMode::IgnoreAspect, + tsclientlib::HostBannerMode::AdjustKeepAspect => HostBannerMode::KeepAspect, + }, + host_button_tooltip: server.hostbutton_tooltip.clone(), + host_button_url: server.hostbutton_url.clone(), + host_button_gfx_url: server.hostbutton_gfx_url.clone(), + icon: server.icon.0, + platform: server.platform.clone(), + version: server.version.clone(), + max_clients: server.max_clients, + default_server_group: Some(server.default_server_group.0), + default_channel_group: Some(server.default_channel_group.0), + } +} + +/// The presence visible through a voice connection; `server_uid` as +/// [`VoiceEvent::Connected`] told it, `talking` the clients talking now. +pub(crate) fn presence_from_book( + book: &data::Connection, + server_uid: Option<&str>, + talking: impl Fn(u16) -> bool, +) -> Presence { let limit = |m: &Option| match m { Some(MaxClients::Limited(n)) => Some(*n as i32), _ => None, }; Presence { server_name: book.server.name.clone(), + server: server_details(&book.server, server_uid), + server_groups: book + .server_groups + .values() + .map(|g| { + let info = + group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type); + (g.id.0, info) + }) + .collect(), + channel_groups: book + .channel_groups + .values() + .map(|g| { + let info = + group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type); + (g.id.0, info) + }) + .collect(), channels: book .channels .values() @@ -113,6 +198,7 @@ pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { 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), }, ) }) @@ -121,6 +207,8 @@ pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { .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 { @@ -132,10 +220,21 @@ pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { away: c.away_message.clone(), input_muted: c.input_muted, output_muted: c.output_muted, - talking: None, + talking: Some(talking(c.id.0)), streaming: c.is_streaming, - server_groups: c.server_groups.iter().map(|g| g.0).collect(), + server_groups, country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), + avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()), + description: Some(c.description.clone()).filter(|d| !d.is_empty()), + talk_power: c.talk_power, + talker: c.talk_power_granted, + channel_group: Some(c.channel_group.0), + badges: parse_badges(&c.badges), + icon: c.icon.0, + recording: c.is_recording, + priority_speaker: c.is_priority_speaker, + channel_commander: c.is_channel_commander, + database_id: Some(c.database_id.0), }, ) }) @@ -203,7 +302,7 @@ async fn run_inner( Some(Err(e)) => return Err(e.into()), None => anyhow::bail!("connection closed"), } - { + let server_uid = { let state = con.get_state()?; let flavor = ServerFlavor::from_version_string(&state.server.version); let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts()); @@ -218,17 +317,18 @@ async fn run_inner( name: state.server.name.clone(), flavor, own_client: state.own_client.0, - server_uid, + server_uid: server_uid.clone(), own_uid, }); - } + server_uid + }; // Subscribe to all channels to see everyone. let cmd = con.get_state()?.server.set_subscribed(true); cmd.send(&mut con)?; - publish_state(&con, events)?; - // Who is talking: last voice packet per client. - let mut talking: std::collections::HashMap = Default::default(); + let mut talking: HashMap = HashMap::new(); + publish_state(&con, &server_uid, &talking, events)?; + let mut tick = tokio::time::interval(Duration::from_millis(250)); // Stream commands waiting for the server's answer. let mut stream_requests: HashMap = HashMap::new(); @@ -280,10 +380,11 @@ async fn run_inner( text: message.clone(), ts_ms: now_ms(), via_relay: false, + blocked: false, })); } } - publish_state(&con, events)?; + publish_state(&con, &server_uid, &talking, events)?; } StreamItem::Audio(packet) => { let from = match packet.data().data() { @@ -351,10 +452,13 @@ fn own_channel(con: &Connection) -> Option { fn publish_state( con: &Connection, + server_uid: &str, + talking: &HashMap, events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { let state = con.get_state()?; - let _ = events.send(VoiceEvent::Presence(presence_from_book(state))); + let presence = presence_from_book(state, Some(server_uid), |id| talking.contains_key(&id)); + let _ = events.send(VoiceEvent::Presence(presence)); if let Some(own) = state.clients.get(&state.own_client) { let _ = events.send(VoiceEvent::OwnChannel(own.channel.0)); } diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs index 9fb294f..4dcf7ed 100644 --- a/crates/voelin-core/tests/gateway.rs +++ b/crates/voelin-core/tests/gateway.rs @@ -77,6 +77,7 @@ impl State { text: text.into(), ts_ms, via_relay: true, + blocked: false, }; let entry = HistoryEntry { rev, ..HistoryEntry::new(self.messages.len() as i64 + 1, message) }; @@ -275,6 +276,7 @@ fn answer( text, ts_ms: now_ms(), via_relay: true, + blocked: false, }; let entry = HistoryEntry { rev, diff --git a/crates/voelin-gateway-proto/src/messages/tests.rs b/crates/voelin-gateway-proto/src/messages/tests.rs index abcb46e..1a18c94 100644 --- a/crates/voelin-gateway-proto/src/messages/tests.rs +++ b/crates/voelin-gateway-proto/src/messages/tests.rs @@ -12,6 +12,7 @@ fn chat(text: &str) -> ChatMessage { text: text.into(), ts_ms: 1_700_000_000_123, via_relay: true, + blocked: false, } } diff --git a/crates/voelin-gateway/src/db/chat.rs b/crates/voelin-gateway/src/db/chat.rs index c2ec70e..12aee2a 100644 --- a/crates/voelin-gateway/src/db/chat.rs +++ b/crates/voelin-gateway/src/db/chat.rs @@ -25,6 +25,7 @@ fn entry_from_row(r: &Row) -> rusqlite::Result { author_id: None, text: r.get(5)?, via_relay: true, + blocked: false, }, topic_id: r.get(6)?, rev: r.get(7)?, diff --git a/crates/voelin-gateway/src/db/tests.rs b/crates/voelin-gateway/src/db/tests.rs index 7cc643f..ffb06e9 100644 --- a/crates/voelin-gateway/src/db/tests.rs +++ b/crates/voelin-gateway/src/db/tests.rs @@ -15,6 +15,7 @@ fn msg(target: ChatTarget, text: &str, ts_ms: i64) -> ChatMessage { text: text.into(), ts_ms, via_relay: true, + blocked: false, } } diff --git a/crates/voelin-gateway/src/hub.rs b/crates/voelin-gateway/src/hub.rs index 70f9ea2..d9d9539 100644 --- a/crates/voelin-gateway/src/hub.rs +++ b/crates/voelin-gateway/src/hub.rs @@ -657,7 +657,7 @@ impl Hub { .filter(|(_, c)| !c.is_query && channels.contains_key(&c.channel)) .map(|(id, c)| (*id, c.clone())) .collect(); - Presence { server_name: p.server_name.clone(), channels, clients } + Presence { server_name: p.server_name.clone(), channels, clients, ..Presence::default() } } // Chat @@ -783,6 +783,7 @@ impl Hub { text: text.to_string(), ts_ms: now_ms(), via_relay: true, + blocked: false, }, topic, )) diff --git a/crates/voelin-model/src/chat.rs b/crates/voelin-model/src/chat.rs index 6380006..e429fc8 100644 --- a/crates/voelin-model/src/chat.rs +++ b/crates/voelin-model/src/chat.rs @@ -1,9 +1,18 @@ //! Chat messages, from any source. +//! +//! Messages can link files in a channel's file browser: TeamSpeak clients +//! post them as `[URL=ts3file://…]name[/URL]`; [`ChatMessage::file_refs`] +//! finds them as [`FileRef`]s (for file cards) and [`FileRef::to_bbcode`] +//! writes one. use serde::{Deserialize, Serialize}; use crate::presence::{ChannelId, ClientId}; +fn is_false(b: &bool) -> bool { + !*b +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(tag = "kind", content = "id", rename_all = "snake_case")] pub enum ChatTarget { @@ -28,6 +37,157 @@ pub struct ChatMessage { /// Carried by a gateway or query relay rather than our own connection. #[serde(default)] pub via_relay: bool, + /// The author is blocked in our contacts (set by the engine when it + /// reports the message; never sent over the wire). + #[serde(default, skip_serializing_if = "is_false")] + pub blocked: bool, +} + +impl ChatMessage { + /// The file links in the text, in order of appearance, each once. + pub fn file_refs(&self) -> Vec { + parse_file_links(&self.text) + } +} + +/// A file in a channel's file browser, as a chat message links it. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct FileRef { + /// The server's unique id (`serverUID`), when the link tells it: a link + /// from another server cannot be downloaded here. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub server_uid: Option, + pub channel: ChannelId, + /// The directory, `/` for the channel's root. + pub path: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(default, skip_serializing_if = "is_false")] + pub is_dir: bool, + /// Unix seconds of the last change, when the link tells it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified_s: Option, + /// The link as it appeared. + pub url: String, +} + +/// URL schemes of file links (`ts3file`; later clients may use others of +/// the same form). +const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"]; + +impl FileRef { + /// The file's path in the channel: [`Self::path`] joined with [`Self::name`]. + pub fn full_path(&self) -> String { + let dir = self.path.trim_end_matches('/'); + format!("{dir}/{}", self.name) + } + + /// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`). + pub fn parse(url: &str) -> Option { + let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase(); + let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?; + let rest = &url[scheme.len()..]; + let (host, query) = rest.split_once('?').unwrap_or((rest, "")); + let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() }; + let mut channel = None; + for pair in query.split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let value = percent_decode(value); + match key.to_ascii_lowercase().as_str() { + "serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()), + "channel" | "cid" => channel = value.parse().ok(), + "path" => file.path = if value.is_empty() { "/".into() } else { value }, + "filename" | "name" => file.name = value, + "isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"), + "size" => file.size = value.parse().ok(), + "filedatetime" => file.modified_s = value.parse().ok(), + _ => {} + } + } + if file.name.is_empty() { + file.name = percent_decode(host.trim_end_matches('/')); + } + file.channel = channel?; + (!file.name.is_empty()).then_some(file) + } + + /// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`. + pub fn to_bbcode(&self) -> String { + let mut url = format!("ts3file://{}?", percent_encode(&self.name)); + if let Some(uid) = &self.server_uid { + url.push_str(&format!("serverUID={}&", percent_encode(uid))); + } + url.push_str(&format!( + "channel={}&path={}&filename={}&isDir={}", + self.channel, + percent_encode(&self.path), + percent_encode(&self.name), + u8::from(self.is_dir) + )); + if let Some(size) = self.size { + url.push_str(&format!("&size={size}")); + } + if let Some(t) = self.modified_s { + url.push_str(&format!("&fileDateTime={t}")); + } + format!("[URL={url}]{}[/URL]", self.name) + } +} + +/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown +/// `[name](…)` or bare), in order, each once. +pub fn parse_file_links(text: &str) -> Vec { + let lower = text.to_ascii_lowercase(); + let mut found: Vec = Vec::new(); + let mut at = 0; + while at < text.len() { + let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min(); + let Some(start) = next else { break }; + let end = text[start..] + .find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>')) + .map_or(text.len(), |i| start + i); + if let Some(file) = FileRef::parse(&text[start..end]) + && !found.iter().any(|f| f.url == file.url) + { + found.push(file); + } + at = end.max(start + 1); + } + found +} + +/// `%XX` escapes to bytes (a `+` stays: file names keep theirs). +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let hex = |b: u8| (b as char).to_digit(16); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && let (Some(h), Some(l)) = + (bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b))) + { + out.push((h * 16 + l) as u8); + i += 3; + continue; + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn percent_encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out } /// Format of messages a relay posts on behalf of a user. @@ -70,6 +230,80 @@ mod tests { assert_eq!(parts.concat(), "ääää"); } + #[test] + fn parses_ts3_file_links() { + let text = "look: [URL=ts3file://Report%20Q3.pdf?serverUID=l%2FHvD5zXg5r4%2F%2FC6Ht7J9Ts3Wmc%3D&channel=5&path=%2Fdocs&filename=Report%20Q3.pdf&isDir=0&size=12345&fileDateTime=1454598011]Report Q3.pdf[/URL] and [URL]ts3file://a.txt?channel=1&path=%2F&filename=a+b.txt[/URL]"; + let files = parse_file_links(text); + assert_eq!(files.len(), 2); + let f = &files[0]; + assert_eq!(f.server_uid.as_deref(), Some("l/HvD5zXg5r4//C6Ht7J9Ts3Wmc=")); + assert_eq!((f.channel, f.path.as_str(), f.name.as_str()), (5, "/docs", "Report Q3.pdf")); + assert_eq!((f.size, f.modified_s, f.is_dir), (Some(12345), Some(1_454_598_011), false)); + assert_eq!(f.full_path(), "/docs/Report Q3.pdf"); + assert_eq!(files[1].name, "a+b.txt"); + assert_eq!(files[1].full_path(), "/a+b.txt"); + } + + #[test] + fn file_links_in_other_forms() { + // Markdown, bare, a repeated link, a link without a channel. + let text = "[x](ts3file://x?channel=2&filename=x&isDir=true) ts3file://y?channel=3&path=/d/ \ + ts3file://y?channel=3&path=/d/ ts3file://z?filename=z"; + let files = parse_file_links(text); + assert_eq!(files.len(), 2); + assert!(files[0].is_dir); + assert_eq!((files[1].name.as_str(), files[1].full_path().as_str()), ("y", "/d/y")); + let msg = ChatMessage { + target: ChatTarget::Channel(1), + author_name: "a".into(), + author_uid: None, + author_id: None, + text: text.into(), + ts_ms: 0, + via_relay: false, + blocked: false, + }; + assert_eq!(msg.file_refs(), files); + assert!(parse_file_links("no links, ts3file:// alone").is_empty()); + } + + #[test] + fn file_link_round_trip() { + let file = FileRef { + server_uid: Some("uid+/=".into()), + channel: 7, + path: "/a dir".into(), + name: "ä b&c.png".into(), + size: Some(10), + is_dir: false, + modified_s: Some(99), + url: String::new(), + }; + let text = file.to_bbcode(); + let parsed = parse_file_links(&text); + assert_eq!(parsed.len(), 1); + assert_eq!(FileRef { url: String::new(), ..parsed[0].clone() }, file); + assert!(text.ends_with("]ä b&c.png[/URL]")); + } + + #[test] + fn blocked_flag_stays_off_the_wire() { + let msg = ChatMessage { + target: ChatTarget::Server, + author_name: "a".into(), + author_uid: None, + author_id: None, + text: "t".into(), + ts_ms: 1, + via_relay: false, + blocked: false, + }; + let json = serde_json::to_string(&msg).unwrap(); + assert!(!json.contains("blocked")); + let back: ChatMessage = serde_json::from_str(&json).unwrap(); + assert_eq!(back, msg); + } + #[test] fn target_json() { assert_eq!( diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index 1bf5275..e8024e0 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -8,9 +8,12 @@ mod presence; mod server; mod tree; -pub use chat::{ChatMessage, ChatTarget, relay_text, split_message}; +pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; pub use presence::{ - ChannelId, ChannelInfo, ClientId, ClientInfo, Presence, PresenceDelta, PresenceSnapshot, + ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, + Presence, PresenceDelta, PresenceSnapshot, parse_badges, +}; +pub use server::{ + Capabilities, HostBannerMode, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, }; -pub use server::{Capabilities, 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 ec4c2c0..d0adf59 100644 --- a/crates/voelin-model/src/presence.rs +++ b/crates/voelin-model/src/presence.rs @@ -3,13 +3,34 @@ //! The same model is fed from a voice connection, a query session or a //! gateway. Sources send a [`PresenceSnapshot`] followed by //! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`]. +//! +//! A voice connection also knows the server's details (welcome message, +//! host banner, …) and its server and channel groups ([`Presence::server`], +//! [`Presence::server_groups`], [`Presence::channel_groups`]); snapshots and +//! deltas do not carry them (other sources leave them empty). use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; +use crate::server::ServerDetails; + pub type ChannelId = u64; pub type ClientId = u16; +/// A server or channel group id. +pub type GroupId = u64; + +fn is_zero_i32(n: &i32) -> bool { + *n == 0 +} + +fn is_zero_u32(n: &u32) -> bool { + *n == 0 +} + +fn is_false(b: &bool) -> bool { + !*b +} #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ChannelInfo { @@ -32,6 +53,9 @@ pub struct ChannelInfo { pub needed_talk_power: i32, #[serde(default)] pub is_default: bool, + /// Icon id (`channel_icon_id`); 0: none. + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub icon: u32, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -44,6 +68,7 @@ pub struct ClientInfo { /// ServerQuery clients (bots, our own relays). UIs normally hide them. #[serde(default)] pub is_query: bool, + /// Away, with the away message (empty without one); `None`: not away. #[serde(default, skip_serializing_if = "Option::is_none")] pub away: Option, #[serde(default)] @@ -56,9 +81,89 @@ pub struct ClientInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub streaming: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub server_groups: Vec, + pub server_groups: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub country: Option, + /// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`: + /// no avatar. A new hash means a new avatar. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub avatar: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "is_zero_i32")] + pub talk_power: i32, + /// Allowed to talk regardless of talk power (`client_is_talker`). + #[serde(default, skip_serializing_if = "is_false")] + pub talker: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel_group: Option, + /// Badge GUIDs (`client_badges`), in display order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub badges: Vec, + /// Icon id (`client_icon_id`); 0: none. + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub icon: u32, + #[serde(default, skip_serializing_if = "is_false")] + pub recording: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub priority_speaker: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub channel_commander: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub database_id: Option, +} + +/// Badge GUIDs of a `client_badges` value +/// (`Overwolf=0:badges=,`). +pub fn parse_badges(value: &str) -> Vec { + value + .split(':') + .filter_map(|part| part.strip_prefix("badges=")) + .flat_map(|list| list.split(',')) + .map(str::trim) + .filter(|g| !g.is_empty()) + .map(str::to_owned) + .collect() +} + +/// 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")] +pub enum GroupNamingMode { + #[default] + None, + /// Before the nickname: `[Admin] Alice`. + Before, + /// After the nickname: `Alice [Admin]`. + After, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GroupType { + /// For new virtual servers; nobody is a member. + Template, + #[default] + Regular, + /// ServerQuery clients. + Query, +} + +/// A server or channel group. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct GroupInfo { + pub id: GroupId, + pub name: String, + /// Icon id; 0: none. + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub icon: u32, + /// Display order: lower first, then by id. + #[serde(default)] + pub sort_id: i32, + #[serde(default)] + pub naming_mode: GroupNamingMode, + #[serde(default)] + pub group_type: GroupType, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -87,6 +192,11 @@ pub struct Presence { pub server_name: String, pub channels: BTreeMap, pub clients: BTreeMap, + /// What the source knows about the server (a voice connection: all of + /// it; other sources: nothing). + pub server: ServerDetails, + pub server_groups: BTreeMap, + pub channel_groups: BTreeMap, } impl Presence { @@ -95,9 +205,23 @@ impl Presence { server_name: s.server_name, channels: s.channels.into_iter().map(|c| (c.id, c)).collect(), clients: s.clients.into_iter().map(|c| (c.id, c)).collect(), + ..Self::default() } } + /// The client with this unique id, if present (the first of several + /// connections with the same identity). + pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> { + self.clients.values().find(|c| c.uid.as_deref() == Some(uid)) + } + + /// Groups in display order (sort id, then id). + pub fn sorted_groups(groups: &BTreeMap) -> Vec<&GroupInfo> { + let mut sorted: Vec<_> = groups.values().collect(); + sorted.sort_by_key(|g| (g.sort_id, g.id)); + sorted + } + pub fn snapshot(&self) -> PresenceSnapshot { PresenceSnapshot { server_name: self.server_name.clone(), @@ -214,6 +338,40 @@ mod tests { assert!(new.diff(&new).is_empty()); } + #[test] + fn badges_and_groups() { + assert_eq!( + parse_badges( + "Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157" + ), + ["c9e97536-5a2d-4c8e-a135-af404587a472", "450f81c1-ab41-4211-a338-222fa94ed157"] + ); + assert!(parse_badges("").is_empty()); + assert!(parse_badges("Overwolf=1").is_empty()); + let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() }; + let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]); + let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect(); + assert_eq!(order, [2, 3, 1]); + let mut alice = cl(1, "Alice", 1); + alice.uid = Some("A=".into()); + let p = presence(vec![ch(1, "Lobby")], vec![alice, cl(2, "Bob", 1)]); + assert_eq!(p.client_by_uid("A=").map(|c| c.id), Some(1)); + assert!(p.client_by_uid("B=").is_none()); + } + + #[test] + fn old_json_without_new_fields() { + let c: ClientInfo = + serde_json::from_str(r#"{"id":1,"nickname":"a","channel":2,"away":""}"#).unwrap(); + assert_eq!(c.away.as_deref(), Some("")); + assert_eq!((c.talk_power, c.avatar.as_ref(), c.badges.len()), (0, None, 0)); + // Defaults stay off the wire. + assert_eq!( + serde_json::to_string(&cl(1, "a", 2)).unwrap(), + r#"{"id":1,"nickname":"a","channel":2,"is_query":false,"input_muted":false,"output_muted":false}"# + ); + } + #[test] fn members_skip_query_clients() { let mut bot = cl(9, "bot", 1); diff --git a/crates/voelin-model/src/server.rs b/crates/voelin-model/src/server.rs index d13e763..20925f7 100644 --- a/crates/voelin-model/src/server.rs +++ b/crates/voelin-model/src/server.rs @@ -78,17 +78,105 @@ impl ServerFlavor { pub fn capabilities(&self) -> Capabilities { match self { - ServerFlavor::Ts3(_) => { - Capabilities { streams: false, raw_query: true, ssh_query: true, http_query: false } - } - ServerFlavor::Ts6(_) => { - Capabilities { streams: true, raw_query: false, ssh_query: true, http_query: true } - } + ServerFlavor::Ts3(_) => Capabilities { + streams: false, + raw_query: true, + ssh_query: true, + http_query: false, + file_transfer: true, + offline_messages: true, + }, + // Verified against 6.0.0-beta13.1: file transfer and offline + // messages work as on TeamSpeak 3. + ServerFlavor::Ts6(_) => Capabilities { + streams: true, + raw_query: false, + ssh_query: true, + http_query: true, + file_transfer: true, + offline_messages: true, + }, ServerFlavor::Unknown(_) => Capabilities::default(), } } } +/// Where the host message shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HostMessageMode { + /// Not shown. + #[default] + None, + /// In the chat log. + Log, + /// In a dialog. + Modal, + /// In a dialog; the connection ends when it is closed. + ModalQuit, +} + +/// How the host banner image is scaled. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HostBannerMode { + /// As it is. + #[default] + NoAdjust, + /// Stretched to the banner area. + IgnoreAspect, + /// Scaled to fit, keeping its aspect ratio. + KeepAspect, +} + +/// What a server tells its (voice) clients about itself. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerDetails { + pub name: String, + /// `virtualserver_unique_identifier` (the key of its chat history). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub uid: Option, + #[serde(default)] + pub welcome_message: String, + #[serde(default)] + pub host_message: String, + #[serde(default)] + pub host_message_mode: HostMessageMode, + /// Where a click on the banner leads. + #[serde(default)] + pub banner_url: String, + /// The banner image. + #[serde(default)] + pub banner_gfx_url: String, + /// Reload the banner image this often (seconds); 0: never. + #[serde(default)] + pub banner_gfx_interval_s: u64, + #[serde(default)] + pub banner_mode: HostBannerMode, + #[serde(default)] + pub host_button_tooltip: String, + #[serde(default)] + pub host_button_url: String, + /// The host button's image. + #[serde(default)] + pub host_button_gfx_url: String, + /// Icon id (`virtualserver_icon_id`); 0: none. + #[serde(default)] + pub icon: u32, + /// Server platform, e.g. `Linux`. + #[serde(default)] + pub platform: String, + /// `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]`. + #[serde(default)] + pub version: String, + #[serde(default)] + pub max_clients: u16, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_server_group: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_channel_group: Option, +} + /// Features that depend on the server software. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Capabilities { @@ -100,6 +188,12 @@ pub struct Capabilities { pub ssh_query: bool, /// HTTP WebQuery (TeamSpeak 6), request/response only, no events. pub http_query: bool, + /// Channel file browsers, avatars and icons (`ftinit*` over TCP). + #[serde(default)] + pub file_transfer: bool, + /// Offline messages to a unique id (`messageadd`, `messagelist`, …). + #[serde(default)] + pub offline_messages: bool, } #[cfg(test)] diff --git a/crates/voelin-observer/src/convert.rs b/crates/voelin-observer/src/convert.rs index d1cb412..288750d 100644 --- a/crates/voelin-observer/src/convert.rs +++ b/crates/voelin-observer/src/convert.rs @@ -17,6 +17,7 @@ pub fn channel_from_row(row: &Row) -> Option { needed_subscribe_power: row.parse("channel_needed_subscribe_power").unwrap_or(0), 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), }) } @@ -69,6 +70,19 @@ pub fn client_from_row(row: &Row) -> Option { .map(|g| g.split(',').filter_map(|g| g.parse().ok()).collect()) .unwrap_or_default(), country: row.get("client_country").filter(|c| !c.is_empty()).map(str::to_string), + // 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), + 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), + channel_group: row.parse("client_channel_group_id"), + badges: row.get("client_badges").map(voelin_model::parse_badges).unwrap_or_default(), + icon: row.parse::("client_icon_id").map_or(0, |i| i as u32), + recording: row.flag("client_is_recording").unwrap_or(false), + priority_speaker: row.flag("client_is_priority_speaker").unwrap_or(false), + channel_commander: row.flag("client_is_channel_commander").unwrap_or(false), + database_id: row.parse("client_database_id"), }) } @@ -130,6 +144,7 @@ pub fn is_text_message(n: &Notification, now_ms: i64) -> Option { text: row.get("msg").unwrap_or_default().to_string(), ts_ms: now_ms, via_relay: true, + blocked: false, }) } diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index cc52a53..af1832e 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -331,6 +331,7 @@ fn demo_ui(app: &mut App) { text: text.into(), ts_ms: now - (60 - minute) * 60_000, via_relay: relay, + blocked: false, }; app.add_message(id, message); } diff --git a/crates/voelin-ui/src/vm/chat.rs b/crates/voelin-ui/src/vm/chat.rs index da4b097..d4268be 100644 --- a/crates/voelin-ui/src/vm/chat.rs +++ b/crates/voelin-ui/src/vm/chat.rs @@ -86,6 +86,7 @@ mod tests { text: text.into(), ts_ms, via_relay: false, + blocked: false, } }