diff --git a/CHANGELOG.md b/CHANGELOG.md index 815ddbb..557dfa7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,8 +29,12 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows in the channel tree and the members panel, and their names on the member card (what each is for on hover). - Links in chat open in the browser; one whose text is not its address - first shows where it goes. A right-click on a link opens or copies it; - TeamSpeak links are copied for now. + first shows where it goes. A right-click on a link opens or copies it. +- `ts3server://` and `teamspeak://` links in chat (and `tmspk.gg/s/…`) + open the server dialog filled in from the link, its channel and key + included, or move you into the link's channel when you are in voice on + that server. Nothing connects before Connect, and a saved server keeps + its nickname. `tmspk.gg` invite codes can't be opened yet. - Every message can be quoted into the composer (`> ` lines) and its text copied, from the actions on hover or a right-click menu, also on servers without a gateway. diff --git a/crates/voelin-model/src/chat.rs b/crates/voelin-model/src/chat.rs index e429fc8..8068b43 100644 --- a/crates/voelin-model/src/chat.rs +++ b/crates/voelin-model/src/chat.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; +use crate::percent; use crate::presence::{ChannelId, ClientId}; fn is_false(b: &bool) -> bool { @@ -93,7 +94,7 @@ impl FileRef { let mut channel = None; for pair in query.split('&') { let (key, value) = pair.split_once('=').unwrap_or((pair, "")); - let value = percent_decode(value); + 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(), @@ -106,7 +107,7 @@ impl FileRef { } } if file.name.is_empty() { - file.name = percent_decode(host.trim_end_matches('/')); + file.name = percent::decode(host.trim_end_matches('/')); } file.channel = channel?; (!file.name.is_empty()).then_some(file) @@ -114,15 +115,15 @@ impl FileRef { /// 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)); + 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!("serverUID={}&", percent::encode(uid))); } url.push_str(&format!( "channel={}&path={}&filename={}&isDir={}", self.channel, - percent_encode(&self.path), - percent_encode(&self.name), + percent::encode(&self.path), + percent::encode(&self.name), u8::from(self.is_dir) )); if let Some(size) = self.size { @@ -157,39 +158,6 @@ pub fn parse_file_links(text: &str) -> Vec { 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. pub fn relay_text(format: &str, nick: &str, text: &str) -> String { format.replace("{nick}", nick).replace("{text}", text) diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index e77193e..fb65c60 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -5,11 +5,14 @@ pub mod badges; mod chat; +mod link; +mod percent; mod presence; mod server; mod tree; pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; +pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path}; pub use presence::{ ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, Presence, PresenceDelta, PresenceSnapshot, parse_badges, diff --git a/crates/voelin-model/src/link.rs b/crates/voelin-model/src/link.rs new file mode 100644 index 0000000..f2e3b99 --- /dev/null +++ b/crates/voelin-model/src/link.rs @@ -0,0 +1,420 @@ +//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://` +//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends +//! the browser on to a `teamspeak://` link. + +use crate::percent; +use crate::presence::ChannelId; + +/// What a link opens ([`Link::parse`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Link { + /// A server, and maybe a channel on it. + Server(ServerLink), + /// A TeamSpeak 6 invite code (`tmspk.gg/`, + /// `teamspeak://invite=`): only a TeamSpeak service knows the + /// server it stands for. + Invite(String), +} + +/// A server link: the server, and what to join it with (none of it empty). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ServerLink { + /// A host name, an IP address (IPv6 without brackets) or a server + /// nickname. + pub host: String, + pub port: Option, + pub nickname: Option, + /// The server's password. + pub password: Option, + /// The channel to join: its names from the top, separated by `/` (a `/` + /// in a name as `\/`, [`split_channel_path`]), or `/` (`cid=`). + pub channel: Option, + pub channel_password: Option, + /// A privilege key: it puts its user in a server or channel group. + pub token: Option, +} + +const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"]; +const WEB: [&str; 2] = ["https://", "http://"]; +const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"]; + +impl Link { + /// Read a link: `ts3server://?` with the keys `port`, + /// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword` + /// and `token` (`teamspeak://` alike; the scheme and the keys in any + /// case, other keys ignored, a `+` kept as it is), + /// `https://tmspk.gg/s/?` (also `/s=`), and the + /// invite codes `tmspk.gg/` and `teamspeak://invite=`. None + /// for anything else. + pub fn parse(text: &str) -> Option { + let text = text.trim(); + // The same length in bytes: an index of one is one of the other. + let lower = text.to_ascii_lowercase(); + match SCHEMES.iter().find(|s| lower.starts_with(**s)) { + Some(scheme) => parse_server(&text[scheme.len()..]), + None => parse_short(text, &lower), + } + } +} + +impl ServerLink { + /// A link to the server at `address` (`host`, `host:port`, `[v6]`, + /// `[v6]:port` or a bare IPv6 address), joining nothing. + pub fn new(address: &str) -> Self { + let (host, port) = split_address(address.trim()); + ServerLink { host: host.to_owned(), port, ..Default::default() } + } + + /// The server's address as a bookmark keeps it: `host`, `host:port` or + /// `[v6]:port`. + pub fn address(&self) -> String { + match self.port { + Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host), + Some(port) => format!("{}:{port}", self.host), + None => self.host.clone(), + } + } + + /// The link as TeamSpeak clients open it: `ts3server://?port=…`, + /// then what is set of nickname, password, channel (or `cid` for + /// `/`), channel password and privilege key. + pub fn to_url(&self) -> String { + let mut url = match self.port { + Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host), + _ => format!("ts3server://{}", self.host), + }; + let pair = |key: &str, value: &Option| { + let value = value.as_deref().filter(|v| !v.is_empty())?; + Some(format!("{key}={}", percent::encode(value))) + }; + let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| { + match channel_path_id(path) { + Some(id) => format!("cid={id}"), + // A `/` between names, `%2F` in one. + None => { + let names: Vec = + split_channel_path(path).iter().map(|n| percent::encode(n)).collect(); + format!("channel={}", names.join("/")) + } + } + }); + let query: Vec = [ + self.port.map(|port| format!("port={port}")), + pair("nickname", &self.nickname), + pair("password", &self.password), + channel, + pair("channelpassword", &self.channel_password), + pair("token", &self.token), + ] + .into_iter() + .flatten() + .collect(); + if !query.is_empty() { + url.push('?'); + url.push_str(&query.join("&")); + } + url + } +} + +/// A channel path's names from the top: `Gaming/Raid Night` → +/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`. +pub fn split_channel_path(path: &str) -> Vec { + let mut names = Vec::new(); + let mut name = String::new(); + let mut chars = path.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '\\' if chars.peek() == Some(&'/') => { + name.push('/'); + chars.next(); + } + '/' => names.push(std::mem::take(&mut name)), + c => name.push(c), + } + } + names.push(name); + names +} + +/// A channel path from its names from the top, a `/` in a name as `\/`: +/// the reverse of [`split_channel_path`]. +pub fn join_channel_path(names: &[impl AsRef]) -> String { + names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::>().join("/") +} + +/// The channel id of a path `/` (what `cid=` gives). +pub fn channel_path_id(path: &str) -> Option { + let id = path.strip_prefix('/')?; + if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + id.parse().ok() +} + +/// After `ts3server://` or `teamspeak://`: `[:port][/]?`, or +/// `invite=`. +fn parse_server(rest: &str) -> Option { + let (head, query) = rest.split_once('?').unwrap_or((rest, "")); + let authority = head.split('/').next().unwrap_or_default(); + if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) { + let code = percent::decode(&authority[key.len()..]); + return (!code.is_empty()).then_some(Link::Invite(code)); + } + let authority = percent::decode(authority); + let (host, port) = split_address(&authority); + if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) { + return None; + } + let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() }; + let mut cid = None; + for pair in query.split('&') { + let (key, raw) = pair.split_once('=').unwrap_or((pair, "")); + let value = Some(percent::decode(raw)).filter(|v| !v.is_empty()); + match key.to_ascii_lowercase().as_str() { + // One that is no port is ignored. + "port" => link.port = value.as_deref().and_then(parse_port).or(link.port), + "nickname" => link.nickname = value, + "password" => link.password = value, + // A `/` between names, `%2F` in one. + "channel" => { + let names: Vec = raw.split('/').map(percent::decode).collect(); + link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != ""); + } + "cid" => cid = value.and_then(|v| v.parse::().ok()).filter(|c| *c != 0), + "channelpassword" => link.channel_password = value, + "token" => link.token = value, + _ => {} + } + } + // The id names one channel for sure. + if let Some(cid) = cid { + link.channel = Some(format!("/{cid}")); + } + Some(Link::Server(link)) +} + +/// `tmspk.gg/s/?…` (or `/s=`), with or without `https://`, goes where +/// its page sends the browser: `teamspeak://?…`; any other path is an +/// invite code. +fn parse_short(text: &str, lower: &str) -> Option { + let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len()); + let (host, path) = text[start..].split_once('/')?; + if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) { + return None; + } + if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) { + return parse_server(&path[2..]); + } + let code = path.split(['?', '#', '/']).next().unwrap_or_default(); + let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'); + (!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned())) +} + +/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the +/// host (an IPv6 address without its brackets) and the port, if one is +/// given that is one. +fn split_address(address: &str) -> (&str, Option) { + if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) { + return (host, after.strip_prefix(':').and_then(parse_port)); + } + match address.rsplit_once(':') { + // A port follows the only colon; more colons: an IPv6 address. + Some((host, port)) + if !host.contains(':') + && !port.is_empty() + && port.bytes().all(|b| b.is_ascii_digit()) => + { + (host, parse_port(port)) + } + _ => (address, None), + } +} + +fn parse_port(text: &str) -> Option { + text.parse().ok().filter(|p| *p != 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn server(text: &str) -> ServerLink { + match Link::parse(text) { + Some(Link::Server(link)) => link, + other => panic!("{text}: {other:?}"), + } + } + + fn host(host: &str, port: Option) -> ServerLink { + ServerLink { host: host.into(), port, ..Default::default() } + } + + #[test] + fn every_parameter() { + let link = server( + "ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine", + ); + assert_eq!( + link, + ServerLink { + host: "ts.example.org".into(), + port: Some(9988), + nickname: Some("Nova X".into()), + password: Some("s3cr?t".into()), + channel: Some("Gaming/Raid Night".into()), + // A `+` stays. + channel_password: Some("raid+1".into()), + token: Some("AbC+d".into()), + } + ); + assert_eq!(link.address(), "ts.example.org:9988"); + assert_eq!( + link.to_url(), + "ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd" + ); + assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link))); + // A channel id names the channel, also next to a path. + assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12")); + assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12")); + assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby")); + assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12"); + // Empty values are none. + assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None)); + } + + #[test] + fn teamspeak_scheme_is_the_same() { + let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova"; + assert_eq!( + Link::parse(&format!("teamspeak://{query}")), + Link::parse(&format!("ts3server://{query}")) + ); + // Any case, of the scheme and the keys; the host as written. + let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID="); + assert_eq!( + link, + ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) } + ); + assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988))); + } + + #[test] + fn short_links() { + for text in [ + "https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby", + "https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby", + "HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby", + "tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby", + "http://tmspk.gg/s/ts.example.org:9988?channel=Lobby", + ] { + assert_eq!( + server(text), + ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) }, + "{text}" + ); + } + let invite = |code: &str| Some(Link::Invite(code.into())); + assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x")); + assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x")); + assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x")); + assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x")); + for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="] + { + assert_eq!(Link::parse(text), None, "{text}"); + } + } + + #[test] + fn ipv6() { + let v6 = host("2001:db8::1", Some(9987)); + assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6); + assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6); + assert_eq!(v6.address(), "[2001:db8::1]:9987"); + assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987"); + // Without a port, with or without brackets. + let bare = host("2001:db8::1", None); + assert_eq!(server("ts3server://2001:db8::1"), bare); + assert_eq!(server("ts3server://[2001:db8::1]"), bare); + assert_eq!(bare.address(), "2001:db8::1"); + assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988))); + } + + #[test] + fn escapes() { + let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen"); + assert_eq!(link.channel.as_deref(), Some("Ärger/Café")); + assert_eq!(link.nickname.as_deref(), Some("Jürgen")); + // `%2F` is a `/` in a name. + let link = server("ts3server://h?channel=AC%2FDC/Live"); + assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live")); + assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]); + assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live"); + assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live"); + assert_eq!(split_channel_path("Lobby"), ["Lobby"]); + assert_eq!(channel_path_id("/12"), Some(12)); + assert_eq!(channel_path_id("12"), None); + assert_eq!(channel_path_id("/1a"), None); + } + + #[test] + fn invalid_ports_are_ignored() { + for text in [ + "ts3server://h?port=abc", + "ts3server://h?port=70000", + "ts3server://h?port=0", + "ts3server://h?port=", + "ts3server://h:70000", + ] { + assert_eq!(server(text), host("h", None), "{text}"); + } + // One in the address stays. + assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988))); + } + + #[test] + fn other_links_are_none() { + for text in [ + "", + "http://example.com", + "https://example.com/s/ts.example.org", + "ts3file://a.png?serverUID=x&channel=1", + "ts3server://", + "ts3server://?port=9987", + "ts3server://a b", + "ts.example.org", + "mailto:a@example.org", + ] { + assert_eq!(Link::parse(text), None, "{text:?}"); + } + } + + #[test] + fn round_trip() { + // The invite links of voelin-ui (`vm::servers::invite_link`). + for (address, names, url) in [ + ( + "ts.example.com:9988", + &["Gaming", "Raid Night"][..], + "ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night", + ), + (" ts.example.com ", &[], "ts3server://ts.example.com"), + ( + "[2001:db8::1]:9987", + &["Chill & Co"], + "ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co", + ), + ("2001:db8::1", &[], "ts3server://2001:db8::1"), + ("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"), + ] { + let mut link = ServerLink::new(address); + link.channel = (!names.is_empty()).then(|| join_channel_path(names)); + assert_eq!(link.to_url(), url); + assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}"); + assert_eq!(link.address(), address.trim()); + if let Some(path) = &link.channel { + assert_eq!(split_channel_path(path), names); + } + } + } +} diff --git a/crates/voelin-model/src/percent.rs b/crates/voelin-model/src/percent.rs new file mode 100644 index 0000000..9c3e3e1 --- /dev/null +++ b/crates/voelin-model/src/percent.rs @@ -0,0 +1,54 @@ +//! Percent escapes in links: file links ([`crate::FileRef`]) and server +//! links ([`crate::Link`]). + +/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and +/// passwords keep theirs). +pub(crate) fn 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() +} + +/// Every byte but letters, digits and `-._~` as `%XX`. +pub(crate) fn 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 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escapes() { + assert_eq!(decode("Raid%20Night"), "Raid Night"); + assert_eq!(decode("%C3%84b"), "Äb"); + assert_eq!(decode("a+b"), "a+b"); + // A broken escape stays as it is. + assert_eq!(decode("100%"), "100%"); + assert_eq!(decode("%zz"), "%zz"); + assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84"); + assert_eq!(decode(&encode("a b+c%")), "a b+c%"); + } +} diff --git a/crates/voelin-ui/src/bind/chat.rs b/crates/voelin-ui/src/bind/chat.rs index 925ccfb..0764edc 100644 --- a/crates/voelin-ui/src/bind/chat.rs +++ b/crates/voelin-ui/src/bind/chat.rs @@ -62,7 +62,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.create_topic(key, title.to_string())); }); bridge.on_open_link(|link, masked| { - with_app(|app| app.open_link_text(&link, masked)).unwrap_or_default().into() + with_app(|app| app.open_link_text(&link, masked)); }); bridge.on_quote_text(|author, text| crate::vm::chat::quote(&author, &text).into()); bridge.on_open_member(|id| { diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 2e3211f..bb4f40d 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -624,9 +624,8 @@ impl App { /// A link in a message was clicked (`masked`: its text shows something /// else, [`vm::bbcode::is_masked`]). A page on the web opens in the /// browser, a masked one once the user saw where it goes (Nav.link-open); - /// a TeamSpeak link is copied until Voelin opens them. Returns what to - /// copy ("": nothing). - pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) -> String { + /// a TeamSpeak link in Voelin ([`App::open_link`]). + pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) { match vm::bbcode::classify_link(link) { LinkKind::Web(url) if masked => { if let Some(ui) = self.ui.upgrade() { @@ -635,20 +634,15 @@ impl App { nav.set_link_url(url.into()); nav.set_link_open(true); } - String::new() } LinkKind::Web(url) => { if let Err(e) = self.open_url(&url) { self.set_status(format!("Cannot open the link: {e}")); } - String::new() - } - LinkKind::Server(url) => { - self.copy_note = Some("TeamSpeak links open in Voelin soon; copied".to_owned()); - url } + LinkKind::Server(url) => self.open_link(&url), // A file opens from its card. - LinkKind::File | LinkKind::Refused => String::new(), + LinkKind::File | LinkKind::Refused => {} } } diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 00de768..de9efda 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -34,7 +34,9 @@ //! the "New" divider, scrolled up to; `unread:end` ten messages before, //! at the list's end, under the bar that counts the new messages), //! `link-confirm[:]` (the question before a masked link opens, by -//! default the sample's raid board), `watch` (the first stream; with +//! default the sample's raid board), `link:` (a TeamSpeak link +//! opened: the server dialog filled in from it, or in voice on its +//! server a move into its channel), `watch` (the first stream; with //! sample data the local test pattern in its place), `popout` (the same, //! popped out), //! `tab:` (phone layout); `friends[:]`, @@ -307,6 +309,8 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { let url = if arg.is_empty() { DEMO_RAID_BOARD } else { arg }; with_app(|app| app.open_link_text(url, true)); } + // As a link from the platform comes. + "link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())), "watch" | "popout" => { with_app(|app| { if switches.demo_ui { app.demo_watch() } else { app.watch_first_stream() } diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index 494cdfd..441dc14 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -1,7 +1,8 @@ //! Requests from the platform around the window: on Android a tapped -//! notification or something shared to the app ("Share to Voelin"). They -//! can come from any thread and before the window runs; [`request`] keeps -//! them until the window takes them on its thread. +//! notification or something shared to the app ("Share to Voelin"), and a +//! TeamSpeak link to open. They can come from any thread and before the +//! window runs; [`request`] keeps them until the window takes them on its +//! thread. use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; @@ -21,6 +22,9 @@ pub enum Request { /// should not post into a chat), the files are uploaded to the current /// channel and linked there, as the composer's attach button does. Share { text: Option, files: Vec }, + /// Open a TeamSpeak link (`ts3server://`, `teamspeak://`, `tmspk.gg`): + /// the server dialog filled in from it, or a move in voice. + OpenLink(String), } static PENDING: Mutex> = Mutex::new(Vec::new()); @@ -52,6 +56,9 @@ pub(crate) fn take() { nav.invoke_show(Page::Server); with_app(|app| app.share(&nav, text, files)); } + Request::OpenLink(url) => { + with_app(|app| app.open_link(&url)); + } } } } diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index 0e8f5b8..11a6dd6 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -13,6 +13,7 @@ mod hotkey; mod identities; mod images; mod inbox; +mod links; mod members; mod messages; #[cfg(not(target_os = "android"))] diff --git a/crates/voelin-ui/src/links.rs b/crates/voelin-ui/src/links.rs new file mode 100644 index 0000000..2445e78 --- /dev/null +++ b/crates/voelin-ui/src/links.rs @@ -0,0 +1,70 @@ +//! TeamSpeak links opened in the app (`ts3server://`, `teamspeak://` and +//! `tmspk.gg`), from a message or the platform. + +use slint::ComponentHandle; +use voelin_core::VoiceState; +use voelin_model::{Link, ServerLink}; + +use crate::app::{App, Nav}; +use crate::vm; + +impl App { + /// Open a TeamSpeak link. In voice on its server: show it and move into + /// the link's channel (a locked one asks for its password if the link + /// has none or a wrong one). Otherwise the server dialog, filled in from + /// the link (the saved server's when there is one): nothing connects + /// before its Connect. + pub(crate) fn open_link(&mut self, url: &str) { + let link = match Link::parse(url) { + Some(Link::Server(link)) => link, + Some(Link::Invite(_)) => { + self.set_status( + "TeamSpeak invite codes (tmspk.gg/…) can't be opened yet; ask for the server address", + ); + return; + } + None => { + self.set_status("Not a TeamSpeak server link"); + return; + } + }; + let in_voice = |id: i64| { + self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) + }; + match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) { + Some((id, true)) => self.move_by_link(id, &link), + saved => self.open_link_form(saved.map(|(id, _)| id), &link), + } + } + + /// In voice on the link's server: show it, and move into its channel. + fn move_by_link(&mut self, session: i64, link: &ServerLink) { + self.show_server(session); + let Some(path) = &link.channel else { return }; + let Some(view) = self.sessions.get_mut(&session) else { return }; + let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else { + let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default(); + self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}")); + return; + }; + if view.state.own_channel == Some(channel) { + return; + } + // As if typed into the password dialog: a wrong one asks again. + if let Some(password) = &link.channel_password { + view.channel_passwords.insert(channel, password.clone()); + } + self.join_channel(session, channel); + } + + /// The server dialog, filled in from the link over the saved server's + /// form, or a new server's. + fn open_link_form(&mut self, saved: Option, link: &ServerLink) { + let form = self.bookmark_form(saved.unwrap_or(-1)); + let form = vm::servers::link_form(link, form, &self.default_nickname()); + let Some(ui) = self.ui.upgrade() else { return }; + let nav = ui.global::