Open ts3server:// links on both apps

A link connects with its nickname, passwords, channel (path or cid) and
privilege key, the key used once on; addbookmark saves it as a bookmark.
A link to a server we are on already goes to its channel instead.

Android takes the links from browsers and other apps through an intent
filter, and from chat. The desktop opens them from chat and descriptions,
and its launcher entry claims the scheme when run from the jar; a second
launch hands its link to the running instance over a Unix socket in the
user's runtime directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 22:19:52 +00:00
co-authored by Claude Opus 5.5
parent 45d6fcda3d
commit e76804fb2d
15 changed files with 474 additions and 14 deletions
+7
View File
@@ -33,6 +33,13 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- TeamSpeak server links from browsers and other apps connect. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="ts3server" />
</intent-filter>
</activity> </activity>
<service <service
@@ -7,6 +7,7 @@ import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import com.ts3client.android.ui.App import com.ts3client.android.ui.App
import com.ts3client.android.ui.Ts3Theme import com.ts3client.android.ui.Ts3Theme
import com.ts3client.session.ServerLink
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
@@ -15,7 +16,7 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge() enableEdgeToEdge()
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (savedInstanceState == null) openRequestedChat(intent) if (savedInstanceState == null) handle(intent)
setContent { setContent {
Ts3Theme { App(sessions) } Ts3Theme { App(sessions) }
} }
@@ -23,7 +24,7 @@ class MainActivity : ComponentActivity() {
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
openRequestedChat(intent) handle(intent)
} }
override fun onStart() { override fun onStart() {
@@ -36,7 +37,14 @@ class MainActivity : ComponentActivity() {
super.onStop() super.onStop()
} }
/** A private message notification opens its conversation. */ /** A notification opens its conversation; a `ts3server://` link connects. */
private fun handle(intent: Intent) {
when (intent.action) {
Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.let { sessions.open(it) }
else -> openRequestedChat(intent)
}
}
private fun openRequestedChat(intent: Intent) { private fun openRequestedChat(intent: Intent) {
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
@@ -10,6 +10,7 @@ import com.ts3client.net.GroupChoice
import com.ts3client.net.ban.BanEntry import com.ts3client.net.ban.BanEntry
import com.ts3client.net.ban.BanRule import com.ts3client.net.ban.BanRule
import com.ts3client.net.ConnectionListener.ChatScope import com.ts3client.net.ConnectionListener.ChatScope
import com.ts3client.session.ServerLink
import com.ts3client.session.ServerSession import com.ts3client.session.ServerSession
import com.ts3client.text.ChatHtml import com.ts3client.text.ChatHtml
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@@ -113,6 +114,13 @@ class ServerController internal constructor(
refresh() refresh()
} }
internal fun open(link: ServerLink, identityId: String) {
network.connecting()
started = true
session.open(link, identityId)
refresh()
}
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */ /** A bookmark leading back to this server, joining [channelId]; not yet saved. */
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId)) fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId))
@@ -24,6 +24,7 @@ import com.ts3client.myts.MyTeamSpeak
import com.ts3client.myts.MyTeamSpeakLogin import com.ts3client.myts.MyTeamSpeakLogin
import com.ts3client.net.HostButton import com.ts3client.net.HostButton
import com.ts3client.session.SelfState import com.ts3client.session.SelfState
import com.ts3client.session.ServerLink
import com.ts3client.session.ServerSession import com.ts3client.session.ServerSession
import com.ts3client.session.Sessions import com.ts3client.session.Sessions
import com.ts3client.sound.SoundNotifier import com.ts3client.sound.SoundNotifier
@@ -71,6 +72,8 @@ internal class SharedFile(val name: String, val size: Long, val data: InputStrea
sealed interface SessionEvent { sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent data class Poke(val from: String, val message: String) : SessionEvent
data class Error(val message: String) : SessionEvent data class Error(val message: String) : SessionEvent
/** A link or shortcut brought a server on screen, in front of whatever page was open. */
data object ServerOpened : SessionEvent
} }
/** /**
@@ -187,19 +190,42 @@ class SessionController(private val context: Context) {
} }
fun connect(bookmark: Bookmark) { fun connect(bookmark: Bookmark) {
start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, bookmark.identityId, start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password,
bookmark.channel, bookmark.channelPassword) bookmark.identityId, bookmark.channel, bookmark.channelPassword) }
} }
private fun start(host: String, port: Int, nickname: String, password: String, identityId: String, private fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) { channel: String, channelPassword: String) {
start { it.start(host, port, nickname, password, identityId, channel, channelPassword) }
}
private fun start(connect: (ServerController) -> Unit) {
val server = ServerController(nextId.incrementAndGet(), this) val server = ServerController(nextId.incrementAndGet(), this)
sessions.add(server.session) sessions.add(server.session)
_servers.update { it + server } _servers.update { it + server }
_current.value = server _current.value = server
_lastEnd.value = null _lastEnd.value = null
context.startForegroundService(Intent(context, ConnectionService::class.java)) context.startForegroundService(Intent(context, ConnectionService::class.java))
server.start(host, port, nickname, password, identityId, channel, channelPassword) connect(server)
}
/**
* Goes where a `ts3server://` link leads: on a server we are on already, to the channel it
* names; else connects there as another server.
*/
fun open(link: ServerLink, identityId: String = "") {
if (link.bookmarkLabel.isNotEmpty()) {
bookmarkStore.add(link.toBookmark())
saveBookmarks()
}
val on = _servers.value.firstOrNull { it.session.isOn(link) }
if (on != null) {
_current.value = on
on.session.follow(link)
} else {
start { it.open(link, identityId) }
}
_events.tryEmit(SessionEvent.ServerOpened)
} }
fun select(server: ServerController) { fun select(server: ServerController) {
@@ -42,6 +42,12 @@ fun App(vm: SessionController) {
when (event) { when (event) {
is SessionEvent.Poke -> poke = event is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message) is SessionEvent.Error -> snackbar.showSnackbar(event.message)
SessionEvent.ServerOpened -> {
connectOpen = false
settingsOpen = false
contactsOpen = false
editingBookmark = null
}
} }
} }
} }
@@ -78,6 +78,7 @@ import com.ts3client.android.TreeFind
import com.ts3client.android.findIn import com.ts3client.android.findIn
import com.ts3client.config.Settings import com.ts3client.config.Settings
import com.ts3client.myts.ChatAttachment import com.ts3client.myts.ChatAttachment
import com.ts3client.session.ServerLink
import com.ts3client.text.TsLink import com.ts3client.text.TsLink
private val ChatKeySaver = Saver<ChatKey, String>( private val ChatKeySaver = Saver<ChatKey, String>(
@@ -159,6 +160,7 @@ fun ServerScreen(
val ref = TsLink.parse(href) val ref = TsLink.parse(href)
when { when {
ChatAttachment.isHref(href) -> attachments.open(href) ChatAttachment.isHref(href) -> attachments.open(href)
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) } ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } ref.client -> { clientSheet = ref.id; clientSheetFromTree = false }
else -> channelSheet = ref.id else -> channelSheet = ref.id
@@ -129,7 +129,7 @@ fun ClientSheet(
} }
} }
/** What can be done with a channel: join it, and whether to hear who is in it. */ /** What can be done with a channel: join it, whether to hear who is in it, its files, and editing it. */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ChannelSheet( fun ChannelSheet(
@@ -0,0 +1,145 @@
package com.ts3client.session;
import com.ts3client.config.Bookmark;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Locale;
/**
* A {@code ts3server://} link, as web pages and chats hand them out:
* {@code ts3server://host[:port]?port=…&nickname=…&password=…&channel=A/B&cid=…
* &channelpassword=…&token=…&addbookmark=…}. Every parameter is optional.
*/
public final class ServerLink {
public static final String SCHEME = "ts3server";
private static final String PREFIX = SCHEME + "://";
private static final int DEFAULT_PORT = 9987;
public final String address;
public final int port;
/** Empty for the identity's or the global nickname. */
public final String nickname;
public final String password;
/** A "/"-separated path or {@code "/<channelId>"}, 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;
}
}
}
@@ -82,6 +82,8 @@ public final class ServerSession {
private volatile String lastChannelPath = ""; private volatile String lastChannelPath = "";
/** The server icon last reported through {@link Listener#onServerIconChanged}; -1 for none yet. */ /** The server icon last reported through {@link Listener#onServerIconChanged}; -1 for none yet. */
private volatile long serverIconId = -1; 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) { private record Target(String address, int port, String nickname, String password, String channelPassword) {
} }
@@ -188,6 +190,29 @@ public final class ServerSession {
}, "identity-resolve").start(); }, "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) { private String nicknameFor(String serverNickname, IdentityEntry identity) {
if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim(); if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim();
if (!identity.getNickname().isBlank()) return identity.getNickname(); if (!identity.getNickname().isBlank()) return identity.getNickname();
@@ -627,6 +652,15 @@ public final class ServerSession {
setStatus(message); 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() { private void checkServerIcon() {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
long id = conn.getModel().serverIconId(); long id = conn.getModel().serverIconId();
@@ -652,6 +686,7 @@ public final class ServerSession {
listener.onSystemMessage("Connected."); listener.onSystemMessage("Connected.");
listener.onSessionChanged(); listener.onSessionChanged();
checkServerIcon(); checkServerIcon();
useConnectToken();
} }
@Override @Override
@@ -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);
}
}
@@ -1,14 +1,17 @@
package com.ts3client; package com.ts3client;
import com.ts3client.config.Settings; import com.ts3client.config.Settings;
import com.ts3client.session.ServerLink;
import com.ts3client.ui.DesktopEntry; import com.ts3client.ui.DesktopEntry;
import com.ts3client.ui.DisplayScale; import com.ts3client.ui.DisplayScale;
import com.ts3client.ui.IconTheme; import com.ts3client.ui.IconTheme;
import com.ts3client.ui.InstanceChannel;
import com.ts3client.ui.LookAndFeelManager; import com.ts3client.ui.LookAndFeelManager;
import com.ts3client.ui.MainFrame; import com.ts3client.ui.MainFrame;
import com.ts3client.ui.WindowClass; import com.ts3client.ui.WindowClass;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import java.util.Arrays;
/** /**
* Application entry point. Loads settings, installs the look-and-feel and shows the * Application entry point. Loads settings, installs the look-and-feel and shows the
@@ -24,6 +27,10 @@ public final class Main {
} catch (Throwable ignored) { } 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(); final Settings settings = Settings.load();
DisplayScale.configure(settings.uiScale); DisplayScale.configure(settings.uiScale);
WindowClass.apply(); WindowClass.apply();
@@ -32,7 +39,10 @@ public final class Main {
LookAndFeelManager.install(settings.appearance); LookAndFeelManager.install(settings.appearance);
IconTheme.get().reload(settings); IconTheme.get().reload(settings);
DesktopEntry.install(); 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);
}); });
} }
} }
@@ -1,6 +1,7 @@
package com.ts3client.ui; package com.ts3client.ui;
import com.ts3client.Main; import com.ts3client.Main;
import com.ts3client.session.ServerLink;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; 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} — * 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. * and files the window under whatever launcher runs Java, with its name and icon.
* *
* <p>A launcher run from a jar also takes {@code ts3server://} links.
*
* <p>The files are only rewritten when their content changes, e.g. after the jar moved. * <p>The files are only rewritten when their content changes, e.g. after the jar moved.
* {@code -Dts3j.desktopEntry=false} turns this off. * {@code -Dts3j.desktopEntry=false} turns this off.
*/ */
@@ -42,8 +45,11 @@ public final class DesktopEntry {
Path data = dataHome(); Path data = dataHome();
Path icon = icon(); Path icon = icon();
writeIfChanged(icon, iconPng()); writeIfChanged(icon, iconPng());
writeIfChanged(data.resolve("applications").resolve(WindowClass.NAME + ".desktop"), Path applications = data.resolve("applications");
entry(icon).getBytes(StandardCharsets.UTF_8)); if (writeIfChanged(applications.resolve(WindowClass.NAME + ".desktop"),
entry(icon).getBytes(StandardCharsets.UTF_8))) {
updateSchemeHandlers(applications);
}
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
System.err.println("Cannot install the desktop entry: " + 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("GenericName=TeamSpeak 3 Client\n")
.append("Comment=Voice chat on TeamSpeak 3 servers\n") .append("Comment=Voice chat on TeamSpeak 3 servers\n")
.append("Icon=").append(icon).append('\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("StartupWMClass=").append(WindowClass.NAME).append('\n')
.append("Categories=Network;InstantMessaging;AudioVideo;\n") .append("Categories=Network;InstantMessaging;AudioVideo;\n")
.append("Terminal=false\n"); .append("Terminal=false\n");
// Run from classes (an IDE, mvn exec:java) there is nothing sensible to launch; // 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. // the entry is still needed to name the window, but stays out of the menu.
if (exec == null) s.append("NoDisplay=true\n"); if (exec == null) s.append("NoDisplay=true\n");
else s.append("MimeType=x-scheme-handler/").append(ServerLink.SCHEME).append(";\n");
return s.toString(); return s.toString();
} }
@@ -108,12 +115,26 @@ public final class DesktopEntry {
return out.toByteArray(); 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()); Files.createDirectories(file.getParent());
Path tmp = file.resolveSibling(file.getFileName() + ".tmp"); Path tmp = file.resolveSibling(file.getFileName() + ".tmp");
Files.write(tmp, content); Files.write(tmp, content);
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE); StandardCopyOption.ATOMIC_MOVE);
return true;
} }
} }
@@ -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<String> 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();
}
}
@@ -1,17 +1,36 @@
package com.ts3client.ui; package com.ts3client.ui;
import com.ts3client.session.ServerLink;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import java.awt.Component; import java.awt.Component;
import java.awt.Desktop; import java.awt.Desktop;
import java.net.URI; 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 { final class Links {
private static volatile Consumer<ServerLink> serverLinks;
private Links() { private Links() {
} }
/** Where {@code ts3server://} links go. */
static void setServerLinkHandler(Consumer<ServerLink> handler) {
serverLinks = handler;
}
static void open(String href, Component parent) { static void open(String href, Component parent) {
ServerLink link = ServerLink.parse(href);
Consumer<ServerLink> handler = serverLinks;
if (link != null && handler != null) {
handler.accept(link);
return;
}
try { try {
URI uri = new URI(href); URI uri = new URI(href);
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(); String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase();
@@ -8,6 +8,7 @@ import com.ts3client.config.AwayMessages;
import com.ts3client.config.BanReasonPresets; import com.ts3client.config.BanReasonPresets;
import com.ts3client.config.Bookmark; import com.ts3client.config.Bookmark;
import com.ts3client.config.Bookmarks; import com.ts3client.config.Bookmarks;
import com.ts3client.session.ServerLink;
import com.ts3client.config.IdentityStore; import com.ts3client.config.IdentityStore;
import com.ts3client.config.Settings; import com.ts3client.config.Settings;
import com.ts3client.myts.ChatAttachments; 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("Welcome to the TS3J Swing client.");
first.chat().appendSystem("Use Connections → Connect to join a server."); first.chat().appendSystem("Use Connections → Connect to join a server.");
Links.setServerLinkHandler(this::openServerLink);
statusTimer = new javax.swing.Timer(3000, e -> updateConnectionStatus()); statusTimer = new javax.swing.Timer(3000, e -> updateConnectionStatus());
statusTimer.start(); statusTimer.start();
setSize(UIScale.scale(new Dimension(880, 560))); 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); 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. */ /** Connects on the current tab, leaving whatever server it is on. */
private void connectToBookmark(Bookmark b) { private void connectToBookmark(Bookmark b) {
startConnection(b.address, b.port, b.nickname == null ? "" : b.nickname, b.password, b.identityId, b.channel, b.channelPassword, true); startConnection(b.address, b.port, b.nickname == null ? "" : b.nickname, b.password, b.identityId, b.channel, b.channelPassword, true);