ui: TeamSpeak links open the server dialog, or move you in voice

Links to ts3server://, teamspeak:// and tmspk.gg in chat were only
copied. voelin_model::Link reads them, and invite_link now writes
through ServerLink::to_url, so a copied invite reads back the same (a
'/' in a channel's name stays %2F in the link, \/ in the path).
App::open_link (links.rs) finds the saved server with that address
(vm::servers::same_address; of several, the one in voice, else the one
shown: link_server). In voice on it, it moves into the link's
channel (channel_by_path) through join_channel, so a locked channel
asks for its password when the link's is missing or wrong. Otherwise
the server dialog opens filled in by link_form, over the saved
server's form when there is one: its nickname stays. Nothing connects
before Connect. Invite codes need a TeamSpeak service; a toast says
so. VOELIN_OPEN=link:<url> goes through inbox::Request::OpenLink,
where the platform's links will come in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
This commit is contained in:
Claude committed 2026-10-07 17:50:04 +00:00
1 parent 432c4f1448
commit 6270fa521c
15 files changed
+843 -96

No files matched your search

+7 -39
View File
@@ -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<FileRef> {
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)
+3
View File
@@ -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,
+420
View File
@@ -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/<code>`,
/// `teamspeak://invite=<code>`): 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<u16>,
pub nickname: Option<String>,
/// The server's password.
pub password: Option<String>,
/// The channel to join: its names from the top, separated by `/` (a `/`
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key: it puts its user in a server or channel group.
pub token: Option<String>,
}
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://<host>?<query>` 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/<host>?<query>` (also `/s=<host>`), and the
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
/// for anything else.
pub fn parse(text: &str) -> Option<Link> {
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://<host>?port=…`,
/// then what is set of nickname, password, channel (or `cid` for
/// `/<id>`), 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<String>| {
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<String> =
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
format!("channel={}", names.join("/"))
}
}
});
let query: Vec<String> = [
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<String> {
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<str>]) -> String {
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
}
/// The channel id of a path `/<id>` (what `cid=` gives).
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
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://`: `<host>[:port][/]?<query>`, or
/// `invite=<code>`.
fn parse_server(rest: &str) -> Option<Link> {
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<String> = raw.split('/').map(percent::decode).collect();
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
}
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().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/<host>?…` (or `/s=`), with or without `https://`, goes where
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
/// invite code.
fn parse_short(text: &str, lower: &str) -> Option<Link> {
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<u16>) {
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<u16> {
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<u16>) -> 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);
}
}
}
}
+54
View File
@@ -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%");
}
}
+1 -1
View File
@@ -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| {
+4 -10
View File
@@ -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 => {}
}
}
+5 -1
View File
@@ -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[:<url>]` (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:<url>` (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:<home|servers|chat|activity|you>` (phone layout); `friends[:<uid>]`,
@@ -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() }
+10 -3
View File
@@ -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<String>, files: Vec<PathBuf> },
/// 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<Vec<Request>> = 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));
}
}
}
}
+1
View File
@@ -13,6 +13,7 @@ mod hotkey;
mod identities;
mod images;
mod inbox;
mod links;
mod members;
mod messages;
#[cfg(not(target_os = "android"))]
+70
View File
@@ -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<i64>, 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::<Nav>();
nav.set_bookmark_form(form);
nav.set_bookmark_open(true);
}
}
+221 -34
View File
@@ -2,7 +2,7 @@
use slint::SharedString;
use voelin_core::{ObserveState, SessionState, VoiceState};
use voelin_model::{ChannelId, ChannelInfo};
use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink};
use voelin_store::Bookmark;
use crate::app::{BookmarkForm, ServerItem};
@@ -107,43 +107,88 @@ pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option<Conne
/// the top) on the server at `address` (`host`, `host:port` or
/// `[v6]:port`), as TeamSpeak clients open them.
pub fn invite_link(address: &str, path: &[&str]) -> String {
fn encode(text: &str) -> String {
text.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
char::from(b).to_string()
}
_ => format!("%{b:02X}"),
})
.collect()
}
let address = address.trim();
// A port follows the last colon, unless that colon is inside an IPv6
// address without brackets.
let (host, port) = match address.rsplit_once(':') {
Some((host, port))
if !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit())
&& (!host.contains(':') || host.ends_with(']')) =>
{
(host, Some(port))
}
_ => (address, None),
let mut link = ServerLink::new(address);
link.channel = (!path.is_empty()).then(|| voelin_model::join_channel_path(path));
link.to_url()
}
/// TeamSpeak's voice port, of an address without one.
const DEFAULT_PORT: u16 = 9987;
/// Whether two addresses name the same server: the host in any case, an
/// IPv6 address with or without its brackets, no port as 9987 (a port a
/// DNS record gives is not looked up).
pub fn same_address(a: &str, b: &str) -> bool {
let key = |address: &str| {
let link = ServerLink::new(address);
(link.host.trim_end_matches('.').to_lowercase(), link.port.unwrap_or(DEFAULT_PORT))
};
let mut link = format!("ts3server://{host}");
let mut query = Vec::new();
if let Some(port) = port {
query.push(format!("port={port}"));
let a = key(a);
!a.0.is_empty() && a == key(b)
}
/// The saved server a link to `address` opens, and whether it has voice
/// (`in_voice`): of those at that address ([`same_address`]; two can be,
/// with other identities), the one in voice, else the one shown
/// (`current`), else the first.
pub fn link_server(
bookmarks: &[Bookmark],
address: &str,
current: Option<i64>,
in_voice: impl Fn(i64) -> bool,
) -> Option<(i64, bool)> {
let saved: Vec<i64> =
bookmarks.iter().filter(|b| same_address(&b.address, address)).map(|b| b.id).collect();
if let Some(id) = saved.iter().copied().find(|id| in_voice(*id)) {
return Some((id, true));
}
if !path.is_empty() {
let names: Vec<String> = path.iter().map(|n| encode(n)).collect();
query.push(format!("channel={}", names.join("/")));
let shown = saved.iter().copied().find(|id| Some(*id) == current);
shown.or_else(|| saved.first().copied()).map(|id| (id, false))
}
/// The channel a link's path names (`/<id>`, or names from the top as the
/// server has them, [`voelin_model::split_channel_path`]). Of siblings with
/// the same name, the first in the tree's order that has the rest of the
/// path.
pub fn channel_by_path(presence: &Presence, path: &str) -> Option<ChannelId> {
fn below(presence: &Presence, parent: ChannelId, names: &[String]) -> Option<ChannelId> {
let (name, rest) = names.split_first()?;
let siblings = presence.channels.values().filter(|c| c.parent == parent).collect();
voelin_model::order_siblings(siblings)
.into_iter()
.filter(|c| c.name == *name)
.find_map(|c| if rest.is_empty() { Some(c.id) } else { below(presence, c.id, rest) })
}
if !query.is_empty() {
link.push('?');
link.push_str(&query.join("&"));
match voelin_model::channel_path_id(path) {
Some(id) => presence.channels.contains_key(&id).then_some(id),
None => below(presence, 0, &voelin_model::split_channel_path(path)),
}
link
}
/// The server dialog's form for a link, over `form`: a saved server's
/// keeps its address, name and nickname (a link never changes it), and its
/// stored password unless the link has one; a new server's takes the
/// link's address, nickname (else `default_nickname`) and password. The
/// link's channel, its password and privilege key come along, for Connect.
pub fn link_form(
link: &ServerLink,
mut form: BookmarkForm,
default_nickname: &str,
) -> BookmarkForm {
let text = |value: &Option<String>| SharedString::from(value.as_deref().unwrap_or_default());
if form.id < 0 {
form.address = link.address().into();
}
if form.id < 0 || form.nickname.is_empty() {
form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into();
}
if let Some(password) = &link.password {
form.server_password = password.into();
}
form.channel = text(&link.channel);
form.channel_password = text(&link.channel_password);
form.token = text(&link.token);
form
}
/// What joining a channel takes ([`join_password`]).
@@ -311,6 +356,148 @@ mod tests {
// A bare IPv6 address has no port.
assert_eq!(invite_link("2001:db8::1", &[]), "ts3server://2001:db8::1");
assert_eq!(invite_link("h:x", &["Ä/b"]), "ts3server://h:x?channel=%C3%84%2Fb");
// Read back, they name the same server and channel.
let Some(voelin_model::Link::Server(link)) =
voelin_model::Link::parse(&invite_link("[2001:db8::1]:9987", &["Games", "Ä/b"]))
else {
panic!("not a server link");
};
assert!(same_address(&link.address(), "[2001:db8::1]:9987"));
assert_eq!(voelin_model::split_channel_path(&link.channel.unwrap()), ["Games", "Ä/b"]);
}
#[test]
fn same_addresses() {
for (a, b) in [
("ts.example.org", "TS.Example.org"),
(" ts.example.org ", "ts.example.org:9987"),
("ts.example.org.", "ts.example.org"),
("[2001:db8::1]:9987", "2001:db8::1"),
("[2001:db8::1]", "[2001:DB8::1]:9987"),
("127.0.0.1:9988", "127.0.0.1:9988"),
] {
assert!(same_address(a, b), "{a} = {b}");
}
for (a, b) in [
("ts.example.org", "ts.example.org:9988"),
("ts.example.org", "example.org"),
("[2001:db8::1]:9988", "2001:db8::1"),
("", ""),
] {
assert!(!same_address(a, b), "{a} != {b}");
}
}
#[test]
fn servers_of_links() {
let saved =
|id, address: &str| Bookmark { id, address: address.into(), ..Default::default() };
let bookmarks = [
saved(1, "other.example"),
saved(2, "ts.example.org"),
saved(3, "TS.example.org:9987"),
saved(4, "ts.example.org:9988"),
];
let voice = |ids: &'static [i64]| move |id| ids.contains(&id);
// Not in voice: the one shown, else the first.
assert_eq!(link_server(&bookmarks, "ts.example.org", None, voice(&[])), Some((2, false)));
assert_eq!(
link_server(&bookmarks, "ts.example.org", Some(3), voice(&[])),
Some((3, false))
);
// In voice on one of them, also when another is shown.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9987", Some(2), voice(&[1, 3])),
Some((3, true))
);
// Voice on the server at another port does not count.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9988", None, voice(&[2])),
Some((4, false))
);
assert_eq!(link_server(&bookmarks, "new.example", Some(1), voice(&[1])), None);
}
#[test]
fn channels_by_path() {
let channel = |id, parent, order, name: &str| ChannelInfo {
id,
parent,
order,
name: name.into(),
..Default::default()
};
let mut p = Presence::default();
for c in [
channel(1, 0, 0, "Lobby"),
// Two of the same name, the first in the tree with the higher id.
channel(4, 0, 1, "Games"),
channel(3, 4, 0, "Chess"),
channel(7, 0, 4, "AC/DC"),
channel(2, 0, 7, "Games"),
channel(5, 2, 0, "Go"),
channel(6, 2, 5, "Chess"),
] {
p.channels.insert(c.id, c);
}
assert_eq!(channel_by_path(&p, "Lobby"), Some(1), "at the top");
assert_eq!(channel_by_path(&p, "Games/Chess"), Some(3), "nested");
// The same name: the first, unless only another has the rest.
assert_eq!(channel_by_path(&p, "Games"), Some(4));
assert_eq!(channel_by_path(&p, "Games/Go"), Some(5));
assert_eq!(channel_by_path(&p, "AC\\/DC"), Some(7), "a / in a name");
assert_eq!(channel_by_path(&p, "/6"), Some(6), "by id");
for missing in ["Chess", "Games/Poker", "Lobby/Games", "/99", "", "lobby"] {
assert_eq!(channel_by_path(&p, missing), None, "{missing}");
}
}
#[test]
fn forms_from_links() {
let link = ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Link".into()),
password: Some("pw".into()),
channel: Some("Gaming/Raid Night".into()),
channel_password: Some("raid".into()),
token: Some("key".into()),
};
let bare = ServerLink::new("ts.example.org");
// A new server: the link's address, nickname and password.
let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() };
let f = link_form(&link, new.clone(), "Me");
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (-1, "", "ts.example.org:9988"));
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw"));
assert_eq!(
(f.channel.as_str(), f.channel_password.as_str(), f.token.as_str()),
("Gaming/Raid Night", "raid", "key")
);
let f = link_form(&bare, new, "Me");
assert_eq!((f.address.as_str(), f.nickname.as_str()), ("ts.example.org", "Me"));
assert_eq!(
(f.server_password.as_str(), f.channel.as_str(), f.token.as_str()),
("", "", "")
);
// A saved server keeps its address, name, nickname and password...
let saved = BookmarkForm {
id: 3,
name: "Nightfall".into(),
address: "TS.example.org:9988".into(),
nickname: "Nova".into(),
server_password: "stored".into(),
..Default::default()
};
let f = link_form(&bare, saved.clone(), "Me");
assert_eq!(
(f.id, f.name.as_str(), f.address.as_str()),
(3, "Nightfall", "TS.example.org:9988")
);
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored"));
// ...the link's password in place of the stored one.
let f = link_form(&link, saved, "Me");
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key"));
}
#[test]
+2 -2
View File
@@ -1135,8 +1135,8 @@ export global Bridge {
callback invite() -> string;
// A link in a message was clicked (`TextRun.link` and `masked`): Rust
// opens a page on the web (a masked one after asking: Nav.link-open),
// or gives back what the caller copies (a TeamSpeak link, for now).
callback open-link(string, bool) -> string;
// or a TeamSpeak link in the app (the server dialog, or a move).
callback open-link(string, bool);
// A message's text (`ChatLine.text`) by its author as a quote for the
// composer: "> Author: line" and "> line" for the next ones.
callback quote-text(string, string) -> string;
+2 -2
View File
@@ -336,9 +336,9 @@ export global Nav {
}
}
// A link in a message: Rust opens it, asks first, or has it copied.
// A link in a message: Rust opens it, or asks first.
public function open-link(link: string, masked: bool) {
copy(Bridge.open-link(link, masked));
Bridge.open-link(link, masked);
}
// Quote a message at the start of the composer, then write after it.