"}, as {@link Bookmark#channel}; empty for the default channel. */
+ public final String channel;
+ public final String channelPassword;
+ /** A privilege key to use once connected; empty for none. */
+ public final String token;
+ /** A name to bookmark the server under, or empty when the link does not ask for a bookmark. */
+ public final String bookmarkLabel;
+
+ private ServerLink(String address, int port, String nickname, String password, String channel,
+ String channelPassword, String token, String bookmarkLabel) {
+ this.address = address;
+ this.port = port;
+ this.nickname = nickname;
+ this.password = password;
+ this.channel = channel;
+ this.channelPassword = channelPassword;
+ this.token = token;
+ this.bookmarkLabel = bookmarkLabel;
+ }
+
+ /** Where a bookmark leads, as a link without a privilege key would. */
+ public static ServerLink of(Bookmark b) {
+ return new ServerLink(b.address.trim(), b.port, orEmpty(b.nickname), orEmpty(b.password), orEmpty(b.channel),
+ orEmpty(b.channelPassword), "", "");
+ }
+
+ private static String orEmpty(String s) {
+ return s == null ? "" : s;
+ }
+
+ public static boolean isLink(String href) {
+ return href != null && href.regionMatches(true, 0, PREFIX, 0, PREFIX.length());
+ }
+
+ /** Parses a link, or returns {@code null} if it is not one or names no server. */
+ public static ServerLink parse(String href) {
+ if (!isLink(href)) return null;
+ String rest = href.substring(PREFIX.length()).trim();
+ int query = rest.indexOf('?');
+ String authority = query < 0 ? rest : rest.substring(0, query);
+ String params = query < 0 ? "" : rest.substring(query + 1);
+ int slash = authority.indexOf('/');
+ if (slash >= 0) authority = authority.substring(0, slash);
+
+ String host = authority;
+ int port = DEFAULT_PORT;
+ if (authority.startsWith("[")) {
+ int close = authority.indexOf(']');
+ if (close < 0) return null;
+ host = authority.substring(1, close);
+ port = portAfter(authority.substring(close + 1), port);
+ } else if (authority.indexOf(':') == authority.lastIndexOf(':') && authority.indexOf(':') >= 0) {
+ host = authority.substring(0, authority.indexOf(':'));
+ port = portAfter(authority.substring(authority.indexOf(':')), port);
+ }
+ host = decode(host).trim();
+ if (host.isEmpty()) return null;
+
+ String nickname = "", password = "", channel = "", channelId = "", channelPassword = "", token = "", label = "";
+ for (String pair : params.split("&")) {
+ int eq = pair.indexOf('=');
+ String key = (eq < 0 ? pair : pair.substring(0, eq)).toLowerCase(Locale.ROOT);
+ String value = eq < 0 ? "" : decode(pair.substring(eq + 1));
+ switch (key) {
+ case "port" -> port = parsePort(value, port);
+ case "nickname" -> nickname = value.trim();
+ case "password" -> password = value;
+ case "channel" -> channel = value.trim();
+ case "cid" -> channelId = value.trim();
+ case "channelpassword" -> channelPassword = value;
+ case "token" -> token = value.trim();
+ case "addbookmark" -> label = value.trim();
+ default -> {
+ }
+ }
+ }
+ // A channel id is exact, where a path may have been renamed since the link was made.
+ if (isChannelId(channelId)) channel = "/" + channelId;
+ return new ServerLink(host, port, nickname, password, channel, channelPassword, token, label);
+ }
+
+ /** Whether this link leads to the server at {@code address}:{@code port}. */
+ public boolean pointsAt(String address, int port) {
+ return this.port == port && address != null && this.address.equalsIgnoreCase(address.trim());
+ }
+
+ /** A bookmark of the server the link leads to, under the name it asks for, else its address. */
+ public Bookmark toBookmark() {
+ Bookmark b = new Bookmark(bookmarkLabel.isEmpty() ? address : bookmarkLabel, address, port, nickname, password);
+ b.channel = channel;
+ b.channelPassword = channelPassword;
+ return b;
+ }
+
+ /** A positive number; 0 names no channel. */
+ private static boolean isChannelId(String s) {
+ return !s.isEmpty() && s.chars().allMatch(Character::isDigit) && s.chars().anyMatch(c -> c != '0');
+ }
+
+ private static int portAfter(String colonPort, int fallback) {
+ return colonPort.startsWith(":") ? parsePort(colonPort.substring(1), fallback) : fallback;
+ }
+
+ private static int parsePort(String value, int fallback) {
+ try {
+ int port = Integer.parseInt(value.trim());
+ return port > 0 && port <= 65535 ? port : fallback;
+ } catch (NumberFormatException e) {
+ return fallback;
+ }
+ }
+
+ /** Percent-decodes; a '+' stays one, as TeamSpeak reads its links. */
+ private static String decode(String s) {
+ try {
+ return URLDecoder.decode(s.replace("+", "%2B"), "UTF-8");
+ } catch (UnsupportedEncodingException | IllegalArgumentException e) {
+ return s;
+ }
+ }
+}
diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java
index 893d17b..d3ea848 100644
--- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java
+++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java
@@ -82,6 +82,8 @@ public final class ServerSession {
private volatile String lastChannelPath = "";
/** The server icon last reported through {@link Listener#onServerIconChanged}; -1 for none yet. */
private volatile long serverIconId = -1;
+ /** The link whose privilege key to use once connected to its server; null for none. */
+ private volatile ServerLink tokenLink;
private record Target(String address, int port, String nickname, String password, String channelPassword) {
}
@@ -188,6 +190,29 @@ public final class ServerSession {
}, "identity-resolve").start();
}
+ /** Whether we are on the server a {@code ts3server://} link leads to. */
+ public boolean isOn(ServerLink link) {
+ return conn.isConnected() && link.pointsAt(address(), port());
+ }
+
+ /** Does what a link to the server we are on asks: goes to its channel, uses its privilege key. */
+ public void follow(ServerLink link) {
+ if (!isOn(link)) return;
+ ChannelNode target = link.channel.isEmpty() ? null : conn.getModel().findChannelByPath(link.channel);
+ ChannelNode current = currentChannel();
+ if (target != null && (current == null || target.id != current.id)) {
+ conn.joinChannel(target.id, link.channelPassword.isEmpty() ? null : link.channelPassword);
+ }
+ tokenLink = link.token.isEmpty() ? null : link;
+ useConnectToken();
+ }
+
+ /** Connects where a {@code ts3server://} link leads, using its privilege key once on. */
+ public void open(ServerLink link, String identityId) {
+ tokenLink = link.token.isEmpty() ? null : link;
+ switchTo(link.address, link.port, link.nickname, link.password, identityId, link.channel, link.channelPassword);
+ }
+
private String nicknameFor(String serverNickname, IdentityEntry identity) {
if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim();
if (!identity.getNickname().isBlank()) return identity.getNickname();
@@ -627,6 +652,15 @@ public final class ServerSession {
setStatus(message);
}
+ private void useConnectToken() {
+ ServerLink link = tokenLink;
+ tokenLink = null;
+ Target target = lastTarget;
+ if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return;
+ conn.usePrivilegeKey(link.token, error -> listener.onSystemMessage(error == null
+ ? "Privilege key used." : "Could not use the privilege key: " + error));
+ }
+
private void checkServerIcon() {
if (!conn.isConnected()) return;
long id = conn.getModel().serverIconId();
@@ -652,6 +686,7 @@ public final class ServerSession {
listener.onSystemMessage("Connected.");
listener.onSessionChanged();
checkServerIcon();
+ useConnectToken();
}
@Override
diff --git a/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java b/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java
new file mode 100644
index 0000000..0868cdd
--- /dev/null
+++ b/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java
@@ -0,0 +1,62 @@
+package com.ts3client.session;
+
+import com.ts3client.config.Bookmark;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+class ServerLinkTest {
+
+ @Test
+ void readsEveryParameter() {
+ ServerLink link = ServerLink.parse("ts3server://ts.example.com?port=9988&nickname=Bob%20B"
+ + "&password=s+cret&channel=Lobby/Games&channelpassword=pw&token=abc&addbookmark=Example");
+ assertEquals("ts.example.com", link.address);
+ assertEquals(9988, link.port);
+ assertEquals("Bob B", link.nickname);
+ assertEquals("s+cret", link.password);
+ assertEquals("Lobby/Games", link.channel);
+ assertEquals("pw", link.channelPassword);
+ assertEquals("abc", link.token);
+ assertEquals("Example", link.bookmarkLabel);
+ }
+
+ @Test
+ void aBareHostTakesTheDefaults() {
+ ServerLink link = ServerLink.parse("TS3SERVER://ts.example.com/");
+ assertEquals("ts.example.com", link.address);
+ assertEquals(9987, link.port);
+ assertEquals("", link.channel);
+ assertEquals("", link.token);
+ }
+
+ @Test
+ void readsThePortFromTheAuthority() {
+ assertEquals(1234, ServerLink.parse("ts3server://1.2.3.4:1234").port);
+ ServerLink v6 = ServerLink.parse("ts3server://[2001:db8::1]:5000?nickname=x");
+ assertEquals("2001:db8::1", v6.address);
+ assertEquals(5000, v6.port);
+ }
+
+ @Test
+ void aChannelIdWinsOverThePath() {
+ assertEquals("/42", ServerLink.parse("ts3server://h?channel=Old%20name&cid=42").channel);
+ assertEquals("Lobby", ServerLink.parse("ts3server://h?cid=0&channel=Lobby").channel);
+ }
+
+ @Test
+ void namesNoServerWithoutAHost() {
+ assertNull(ServerLink.parse("ts3server://?port=1"));
+ assertNull(ServerLink.parse("https://example.com"));
+ }
+
+ @Test
+ void bookmarksUnderTheAskedName() {
+ Bookmark b = ServerLink.parse("ts3server://h?addbookmark=Mine&cid=3&channelpassword=x").toBookmark();
+ assertEquals("Mine", b.label);
+ assertEquals("/3", b.channel);
+ assertEquals("x", b.channelPassword);
+ assertEquals("h", ServerLink.parse("ts3server://h").toBookmark().label);
+ }
+}
diff --git a/ts3-client/swing/src/main/java/com/ts3client/Main.java b/ts3-client/swing/src/main/java/com/ts3client/Main.java
index 174b00a..0cdabfb 100644
--- a/ts3-client/swing/src/main/java/com/ts3client/Main.java
+++ b/ts3-client/swing/src/main/java/com/ts3client/Main.java
@@ -1,14 +1,17 @@
package com.ts3client;
import com.ts3client.config.Settings;
+import com.ts3client.session.ServerLink;
import com.ts3client.ui.DesktopEntry;
import com.ts3client.ui.DisplayScale;
import com.ts3client.ui.IconTheme;
+import com.ts3client.ui.InstanceChannel;
import com.ts3client.ui.LookAndFeelManager;
import com.ts3client.ui.MainFrame;
import com.ts3client.ui.WindowClass;
import javax.swing.SwingUtilities;
+import java.util.Arrays;
/**
* Application entry point. Loads settings, installs the look-and-feel and shows the
@@ -24,6 +27,10 @@ public final class Main {
} catch (Throwable ignored) {
}
+ // A link a browser opened goes to the instance already running, if there is one.
+ final String link = Arrays.stream(args).filter(ServerLink::isLink).findFirst().orElse(null);
+ if (link != null && InstanceChannel.send(link)) return;
+
final Settings settings = Settings.load();
DisplayScale.configure(settings.uiScale);
WindowClass.apply();
@@ -32,7 +39,10 @@ public final class Main {
LookAndFeelManager.install(settings.appearance);
IconTheme.get().reload(settings);
DesktopEntry.install();
- new MainFrame(settings).setVisible(true);
+ MainFrame frame = new MainFrame(settings);
+ frame.setVisible(true);
+ InstanceChannel.listen(href -> SwingUtilities.invokeLater(() -> frame.openLink(href)));
+ if (link != null) frame.openLink(link);
});
}
}
diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java
index 3b0781b..79d6f6c 100644
--- a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java
+++ b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java
@@ -1,6 +1,7 @@
package com.ts3client.ui;
import com.ts3client.Main;
+import com.ts3client.session.ServerLink;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
@@ -22,6 +23,8 @@ import java.util.Locale;
* claims the class, Plasma falls back to the process's command line — {@code java} —
* and files the window under whatever launcher runs Java, with its name and icon.
*
+ * A launcher run from a jar also takes {@code ts3server://} links.
+ *
*
The files are only rewritten when their content changes, e.g. after the jar moved.
* {@code -Dts3j.desktopEntry=false} turns this off.
*/
@@ -42,8 +45,11 @@ public final class DesktopEntry {
Path data = dataHome();
Path icon = icon();
writeIfChanged(icon, iconPng());
- writeIfChanged(data.resolve("applications").resolve(WindowClass.NAME + ".desktop"),
- entry(icon).getBytes(StandardCharsets.UTF_8));
+ Path applications = data.resolve("applications");
+ if (writeIfChanged(applications.resolve(WindowClass.NAME + ".desktop"),
+ entry(icon).getBytes(StandardCharsets.UTF_8))) {
+ updateSchemeHandlers(applications);
+ }
} catch (IOException | RuntimeException e) {
System.err.println("Cannot install the desktop entry: " + e);
}
@@ -69,13 +75,14 @@ public final class DesktopEntry {
.append("GenericName=TeamSpeak 3 Client\n")
.append("Comment=Voice chat on TeamSpeak 3 servers\n")
.append("Icon=").append(icon).append('\n')
- .append("Exec=").append(exec == null ? "java" : exec).append('\n')
+ .append("Exec=").append(exec == null ? "java" : exec + " %u").append('\n')
.append("StartupWMClass=").append(WindowClass.NAME).append('\n')
.append("Categories=Network;InstantMessaging;AudioVideo;\n")
.append("Terminal=false\n");
// Run from classes (an IDE, mvn exec:java) there is nothing sensible to launch;
// the entry is still needed to name the window, but stays out of the menu.
if (exec == null) s.append("NoDisplay=true\n");
+ else s.append("MimeType=x-scheme-handler/").append(ServerLink.SCHEME).append(";\n");
return s.toString();
}
@@ -108,12 +115,26 @@ public final class DesktopEntry {
return out.toByteArray();
}
- private static void writeIfChanged(Path file, byte[] content) throws IOException {
- if (Files.exists(file) && Arrays.equals(Files.readAllBytes(file), content)) return;
+ /**
+ * Browsers find the handler of a {@code ts3server://} link in the folder's MIME cache, which
+ * only this tool rebuilds; without it the entry still names the window.
+ */
+ private static void updateSchemeHandlers(Path applications) {
+ try {
+ new ProcessBuilder("update-desktop-database", applications.toString())
+ .redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start();
+ } catch (IOException ignored) {
+ }
+ }
+
+ /** @return whether the file changed */
+ private static boolean writeIfChanged(Path file, byte[] content) throws IOException {
+ if (Files.exists(file) && Arrays.equals(Files.readAllBytes(file), content)) return false;
Files.createDirectories(file.getParent());
Path tmp = file.resolveSibling(file.getFileName() + ".tmp");
Files.write(tmp, content);
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
+ return true;
}
}
diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java
new file mode 100644
index 0000000..580eaa8
--- /dev/null
+++ b/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java
@@ -0,0 +1,81 @@
+package com.ts3client.ui;
+
+import com.ts3client.config.AppDirs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.StandardProtocolFamily;
+import java.net.UnixDomainSocketAddress;
+import java.nio.channels.Channels;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.function.Consumer;
+
+/**
+ * Lets a second launch of the client hand what it was started with (a {@code ts3server://}
+ * link a browser opened) to the instance already running on the same profile, over a Unix
+ * domain socket.
+ */
+public final class InstanceChannel {
+
+ private static final int MAX_MESSAGE = 8192;
+
+ private InstanceChannel() {
+ }
+
+ /**
+ * In the user's private runtime directory where there is one, as a socket path may not be
+ * much over 100 bytes and a profile's can be longer; named after the profile, so each
+ * profile has an instance of its own.
+ */
+ private static Path socketPath() {
+ String runtime = System.getenv("XDG_RUNTIME_DIR");
+ if (runtime == null || runtime.isBlank()) return AppDirs.file("instance.sock").toPath();
+ String profile = AppDirs.profile().getAbsolutePath();
+ return Path.of(runtime, "ts3j-" + Integer.toHexString(profile.hashCode()) + ".sock");
+ }
+
+ /** Sends {@code message} to the running instance; false when there is none to take it. */
+ public static boolean send(String message) {
+ try (SocketChannel channel = SocketChannel.open(UnixDomainSocketAddress.of(socketPath()));
+ OutputStream out = Channels.newOutputStream(channel)) {
+ out.write(message.getBytes(StandardCharsets.UTF_8));
+ return true;
+ } catch (IOException | UnsupportedOperationException e) {
+ return false;
+ }
+ }
+
+ /** Takes the messages later launches send, each on a thread of its own; quietly does nothing where it cannot. */
+ public static void listen(Consumer onMessage) {
+ Path path = socketPath();
+ ServerSocketChannel server;
+ try {
+ AppDirs.createProfile();
+ // Left behind by an instance that did not exit cleanly; a live one answered send() already.
+ Files.deleteIfExists(path);
+ server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
+ server.bind(UnixDomainSocketAddress.of(path));
+ path.toFile().deleteOnExit();
+ } catch (IOException | UnsupportedOperationException e) {
+ System.err.println("Cannot take links from other launches: " + e);
+ return;
+ }
+ Thread accept = new Thread(() -> {
+ while (server.isOpen()) {
+ try (SocketChannel client = server.accept(); InputStream in = Channels.newInputStream(client)) {
+ String message = new String(in.readNBytes(MAX_MESSAGE), StandardCharsets.UTF_8).trim();
+ if (!message.isEmpty()) onMessage.accept(message);
+ } catch (IOException e) {
+ if (!server.isOpen()) return;
+ }
+ }
+ }, "instance-channel");
+ accept.setDaemon(true);
+ accept.start();
+ }
+}
diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java
index ff30f9c..ff5f514 100644
--- a/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java
+++ b/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java
@@ -1,17 +1,36 @@
package com.ts3client.ui;
+import com.ts3client.session.ServerLink;
+
import javax.swing.JOptionPane;
import java.awt.Component;
import java.awt.Desktop;
import java.net.URI;
+import java.util.function.Consumer;
-/** Opens http(s) links from chat messages and descriptions in the system browser. */
+/**
+ * Opens http(s) links from chat messages and descriptions in the system browser, and
+ * {@code ts3server://} links in the client itself.
+ */
final class Links {
+ private static volatile Consumer serverLinks;
+
private Links() {
}
+ /** Where {@code ts3server://} links go. */
+ static void setServerLinkHandler(Consumer handler) {
+ serverLinks = handler;
+ }
+
static void open(String href, Component parent) {
+ ServerLink link = ServerLink.parse(href);
+ Consumer handler = serverLinks;
+ if (link != null && handler != null) {
+ handler.accept(link);
+ return;
+ }
try {
URI uri = new URI(href);
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase();
diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java
index df610c5..2d0e03a 100644
--- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java
+++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java
@@ -8,6 +8,7 @@ import com.ts3client.config.AwayMessages;
import com.ts3client.config.BanReasonPresets;
import com.ts3client.config.Bookmark;
import com.ts3client.config.Bookmarks;
+import com.ts3client.session.ServerLink;
import com.ts3client.config.IdentityStore;
import com.ts3client.config.Settings;
import com.ts3client.myts.ChatAttachments;
@@ -186,6 +187,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
first.chat().appendSystem("Welcome to the TS3J Swing client.");
first.chat().appendSystem("Use Connections → Connect to join a server.");
+ Links.setServerLinkHandler(this::openServerLink);
+
statusTimer = new javax.swing.Timer(3000, e -> updateConnectionStatus());
statusTimer.start();
setSize(UIScale.scale(new Dimension(880, 560)));
@@ -815,6 +818,33 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
tab.session().switchTo(address, port, nickname, password, identityId, channel, channelPassword);
}
+ /** Opens a {@code ts3server://} link handed over by the system or a later launch. */
+ public void openLink(String href) {
+ ServerLink link = ServerLink.parse(href);
+ if (link == null) return;
+ bringToFront();
+ openServerLink(link);
+ }
+
+ /** Goes where a link leads: on a server we are on already, to its channel; else connects there. */
+ private void openServerLink(ServerLink link) {
+ if (!link.bookmarkLabel.isEmpty()) {
+ bookmarks.add(link.toBookmark());
+ bookmarks.save();
+ menuBar.rebuildBookmarks();
+ }
+ for (ServerTab tab : tabs) {
+ if (tab.session().isOn(link)) {
+ selectTab(tab);
+ tab.session().follow(link);
+ return;
+ }
+ }
+ ServerTab tab = tabForNewConnection();
+ if (sessions.microphoneOwner() == null) sessions.giveMicrophoneTo(tab.session());
+ tab.session().open(link, "");
+ }
+
/** Connects on the current tab, leaving whatever server it is on. */
private void connectToBookmark(Bookmark b) {
startConnection(b.address, b.port, b.nickname == null ? "" : b.nickname, b.password, b.identityId, b.channel, b.channelPassword, true);