diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index 672332b..18ec843 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -12,8 +12,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo | 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | done (`e255a46`): one `applyClientProperties`. It also fixed a joining channel commander shown as none, and picks up the description a client enters with | | 3 | What we may do is answered in five places: `ServerSession.can*`, `ServerModel.can*/permits/mayHavePower`, `TeamspeakConnection.canSendOfflineMessages/canTransferFiles`, and raw permission names in Swing dialogs and `ServerController.canCreateBans` | done (`13e3a62`): `Permissions` owns the table, the rules and one named question per capability; `ServerSession.permissions()` is `NONE` while disconnected; no permission names outside core except channel-permission editing | | 4 | `TeamspeakConnection` (2,157 lines) still does lifecycle, mic/speaker, recording, chat logs, log/sound text, contacts, avatars, icons, file transfers, myTeamSpeak and job plumbing. The `*Admin` helpers take the whole connection, which forwards ~90 methods to them | in progress, in sub-steps: | -| 4a | … chat log and what we tell the user (log lines, sounds, links and sound variables) | done (`c28c2ce`): `ChatLog`, `Announcer` | -| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | open | +| 4a | … chat log and what we tell the user (log lines, sounds, links and sound variables) | done (`1bc7eb5`): `ChatLog`, `Announcer` | +| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | done (uncommitted): `ServerLink` owns the socket, event and request threads and file transfers, and runs requests; the helpers take it (plus the model, permissions or avatars where they need them) | | 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | open | | 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | open | | 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | open | diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java index 2964c7e..33bbf93 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java @@ -4,14 +4,15 @@ import com.github.manevolent.ts3j.command.SingleCommand; import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; import com.github.manevolent.ts3j.protocol.ProtocolRole; import eu.lixko.ts3j.client.net.avatar.AvatarNaming; +import eu.lixko.ts3j.client.net.avatar.AvatarRepository; import eu.lixko.ts3j.client.net.avatar.ImageFormat; import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; -import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; import java.io.File; import java.nio.file.Files; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; /** * Publishes and withdraws the local client's avatar, the way the official client does @@ -26,10 +27,17 @@ final class AvatarAdmin { private static final long UPLOAD_TIMEOUT_MS = 60_000; - private final TeamspeakConnection conn; + private final ServerLink link; + private final Permissions permissions; + private final AvatarRepository avatars; + /** Our unique id, which names our avatar file. */ + private final Supplier selfUniqueId; - AvatarAdmin(TeamspeakConnection conn) { - this.conn = conn; + AvatarAdmin(ServerLink link, Permissions permissions, AvatarRepository avatars, Supplier selfUniqueId) { + this.link = link; + this.permissions = permissions; + this.avatars = avatars; + this.selfUniqueId = selfUniqueId; } /** Uploads {@code source} as our avatar and announces it; returns its flag. */ @@ -39,14 +47,14 @@ final class AvatarAdmin { if (ImageFormat.detect(data) == null) { throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images"); } - int limit = conn.getModel().permissions().maxAvatarBytes(); + int limit = permissions.maxAvatarBytes(); if (data.length > limit) { throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB"); } String name = ownFileName(); CountDownLatch done = new CountDownLatch(1); - FileTransfer transfer = fileTransfers().upload(0, "", "/" + name, source, true, t -> { + FileTransfer transfer = link.files().upload(0, "", "/" + name, source, true, t -> { if (t.isDone()) done.countDown(); }); if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { @@ -58,7 +66,7 @@ final class AvatarAdmin { } String flag = AvatarNaming.flag(data); setFlag(flag); - conn.getAvatars().put(data); + avatars.put(data); return flag; } @@ -66,7 +74,7 @@ final class AvatarAdmin { void remove() throws Exception { setFlag(""); try { - deleteFile(conn.getSelfUniqueId()); + deleteFile(selfUniqueId.get()); } catch (Exception ignored) { // The flag is what other clients go by; a leftover file only wastes space. // Servers refuse the deletion unless we may delete others' avatars too. @@ -86,24 +94,18 @@ final class AvatarAdmin { * server maps to the stored file itself; the stored name is refused ("convert error"). */ private void deleteFile(String uniqueId) throws Exception { - fileTransfers().delete(0, "", "/avatar_" + uniqueId); + link.files().delete(0, "", "/avatar_" + uniqueId); } private void setFlag(String flag) throws Exception { SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT, new CommandSingleParameter("client_flag_avatar", flag)); - conn.socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); } private String ownFileName() { - String name = AvatarNaming.fileName(conn.getSelfUniqueId()); + String name = AvatarNaming.fileName(selfUniqueId.get()); if (name == null) throw new IllegalStateException("Our identity has no usable unique id"); return name; } - - private FileTransferManager fileTransfers() { - FileTransferManager ft = conn.fileTransfers(); - if (ft == null) throw new IllegalStateException("Not connected"); - return ft; - } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java index 1d488ba..4c767c2 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java @@ -26,7 +26,7 @@ final class BanAdmin { /** What {@code banlist} answers when there are no bans at all. */ private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - private final TeamspeakConnection conn; + private final ServerLink link; /** * The {@code banlist} reply in progress. The server answers the command with a burst @@ -36,8 +36,8 @@ final class BanAdmin { */ private volatile List listing; - BanAdmin(TeamspeakConnection conn) { - this.conn = conn; + BanAdmin(ServerLink link) { + this.link = link; } /** Reads every ban on the server. */ @@ -45,10 +45,10 @@ final class BanAdmin { List entries = Collections.synchronizedList(new ArrayList<>()); listing = entries; try { - conn.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete(); + link.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete(); // The entries were queued on the event thread before the command's own reply // was read, so draining that thread is what guarantees they have all landed. - conn.awaitEventsProcessed(); + link.awaitEventsProcessed(); } catch (CommandException e) { if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; } finally { @@ -79,7 +79,7 @@ final class BanAdmin { addIfSet(cmd, "mytsid", rule.mytsid); if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds))); addIfSet(cmd, "banreason", rule.reason); - for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { + for (SingleCommand answer : link.socket().executeCommand(cmd).get()) { Map fields = answer.toMap(); if (fields.containsKey("banid")) { return BanEntry.from(fields).id; @@ -106,7 +106,7 @@ final class BanAdmin { void delete(int banId) throws Exception { SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT, new CommandSingleParameter("banid", Integer.toString(banId))); - conn.socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); } private static void addIfSet(SingleCommand cmd, String key, String value) { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java index fa34f52..8ee3681 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java @@ -7,7 +7,6 @@ import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; import com.github.manevolent.ts3j.protocol.ProtocolRole; import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; -import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; import eu.lixko.ts3j.client.net.filetransfer.RemoteFile; import java.io.File; @@ -38,7 +37,8 @@ final class ChannelAdmin { /** How long to wait for a whole icon to travel over the file connection. */ private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000; - private final TeamspeakConnection conn; + private final ServerLink link; + private final ServerModel model; /** * The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a @@ -48,15 +48,16 @@ final class ChannelAdmin { */ private volatile PermRequest permRequest; - ChannelAdmin(TeamspeakConnection conn) { - this.conn = conn; + ChannelAdmin(ServerLink link, ServerModel model) { + this.link = link; + this.model = model; } // ---- channel properties ---- /** Reads a channel's full property set. */ ChannelSettings readSettings(int channelId) throws Exception { - Channel info = conn.socket().getChannelInfo(channelId); + Channel info = link.socket().getChannelInfo(channelId); if (info == null) throw new IllegalStateException("The server did not describe that channel"); return ChannelSettings.from(channelId, info.getMap()); } @@ -73,15 +74,15 @@ final class ChannelAdmin { for (Map.Entry property : properties.entrySet()) { cmd.add(new CommandSingleParameter(property.getKey(), property.getValue())); } - for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { + for (SingleCommand answer : link.socket().executeCommand(cmd).get()) { int cid = parseInt(answer.toMap().get("cid"), -1); if (cid > 0) return cid; } // Some servers acknowledge the command without naming the channel; the // notifychannelcreated they also send does name it, so read it off the model // once that event has been handled. - conn.awaitEventsProcessed(); - ChannelNode created = conn.getModel().findChannelByName(parentId, properties.get("channel_name")); + link.awaitEventsProcessed(); + ChannelNode created = model.findChannelByName(parentId, properties.get("channel_name")); if (created == null) throw new IllegalStateException("The server did not report the new channel"); return created.id; } @@ -94,12 +95,12 @@ final class ChannelAdmin { for (Map.Entry change : changes.entrySet()) { cmd.add(new CommandSingleParameter(change.getKey(), change.getValue())); } - conn.socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); } /** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */ void delete(int channelId, boolean force) throws Exception { - conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT, new CommandSingleParameter("cid", Integer.toString(channelId)), new CommandSingleParameter("force", force ? "1" : "0"))).complete(); } @@ -113,7 +114,7 @@ final class ChannelAdmin { * carries — anything inherited from a group is absent */ Map readPermissions(int channelId) throws Exception { - if (!conn.getModel().permissions().hasNames()) { + if (!model.permissions().hasNames()) { // channelpermlist reports numeric ids, which only the permissionlist response // gives names to; without it the values could not be told apart. throw new IllegalStateException("The server did not send its permission list"); @@ -123,17 +124,17 @@ final class ChannelAdmin { try { SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT, new CommandSingleParameter("cid", Integer.toString(channelId))); - conn.socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); // The entries were queued on the event thread before the command's own reply // was read, so draining that thread is what guarantees they have all landed. - conn.awaitEventsProcessed(); + link.awaitEventsProcessed(); } finally { permRequest = null; } Map byName = new LinkedHashMap<>(); for (Map.Entry entry : request.values.entrySet()) { - String name = conn.getModel().permissions().name(entry.getKey()); + String name = model.permissions().name(entry.getKey()); if (name != null) byName.put(name, entry.getValue()); } return byName; @@ -177,7 +178,7 @@ final class ChannelAdmin { private void send(String name, int channelId, List parts) throws Exception { MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts); cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - conn.socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); } // ---- the server's icon store ---- @@ -189,7 +190,7 @@ final class ChannelAdmin { List listIcons() throws Exception { List ids = new ArrayList<>(); boolean hasIconDirectory = false; - for (RemoteFile file : fileTransfers().list(0, "", "/")) { + for (RemoteFile file : link.files().list(0, "", "/")) { if (file.isDirectory()) { hasIconDirectory |= file.getName().equals(ICON_DIRECTORY); continue; @@ -199,7 +200,7 @@ final class ChannelAdmin { // Newer servers keep the icons in their own directory rather than loose in the // repository's root; both layouts exist, so whichever this server uses is read. if (hasIconDirectory) { - for (RemoteFile file : fileTransfers().list(0, "", "/" + ICON_DIRECTORY)) { + for (RemoteFile file : link.files().list(0, "", "/" + ICON_DIRECTORY)) { if (!file.isDirectory()) addIcon(ids, file); } } @@ -229,7 +230,7 @@ final class ChannelAdmin { long id = crc.getValue(); CountDownLatch done = new CountDownLatch(1); - FileTransfer transfer = fileTransfers().upload(0, "", "/icon_" + id, source, true, t -> { + FileTransfer transfer = link.files().upload(0, "", "/icon_" + id, source, true, t -> { if (t.isDone()) done.countDown(); }); if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { @@ -243,13 +244,7 @@ final class ChannelAdmin { } void deleteIcon(long iconId) throws Exception { - fileTransfers().delete(0, "", "/icon_" + iconId); - } - - private FileTransferManager fileTransfers() { - FileTransferManager ft = conn.fileTransfers(); - if (ft == null) throw new IllegalStateException("Not connected"); - return ft; + link.files().delete(0, "", "/icon_" + iconId); } // ---- helpers ---- diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java index a347cdc..21c2a5a 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java @@ -25,21 +25,21 @@ final class ComplaintAdmin { /** What {@code complainadd} answers when we already complained about that client. */ private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502; - private final TeamspeakConnection conn; + private final ServerLink link; /** The {@code complainlist} reply in progress; one request may be in flight at a time. */ private volatile List listing; - ComplaintAdmin(TeamspeakConnection conn) { - this.conn = conn; + ComplaintAdmin(ServerLink link) { + this.link = link; } List list() throws Exception { List complaints = Collections.synchronizedList(new ArrayList<>()); listing = complaints; try { - conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); - conn.awaitEventsProcessed(); + link.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); + link.awaitEventsProcessed(); } catch (CommandException e) { if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; } finally { @@ -56,7 +56,7 @@ final class ComplaintAdmin { /** Files a complaint about a client; the server takes one per client from each of us. */ void add(int targetDbId, String message) throws Exception { try { - conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)), new CommandSingleParameter("message", message))).complete(); } catch (CommandException e) { @@ -66,14 +66,14 @@ final class ComplaintAdmin { } void delete(Complaint complaint) throws Exception { - conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())), new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete(); } /** Removes every complaint about one client. */ void deleteAll(int targetDbId) throws Exception { - conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT, new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete(); } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java index 0d0ddcd..930aad4 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java @@ -102,7 +102,7 @@ final class ConnectionStatsCollector { } private void awaitReports(ConnectionStats s, int expected) { - LocalTeamspeakClientSocket client = conn.client; + LocalTeamspeakClientSocket client = conn.link.currentSocket(); if (client == null) return; Pending p = new Pending(s, expected); pending.put(s.clientId, p); @@ -133,7 +133,7 @@ final class ConnectionStatsCollector { long connectedAt = conn.connectedAtMs; if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt; - LocalTeamspeakClientSocket c = conn.client; + LocalTeamspeakClientSocket c = conn.link.currentSocket(); if (c == null) return; try { Pair ping = c.getPing(); @@ -158,7 +158,7 @@ final class ConnectionStatsCollector { /** Our file transfer rate since the previous poll; the server reports it only for others. */ private synchronized void applyTransferRate(ConnectionStats s) { - FileTransferManager ft = conn.fileTransfers(); + FileTransferManager ft = conn.link.currentFiles(); if (ft == null) return; long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()}; long[] last = lastTransferSample; diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java index f95e2de..9a94756 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java @@ -30,7 +30,7 @@ final class OfflineMessageAdmin { /** The most matches a nickname search names; each costs a lookup, and lookups flood quickly. */ private static final int MAX_SEARCH_RESULTS = 10; - private final TeamspeakConnection conn; + private final ServerLink link; /** Senders' nicknames by unique id; they cost a lookup each, so a connection asks once. */ private final Map names = new ConcurrentHashMap<>(); @@ -38,8 +38,8 @@ final class OfflineMessageAdmin { private volatile String awaited; private volatile List> replies; - OfflineMessageAdmin(TeamspeakConnection conn) { - this.conn = conn; + OfflineMessageAdmin(ServerLink link) { + this.link = link; } /** Forgets what the last server told us; a reconnect may be to another server. */ @@ -59,8 +59,8 @@ final class OfflineMessageAdmin { awaited = notification; replies = collected; try { - conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); - conn.awaitEventsProcessed(); + link.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); + link.awaitEventsProcessed(); } catch (CommandException e) { if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; } finally { @@ -71,7 +71,7 @@ final class OfflineMessageAdmin { } private synchronized void execute(String command, CommandParameter... params) throws Exception { - conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); + link.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); } private static CommandSingleParameter param(String key, Object value) { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java index bf11b15..ed364aa 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java @@ -23,23 +23,23 @@ final class PrivilegeKeyAdmin { /** What {@code tokenlist} answers when there are no keys at all. */ private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - private final TeamspeakConnection conn; + private final ServerLink link; /** The {@code tokenlist} reply in progress; one request may be in flight at a time. */ private volatile List listing; /** The key the {@code tokenadd} in flight was answered with. */ private volatile String created; - PrivilegeKeyAdmin(TeamspeakConnection conn) { - this.conn = conn; + PrivilegeKeyAdmin(ServerLink link) { + this.link = link; } List list() throws Exception { List keys = Collections.synchronizedList(new ArrayList<>()); listing = keys; try { - conn.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete(); - conn.awaitEventsProcessed(); + link.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete(); + link.awaitEventsProcessed(); } catch (CommandException e) { if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; } finally { @@ -66,8 +66,8 @@ final class PrivilegeKeyAdmin { cmd.add(new CommandSingleParameter("tokenid2", channelGroup ? Integer.toString(channelId) : "0")); cmd.add(new CommandSingleParameter("tokendescription", description)); created = null; - conn.socket().executeCommand(cmd).complete(); - conn.awaitEventsProcessed(); + link.socket().executeCommand(cmd).complete(); + link.awaitEventsProcessed(); String token = created; if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key"); return token; @@ -78,13 +78,13 @@ final class PrivilegeKeyAdmin { } void delete(String token) throws Exception { - conn.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT, new CommandSingleParameter("token", token))).complete(); } /** Redeems a key; the server announces the resulting group change itself. */ void use(String token) throws Exception { - conn.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT, + link.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT, new CommandSingleParameter("token", token))).complete(); } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLink.java new file mode 100644 index 0000000..b4e26b3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLink.java @@ -0,0 +1,207 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; +import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * The live link to the server, from one connect to its teardown: the socket, the thread + * ts3j dispatches events on, the threads requests run on, and the file transfer channel. + * It runs requests in the background and is all the admin helpers need of a connection. + * + *

Set up by the connect thread and torn down by whichever thread notices the end; read + * from the UI, event and action threads, so each reader copies a field before using it. + */ +final class ServerLink { + + /** A request made on the socket it was issued on. */ + interface Action { + void run(LocalTeamspeakClientSocket sock) throws Exception; + } + + /** A request that produces a value. */ + interface Job { + T call() throws Exception; + } + + /** A request with no result. */ + interface VoidJob { + void call() throws Exception; + } + + private volatile LocalTeamspeakClientSocket socket; + /** + * Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make + * its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server + * has already sent has been handled. + */ + private volatile ExecutorService events; + private volatile ExecutorService actions; + private volatile FileTransferManager fileTransfers; + /** Past the handshake and not yet torn down. */ + private volatile boolean up; + + /** A fresh socket, dispatching its events on our event thread, for a connect to set up. */ + LocalTeamspeakClientSocket open() { + LocalTeamspeakClientSocket sock = new LocalTeamspeakClientSocket(); + ExecutorService eventThread = Executors.newSingleThreadExecutor(r -> daemon(r, "ts3j-events")); + sock.setCommandExecutorService(eventThread); + events = eventThread; + actions = Executors.newCachedThreadPool(r -> daemon(r, "ts3j-action")); + socket = sock; + return sock; + } + + /** The handshake is done: requests may go out, and files travel over {@code transfers}. */ + void established(FileTransferManager transfers) { + fileTransfers = transfers; + up = true; + } + + /** The connection is ending; requests are refused from now on, and failures go unreported. */ + void markDown() { + up = false; + } + + /** Shuts everything down; there is no server left to tell. */ + void close() { + up = false; + LocalTeamspeakClientSocket sock = socket; + FileTransferManager ft = fileTransfers; + ExecutorService eventThread = events; + ExecutorService pool = actions; + socket = null; + fileTransfers = null; + events = null; + actions = null; + if (ft != null) { + try { + ft.shutdown(); + } catch (Exception ignored) { + } + } + if (sock != null) { + try { + sock.close(); + } catch (Exception ignored) { + } + } + if (eventThread != null) eventThread.shutdownNow(); + if (pool != null) pool.shutdownNow(); + } + + boolean isUp() { + return up; + } + + /** The socket, also while the handshake is under way; {@code null} once closed. */ + LocalTeamspeakClientSocket currentSocket() { + return socket; + } + + /** The live socket, for a request running in the background. */ + LocalTeamspeakClientSocket socket() { + LocalTeamspeakClientSocket sock = socket; + if (sock == null || !up) throw new IllegalStateException("Not connected"); + return sock; + } + + /** Whether files can travel now. */ + boolean canTransferFiles() { + return up && fileTransfers != null; + } + + /** The file transfer channel, for a request running in the background. */ + FileTransferManager files() { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + return ft; + } + + /** The file transfer channel, or {@code null} while there is none. */ + FileTransferManager currentFiles() { + return fileTransfers; + } + + /** + * Blocks until ts3j has finished dispatching every event it had already queued, so a + * caller that just saw a command complete can be sure the notifications the server sent + * alongside it have been handled. Must not be called from the event thread itself. + */ + void awaitEventsProcessed() { + ExecutorService eventThread = events; + if (eventThread == null) return; + try { + eventThread.submit(() -> { + }).get(5, TimeUnit.SECONDS); + } catch (Exception ignored) { + // A shutting-down or wedged event thread just means the caller gets what arrived. + } + } + + /** + * Runs a request in the background, handing a failure to {@code onFailure} unless the + * connection ended meanwhile: leaving fails whatever was still in flight. + */ + void submit(Action action, Consumer onFailure) { + LocalTeamspeakClientSocket sock = socket; + ExecutorService pool = actions; + if (sock == null || pool == null || !up) return; + try { + pool.execute(() -> { + try { + action.run(sock); + } catch (Exception e) { + if (socket == sock && up) onFailure.accept(e); + } + }); + } catch (RejectedExecutionException ignored) { + // disconnected in the meantime + } + } + + /** + * Runs a blocking server request in the background. The future completes there, so + * whatever is chained onto it does not run on the UI thread; it fails with a + * {@link RequestException}. + */ + CompletableFuture request(Job job) { + CompletableFuture result = new CompletableFuture<>(); + ExecutorService pool = actions; + if (pool == null || socket == null || !up) { + result.completeExceptionally(RequestException.notConnected()); + return result; + } + try { + pool.execute(() -> { + try { + result.complete(job.call()); + } catch (Exception e) { + result.completeExceptionally(up ? RequestException.of(e) : RequestException.notConnected()); + } + }); + } catch (RejectedExecutionException e) { + result.completeExceptionally(RequestException.notConnected()); + } + return result; + } + + CompletableFuture requestVoid(VoidJob job) { + return request(() -> { + job.call(); + return null; + }); + } + + private static Thread daemon(Runnable r, String name) { + Thread t = new Thread(r, name); + t.setDaemon(true); + return t; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java index 2fd1785..8ec1c4a 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java @@ -26,7 +26,7 @@ final class ServerLogAdmin { /** What {@code logview} may answer for an empty log. */ private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - private final TeamspeakConnection conn; + private final ServerLink link; /** The {@code logview} reply in progress; one request may be in flight at a time. */ private volatile Reply reply; @@ -36,8 +36,8 @@ final class ServerLogAdmin { volatile long lastPos; } - ServerLogAdmin(TeamspeakConnection conn) { - this.conn = conn; + ServerLogAdmin(ServerLink link) { + this.link = link; } /** @@ -53,8 +53,8 @@ final class ServerLogAdmin { Reply r = new Reply(); reply = r; try { - conn.socket().executeCommand(cmd).complete(); - conn.awaitEventsProcessed(); + link.socket().executeCommand(cmd).complete(); + link.awaitEventsProcessed(); } catch (CommandException e) { if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; } finally { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java index 03bf59f..1959769 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -44,10 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** @@ -88,6 +84,8 @@ public final class TeamspeakConnection implements TS3Listener { private final Settings settings; private final AudioBackend audio; private final ServerModel model = new ServerModel(); + /** The socket and the threads requests run on; package-private for {@link ConnectionStatsCollector}. */ + final ServerLink link = new ServerLink(); /** Package-private: read directly by {@link ConnectionEventHandler}. */ final ConnectionListener ui; private final IconRepository icons; @@ -103,40 +101,27 @@ public final class TeamspeakConnection implements TS3Listener { /** Builds {@code getconnectioninfo} snapshots; also package-private for {@link ConnectionEventHandler}. */ final ConnectionStatsCollector stats = new ConnectionStatsCollector(this); /** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */ - final ChannelAdmin channels = new ChannelAdmin(this); + final ChannelAdmin channels; /** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */ - final BanAdmin bans = new BanAdmin(this); - final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); - final ComplaintAdmin complaints = new ComplaintAdmin(this); - final ServerLogAdmin serverLog = new ServerLogAdmin(this); + final BanAdmin bans = new BanAdmin(link); + final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(link); + final ComplaintAdmin complaints = new ComplaintAdmin(link); + final ServerLogAdmin serverLog = new ServerLogAdmin(link); /** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */ - final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(this); - private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); + final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(link); + private final AvatarAdmin avatarAdmin; /* * Set up by the connect thread and torn down by whichever thread notices the end; read from * the UI, event and action threads, so each reader copies the field before using it. */ - /** Package-private: read directly by {@link ConnectionStatsCollector}. */ - volatile LocalTeamspeakClientSocket client; /** The client whose whisper we heard last, to reply to; 0 for none yet. */ private volatile int lastWhisperer; private volatile VoiceInput microphone; private volatile VoiceOutput playback; private volatile LocalIdentity identity; - private volatile FileTransferManager fileTransfers; /** The recording in progress; guarded by this connection. */ private VoiceRecorder recorder; - /** - * Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make - * its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server - * has already sent has been handled. Closed together with the socket. - */ - private volatile ExecutorService eventExecutor; - /** Runs this connection's requests to the server; created on connect, shut down with the socket. */ - private volatile ExecutorService actions; - - private volatile boolean connected; /** * The connect in progress. A disconnect clears it and a newer connect replaces it, which * tells a superseded attempt that is still failing not to clean up after itself. @@ -184,32 +169,21 @@ public final class TeamspeakConnection implements TS3Listener { /** Refreshes account authentication after sign-in/out while connected. */ public void updateMyTeamSpeak() { - LocalTeamspeakClientSocket socket = client; - ExecutorService executor = actions; - if (!connected || socket == null || executor == null) return; - try { - executor.execute(() -> { - synchronized (myTeamSpeakUpdateLock) { - try { - var login = myTeamSpeak; - var account = myTeamSpeakFeatures && login != null ? login.serverIdentity() : null; - if (client != socket || !connected) return; - socket.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate); - SingleCommand command = new SingleCommand("updatemytsid", ProtocolRole.CLIENT); - socket.addMyTeamSpeakParameters(command); - if (command.toMap().isEmpty()) { - for (String name : new String[] {"myTeamspeakId", "acTime", "userPubKey", "pubSign", "pubSignCert", "authSign"}) - command.add(new CommandSingleParameter(name, "")); - } - socket.executeCommand(command).complete(); - } catch (Exception e) { - ui.onError("Could not update myTeamSpeak identity: " + messageChain(e)); - } + link.submit(socket -> { + synchronized (myTeamSpeakUpdateLock) { + var login = myTeamSpeak; + var account = myTeamSpeakFeatures && login != null ? login.serverIdentity() : null; + if (link.currentSocket() != socket || !link.isUp()) return; + socket.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate); + SingleCommand command = new SingleCommand("updatemytsid", ProtocolRole.CLIENT); + socket.addMyTeamSpeakParameters(command); + if (command.toMap().isEmpty()) { + for (String name : new String[] {"myTeamspeakId", "acTime", "userPubKey", "pubSign", "pubSignCert", "authSign"}) + command.add(new CommandSingleParameter(name, "")); } - }); - } catch (RejectedExecutionException ignored) { - // The connection closed while scheduling the update. - } + socket.executeCommand(command).complete(); + } + }, e -> ui.onError("Could not update myTeamSpeak identity: " + messageChain(e))); } public TeamspeakConnection(Settings settings, AudioBackend audio, ConnectionListener ui, @@ -219,10 +193,12 @@ public final class TeamspeakConnection implements TS3Listener { this.ui = ui; this.contacts = contacts; this.chatLog = new ChatLog(settings, ui); - this.announce = new Announcer(model, sounds, ui, chatLog, () -> deafened, () -> connected); + this.announce = new Announcer(model, sounds, ui, chatLog, () -> deafened, link::isUp); this.events = new ConnectionEventHandler(this); this.icons = new IconRepository(this::fetchIcon, ui::onIconsUpdated); this.avatars = new AvatarRepository(this::fetchAvatar, ui::onInfoUpdated); + this.channels = new ChannelAdmin(link, model); + this.avatarAdmin = new AvatarAdmin(link, model.permissions(), avatars, this::getSelfUniqueId); } public ServerModel getModel() { @@ -230,7 +206,7 @@ public final class TeamspeakConnection implements TS3Listener { } public boolean isConnected() { - return connected; + return link.isUp(); } public int getSelfClientId() { @@ -293,7 +269,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Starts or stops capture to match {@link #microphoneActive}. */ private synchronized void applyMicrophoneState() { VoiceInput mic = microphone; - if (mic == null || !connected) return; + if (mic == null || !link.isUp()) return; try { if (microphoneActive) mic.start(); else mic.stop(); @@ -341,7 +317,6 @@ public final class TeamspeakConnection implements TS3Listener { connectErrorId = 0; disconnectReasonId = -1; // A socket or audio line an earlier connect left behind must not outlive it. - connected = false; safeCleanup(); try { var login = myTeamSpeak; @@ -385,22 +360,11 @@ public final class TeamspeakConnection implements TS3Listener { }); microphone.setMutedTalkListener(this::onTalkingWhileMuted); - client = new LocalTeamspeakClientSocket(); + LocalTeamspeakClientSocket client = link.open(); client.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate); - eventExecutor = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "ts3j-events"); - t.setDaemon(true); - return t; - }); - client.setCommandExecutorService(eventExecutor); - actions = Executors.newCachedThreadPool(r -> { - Thread t = new Thread(r, "ts3j-action"); - t.setDaemon(true); - return t; - }); client.setIdentity(identity); client.setNickname(nickname); - setIfPresent("client.nickname_phonetic", phoneticNickname); + setIfPresent(client, "client.nickname_phonetic", phoneticNickname); client.setHWID("ts3jswing-" + Integer.toHexString(nickname.hashCode())); client.addListener(this); client.addListener(events); @@ -417,8 +381,8 @@ public final class TeamspeakConnection implements TS3Listener { ui.onError("Network error: " + messageChain(t)); }); - applyClientVersion(); - applyDefaultChannel(channel, channelPassword); + applyClientVersion(client); + applyDefaultChannel(client, channel, channelPassword); ui.onStatus("Connecting to " + address + ":" + port + "…"); client.connect(new InetSocketAddress(address, port), @@ -435,11 +399,10 @@ public final class TeamspeakConnection implements TS3Listener { ourselves.self = true; model.enteredChannel(ourselves.channelId); } - fileTransfers = new FileTransferManager(client, () -> serverHost); client.setMicrophone(microphone); + link.established(new FileTransferManager(client, () -> serverHost)); icons.retryFailed(); avatars.retryFailed(); - connected = true; if (login != null && login.revision() != loginRevision) updateMyTeamSpeak(); connectedAtMs = System.currentTimeMillis(); leaving = false; @@ -452,7 +415,7 @@ public final class TeamspeakConnection implements TS3Listener { requestSelfPowers(); ui.onStatus("Retrieving channels…"); - syncAll(); + syncAll(client); ui.onModelChanged(); joinDefaultChannelIfNeeded(channel, channelPassword); ui.onStatus("Connected to " + model.getServerName()); @@ -465,7 +428,7 @@ public final class TeamspeakConnection implements TS3Listener { // Whoever took over reports on their own; cleaning up here would tear down what a newer // connect has set up in the meantime. if (connectAttempt != attempt) return; - connected = false; + link.markDown(); connectErrorId = refusalId(e); String failure = "Connection failed: " + RequestException.rootMessage(e) + versionHint(e); ui.onError(failure); @@ -505,14 +468,14 @@ public final class TeamspeakConnection implements TS3Listener { * built-in one when left empty; the signature has to match the version and * platform it was issued for, or a server may refuse the connection. */ - private void applyClientVersion() { + private void applyClientVersion(LocalTeamspeakClientSocket client) { if (!settings.customVersion) return; - setIfPresent("client.version_string", settings.clientVersion); - setIfPresent("client.version_platform", settings.clientPlatform); - setIfPresent("client.version_sign", settings.clientVersionSign); + setIfPresent(client, "client.version_string", settings.clientVersion); + setIfPresent(client, "client.version_platform", settings.clientPlatform); + setIfPresent(client, "client.version_sign", settings.clientVersionSign); } - private void setIfPresent(String option, String value) { + private static void setIfPresent(LocalTeamspeakClientSocket client, String option, String value) { if (value != null && !value.isBlank()) client.setOption(option, value.trim()); } @@ -521,7 +484,7 @@ public final class TeamspeakConnection implements TS3Listener { * channel right away instead of the default one. This is the path a real client * takes for bookmarks, and it avoids being briefly visible in the wrong channel. */ - private void applyDefaultChannel(String channel, String channelPassword) { + private static void applyDefaultChannel(LocalTeamspeakClientSocket client, String channel, String channelPassword) { String path = normaliseChannelRef(channel); if (path == null) return; client.setOption("client.default_channel", path); @@ -538,8 +501,8 @@ public final class TeamspeakConnection implements TS3Listener { */ private void joinDefaultChannelIfNeeded(String channel, String channelPassword) { if (normaliseChannelRef(channel) == null) return; - LocalTeamspeakClientSocket sock = client; - if (sock == null || !connected) return; // already left again + LocalTeamspeakClientSocket sock = link.currentSocket(); + if (sock == null || !link.isUp()) return; // already left again ChannelNode target = model.findChannelByPath(channel); if (target == null) { ui.onError("Channel \"" + channel.trim() + "\" not found on this server."); @@ -550,7 +513,7 @@ public final class TeamspeakConnection implements TS3Listener { sock.joinChannel(target.id, (channelPassword == null || channelPassword.isEmpty()) ? null : channelPassword); } catch (Exception e) { - if (!connected) return; + if (!link.isUp()) return; announce.error("Could not join channel \"" + target.name + "\": ", e); } } @@ -565,7 +528,7 @@ public final class TeamspeakConnection implements TS3Listener { ClientEntry self = model.getClient(selfClientId); if (self != null) return self.channelId; try { - return client.getClientInfo(selfClientId).getChannelId(); + return link.socket().getClientInfo(selfClientId).getChannelId(); } catch (Exception e) { return -1; } @@ -591,7 +554,7 @@ public final class TeamspeakConnection implements TS3Listener { * them: their rows lack groups, unique ids and away state, and they count heavily * against the server's flood protection. */ - private void syncAll() { + private void syncAll(LocalTeamspeakClientSocket client) { try { client.subscribeAll(); } catch (Exception e) { @@ -618,11 +581,11 @@ public final class TeamspeakConnection implements TS3Listener { leaving = true; disconnectReasonId = -1; try { + LocalTeamspeakClientSocket client = link.currentSocket(); if (client != null) client.disconnect(reason); } catch (Exception ignored) { } finally { safeCleanup(); - connected = false; announceDisconnect(true); ui.onDisconnected("You disconnected"); ui.onStatus("Disconnected"); @@ -659,27 +622,12 @@ public final class TeamspeakConnection implements TS3Listener { } VoiceInput mic = microphone; VoiceOutput out = playback; - LocalTeamspeakClientSocket sock = client; - FileTransferManager ft = fileTransfers; - ExecutorService events = eventExecutor; - ExecutorService pool = actions; - eventExecutor = null; - actions = null; microphone = null; playback = null; - client = null; - fileTransfers = null; chatLog.close(); selfClientId = -1; stats.clear(); - if (ft != null) { - try { - ft.shutdown(); - } catch (Exception ignored) { - } - } - if (mic != null) { try { mic.stop(); @@ -692,14 +640,7 @@ public final class TeamspeakConnection implements TS3Listener { } catch (Exception ignored) { } } - if (sock != null) { - try { - sock.close(); - } catch (Exception ignored) { - } - } - if (events != null) events.shutdownNow(); - if (pool != null) pool.shutdownNow(); + link.close(); } // ---- self actions ---- @@ -890,7 +831,7 @@ public final class TeamspeakConnection implements TS3Listener { for (String name : Permissions.UNREPORTED) { rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name))); } - submit(sock -> { + link.submit(sock -> { Map powers = new HashMap<>(); for (SingleCommand answer : sock.executeCommand(new MultiCommand("permget", ProtocolRole.CLIENT, rows)).get()) { Map fields = answer.toMap(); @@ -1060,7 +1001,7 @@ public final class TeamspeakConnection implements TS3Listener { public synchronized VoiceRecorder startRecording(VoiceRecorder.Mode mode, Path file) throws IOException { VoiceOutput out = playback; VoiceInput mic = microphone; - if (!connected || out == null || mic == null) throw new IllegalStateException("Not connected"); + if (!link.isUp() || out == null || mic == null) throw new IllegalStateException("Not connected"); if (recorder != null) throw new IllegalStateException("Already recording"); Map names = new HashMap<>(); @@ -1106,7 +1047,7 @@ public final class TeamspeakConnection implements TS3Listener { if (recorder != rec) return false; detachRecorder(); } - if (announce && connected) publishRecording(false); + if (announce && link.isUp()) publishRecording(false); return true; } @@ -1150,7 +1091,7 @@ public final class TeamspeakConnection implements TS3Listener { public double getPingMillis() { try { - LocalTeamspeakClientSocket sock = client; + LocalTeamspeakClientSocket sock = link.currentSocket(); return sock != null ? sock.getPing().getKey() * 1000.0 : -1; } catch (Exception e) { return -1; @@ -1194,8 +1135,8 @@ public final class TeamspeakConnection implements TS3Listener { * live text instead of whatever an earlier info request cached. */ public CompletableFuture requestClientDescription(int clientId) { - return request(() -> { - Client c = socket().getClientInfo(clientId); + return link.request(() -> { + Client c = link.socket().getClientInfo(clientId); String description = c == null ? "" : orEmpty(c.get("client_description")); ClientEntry e = model.getClient(clientId); if (e != null) e.description = description; @@ -1210,11 +1151,11 @@ public final class TeamspeakConnection implements TS3Listener { */ public CompletableFuture setClientDescription(int clientId, String description) { boolean self = clientId == selfClientId; - return requestVoid(() -> { + return link.requestVoid(() -> { SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT); cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); cmd.add(new CommandSingleParameter("client_description", description)); - socket().executeCommand(cmd).complete(); + link.socket().executeCommand(cmd).complete(); // Only the other clients are told about our own update, so the local entry // (and the info panel showing it) has to be caught up here. if (self) { @@ -1229,7 +1170,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Reads the server's privilege keys. */ public CompletableFuture> requestPrivilegeKeys() { - return request(privilegeKeys::list); + return link.request(privilegeKeys::list); } /** @@ -1238,20 +1179,20 @@ public final class TeamspeakConnection implements TS3Listener { * @return the new key */ public CompletableFuture addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) { - return request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description)); + return link.request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description)); } /** * Deletes privilege keys one by one, stopping at the first the server refuses. */ public CompletableFuture deletePrivilegeKeys(Collection tokens) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (String token : tokens) privilegeKeys.delete(token); }); } public CompletableFuture usePrivilegeKey(String token) { - return requestVoid(() -> privilegeKeys.use(token)); + return link.requestVoid(() -> privilegeKeys.use(token)); } // ---- complaints ---- @@ -1266,7 +1207,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Reads the server's complaints. */ public CompletableFuture> requestComplaints() { - return request(complaints::list); + return link.request(complaints::list); } /** @@ -1274,7 +1215,7 @@ public final class TeamspeakConnection implements TS3Listener { * stopping at the first the server refuses. */ public CompletableFuture deleteComplaints(Collection targetDbIds, Collection single) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (int target : targetDbIds) complaints.deleteAll(target); for (Complaint complaint : single) complaints.delete(complaint); }); @@ -1300,25 +1241,25 @@ public final class TeamspeakConnection implements TS3Listener { /** Lists our offline message inbox. */ public CompletableFuture> requestOfflineMessages() { - return request(offlineMessages::list); + return link.request(offlineMessages::list); } /** Reads a message's body. */ public CompletableFuture requestOfflineMessageBody(int messageId) { - return request(() -> offlineMessages.body(messageId)); + return link.request(() -> offlineMessages.body(messageId)); } /** * Marks messages read or unread, stopping at the first the server refuses. */ public CompletableFuture markOfflineMessages(Collection messageIds, boolean read) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (int id : messageIds) offlineMessages.setRead(id, read); }); } public CompletableFuture deleteOfflineMessages(Collection messageIds) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (int id : messageIds) offlineMessages.delete(id); }); } @@ -1327,7 +1268,7 @@ public final class TeamspeakConnection implements TS3Listener { * Sends one offline message to each recipient, stopping at the first the server refuses. */ public CompletableFuture sendOfflineMessage(Collection recipientUids, String subject, String message) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (String uid : recipientUids) offlineMessages.send(uid, subject, message); announce.log("Offline message sent."); }); @@ -1335,7 +1276,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Looks a client up by unique id; empty when the server has never seen them. */ public CompletableFuture> lookupDatabaseClient(String uniqueId) { - return request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId))); + return link.request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId))); } /** @@ -1344,7 +1285,7 @@ public final class TeamspeakConnection implements TS3Listener { * A server that will not let us search refuses for lack of permission. */ public CompletableFuture> searchDatabaseClients(String nickname) { - return request(() -> offlineMessages.search(nickname)); + return link.request(() -> offlineMessages.search(nickname)); } // ---- server log ---- @@ -1354,32 +1295,32 @@ public final class TeamspeakConnection implements TS3Listener { * earlier page's. */ public CompletableFuture requestServerLog(long olderFrom) { - return request(() -> serverLog.read(olderFrom)); + return link.request(() -> serverLog.read(olderFrom)); } // ---- bans ---- /** Reads the server's ban list. */ public CompletableFuture> requestBanList() { - return request(bans::list); + return link.request(bans::list); } public CompletableFuture addBan(BanRule rule) { - return requestVoid(() -> bans.add(rule)); + return link.requestVoid(() -> bans.add(rule)); } /** * Rewrites an existing ban. */ public CompletableFuture replaceBan(int banId, BanRule rule) { - return requestVoid(() -> bans.replace(banId, rule)); + return link.requestVoid(() -> bans.replace(banId, rule)); } /** * Deletes bans one by one, stopping at the first the server refuses. */ public CompletableFuture deleteBans(Collection banIds) { - return requestVoid(() -> { + return link.requestVoid(() -> { for (int id : banIds) bans.delete(id); }); } @@ -1441,7 +1382,7 @@ public final class TeamspeakConnection implements TS3Listener { * own server, which is a change that triggers the other's re-application, and so on. */ public void applyContacts() { - if (!connected) return; + if (!link.isUp()) return; for (ClientEntry c : model.allClients()) { Contact contact = applyContactPlayback(c); if (contact != null && contact.lastSeen == null) { @@ -1481,7 +1422,7 @@ public final class TeamspeakConnection implements TS3Listener { * Reads a channel's editable properties. */ public CompletableFuture requestChannelSettings(int channelId) { - return request(() -> channels.readSettings(channelId)); + return link.request(() -> channels.readSettings(channelId)); } /** @@ -1489,7 +1430,7 @@ public final class TeamspeakConnection implements TS3Listener { * server does not let us look at them. */ public CompletableFuture> requestChannelPermissions(int channelId) { - return request(() -> channels.readPermissions(channelId)); + return link.request(() -> channels.readPermissions(channelId)); } /** @@ -1499,7 +1440,7 @@ public final class TeamspeakConnection implements TS3Listener { public CompletableFuture applyChannelEdit(int channelId, Map changes, Map setPermissions, Collection removePermissions) { - return requestVoid(() -> { + return link.requestVoid(() -> { channels.edit(channelId, changes); channels.writePermissions(channelId, setPermissions, removePermissions); if (changes.containsKey("channel_description")) { @@ -1522,7 +1463,7 @@ public final class TeamspeakConnection implements TS3Listener { */ public CompletableFuture createChannel(int parentId, Map properties, Map permissions) { - return request(() -> { + return link.request(() -> { int channelId = channels.create(parentId, properties); try { channels.writePermissions(channelId, permissions, List.of()); @@ -1538,129 +1479,35 @@ public final class TeamspeakConnection implements TS3Listener { * Deletes a channel; with {@code force}, also one that has sub-channels or clients in it. */ public CompletableFuture deleteChannel(int channelId, boolean force) { - return requestVoid(() -> channels.delete(channelId, force)); + return link.requestVoid(() -> channels.delete(channelId, force)); } /** The ids of the icons uploaded to this virtual server. */ public CompletableFuture> requestServerIcons() { - return request(channels::listIcons); + return link.request(channels::listIcons); } /** Uploads an image as a server icon and reports the new icon's id. */ public CompletableFuture uploadIcon(File source) { - return request(() -> channels.uploadIcon(source)); + return link.request(() -> channels.uploadIcon(source)); } /** Deletes a server icon. */ public CompletableFuture deleteIcon(long iconId) { - return requestVoid(() -> channels.deleteIcon(iconId)); - } - - /** A request made on the socket of the connection it was issued on. */ - private interface Action { - void run(LocalTeamspeakClientSocket sock) throws Exception; - } - - /** Work that produces a value or an error message. */ - private interface Job { - T call() throws Exception; + return link.requestVoid(() -> channels.deleteIcon(iconId)); } /** Sends a request in the background, reporting a failure as {@code errorPrefix} and the reason. */ - private void act(String errorPrefix, Action action) { - submit(action, e -> announce.error(errorPrefix, e)); + private void act(String errorPrefix, ServerLink.Action action) { + link.submit(action, e -> announce.error(errorPrefix, e)); } /** Sends a request in the background whose failure nobody needs to hear about. */ - private void attempt(Action action) { - submit(action, e -> { + private void attempt(ServerLink.Action action) { + link.submit(action, e -> { }); } - private void submit(Action action, Consumer onFailure) { - LocalTeamspeakClientSocket sock = client; - ExecutorService pool = actions; - if (sock == null || pool == null || !connected) return; - try { - pool.execute(() -> { - try { - action.run(sock); - } catch (Exception e) { - // Leaving fails whatever was still in flight; that is no error to report. - if (client == sock && connected) onFailure.accept(e); - } - }); - } catch (RejectedExecutionException ignored) { - // disconnected in the meantime - } - } - - /** A request with no result. */ - private interface VoidJob { - void call() throws Exception; - } - - /** - * Runs a blocking server request in the background. The future completes there, so - * whatever is chained onto it does not run on the UI thread; it fails with a - * {@link RequestException}. - */ - private CompletableFuture request(Job job) { - CompletableFuture result = new CompletableFuture<>(); - ExecutorService pool = actions; - if (pool == null || client == null || !connected) { - result.completeExceptionally(RequestException.notConnected()); - return result; - } - try { - pool.execute(() -> { - try { - result.complete(job.call()); - } catch (Exception e) { - result.completeExceptionally(connected ? RequestException.of(e) : RequestException.notConnected()); - } - }); - } catch (RejectedExecutionException e) { - result.completeExceptionally(RequestException.notConnected()); - } - return result; - } - - private CompletableFuture requestVoid(VoidJob job) { - return request(() -> { - job.call(); - return null; - }); - } - - /** The live socket. Package-private for {@link ChannelAdmin}. */ - LocalTeamspeakClientSocket socket() { - LocalTeamspeakClientSocket sock = client; - if (sock == null || !connected) throw new IllegalStateException("Not connected"); - return sock; - } - - /** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */ - FileTransferManager fileTransfers() { - return fileTransfers; - } - - /** - * Blocks until ts3j has finished dispatching every event it had already queued, so a - * caller that just saw a command complete can be sure the notifications the server sent - * alongside it have been handled. Must not be called from the event thread itself. - */ - void awaitEventsProcessed() { - ExecutorService events = eventExecutor; - if (events == null) return; - try { - events.submit(() -> { - }).get(5, TimeUnit.SECONDS); - } catch (Exception ignored) { - // A shutting-down or wedged event thread just means the caller gets what arrived. - } - } - // ---- icons ---- /** Group icons for this server: bundled defaults plus the server's own uploads. */ @@ -1670,9 +1517,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Reads an icon out of the virtual server's file repository (channel 0). */ private byte[] fetchIcon(long iconId) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES); + return link.files().downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES); } // ---- avatars ---- @@ -1696,7 +1541,7 @@ public final class TeamspeakConnection implements TS3Listener { * Uploads an image as our avatar and publishes it to the other clients. */ public CompletableFuture setAvatar(File source) { - return requestVoid(() -> { + return link.requestVoid(() -> { String flag = avatarAdmin.upload(source); updateSelf(self -> self.avatarFlag = flag); }); @@ -1704,7 +1549,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Withdraws our avatar. */ public CompletableFuture removeAvatar() { - return requestVoid(() -> { + return link.requestVoid(() -> { avatarAdmin.remove(); updateSelf(self -> self.avatarFlag = ""); }); @@ -1712,23 +1557,21 @@ public final class TeamspeakConnection implements TS3Listener { /** Deletes another client's avatar. */ public CompletableFuture removeAvatarOf(ClientEntry client) { - return requestVoid(() -> avatarAdmin.removeOther(client.uniqueId)); + return link.requestVoid(() -> avatarAdmin.removeOther(client.uniqueId)); } /** Reads a client's avatar out of the virtual server's file repository (channel 0). */ private byte[] fetchAvatar(String uniqueId) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); String name = AvatarNaming.fileName(uniqueId); if (name == null) throw new IllegalArgumentException("Not a client unique id: " + uniqueId); - return ft.downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES); + return link.files().downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES); } // ---- whisper ---- /** Sends the microphone's voice to {@code targets} as a whisper, or to our channel again with null. */ public void setWhisperTargets(Whisper.Targets targets) { - LocalTeamspeakClientSocket sock = client; + LocalTeamspeakClientSocket sock = link.currentSocket(); if (sock == null) return; if (targets == null) { sock.setWhisperTarget(null); @@ -1750,7 +1593,7 @@ public final class TeamspeakConnection implements TS3Listener { /** Whether a live connection capable of file transfers is available. */ public boolean canTransferFiles() { - return connected && fileTransfers != null; + return link.canTransferFiles(); } /** @@ -1759,44 +1602,32 @@ public final class TeamspeakConnection implements TS3Listener { */ public java.util.List listFiles(int channelId, String channelPassword, String path) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.list(channelId, channelPassword, path); + return link.files().list(channelId, channelPassword, path); } public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.createDirectory(channelId, channelPassword, dirPath); + link.files().createDirectory(channelId, channelPassword, dirPath); } public void deleteFile(int channelId, String channelPassword, String fullPath) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.delete(channelId, channelPassword, fullPath); + link.files().delete(channelId, channelPassword, fullPath); } public void renameFile(int channelId, String channelPassword, String oldFullPath, String newFullPath) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.rename(channelId, channelPassword, oldFullPath, newFullPath); + link.files().rename(channelId, channelPassword, oldFullPath, newFullPath); } /** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */ public FileTransfer downloadFile(int channelId, String channelPassword, String remoteFullPath, File target, FileTransfer.Listener listener) { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.download(channelId, channelPassword, remoteFullPath, target, announcing(listener)); + return link.files().download(channelId, channelPassword, remoteFullPath, target, announcing(listener)); } /** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */ public FileTransfer uploadFile(int channelId, String channelPassword, String remoteFullPath, File source, boolean overwrite, FileTransfer.Listener listener) { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener)); + return link.files().upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener)); } /** @@ -1828,7 +1659,7 @@ public final class TeamspeakConnection implements TS3Listener { * version, platform and idle time. May be called repeatedly to poll. */ public void requestConnectionInfo(int clientId, Consumer callback) { - if (client == null || !connected) return; + if (!link.isUp()) return; stats.request(clientId, callback); } @@ -1842,7 +1673,7 @@ public final class TeamspeakConnection implements TS3Listener { */ @Override public void onDisconnected(DisconnectedEvent e) { - connected = false; + link.markDown(); disconnectReasonId = e.getReasonId(); safeCleanup(); announceDisconnect(false); @@ -1858,7 +1689,7 @@ public final class TeamspeakConnection implements TS3Listener { * never told it); {@code null} before the server has introduced itself. */ public String serverUniqueId() { - LocalTeamspeakClientSocket client = this.client; + LocalTeamspeakClientSocket client = link.currentSocket(); if (client == null) return null; Uid uid = client.getServerUid(); return uid == null ? null : uid.toBase64();