diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Requests.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Requests.kt new file mode 100644 index 0000000..7dcfa4f --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Requests.kt @@ -0,0 +1,19 @@ +package eu.lixko.ts3j.client.android + +import eu.lixko.ts3j.client.net.RequestException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.future.await +import java.util.concurrent.CompletableFuture + +/** A server request's outcome, failing with its [RequestException]. */ +internal suspend fun CompletableFuture.result(): Result = + try { + Result.success(await()) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Result.failure(RequestException.of(e)) + } + +/** The same for a request with no result. */ +internal suspend fun CompletableFuture.done(): Result = result().map { } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt index 8fd9ea9..f69a603 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -10,6 +10,7 @@ import eu.lixko.ts3j.client.net.ChannelSettings import eu.lixko.ts3j.client.net.ConnectionStats import eu.lixko.ts3j.client.net.Details import eu.lixko.ts3j.client.net.GroupChoice +import eu.lixko.ts3j.client.net.RequestException import eu.lixko.ts3j.client.net.Whisper import eu.lixko.ts3j.client.net.ban.BanEntry import eu.lixko.ts3j.client.net.ban.BanRule @@ -249,24 +250,17 @@ class ServerController internal constructor( if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId) /** A channel's editable properties as the server has them. */ - suspend fun channelSettings(channelId: Int): Result = suspendCoroutine { done -> - conn.requestChannelSettings(channelId) { settings, error -> - done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error))) - } - } + suspend fun channelSettings(channelId: Int): Result = conn.requestChannelSettings(channelId).result() - /** Each of these answers null once done, else why not. */ - suspend fun editChannel(channelId: Int, changes: Map): String? = - if (changes.isEmpty()) null - else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } } + suspend fun editChannel(channelId: Int, changes: Map): Result = + if (changes.isEmpty()) Result.success(Unit) + else conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()).done() - suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done -> - conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) } - } + suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result = + conn.createChannel(parentId, settings.creationParameters(), emptyMap()).result().map { } /** Deletes a channel, with its sub-channels and the clients in it moved out. */ - suspend fun deleteChannel(channelId: Int): String? = - suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } } + suspend fun deleteChannel(channelId: Int): Result = conn.deleteChannel(channelId, true).done() // ---- files ---- @@ -276,19 +270,16 @@ class ServerController internal constructor( suspend fun listFiles(channelId: Int, password: String, path: String): Result> = withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } } - /** Each of these answers null once done, else why not. */ - suspend fun createDirectory(channelId: Int, password: String, path: String): String? = + suspend fun createDirectory(channelId: Int, password: String, path: String): Result = fileCall { conn.createDirectory(channelId, password, path) } - suspend fun deleteFile(channelId: Int, password: String, path: String): String? = + suspend fun deleteFile(channelId: Int, password: String, path: String): Result = fileCall { conn.deleteFile(channelId, password, path) } - suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? = + suspend fun renameFile(channelId: Int, password: String, from: String, to: String): Result = fileCall { conn.renameFile(channelId, password, from, to) } - private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) { - runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName } - } + private suspend fun fileCall(call: () -> Unit): Result = withContext(Dispatchers.IO) { runCatching(call) } // ---- moderation ---- @@ -340,26 +331,19 @@ class ServerController internal constructor( // ---- ban list ---- - /** The server's bans, or why they could not be read. */ /** One reading of a client's connection figures, or null when not connected. */ suspend fun connectionStats(clientId: Int): ConnectionStats? = if (!session.isConnected) null else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } - suspend fun banList(): Result> = suspendCoroutine { done -> - conn.requestBanList { bans, error -> - done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error))) - } - } + /** The server's bans, or why they could not be read. */ + suspend fun banList(): Result> = conn.requestBanList().result() - /** Each of these answers null once done, else why not. */ - suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } } + suspend fun addBan(rule: BanRule): Result = conn.addBan(rule).done() - suspend fun replaceBan(banId: Int, rule: BanRule): String? = - suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } } + suspend fun replaceBan(banId: Int, rule: BanRule): Result = conn.replaceBan(banId, rule).done() - suspend fun deleteBans(banIds: Collection): String? = - suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } } + suspend fun deleteBans(banIds: Collection): Result = conn.deleteBans(banIds).done() fun canDeleteBans(bans: Collection): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) @@ -367,14 +351,14 @@ class ServerController internal constructor( fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) - /** Uploads [data] as our avatar; null once it is set, else why not. */ - suspend fun setAvatar(data: ByteArray): String? { - if (!session.isConnected) return "Not connected" + /** Uploads [data] as our avatar. */ + suspend fun setAvatar(data: ByteArray): Result { + if (!session.isConnected) return Result.failure(RequestException.notConnected()) val file = withContext(Dispatchers.IO) { File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) } } return try { - suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } } + conn.setAvatar(file).done() } finally { file.delete() } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt index d5ee3a1..8629a7e 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt @@ -92,10 +92,9 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: ( } /** Reports a failed change, or re-reads the list to show what the server now holds. */ - val change = { action: suspend () -> String?, failure: String -> + val change = { action: suspend () -> Result, failure: String -> scope.launch { - val error = action() - if (error != null) snackbar.showSnackbar("$failure: $error") + action().onFailure { snackbar.showSnackbar("$failure: ${it.message}") } generation++ } Unit diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt index 8fbb3b5..50d357c 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt @@ -83,11 +83,12 @@ fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> saving = true scope.launch { val trimmed = e.copy().apply { name = name.trim() } - val error = if (creating) server.createChannel(edit.parentId, trimmed) + val saved = if (creating) server.createChannel(edit.parentId, trimmed) else server.editChannel(edit.channelId, trimmed.changesFrom(o)) saving = false - if (error == null) onDone() - else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error) + saved.onSuccess { onDone() }.onFailure { + snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + it.message) + } } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt index 9c6ccb6..48af2d1 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt @@ -78,10 +78,9 @@ fun FilesScreen(server: ServerController, channelId: Int, channelName: String, p LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ } val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } - val act = { call: suspend () -> String? -> + val act = { call: suspend () -> Result -> scope.launch { - val error = call() - if (error != null) snackbar.showSnackbar(error) else reloads++ + call().onSuccess { reloads++ }.onFailure { snackbar.showSnackbar(it.message ?: it.javaClass.simpleName) } } Unit } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt index 0728a70..9e24f76 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt @@ -79,8 +79,8 @@ fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) PictureViewer( picture, onSteal = if (picture.ownAvatar) null else { data -> - val error = server.setAvatar(data) - Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show() + val message = server.setAvatar(data).fold({ "Avatar set." }, { it.message }) + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }, onDismiss = { viewed = null }, ) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt index 866649a..ba0d241 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -551,7 +551,7 @@ fun ServerScreen( confirmButton = { TextButton(onClick = { deletingChannel = null - scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } } + scope.launch { server.deleteChannel(id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } } }) { Text("Delete") } }, dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } }, diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md new file mode 100644 index 0000000..f492d32 --- /dev/null +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -0,0 +1,24 @@ +# Structural audit — ts3-client and Android + +Audit: 2026-10-11. Design and maintainability (DRY, SOLID, separation of concerns); the +correctness audit is [AUDIT.md](AUDIT.md). Not reviewed: the audio/DSP packages, tray/X11, +D-Bus and the ts3j submodule. + +Items are worked through in the order below. Status: open, done (commit), or closed (reason). + +| # | Finding | Status | +|---|---|---| +| 1 | Request failures reach frontends as strings, so they guess the kind by substring (`BanListDialog`, `ServerLogDialog`) and core needs a sentinel message (`SEARCH_NOT_PERMITTED`); success is signalled by a `null` error, here and in Android's `ServerController` (`String?`) | done: requests return `CompletableFuture`, failing with `RequestException` (kind + message); `Replies`/`Edt` split success and failure; Android uses `Result` | +| 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | open | +| 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` | open | +| 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 | open | +| 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | open | +| 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | open | +| 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding | open | +| 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | open | +| 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | open | +| 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | open | +| 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open | +| 12 | Swing `ui` package: 118 files, flat | open | +| 13 | `ClientEntry`/`ChannelNode` are bags of public volatile fields; a reader can see a half-applied update | open | +| 14 | Core produces English UI copy (status lines, log lines) | open | diff --git a/ts3-client/AUDIT.md b/ts3-client/AUDIT.md index d9c8d06..e839b93 100644 --- a/ts3-client/AUDIT.md +++ b/ts3-client/AUDIT.md @@ -2,6 +2,7 @@ First audit: 2026-09-11. Revisited and worked through: 2026-09-25. Every finding below was either fixed (commit given) or closed with a reason. Logging (§3) was left out on purpose. +The structural audit of 2026-10-11 is [AUDIT-STRUCTURE.md](AUDIT-STRUCTURE.md). State after the fixes: `mvn -o test` passes (177 tests: 25 in ts3j, 135 core, 11 desktop, 6 swing), on Java 25 and 26. The Android release build (R8 over core and ts3j) passes. The diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Replies.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Replies.java new file mode 100644 index 0000000..d2dfd5b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Replies.java @@ -0,0 +1,32 @@ +package eu.lixko.ts3j.client.net; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.Consumer; + +/** Hands a request's outcome to one of two handlers, run by {@code executor} (a UI thread, say). */ +public final class Replies { + + private Replies() { + } + + public static void handle(CompletableFuture request, Executor executor, + Consumer onSuccess, Consumer onFailure) { + request.whenCompleteAsync((value, failure) -> { + if (failure == null) onSuccess.accept(value); + else onFailure.accept(RequestException.of(failure)); + }, executor); + } + + /** For a request with no result. */ + public static void handle(CompletableFuture request, Executor executor, + Runnable onSuccess, Consumer onFailure) { + handle(request, executor, ignored -> onSuccess.run(), onFailure); + } + + /** For a request whose success needs no handling. */ + public static void onFailure(CompletableFuture request, Executor executor, Consumer onFailure) { + handle(request, executor, ignored -> { + }, onFailure); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/RequestException.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/RequestException.java new file mode 100644 index 0000000..90df03b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/RequestException.java @@ -0,0 +1,78 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; + +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; + +/** + * Why a request to the server failed, as a failed request's future carries it: what kind of + * failure, for a frontend to act on, and the reason as the server or the network gave it. + */ +public final class RequestException extends RuntimeException { + + public enum Kind { + /** There was no connection to send it on, or it ended before the answer came. */ + NOT_CONNECTED, + /** The server refused for lack of permission. */ + PERMISSION, + FAILED, + } + + private static final int ERROR_PERMISSIONS_CLIENT_INSUFFICIENT = 0x0a08; + private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; + private static final int ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER = 0x0a0a; + + private final Kind kind; + + private RequestException(Kind kind, String message, Throwable cause) { + super(message, cause); + this.kind = kind; + } + + public static RequestException notConnected() { + return new RequestException(Kind.NOT_CONNECTED, "Not connected", null); + } + + /** + * The failure {@code t} stands for, looking through the wrappers a future adds; any + * frontend handling a failed request turns what it got into one with this. + */ + public static RequestException of(Throwable t) { + Throwable cause = t; + while ((cause instanceof CompletionException || cause instanceof ExecutionException) + && cause.getCause() != null) { + cause = cause.getCause(); + } + if (cause instanceof RequestException known) return known; + return new RequestException(isPermissionError(cause) ? Kind.PERMISSION : Kind.FAILED, rootMessage(cause), cause); + } + + public Kind kind() { + return kind; + } + + public boolean permissionDenied() { + return kind == Kind.PERMISSION; + } + + /** Whether the server refused for lack of permission, wherever in the cause chain it said so. */ + static boolean isPermissionError(Throwable t) { + for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { + if (c instanceof CommandException ce) { + int id = ce.getErrorId(); + return id == ERROR_PERMISSIONS_CLIENT_INSUFFICIENT + || id == ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER + || id == ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER; + } + } + return false; + } + + static String rootMessage(Throwable t) { + Throwable r = t; + while (r.getCause() != null && r.getCause() != r) r = r.getCause(); + String m = r.getMessage(); + return m != null ? m : r.getClass().getSimpleName(); + } +} 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 f32a985..fdaec2b 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 @@ -45,13 +45,12 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; import java.util.function.Consumer; /** @@ -71,9 +70,6 @@ public final class TeamspeakConnection implements TS3Listener { /** The longest subject and body an offline message may carry, in characters. */ public static final int OFFLINE_MESSAGE_SUBJECT_LIMIT = 200; public static final int OFFLINE_MESSAGE_LIMIT = 4096; - /** What {@link #searchDatabaseClients} reports when the server will not let us search. */ - public static final String SEARCH_NOT_PERMITTED = - "You have no permission to search for users on this server, so you can only use contacts or unique IDs."; /** The protocol's reason ids for the two flavours of clientkick. */ private static final int REASON_KICK_CHANNEL = 4; @@ -82,9 +78,6 @@ public final class TeamspeakConnection implements TS3Listener { private static final int REASON_CONNECTION_LOST = 3; private static final int REASON_SERVER_SHUTDOWN = 11; - private static final int ERROR_PERMISSIONS_CLIENT_INSUFFICIENT = 0x0a08; - private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; - private static final int ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER = 0x0a0a; /** Shortest gap between two "you are talking while muted" reminders. */ private static final long MUTED_TALK_COOLDOWN_NANOS = 5_000_000_000L; @@ -305,7 +298,7 @@ public final class TeamspeakConnection implements TS3Listener { if (microphoneActive) mic.start(); else mic.stop(); } catch (Exception e) { - ui.onError("Microphone unavailable: " + rootMessage(e)); + ui.onError("Microphone unavailable: " + RequestException.rootMessage(e)); } pushInputHardware(); } @@ -474,7 +467,7 @@ public final class TeamspeakConnection implements TS3Listener { if (connectAttempt != attempt) return; connected = false; connectErrorId = refusalId(e); - String failure = "Connection failed: " + rootMessage(e) + versionHint(e); + String failure = "Connection failed: " + RequestException.rootMessage(e) + versionHint(e); ui.onError(failure); safeCleanup(); // Report the failed attempt as a disconnect too, so the UI leaves the @@ -499,7 +492,7 @@ public final class TeamspeakConnection implements TS3Listener { */ private String versionHint(Exception e) { if (!settings.customVersion) return ""; - String message = rootMessage(e); + String message = RequestException.rootMessage(e); return message != null && message.contains("client is modified") ? " — the server did not accept the custom client version; pick a newer one" + " of the listed versions in Options." @@ -602,7 +595,7 @@ public final class TeamspeakConnection implements TS3Listener { try { client.subscribeAll(); } catch (Exception e) { - ui.onStatus("Limited subscription: " + rootMessage(e)); + ui.onStatus("Limited subscription: " + RequestException.rootMessage(e)); } // The name comes with initserver; servergetvariables never reports it. model.setServerName(client.getServerName()); @@ -1200,8 +1193,8 @@ public final class TeamspeakConnection implements TS3Listener { * Reads a client's description straight from the server, so an editor opens on the * live text instead of whatever an earlier info request cached. */ - public void requestClientDescription(int clientId, BiConsumer callback) { - run(callback, () -> { + public CompletableFuture requestClientDescription(int clientId) { + return request(() -> { Client c = socket().getClientInfo(clientId); String description = c == null ? "" : orEmpty(c.get("client_description")); ClientEntry e = model.getClient(clientId); @@ -1214,12 +1207,10 @@ public final class TeamspeakConnection implements TS3Listener { * Changes a client's description. Unlike the nickname or the away state, this is not * a {@code clientupdate} property even for ourselves: the server only takes it * through {@code clientedit}, gated by {@code b_client_modify_own_description}. - * - * @param callback given {@code null} on success, or the failure message */ - public void setClientDescription(int clientId, String description, Consumer callback) { + public CompletableFuture setClientDescription(int clientId, String description) { boolean self = clientId == selfClientId; - run((ignored, error) -> callback.accept(error), () -> { + return requestVoid(() -> { SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT); cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); cmd.add(new CommandSingleParameter("client_description", description)); @@ -1231,45 +1222,36 @@ public final class TeamspeakConnection implements TS3Listener { if (e != null) e.description = description; ui.onInfoUpdated(); } - return null; }); } // ---- privilege keys ---- - /** Reads the server's privilege keys, delivering them (or a failure message) off the UI thread. */ - public void requestPrivilegeKeys(BiConsumer, String> callback) { - run(callback, privilegeKeys::list); + /** Reads the server's privilege keys. */ + public CompletableFuture> requestPrivilegeKeys() { + return request(privilegeKeys::list); } /** * Creates a privilege key for a server group, or for a channel group in {@code channelId}. * - * @param callback given the new key, or the failure message + * @return the new key */ - public void addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description, - BiConsumer callback) { - run(callback, () -> privilegeKeys.add(channelGroup, groupId, channelId, description)); + public CompletableFuture addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) { + return request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description)); } /** * Deletes privilege keys one by one, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message */ - public void deletePrivilegeKeys(Collection tokens, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture deletePrivilegeKeys(Collection tokens) { + return requestVoid(() -> { for (String token : tokens) privilegeKeys.delete(token); - return null; }); } - /** @param callback given {@code null} on success, or the failure message */ - public void usePrivilegeKey(String token, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - privilegeKeys.use(token); - return null; - }); + public CompletableFuture usePrivilegeKey(String token) { + return requestVoid(() -> privilegeKeys.use(token)); } // ---- complaints ---- @@ -1282,23 +1264,19 @@ public final class TeamspeakConnection implements TS3Listener { }); } - /** Reads the server's complaints, delivering them (or a failure message) off the UI thread. */ - public void requestComplaints(BiConsumer, String> callback) { - run(callback, complaints::list); + /** Reads the server's complaints. */ + public CompletableFuture> requestComplaints() { + return request(complaints::list); } /** * Removes every complaint about each of {@code targetDbIds}, then each of {@code single}, * stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message */ - public void deleteComplaints(Collection targetDbIds, Collection single, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture deleteComplaints(Collection targetDbIds, Collection single) { + return requestVoid(() -> { for (int target : targetDbIds) complaints.deleteAll(target); for (Complaint complaint : single) complaints.delete(complaint); - return null; }); } @@ -1325,117 +1303,89 @@ public final class TeamspeakConnection implements TS3Listener { ui.onUnreadMessagesChanged(unread); } - /** Lists our offline message inbox, delivering it (or a failure message) off the UI thread. */ - public void requestOfflineMessages(BiConsumer, String> callback) { - run(callback, offlineMessages::list); + /** Lists our offline message inbox. */ + public CompletableFuture> requestOfflineMessages() { + return request(offlineMessages::list); } - /** Reads a message's body, delivering it (or a failure message) off the UI thread. */ - public void requestOfflineMessageBody(int messageId, BiConsumer callback) { - run(callback, () -> offlineMessages.body(messageId)); + /** Reads a message's body. */ + public CompletableFuture requestOfflineMessageBody(int messageId) { + return request(() -> offlineMessages.body(messageId)); } /** * Marks messages read or unread, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message */ - public void markOfflineMessages(Collection messageIds, boolean read, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture markOfflineMessages(Collection messageIds, boolean read) { + return requestVoid(() -> { for (int id : messageIds) offlineMessages.setRead(id, read); - return null; }); } - /** @param callback given {@code null} on success, or the failure message */ - public void deleteOfflineMessages(Collection messageIds, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture deleteOfflineMessages(Collection messageIds) { + return requestVoid(() -> { for (int id : messageIds) offlineMessages.delete(id); - return null; }); } /** * Sends one offline message to each recipient, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message */ - public void sendOfflineMessage(Collection recipientUids, String subject, String message, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture sendOfflineMessage(Collection recipientUids, String subject, String message) { + return requestVoid(() -> { for (String uid : recipientUids) offlineMessages.send(uid, subject, message); log("Offline message sent."); - return null; }); } - /** Looks a client up by unique id; delivers {@code null} when the server has never seen them. */ - public void lookupDatabaseClient(String uniqueId, BiConsumer callback) { - run(callback, () -> offlineMessages.lookupUid(uniqueId)); + /** 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))); } /** * Finds clients whose last nickname contains {@code nickname}. * - * @param callback given the matches, or {@link #SEARCH_NOT_PERMITTED} or another failure message + * A server that will not let us search refuses for lack of permission. */ - public void searchDatabaseClients(String nickname, BiConsumer, String> callback) { - run(callback, () -> { - try { - return offlineMessages.search(nickname); - } catch (CommandException e) { - if (isPermissionError(e)) throw new IllegalStateException(SEARCH_NOT_PERMITTED); - throw e; - } - }); + public CompletableFuture> searchDatabaseClients(String nickname) { + return request(() -> offlineMessages.search(nickname)); } // ---- server log ---- /** * Reads the server's newest log lines, or with {@code olderFrom} > 0 the ones before an - * earlier page's, delivering them (or a failure message) off the UI thread. + * earlier page's. */ - public void requestServerLog(long olderFrom, BiConsumer callback) { - run(callback, () -> serverLog.read(olderFrom)); + public CompletableFuture requestServerLog(long olderFrom) { + return request(() -> serverLog.read(olderFrom)); } // ---- bans ---- - /** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ - public void requestBanList(BiConsumer, String> callback) { - run(callback, bans::list); + /** Reads the server's ban list. */ + public CompletableFuture> requestBanList() { + return request(bans::list); } - /** @param callback given {@code null} on success, or the failure message */ - public void addBan(BanRule rule, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - bans.add(rule); - return null; - }); + public CompletableFuture addBan(BanRule rule) { + return requestVoid(() -> bans.add(rule)); } /** * Rewrites an existing ban. - * - * @param callback given {@code null} on success, or the failure message */ - public void replaceBan(int banId, BanRule rule, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - bans.replace(banId, rule); - return null; - }); + public CompletableFuture replaceBan(int banId, BanRule rule) { + return requestVoid(() -> bans.replace(banId, rule)); } /** * Deletes bans one by one, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message */ - public void deleteBans(Collection banIds, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + public CompletableFuture deleteBans(Collection banIds) { + return requestVoid(() -> { for (int id : banIds) bans.delete(id); - return null; }); } @@ -1533,33 +1483,28 @@ public final class TeamspeakConnection implements TS3Listener { // ---- channel administration ---- /** - * Reads a channel's editable properties, delivering them (or a failure message) to - * {@code callback} off the UI thread. + * Reads a channel's editable properties. */ - public void requestChannelSettings(int channelId, BiConsumer callback) { - run(callback, () -> channels.readSettings(channelId)); + public CompletableFuture requestChannelSettings(int channelId) { + return request(() -> channels.readSettings(channelId)); } /** * Reads the permissions set directly on a channel, as name/value pairs. Fails when the * server does not let us look at them. */ - public void requestChannelPermissions(int channelId, - BiConsumer, String> callback) { - run(callback, () -> channels.readPermissions(channelId)); + public CompletableFuture> requestChannelPermissions(int channelId) { + return request(() -> channels.readPermissions(channelId)); } /** * Applies an edited channel: its changed properties first, then its needed-power * permissions. - * - * @param callback given {@code null} on success, or the failure message */ - public void applyChannelEdit(int channelId, Map changes, + public CompletableFuture applyChannelEdit(int channelId, Map changes, Map setPermissions, - Collection removePermissions, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { + Collection removePermissions) { + return requestVoid(() -> { channels.edit(channelId, changes); channels.writePermissions(channelId, setPermissions, removePermissions); if (changes.containsKey("channel_description")) { @@ -1570,7 +1515,6 @@ public final class TeamspeakConnection implements TS3Listener { requestChannelInfo(channelId); } } - return null; }); } @@ -1578,20 +1522,18 @@ public final class TeamspeakConnection implements TS3Listener { * Creates a channel below {@code parentId} (0 being the top level) and gives it the * channel permissions it was created with. * - * @param callback given the new channel's id, or the failure message. A channel whose - * permissions could not be set still exists, and is reported as an error - * saying so. + * @return the new channel's id. A channel whose permissions could not be set still + * exists, and fails the request with a message saying so. */ - public void createChannel(int parentId, Map properties, - Map permissions, - BiConsumer callback) { - run(callback, () -> { + public CompletableFuture createChannel(int parentId, Map properties, + Map permissions) { + return request(() -> { int channelId = channels.create(parentId, properties); try { channels.writePermissions(channelId, permissions, List.of()); } catch (Exception e) { throw new IllegalStateException("The channel was created, but its permissions" - + " could not be set: " + rootMessage(e)); + + " could not be set: " + RequestException.rootMessage(e)); } return channelId; }); @@ -1599,32 +1541,24 @@ public final class TeamspeakConnection implements TS3Listener { /** * Deletes a channel; with {@code force}, also one that has sub-channels or clients in it. - * - * @param callback given {@code null} on success, or the failure message */ - public void deleteChannel(int channelId, boolean force, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - channels.delete(channelId, force); - return null; - }); + public CompletableFuture deleteChannel(int channelId, boolean force) { + return requestVoid(() -> channels.delete(channelId, force)); } /** The ids of the icons uploaded to this virtual server. */ - public void requestServerIcons(BiConsumer, String> callback) { - run(callback, channels::listIcons); + public CompletableFuture> requestServerIcons() { + return request(channels::listIcons); } /** Uploads an image as a server icon and reports the new icon's id. */ - public void uploadIcon(File source, BiConsumer callback) { - run(callback, () -> channels.uploadIcon(source)); + public CompletableFuture uploadIcon(File source) { + return request(() -> channels.uploadIcon(source)); } - /** Deletes a server icon; {@code callback} is given {@code null} on success. */ - public void deleteIcon(long iconId, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - channels.deleteIcon(iconId); - return null; - }); + /** 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. */ @@ -1666,27 +1600,42 @@ public final class TeamspeakConnection implements TS3Listener { } } + /** A request with no result. */ + private interface VoidJob { + void call() throws Exception; + } + /** - * Runs a blocking server request in the background and hands the result — or the - * failure message — to {@code callback}, which therefore never runs on the UI thread. + * 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 void run(BiConsumer callback, Job job) { + private CompletableFuture request(Job job) { + CompletableFuture result = new CompletableFuture<>(); ExecutorService pool = actions; if (pool == null || client == null || !connected) { - callback.accept(null, "Not connected"); - return; + result.completeExceptionally(RequestException.notConnected()); + return result; } try { pool.execute(() -> { try { - callback.accept(job.call(), null); + result.complete(job.call()); } catch (Exception e) { - callback.accept(null, connected ? rootMessage(e) : "Not connected"); + result.completeExceptionally(connected ? RequestException.of(e) : RequestException.notConnected()); } }); } catch (RejectedExecutionException e) { - callback.accept(null, "Not connected"); + 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}. */ @@ -1750,33 +1699,25 @@ public final class TeamspeakConnection implements TS3Listener { /** * Uploads an image as our avatar and publishes it to the other clients. - * - * @param callback given {@code null} on success, or the failure message */ - public void setAvatar(File source, Consumer callback) { - run((flag, error) -> { - if (error == null) updateSelf(self -> self.avatarFlag = flag); - callback.accept(error); - }, () -> avatarAdmin.upload(source)); + public CompletableFuture setAvatar(File source) { + return requestVoid(() -> { + String flag = avatarAdmin.upload(source); + updateSelf(self -> self.avatarFlag = flag); + }); } - /** Withdraws our avatar; {@code callback} is given {@code null} on success. */ - public void removeAvatar(Consumer callback) { - run((ignored, error) -> { - if (error == null) updateSelf(self -> self.avatarFlag = ""); - callback.accept(error); - }, () -> { + /** Withdraws our avatar. */ + public CompletableFuture removeAvatar() { + return requestVoid(() -> { avatarAdmin.remove(); - return null; + updateSelf(self -> self.avatarFlag = ""); }); } - /** Deletes another client's avatar; {@code callback} is given {@code null} on success. */ - public void removeAvatarOf(ClientEntry client, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - avatarAdmin.removeOther(client.uniqueId); - return null; - }); + /** Deletes another client's avatar. */ + public CompletableFuture removeAvatarOf(ClientEntry client) { + return requestVoid(() -> avatarAdmin.removeOther(client.uniqueId)); } /** Reads a client's avatar out of the virtual server's file repository (channel 0). */ @@ -1953,7 +1894,7 @@ public final class TeamspeakConnection implements TS3Listener { + " (" + serverHistory.size() + " server, " + channelHistory.size() + " channel)"); } catch (Exception e) { chatLogs = null; - ui.onStatus("Chat logs unavailable: " + rootMessage(e)); + ui.onStatus("Chat logs unavailable: " + RequestException.rootMessage(e)); } } @@ -1976,7 +1917,7 @@ public final class TeamspeakConnection implements TS3Listener { ui.onPrivateChatHistory(clientId, c != null ? c.nickname : "Client " + clientId, logs.privateHtmlHistory(uniqueId)); } catch (IOException e) { - ui.onStatus("Private chat log unavailable: " + rootMessage(e)); + ui.onStatus("Private chat log unavailable: " + RequestException.rootMessage(e)); } } @@ -1987,7 +1928,7 @@ public final class TeamspeakConnection implements TS3Listener { try { logs.appendMessage(toLogScope(scope), false, fromClientId, fromUniqueId, fromName, message); } catch (IOException e) { - ui.onStatus("Could not write chat log: " + rootMessage(e)); + ui.onStatus("Could not write chat log: " + RequestException.rootMessage(e)); } } @@ -2006,7 +1947,7 @@ public final class TeamspeakConnection implements TS3Listener { logs.appendMessage(toLogScope(scope), true, selfClientId, uid, name, message); } } catch (IOException e) { - ui.onStatus("Could not write chat log: " + rootMessage(e)); + ui.onStatus("Could not write chat log: " + RequestException.rootMessage(e)); } } @@ -2030,7 +1971,7 @@ public final class TeamspeakConnection implements TS3Listener { ui.onServerLogHtml(logs.appendServerEvent(message)); } catch (IOException e) { ui.onServerLog(message); - ui.onStatus("Could not write server log: " + rootMessage(e)); + ui.onStatus("Could not write server log: " + RequestException.rootMessage(e)); } } @@ -2089,23 +2030,10 @@ public final class TeamspeakConnection implements TS3Listener { /** Reports a failure to the UI and plays the matching server sound. */ private void error(String prefix, Exception e) { - sound(isPermissionError(e) + sound(RequestException.isPermissionError(e) ? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS : SoundEvent.SERVER_ERROR, serverVars()); - ui.onError(prefix + rootMessage(e)); - } - - /** Whether the server refused for lack of permission, wherever in the cause chain it said so. */ - static boolean isPermissionError(Throwable t) { - for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { - if (c instanceof CommandException ce) { - int id = ce.getErrorId(); - return id == ERROR_PERMISSIONS_CLIENT_INSUFFICIENT - || id == ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER - || id == ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER; - } - } - return false; + ui.onError(prefix + RequestException.rootMessage(e)); } /** Whether the client is in the channel we are in ourselves. Package-private: also @@ -2147,11 +2075,4 @@ public final class TeamspeakConnection implements TS3Listener { } return chain.length() > 0 ? chain.toString() : t.getClass().getSimpleName(); } - - private static String rootMessage(Throwable t) { - Throwable r = t; - while (r.getCause() != null && r.getCause() != r) r = r.getCause(); - String m = r.getMessage(); - return m != null ? m : r.getClass().getSimpleName(); - } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java index a1b6c42..e555043 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -12,7 +12,7 @@ import eu.lixko.ts3j.client.contacts.ContactStore; import eu.lixko.ts3j.client.net.ChannelNode; import eu.lixko.ts3j.client.net.ClientEntry; import eu.lixko.ts3j.client.net.ConnectionListener; -import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.Replies; import eu.lixko.ts3j.client.net.TeamspeakConnection; import eu.lixko.ts3j.client.net.Whisper; import eu.lixko.ts3j.client.recording.VoiceRecorder; @@ -804,8 +804,9 @@ public final class ServerSession { 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)); + Replies.handle(conn.usePrivilegeKey(link.token), Runnable::run, + () -> listener.onSystemMessage("Privilege key used."), + failure -> listener.onSystemMessage("Could not use the privilege key: " + failure.getMessage())); } private void checkServerIcon() { diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/RequestExceptionTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/RequestExceptionTest.java new file mode 100644 index 0000000..7f85790 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/RequestExceptionTest.java @@ -0,0 +1,44 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RequestExceptionTest { + + @Test + void permissionRefusalIsRecognisedByIdAnywhereInTheChain() { + Exception refused = new ExecutionException(new CommandException("insufficient client permissions", 0x0a08)); + RequestException failure = RequestException.of(refused); + assertTrue(failure.permissionDenied()); + assertEquals("insufficient client permissions", failure.getMessage()); + } + + @Test + void otherRefusalsAndFailuresAreJustFailures() { + assertEquals(RequestException.Kind.FAILED, + RequestException.of(new CommandException("invalid channelID", 0x0300)).kind()); + // Wording alone does not make a permission error. + assertEquals(RequestException.Kind.FAILED, RequestException.of(new IllegalStateException("no permission")).kind()); + } + + @Test + void aFutureHandsOverTheFailureItWasGiven() { + RequestException notConnected = RequestException.notConnected(); + assertSame(notConnected, RequestException.of(new CompletionException(notConnected))); + + AtomicReference seen = new AtomicReference<>(); + Replies.handle(CompletableFuture.failedFuture(notConnected).thenApply(String::trim), Runnable::run, + value -> { + }, seen::set); + assertSame(notConnected, seen.get()); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java index 04141f7..4062e84 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java @@ -6,12 +6,12 @@ import eu.lixko.ts3j.client.net.avatar.Avatar; import javax.swing.JFileChooser; import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.Component; import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.util.concurrent.CompletableFuture; /** Sets, takes and deletes our avatar on one server, reporting failures in a dialog. */ final class AvatarActions { @@ -36,7 +36,7 @@ final class AvatarActions { if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); lastDirectory = file.getParentFile(); - conn.setAvatar(file, error -> fail("Error uploading avatar: ", error)); + Edt.onFailure(conn.setAvatar(file), failure -> show("Error uploading avatar: " + failure.getMessage())); } /** Uploads someone else's avatar as ours. */ @@ -47,30 +47,26 @@ final class AvatarActions { file = Files.createTempFile("avatar", "." + avatar.format().extension).toFile(); Files.write(file.toPath(), avatar.data()); } catch (IOException e) { - fail("Error uploading avatar: ", e.getMessage()); + show("Error uploading avatar: " + e.getMessage()); return; } - conn.setAvatar(file, error -> { - file.delete(); - fail("Error uploading avatar: ", error); - }); + CompletableFuture upload = conn.setAvatar(file); + upload.whenComplete((ignored, failure) -> file.delete()); + Edt.onFailure(upload, failure -> show("Error uploading avatar: " + failure.getMessage())); } void delete() { if (!conn.isConnected()) return; - conn.removeAvatar(error -> fail("Error deleting avatar: ", error)); + Edt.onFailure(conn.removeAvatar(), failure -> show("Error deleting avatar: " + failure.getMessage())); } /** Deletes another client's avatar for everyone. */ void deleteOf(ClientEntry client) { if (!conn.isConnected()) return; - conn.removeAvatarOf(client, error -> fail("Error deleting avatar: ", error)); + Edt.onFailure(conn.removeAvatarOf(client), failure -> show("Error deleting avatar: " + failure.getMessage())); } - /** Shows {@code error}, if there is one; callable from any thread. */ - private void fail(String what, String error) { - if (error == null) return; - SwingUtilities.invokeLater(() -> - JOptionPane.showMessageDialog(owner, what + error, "Error", JOptionPane.ERROR_MESSAGE)); + private void show(String message) { + JOptionPane.showMessageDialog(owner, message, "Error", JOptionPane.ERROR_MESSAGE); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java index c5c4c10..0e78ddc 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java @@ -55,6 +55,7 @@ import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** @@ -373,26 +374,21 @@ final class BanListDialog extends JDialog { if (loading) return; loading = true; status.setText("Loading…"); - conn.requestBanList((bans, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestBanList(), bans -> { loading = false; if (!isDisplayable()) return; - if (error != null) { - tableModel.setBans(List.of()); - status.setText(isPermissionError(error) - ? "You have insufficient permissions to view the ban list." - : "Failed to request ban list: " + error); - updateButtons(); - return; - } tableModel.setBans(bans); status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); updateButtons(); - })); - } - - private static boolean isPermissionError(String message) { - String m = message.toLowerCase(Locale.ROOT); - return m.contains("insufficient") || m.contains("permission"); + }, failure -> { + loading = false; + if (!isDisplayable()) return; + tableModel.setBans(List.of()); + status.setText(failure.permissionDenied() + ? "You have insufficient permissions to view the ban list." + : "Failed to request ban list: " + failure.getMessage()); + updateButtons(); + }); } private void applyFilter() { @@ -448,9 +444,9 @@ final class BanListDialog extends JDialog { dialog.setVisible(true); BanRule rule = dialog.getRule(); if (rule == null) return; - conn.addBan(rule, error -> afterChange(error, "Error adding ban: ", + afterChange(conn.addBan(rule), "Error adding ban: ", () -> JOptionPane.showMessageDialog(this, "Your ban was successfully added.", "Ban List", - JOptionPane.INFORMATION_MESSAGE))); + JOptionPane.INFORMATION_MESSAGE)); } private void editBan() { @@ -460,7 +456,7 @@ final class BanListDialog extends JDialog { dialog.setVisible(true); BanRule rule = dialog.getRule(); if (rule == null) return; - conn.replaceBan(ban.id, rule, error -> afterChange(error, "Error editing ban: ", null)); + afterChange(conn.replaceBan(ban.id, rule), "Error editing ban: "); } private void removeBans() { @@ -470,18 +466,23 @@ final class BanListDialog extends JDialog { "Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List ids = bans.stream().map(b -> b.id).collect(Collectors.toList()); - conn.deleteBans(ids, error -> afterChange(error, "Error deleting ban: ", null)); + afterChange(conn.deleteBans(ids), "Error deleting ban: "); } /** Reports a failed change, or re-reads the list so the table shows what the server now holds. */ - private void afterChange(String error, String errorPrefix, Runnable onSuccess) { - SwingUtilities.invokeLater(() -> { + private void afterChange(CompletableFuture change, String errorPrefix) { + afterChange(change, errorPrefix, () -> { + }); + } + + private void afterChange(CompletableFuture change, String errorPrefix, Runnable onSuccess) { + Edt.handle(change, () -> { if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, errorPrefix + error, "Ban List", JOptionPane.ERROR_MESSAGE); - } else if (onSuccess != null) { - onSuccess.run(); - } + onSuccess.run(); + reload(); + }, failure -> { + if (!isDisplayable()) return; + JOptionPane.showMessageDialog(this, errorPrefix + failure.getMessage(), "Ban List", JOptionPane.ERROR_MESSAGE); reload(); }); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java index 3ed3ad0..bd67ec8 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java @@ -19,7 +19,6 @@ import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; -import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; @@ -33,6 +32,7 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * TeamSpeak's channel editor: the channel's name, icon, password, topic and description @@ -286,19 +286,13 @@ final class ChannelDialog extends JDialog { // ---- loading ---- private void load() { - conn.requestChannelSettings(channel.id, (settings, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(this, "Could not read the channel: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - dispose(); - return; - } - apply(settings); - })); - conn.requestChannelPermissions(channel.id, (permissions, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) permissionsPanel.showUnavailable("No permission to view channel permissions."); - else permissionsPanel.read(permissions); - })); + Edt.handle(conn.requestChannelSettings(channel.id), this::apply, failure -> { + JOptionPane.showMessageDialog(this, "Could not read the channel: " + failure.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + dispose(); + }); + Edt.handle(conn.requestChannelPermissions(channel.id), permissionsPanel::read, + failure -> permissionsPanel.showUnavailable("No permission to view channel permissions.")); } /** @@ -403,9 +397,8 @@ final class ChannelDialog extends JDialog { if (channel == null) { ok.setEnabled(false); - conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed(), - (channelId, error) -> SwingUtilities.invokeLater( - () -> finish(error, "Could not create the channel: "))); + finish(conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed()), + "Could not create the channel: "); return; } @@ -418,17 +411,15 @@ final class ChannelDialog extends JDialog { } ok.setEnabled(false); - conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions, - error -> SwingUtilities.invokeLater(() -> finish(error, "Could not save the channel: "))); + finish(conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions), + "Could not save the channel: "); } /** Closes the dialog, or reports why the server would not have it and lets the user retry. */ - private void finish(String error, String errorPrefix) { - if (error == null) { - dispose(); - return; - } - ok.setEnabled(true); - JOptionPane.showMessageDialog(this, errorPrefix + error, "Error", JOptionPane.ERROR_MESSAGE); + private void finish(CompletableFuture request, String errorPrefix) { + Edt.handle(request, ignored -> dispose(), failure -> { + ok.setEnabled(true); + JOptionPane.showMessageDialog(this, errorPrefix + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + }); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java index 9fc86e1..b49aaf0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java @@ -256,17 +256,17 @@ final class ComplaintsDialog extends JDialog { if (loading) return; loading = true; status.setText("Loading…"); - conn.requestComplaints((complaints, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestComplaints(), complaints -> { loading = false; if (!isDisplayable()) return; - if (error != null) { - setTargets(List.of()); - status.setText("Failed to request complaint list: " + error); - } else { - setTargets(groupByTarget(complaints)); - status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); - } - })); + setTargets(groupByTarget(complaints)); + status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); + }, failure -> { + loading = false; + if (!isDisplayable()) return; + setTargets(List.of()); + status.setText("Failed to request complaint list: " + failure.getMessage()); + }); } private static List groupByTarget(List complaints) { @@ -384,14 +384,14 @@ final class ComplaintsDialog extends JDialog { JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List whole = sel.whole().stream().map(Target::dbId).toList(); - conn.deleteComplaints(whole, sel.single(), error -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.deleteComplaints(whole, sel.single()), () -> { + if (isDisplayable()) reload(); + }, failure -> { if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - } + JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + failure.getMessage(), getTitle(), + JOptionPane.ERROR_MESSAGE); reload(); - })); + }); } private void banSelected() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Edt.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Edt.java new file mode 100644 index 0000000..c7584c4 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Edt.java @@ -0,0 +1,27 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.Replies; +import eu.lixko.ts3j.client.net.RequestException; + +import javax.swing.SwingUtilities; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +/** {@link Replies} on the event dispatch thread. */ +final class Edt { + + private Edt() { + } + + static void handle(CompletableFuture request, Consumer onSuccess, Consumer onFailure) { + Replies.handle(request, SwingUtilities::invokeLater, onSuccess, onFailure); + } + + static void handle(CompletableFuture request, Runnable onSuccess, Consumer onFailure) { + Replies.handle(request, SwingUtilities::invokeLater, onSuccess, onFailure); + } + + static void onFailure(CompletableFuture request, Consumer onFailure) { + Replies.onFailure(request, SwingUtilities::invokeLater, onFailure); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java index 6555b51..a3a2be2 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java @@ -18,7 +18,6 @@ import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.BorderLayout; @@ -179,15 +178,11 @@ final class IconChooserDialog extends JDialog { private void loadRemoteIcons() { status.setText("Loading icons…"); - conn.requestServerIcons((ids, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - status.setText("Could not list the server's icons: " + error); - return; - } + Edt.handle(conn.requestServerIcons(), ids -> { status.setText(" "); remoteModel.clear(); for (Long id : ids) remoteModel.addElement(id); - })); + }, failure -> status.setText("Could not list the server's icons: " + failure.getMessage())); } private void uploadIcon() { @@ -197,16 +192,14 @@ final class IconChooserDialog extends JDialog { if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); status.setText("Uploading " + file.getName() + "…"); - conn.uploadIcon(file, (iconId, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - status.setText(" "); - JOptionPane.showMessageDialog(this, "Error uploading icon: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } + Edt.handle(conn.uploadIcon(file), iconId -> { loadRemoteIcons(); startRefreshing(); - })); + }, failure -> { + status.setText(" "); + JOptionPane.showMessageDialog(this, "Error uploading icon: " + failure.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + }); } private void deleteSelectedIcon() { @@ -216,14 +209,9 @@ final class IconChooserDialog extends JDialog { "Permanently delete this icon from the server?", "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; - conn.deleteIcon(id, error -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } - remoteModel.removeElement(id); - })); + Edt.handle(conn.deleteIcon(id), () -> remoteModel.removeElement(id), + failure -> JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + failure.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE)); } /** diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java index 7000e9b..ca5f6c6 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java @@ -54,6 +54,7 @@ import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.regex.Pattern; /** @@ -361,11 +362,10 @@ final class OfflineMessageComposeDialog extends JDialog { String typed = recipientField.getText().trim(); if (typed.isEmpty()) return; if (UNIQUE_ID.matcher(typed).matches()) { - conn.lookupDatabaseClient(typed, (client, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) showRecipientError(error); - else if (client == null) showRecipientError("The unique ID is unknown on this server."); - else accept(client); - })); + Edt.handle(conn.lookupDatabaseClient(typed), + client -> client.ifPresentOrElse(this::accept, + () -> showRecipientError("The unique ID is unknown on this server.")), + failure -> showRecipientError(failure.getMessage())); return; } for (int i = 0; i < available.size(); i++) { @@ -374,18 +374,18 @@ final class OfflineMessageComposeDialog extends JDialog { return; } } - conn.searchDatabaseClients(typed, (found, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - showRecipientError(error); - } else if (found.isEmpty()) { + Edt.handle(conn.searchDatabaseClients(typed), found -> { + if (found.isEmpty()) { showRecipientError("The nickname is unknown on this server."); - } else { - offer(found); - DatabaseClient exact = found.stream().filter(c -> c.nickname().equalsIgnoreCase(typed)) - .findFirst().orElse(found.size() == 1 ? found.get(0) : null); - if (exact != null) accept(exact); + return; } - })); + offer(found); + found.stream().filter(c -> c.nickname().equalsIgnoreCase(typed)).findFirst() + .or(() -> found.size() == 1 ? Optional.of(found.get(0)) : Optional.empty()) + .ifPresent(this::accept); + }, failure -> showRecipientError(failure.permissionDenied() + ? "You have no permission to search for users on this server, so you can only use contacts or unique IDs." + : failure.getMessage())); } private void accept(DatabaseClient client) { @@ -431,18 +431,17 @@ final class OfflineMessageComposeDialog extends JDialog { if (!sendButton.isEnabled()) return; sending = true; updateSendButton(); - conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText(), - error -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText()), + () -> { + sending = false; + if (isDisplayable()) dispose(); + }, failure -> { sending = false; if (!isDisplayable()) return; - if (error == null) { - dispose(); - return; - } updateSendButton(); - JOptionPane.showMessageDialog(this, "Failed to send offline message: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - })); + JOptionPane.showMessageDialog(this, "Failed to send offline message: " + failure.getMessage(), + getTitle(), JOptionPane.ERROR_MESSAGE); + }); } private void cancel() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java index e5d22c7..9d813d4 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java @@ -27,7 +27,6 @@ import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.RowSorter; import javax.swing.SortOrder; -import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.HyperlinkEvent; import javax.swing.event.PopupMenuEvent; @@ -328,16 +327,15 @@ final class OfflineMessagesDialog extends JDialog { if (loading) return; loading = true; status.setText("Loading…"); - conn.requestOfflineMessages((messages, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestOfflineMessages(), messages -> { loading = false; if (!isDisplayable()) return; - if (error != null) { - status.setText("Failed to list offline messages: " + error); - return; - } setMessages(messages); status.setText(messages.isEmpty() ? "No messages" : " "); - })); + }, failure -> { + loading = false; + if (isDisplayable()) status.setText("Failed to list offline messages: " + failure.getMessage()); + }); } private void setMessages(List messages) { @@ -390,15 +388,15 @@ final class OfflineMessagesDialog extends JDialog { return; } bodyPane.setText(""); - conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> { if (!isDisplayable()) return; - if (error != null) { - if (shownId == message.id()) status.setText("Failed to get offline message: " + error); - return; - } bodies.put(message.id(), text); if (shownId == message.id()) showBody(message, text); - })); + }, failure -> { + if (isDisplayable() && shownId == message.id()) { + status.setText("Failed to get offline message: " + failure.getMessage()); + } + }); } private void showBody(OfflineMessage message, String body) { @@ -421,15 +419,13 @@ final class OfflineMessagesDialog extends JDialog { composer.reply(message, body); return; } - conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> { if (!isDisplayable()) return; - if (error != null) { - status.setText("Failed to get offline message: " + error); - return; - } bodies.put(message.id(), text); composer.reply(message, text); - })); + }, failure -> { + if (isDisplayable()) status.setText("Failed to get offline message: " + failure.getMessage()); + }); } private void markSelected(boolean read) { @@ -440,12 +436,11 @@ final class OfflineMessagesDialog extends JDialog { private void mark(List messages, boolean read) { if (messages.isEmpty()) return; for (OfflineMessage m : messages) tableModel.replace(m.withRead(read)); - conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read, - error -> SwingUtilities.invokeLater(() -> { - if (error == null || !isDisplayable()) return; - status.setText("Failed to update offline message: " + error); - reload(); - })); + Edt.onFailure(conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read), failure -> { + if (!isDisplayable()) return; + status.setText("Failed to update offline message: " + failure.getMessage()); + reload(); + }); } private void deleteSelected() { @@ -461,16 +456,18 @@ final class OfflineMessagesDialog extends JDialog { JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; } - conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList(), - error -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + error, - getTitle(), JOptionPane.ERROR_MESSAGE); - } - for (OfflineMessage m : selected) bodies.remove(m.id()); - reload(); - })); + Runnable deleted = () -> { + for (OfflineMessage m : selected) bodies.remove(m.id()); + reload(); + }; + Edt.handle(conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList()), () -> { + if (isDisplayable()) deleted.run(); + }, failure -> { + if (!isDisplayable()) return; + JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + failure.getMessage(), + getTitle(), JOptionPane.ERROR_MESSAGE); + deleted.run(); + }); } private static String subjectOrPlaceholder(OfflineMessage m) { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java index adeba13..2883767 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java @@ -19,7 +19,6 @@ import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; -import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; @@ -149,20 +148,20 @@ final class PrivilegeKeyCreateDialog extends JDialog { Group group = (Group) groupBox.getSelectedItem(); ChannelNode channel = (ChannelNode) channelBox.getSelectedItem(); create.setEnabled(false); - conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id, - descriptionField.getText().trim(), (key, error) -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - updateCreate(); - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + error, - getTitle(), JOptionPane.ERROR_MESSAGE); - return; - } - keyField.setText(key); - keyField.selectAll(); - keyField.requestFocusInWindow(); - copy.setEnabled(true); - onCreated.run(); - })); + Edt.handle(conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id, + descriptionField.getText().trim()), key -> { + if (!isDisplayable()) return; + updateCreate(); + keyField.setText(key); + keyField.selectAll(); + keyField.requestFocusInWindow(); + copy.setEnabled(true); + onCreated.run(); + }, failure -> { + if (!isDisplayable()) return; + updateCreate(); + JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + failure.getMessage(), + getTitle(), JOptionPane.ERROR_MESSAGE); + }); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java index 5768d36..5e97049 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java @@ -22,7 +22,6 @@ import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableRowSorter; @@ -213,18 +212,19 @@ final class PrivilegeKeysDialog extends JDialog { if (loading) return; loading = true; status.setText("Loading…"); - conn.requestPrivilegeKeys((keys, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestPrivilegeKeys(), keys -> { loading = false; if (!isDisplayable()) return; - if (error != null) { - tableModel.setKeys(List.of()); - status.setText("Failed to request Privilege Key list: " + error); - } else { - tableModel.setKeys(keys); - status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); - } + tableModel.setKeys(keys); + status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); updateButtons(); - })); + }, failure -> { + loading = false; + if (!isDisplayable()) return; + tableModel.setKeys(List.of()); + status.setText("Failed to request Privilege Key list: " + failure.getMessage()); + updateButtons(); + }); } private List selectedKeys() { @@ -252,14 +252,14 @@ final class PrivilegeKeysDialog extends JDialog { "Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList()); - conn.deletePrivilegeKeys(tokens, error -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.deletePrivilegeKeys(tokens), () -> { + if (isDisplayable()) reload(); + }, failure -> { if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - } + JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + failure.getMessage(), getTitle(), + JOptionPane.ERROR_MESSAGE); reload(); - })); + }); } private void copyKeys() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java index 26ef921..031a8f3 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java @@ -5,6 +5,7 @@ import com.formdev.flatlaf.util.UIScale; import eu.lixko.ts3j.client.config.ServerLogSettings; import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.RequestException; import eu.lixko.ts3j.client.net.ServerLogEntry; import eu.lixko.ts3j.client.net.ServerLogEntry.Level; import eu.lixko.ts3j.client.net.ServerLogPage; @@ -263,16 +264,15 @@ final class ServerLogDialog extends JDialog { loading = true; olderButton.setEnabled(false); showStatus("Loading…", Theme.chatEvent()); - conn.requestServerLog(from, (page, error) -> SwingUtilities.invokeLater(() -> { + Edt.handle(conn.requestServerLog(from), page -> { + loading = false; + if (isDisplayable()) received(page, from > 0); + }, failure -> { loading = false; if (!isDisplayable()) return; - if (error != null) { - failed(error); - olderButton.setEnabled(olderFrom > 0); - return; - } - received(page, from > 0); - })); + failed(failure); + olderButton.setEnabled(olderFrom > 0); + }); } private void received(ServerLogPage page, boolean older) { @@ -284,10 +284,10 @@ final class ServerLogDialog extends JDialog { if (older) log.setCaretPosition(0); } - private void failed(String error) { - showStatus(error.toLowerCase(Locale.ROOT).contains("insufficient") + private void failed(RequestException failure) { + showStatus(failure.permissionDenied() ? "Insufficient permissions to view Server Log" - : "Error requesting server log: " + error, + : "Error requesting server log: " + failure.getMessage(), Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index 6608208..da33246 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -19,7 +19,6 @@ import eu.lixko.ts3j.client.text.TsLink; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JSplitPane; -import javax.swing.SwingUtilities; import java.awt.Component; import java.awt.Window; @@ -255,11 +254,8 @@ final class ServerTab { String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key", JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null); if (key == null || key.isBlank()) return; - conn.usePrivilegeKey(key.trim(), error -> { - if (error == null) return; - SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, error, - "Error using Privilege Key", JOptionPane.ERROR_MESSAGE)); - }); + Edt.onFailure(conn.usePrivilegeKey(key.trim()), failure -> JOptionPane.showMessageDialog(host, + failure.getMessage(), "Error using Privilege Key", JOptionPane.ERROR_MESSAGE)); } /** Opens the server's privilege keys, or brings the already open window forward. */ diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java index f278dd9..6edd2ac 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java @@ -10,7 +10,6 @@ import eu.lixko.ts3j.client.net.TeamspeakConnection; import eu.lixko.ts3j.client.text.TsLink; import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; import java.awt.Component; import java.util.ArrayList; import java.util.List; @@ -251,23 +250,15 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { @Override public void changeClientDescription(ClientEntry client) { if (!conn.isConnected()) return; - conn.requestClientDescription(client.id, (description, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(host, "Could not read the description: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } + Edt.handle(conn.requestClientDescription(client.id), description -> { String edited = (String) JOptionPane.showInputDialog(host, "Description for " + client.nickname + ":", "Change Description", JOptionPane.PLAIN_MESSAGE, Icons.of("EDIT"), null, description); if (edited == null || edited.equals(description)) return; - conn.setClientDescription(client.id, edited, failure -> SwingUtilities.invokeLater(() -> { - if (failure != null) { - JOptionPane.showMessageDialog(host, "Could not change the description: " + failure, - "Error", JOptionPane.ERROR_MESSAGE); - } - })); - })); + Edt.onFailure(conn.setClientDescription(client.id, edited), failure -> JOptionPane.showMessageDialog(host, + "Could not change the description: " + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE)); + }, failure -> JOptionPane.showMessageDialog(host, "Could not read the description: " + failure.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE)); } @Override @@ -323,10 +314,8 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) { return; } - conn.deleteChannel(channel.id, true, error -> { - if (error != null) SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, - "Could not delete the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE)); - }); + Edt.onFailure(conn.deleteChannel(channel.id, true), failure -> JOptionPane.showMessageDialog(host, + "Could not delete the channel: " + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE)); } @Override