diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 5eb3c07..67f7b75 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -33,6 +33,13 @@ + + + + + + + ServerLink.parse(intent.dataString)?.let { sessions.open(it) } + else -> openRequestedChat(intent) + } + } + private fun openRequestedChat(intent: Intent) { val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) diff --git a/android/app/src/main/java/com/ts3client/android/ServerController.kt b/android/app/src/main/java/com/ts3client/android/ServerController.kt index e8892bf..f21f4cf 100644 --- a/android/app/src/main/java/com/ts3client/android/ServerController.kt +++ b/android/app/src/main/java/com/ts3client/android/ServerController.kt @@ -10,6 +10,7 @@ import com.ts3client.net.GroupChoice import com.ts3client.net.ban.BanEntry import com.ts3client.net.ban.BanRule import com.ts3client.net.ConnectionListener.ChatScope +import com.ts3client.session.ServerLink import com.ts3client.session.ServerSession import com.ts3client.text.ChatHtml import kotlinx.coroutines.CoroutineScope @@ -113,6 +114,13 @@ class ServerController internal constructor( 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. */ fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId)) diff --git a/android/app/src/main/java/com/ts3client/android/SessionController.kt b/android/app/src/main/java/com/ts3client/android/SessionController.kt index fae9b32..088e005 100644 --- a/android/app/src/main/java/com/ts3client/android/SessionController.kt +++ b/android/app/src/main/java/com/ts3client/android/SessionController.kt @@ -24,6 +24,7 @@ import com.ts3client.myts.MyTeamSpeak import com.ts3client.myts.MyTeamSpeakLogin import com.ts3client.net.HostButton import com.ts3client.session.SelfState +import com.ts3client.session.ServerLink import com.ts3client.session.ServerSession import com.ts3client.session.Sessions import com.ts3client.sound.SoundNotifier @@ -71,6 +72,8 @@ internal class SharedFile(val name: String, val size: Long, val data: InputStrea sealed interface SessionEvent { data class Poke(val from: String, 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) { - start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, bookmark.identityId, - bookmark.channel, bookmark.channelPassword) + start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, + bookmark.identityId, bookmark.channel, bookmark.channelPassword) } } private fun start(host: String, port: Int, nickname: String, password: String, identityId: 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) sessions.add(server.session) _servers.update { it + server } _current.value = server _lastEnd.value = null 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) { diff --git a/android/app/src/main/java/com/ts3client/android/ui/App.kt b/android/app/src/main/java/com/ts3client/android/ui/App.kt index ad9e2c0..c70f2ad 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/App.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/App.kt @@ -42,6 +42,12 @@ fun App(vm: SessionController) { when (event) { is SessionEvent.Poke -> poke = event is SessionEvent.Error -> snackbar.showSnackbar(event.message) + SessionEvent.ServerOpened -> { + connectOpen = false + settingsOpen = false + contactsOpen = false + editingBookmark = null + } } } } diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt index 14b803e..56968d7 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt @@ -78,6 +78,7 @@ import com.ts3client.android.TreeFind import com.ts3client.android.findIn import com.ts3client.config.Settings import com.ts3client.myts.ChatAttachment +import com.ts3client.session.ServerLink import com.ts3client.text.TsLink private val ChatKeySaver = Saver( @@ -159,6 +160,7 @@ fun ServerScreen( val ref = TsLink.parse(href) when { ChatAttachment.isHref(href) -> attachments.open(href) + ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) } ref == null -> runCatching { uriHandler.openUri(href) } ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } else -> channelSheet = ref.id diff --git a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt index 45f9601..7b83cd4 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt @@ -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) @Composable fun ChannelSheet( diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java new file mode 100644 index 0000000..c2b0b8d --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java @@ -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 "/"}, 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);