Requests return futures that fail with a typed RequestException

Server requests on TeamspeakConnection took callbacks given a value and an
error string, null on success, so frontends told a permission refusal from
other failures by the message's wording (ban list, server log) and core
needed a sentinel message for a refused search. They now return a
CompletableFuture that fails with a RequestException carrying the kind
(not connected, permission, failed) and the server's reason.

Replies hands the outcome to a success or a failure handler on a given
executor; Swing's Edt runs them on the event thread, so call sites no
longer marshal by hand. Android's ServerController, whose suspend calls
answered a String? that was null once done, returns Result instead.
lookupDatabaseClient answers an Optional rather than null.

Starts the structural audit in AUDIT-STRUCTURE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 16:25:07 +00:00
co-authored by Claude Opus 5.5
parent 985c54a362
commit 0552ed8be6
27 changed files with 566 additions and 480 deletions
@@ -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 <T> CompletableFuture<T>.result(): Result<T> =
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<Void>.done(): Result<Unit> = result().map { }
@@ -10,6 +10,7 @@ import eu.lixko.ts3j.client.net.ChannelSettings
import eu.lixko.ts3j.client.net.ConnectionStats import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.Details import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.net.GroupChoice 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.Whisper
import eu.lixko.ts3j.client.net.ban.BanEntry import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanRule 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) if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId)
/** A channel's editable properties as the server has them. */ /** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = suspendCoroutine { done -> suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = conn.requestChannelSettings(channelId).result()
conn.requestChannelSettings(channelId) { settings, error ->
done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */ suspend fun editChannel(channelId: Int, changes: Map<String, String>): Result<Unit> =
suspend fun editChannel(channelId: Int, changes: Map<String, String>): String? = if (changes.isEmpty()) Result.success(Unit)
if (changes.isEmpty()) null else conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()).done()
else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } }
suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done -> suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result<Unit> =
conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) } conn.createChannel(parentId, settings.creationParameters(), emptyMap()).result().map { }
}
/** Deletes a channel, with its sub-channels and the clients in it moved out. */ /** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): String? = suspend fun deleteChannel(channelId: Int): Result<Unit> = conn.deleteChannel(channelId, true).done()
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
// ---- files ---- // ---- files ----
@@ -276,19 +270,16 @@ class ServerController internal constructor(
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> = suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } } 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): Result<Unit> =
suspend fun createDirectory(channelId: Int, password: String, path: String): String? =
fileCall { conn.createDirectory(channelId, password, path) } 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<Unit> =
fileCall { conn.deleteFile(channelId, password, path) } 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<Unit> =
fileCall { conn.renameFile(channelId, password, from, to) } fileCall { conn.renameFile(channelId, password, from, to) }
private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) { private suspend fun fileCall(call: () -> Unit): Result<Unit> = withContext(Dispatchers.IO) { runCatching(call) }
runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName }
}
// ---- moderation ---- // ---- moderation ----
@@ -340,26 +331,19 @@ class ServerController internal constructor(
// ---- ban list ---- // ---- 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. */ /** One reading of a client's connection figures, or null when not connected. */
suspend fun connectionStats(clientId: Int): ConnectionStats? = suspend fun connectionStats(clientId: Int): ConnectionStats? =
if (!session.isConnected) null if (!session.isConnected) null
else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } }
suspend fun banList(): Result<List<BanEntry>> = suspendCoroutine { done -> /** The server's bans, or why they could not be read. */
conn.requestBanList { bans, error -> suspend fun banList(): Result<List<BanEntry>> = conn.requestBanList().result()
done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */ suspend fun addBan(rule: BanRule): Result<Unit> = conn.addBan(rule).done()
suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } }
suspend fun replaceBan(banId: Int, rule: BanRule): String? = suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = conn.replaceBan(banId, rule).done()
suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } }
suspend fun deleteBans(banIds: Collection<Int>): String? = suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = conn.deleteBans(banIds).done()
suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } }
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId)
@@ -367,14 +351,14 @@ class ServerController internal constructor(
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId)
/** Uploads [data] as our avatar; null once it is set, else why not. */ /** Uploads [data] as our avatar. */
suspend fun setAvatar(data: ByteArray): String? { suspend fun setAvatar(data: ByteArray): Result<Unit> {
if (!session.isConnected) return "Not connected" if (!session.isConnected) return Result.failure(RequestException.notConnected())
val file = withContext(Dispatchers.IO) { val file = withContext(Dispatchers.IO) {
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) } File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) }
} }
return try { return try {
suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } } conn.setAvatar(file).done()
} finally { } finally {
file.delete() file.delete()
} }
@@ -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. */ /** 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<Unit>, failure: String ->
scope.launch { scope.launch {
val error = action() action().onFailure { snackbar.showSnackbar("$failure: ${it.message}") }
if (error != null) snackbar.showSnackbar("$failure: $error")
generation++ generation++
} }
Unit Unit
@@ -83,11 +83,12 @@ fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () ->
saving = true saving = true
scope.launch { scope.launch {
val trimmed = e.copy().apply { name = name.trim() } 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)) else server.editChannel(edit.channelId, trimmed.changesFrom(o))
saving = false saving = false
if (error == null) onDone() saved.onSuccess { onDone() }.onFailure {
else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error) snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + it.message)
}
} }
} }
@@ -78,10 +78,9 @@ fun FilesScreen(server: ServerController, channelId: Int, channelName: String, p
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ } LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
val act = { call: suspend () -> String? -> val act = { call: suspend () -> Result<Unit> ->
scope.launch { scope.launch {
val error = call() call().onSuccess { reloads++ }.onFailure { snackbar.showSnackbar(it.message ?: it.javaClass.simpleName) }
if (error != null) snackbar.showSnackbar(error) else reloads++
} }
Unit Unit
} }
@@ -79,8 +79,8 @@ fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit)
PictureViewer( PictureViewer(
picture, picture,
onSteal = if (picture.ownAvatar) null else { data -> onSteal = if (picture.ownAvatar) null else { data ->
val error = server.setAvatar(data) val message = server.setAvatar(data).fold({ "Avatar set." }, { it.message })
Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show() Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}, },
onDismiss = { viewed = null }, onDismiss = { viewed = null },
) )
@@ -551,7 +551,7 @@ fun ServerScreen(
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
deletingChannel = null 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") } }) { Text("Delete") }
}, },
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } }, dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
+24
View File
@@ -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 |
+1
View File
@@ -2,6 +2,7 @@
First audit: 2026-09-11. Revisited and worked through: 2026-09-25. Every finding below was 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. 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, 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 6 swing), on Java 25 and 26. The Android release build (R8 over core and ts3j) passes. The
@@ -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 <T> void handle(CompletableFuture<T> request, Executor executor,
Consumer<T> onSuccess, Consumer<RequestException> 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<Void> request, Executor executor,
Runnable onSuccess, Consumer<RequestException> 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<RequestException> onFailure) {
handle(request, executor, ignored -> {
}, onFailure);
}
}
@@ -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();
}
}
@@ -45,13 +45,12 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer; 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. */ /** 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_SUBJECT_LIMIT = 200;
public static final int OFFLINE_MESSAGE_LIMIT = 4096; 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 <b>clientkick</b>. */ /** The protocol's reason ids for the two flavours of <b>clientkick</b>. */
private static final int REASON_KICK_CHANNEL = 4; 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_CONNECTION_LOST = 3;
private static final int REASON_SERVER_SHUTDOWN = 11; 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. */ /** Shortest gap between two "you are talking while muted" reminders. */
private static final long MUTED_TALK_COOLDOWN_NANOS = 5_000_000_000L; 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(); if (microphoneActive) mic.start();
else mic.stop(); else mic.stop();
} catch (Exception e) { } catch (Exception e) {
ui.onError("Microphone unavailable: " + rootMessage(e)); ui.onError("Microphone unavailable: " + RequestException.rootMessage(e));
} }
pushInputHardware(); pushInputHardware();
} }
@@ -474,7 +467,7 @@ public final class TeamspeakConnection implements TS3Listener {
if (connectAttempt != attempt) return; if (connectAttempt != attempt) return;
connected = false; connected = false;
connectErrorId = refusalId(e); connectErrorId = refusalId(e);
String failure = "Connection failed: " + rootMessage(e) + versionHint(e); String failure = "Connection failed: " + RequestException.rootMessage(e) + versionHint(e);
ui.onError(failure); ui.onError(failure);
safeCleanup(); safeCleanup();
// Report the failed attempt as a disconnect too, so the UI leaves the // 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) { private String versionHint(Exception e) {
if (!settings.customVersion) return ""; if (!settings.customVersion) return "";
String message = rootMessage(e); String message = RequestException.rootMessage(e);
return message != null && message.contains("client is modified") return message != null && message.contains("client is modified")
? " — the server did not accept the custom client version; pick a newer one" ? " — the server did not accept the custom client version; pick a newer one"
+ " of the listed versions in Options." + " of the listed versions in Options."
@@ -602,7 +595,7 @@ public final class TeamspeakConnection implements TS3Listener {
try { try {
client.subscribeAll(); client.subscribeAll();
} catch (Exception e) { } 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. // The name comes with initserver; servergetvariables never reports it.
model.setServerName(client.getServerName()); 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 * 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. * live text instead of whatever an earlier info request cached.
*/ */
public void requestClientDescription(int clientId, BiConsumer<String, String> callback) { public CompletableFuture<String> requestClientDescription(int clientId) {
run(callback, () -> { return request(() -> {
Client c = socket().getClientInfo(clientId); Client c = socket().getClientInfo(clientId);
String description = c == null ? "" : orEmpty(c.get("client_description")); String description = c == null ? "" : orEmpty(c.get("client_description"));
ClientEntry e = model.getClient(clientId); 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 * 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 * a {@code clientupdate} property even for ourselves: the server only takes it
* through {@code clientedit}, gated by {@code b_client_modify_own_description}. * 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<String> callback) { public CompletableFuture<Void> setClientDescription(int clientId, String description) {
boolean self = clientId == selfClientId; boolean self = clientId == selfClientId;
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> {
SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT); SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId)));
cmd.add(new CommandSingleParameter("client_description", description)); cmd.add(new CommandSingleParameter("client_description", description));
@@ -1231,45 +1222,36 @@ public final class TeamspeakConnection implements TS3Listener {
if (e != null) e.description = description; if (e != null) e.description = description;
ui.onInfoUpdated(); ui.onInfoUpdated();
} }
return null;
}); });
} }
// ---- privilege keys ---- // ---- privilege keys ----
/** Reads the server's privilege keys, delivering them (or a failure message) off the UI thread. */ /** Reads the server's privilege keys. */
public void requestPrivilegeKeys(BiConsumer<List<PrivilegeKey>, String> callback) { public CompletableFuture<List<PrivilegeKey>> requestPrivilegeKeys() {
run(callback, privilegeKeys::list); return request(privilegeKeys::list);
} }
/** /**
* Creates a privilege key for a server group, or for a channel group in {@code channelId}. * 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, public CompletableFuture<String> addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) {
BiConsumer<String, String> callback) { return request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description));
run(callback, () -> privilegeKeys.add(channelGroup, groupId, channelId, description));
} }
/** /**
* Deletes privilege keys one by one, stopping at the first the server refuses. * 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<String> tokens, Consumer<String> callback) { public CompletableFuture<Void> deletePrivilegeKeys(Collection<String> tokens) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> {
for (String token : tokens) privilegeKeys.delete(token); for (String token : tokens) privilegeKeys.delete(token);
return null;
}); });
} }
/** @param callback given {@code null} on success, or the failure message */ public CompletableFuture<Void> usePrivilegeKey(String token) {
public void usePrivilegeKey(String token, Consumer<String> callback) { return requestVoid(() -> privilegeKeys.use(token));
run((ignored, error) -> callback.accept(error), () -> {
privilegeKeys.use(token);
return null;
});
} }
// ---- complaints ---- // ---- 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. */ /** Reads the server's complaints. */
public void requestComplaints(BiConsumer<List<Complaint>, String> callback) { public CompletableFuture<List<Complaint>> requestComplaints() {
run(callback, complaints::list); return request(complaints::list);
} }
/** /**
* Removes every complaint about each of {@code targetDbIds}, then each of {@code single}, * Removes every complaint about each of {@code targetDbIds}, then each of {@code single},
* stopping at the first the server refuses. * stopping at the first the server refuses.
*
* @param callback given {@code null} on success, or the failure message
*/ */
public void deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> single, public CompletableFuture<Void> deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> single) {
Consumer<String> callback) { return requestVoid(() -> {
run((ignored, error) -> callback.accept(error), () -> {
for (int target : targetDbIds) complaints.deleteAll(target); for (int target : targetDbIds) complaints.deleteAll(target);
for (Complaint complaint : single) complaints.delete(complaint); for (Complaint complaint : single) complaints.delete(complaint);
return null;
}); });
} }
@@ -1325,117 +1303,89 @@ public final class TeamspeakConnection implements TS3Listener {
ui.onUnreadMessagesChanged(unread); ui.onUnreadMessagesChanged(unread);
} }
/** Lists our offline message inbox, delivering it (or a failure message) off the UI thread. */ /** Lists our offline message inbox. */
public void requestOfflineMessages(BiConsumer<List<OfflineMessage>, String> callback) { public CompletableFuture<List<OfflineMessage>> requestOfflineMessages() {
run(callback, offlineMessages::list); return request(offlineMessages::list);
} }
/** Reads a message's body, delivering it (or a failure message) off the UI thread. */ /** Reads a message's body. */
public void requestOfflineMessageBody(int messageId, BiConsumer<String, String> callback) { public CompletableFuture<String> requestOfflineMessageBody(int messageId) {
run(callback, () -> offlineMessages.body(messageId)); return request(() -> offlineMessages.body(messageId));
} }
/** /**
* Marks messages read or unread, stopping at the first the server refuses. * 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<Integer> messageIds, boolean read, Consumer<String> callback) { public CompletableFuture<Void> markOfflineMessages(Collection<Integer> messageIds, boolean read) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> {
for (int id : messageIds) offlineMessages.setRead(id, read); for (int id : messageIds) offlineMessages.setRead(id, read);
return null;
}); });
} }
/** @param callback given {@code null} on success, or the failure message */ public CompletableFuture<Void> deleteOfflineMessages(Collection<Integer> messageIds) {
public void deleteOfflineMessages(Collection<Integer> messageIds, Consumer<String> callback) { return requestVoid(() -> {
run((ignored, error) -> callback.accept(error), () -> {
for (int id : messageIds) offlineMessages.delete(id); for (int id : messageIds) offlineMessages.delete(id);
return null;
}); });
} }
/** /**
* Sends one offline message to each recipient, stopping at the first the server refuses. * 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<String> recipientUids, String subject, String message, public CompletableFuture<Void> sendOfflineMessage(Collection<String> recipientUids, String subject, String message) {
Consumer<String> callback) { return requestVoid(() -> {
run((ignored, error) -> callback.accept(error), () -> {
for (String uid : recipientUids) offlineMessages.send(uid, subject, message); for (String uid : recipientUids) offlineMessages.send(uid, subject, message);
log("Offline message sent."); log("Offline message sent.");
return null;
}); });
} }
/** Looks a client up by unique id; delivers {@code null} when the server has never seen them. */ /** Looks a client up by unique id; empty when the server has never seen them. */
public void lookupDatabaseClient(String uniqueId, BiConsumer<DatabaseClient, String> callback) { public CompletableFuture<Optional<DatabaseClient>> lookupDatabaseClient(String uniqueId) {
run(callback, () -> offlineMessages.lookupUid(uniqueId)); return request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId)));
} }
/** /**
* Finds clients whose last nickname contains {@code nickname}. * 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<List<DatabaseClient>, String> callback) { public CompletableFuture<List<DatabaseClient>> searchDatabaseClients(String nickname) {
run(callback, () -> { return request(() -> offlineMessages.search(nickname));
try {
return offlineMessages.search(nickname);
} catch (CommandException e) {
if (isPermissionError(e)) throw new IllegalStateException(SEARCH_NOT_PERMITTED);
throw e;
}
});
} }
// ---- server log ---- // ---- server log ----
/** /**
* Reads the server's newest log lines, or with {@code olderFrom} > 0 the ones before an * 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<ServerLogPage, String> callback) { public CompletableFuture<ServerLogPage> requestServerLog(long olderFrom) {
run(callback, () -> serverLog.read(olderFrom)); return request(() -> serverLog.read(olderFrom));
} }
// ---- bans ---- // ---- bans ----
/** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ /** Reads the server's ban list. */
public void requestBanList(BiConsumer<List<BanEntry>, String> callback) { public CompletableFuture<List<BanEntry>> requestBanList() {
run(callback, bans::list); return request(bans::list);
} }
/** @param callback given {@code null} on success, or the failure message */ public CompletableFuture<Void> addBan(BanRule rule) {
public void addBan(BanRule rule, Consumer<String> callback) { return requestVoid(() -> bans.add(rule));
run((ignored, error) -> callback.accept(error), () -> {
bans.add(rule);
return null;
});
} }
/** /**
* Rewrites an existing ban. * Rewrites an existing ban.
*
* @param callback given {@code null} on success, or the failure message
*/ */
public void replaceBan(int banId, BanRule rule, Consumer<String> callback) { public CompletableFuture<Void> replaceBan(int banId, BanRule rule) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> bans.replace(banId, rule));
bans.replace(banId, rule);
return null;
});
} }
/** /**
* Deletes bans one by one, stopping at the first the server refuses. * 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<Integer> banIds, Consumer<String> callback) { public CompletableFuture<Void> deleteBans(Collection<Integer> banIds) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> {
for (int id : banIds) bans.delete(id); for (int id : banIds) bans.delete(id);
return null;
}); });
} }
@@ -1533,33 +1483,28 @@ public final class TeamspeakConnection implements TS3Listener {
// ---- channel administration ---- // ---- channel administration ----
/** /**
* Reads a channel's editable properties, delivering them (or a failure message) to * Reads a channel's editable properties.
* {@code callback} off the UI thread.
*/ */
public void requestChannelSettings(int channelId, BiConsumer<ChannelSettings, String> callback) { public CompletableFuture<ChannelSettings> requestChannelSettings(int channelId) {
run(callback, () -> channels.readSettings(channelId)); return request(() -> channels.readSettings(channelId));
} }
/** /**
* Reads the permissions set directly on a channel, as name/value pairs. Fails when the * Reads the permissions set directly on a channel, as name/value pairs. Fails when the
* server does not let us look at them. * server does not let us look at them.
*/ */
public void requestChannelPermissions(int channelId, public CompletableFuture<Map<String, Integer>> requestChannelPermissions(int channelId) {
BiConsumer<Map<String, Integer>, String> callback) { return request(() -> channels.readPermissions(channelId));
run(callback, () -> channels.readPermissions(channelId));
} }
/** /**
* Applies an edited channel: its changed properties first, then its needed-power * Applies an edited channel: its changed properties first, then its needed-power
* permissions. * permissions.
*
* @param callback given {@code null} on success, or the failure message
*/ */
public void applyChannelEdit(int channelId, Map<String, String> changes, public CompletableFuture<Void> applyChannelEdit(int channelId, Map<String, String> changes,
Map<String, Integer> setPermissions, Map<String, Integer> setPermissions,
Collection<String> removePermissions, Collection<String> removePermissions) {
Consumer<String> callback) { return requestVoid(() -> {
run((ignored, error) -> callback.accept(error), () -> {
channels.edit(channelId, changes); channels.edit(channelId, changes);
channels.writePermissions(channelId, setPermissions, removePermissions); channels.writePermissions(channelId, setPermissions, removePermissions);
if (changes.containsKey("channel_description")) { if (changes.containsKey("channel_description")) {
@@ -1570,7 +1515,6 @@ public final class TeamspeakConnection implements TS3Listener {
requestChannelInfo(channelId); 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 * Creates a channel below {@code parentId} (0 being the top level) and gives it the
* channel permissions it was created with. * channel permissions it was created with.
* *
* @param callback given the new channel's id, or the failure message. A channel whose * @return the new channel's id. A channel whose permissions could not be set still
* permissions could not be set still exists, and is reported as an error * exists, and fails the request with a message saying so.
* saying so.
*/ */
public void createChannel(int parentId, Map<String, String> properties, public CompletableFuture<Integer> createChannel(int parentId, Map<String, String> properties,
Map<String, Integer> permissions, Map<String, Integer> permissions) {
BiConsumer<Integer, String> callback) { return request(() -> {
run(callback, () -> {
int channelId = channels.create(parentId, properties); int channelId = channels.create(parentId, properties);
try { try {
channels.writePermissions(channelId, permissions, List.of()); channels.writePermissions(channelId, permissions, List.of());
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException("The channel was created, but its permissions" 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; 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. * 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<String> callback) { public CompletableFuture<Void> deleteChannel(int channelId, boolean force) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> channels.delete(channelId, force));
channels.delete(channelId, force);
return null;
});
} }
/** The ids of the icons uploaded to this virtual server. */ /** The ids of the icons uploaded to this virtual server. */
public void requestServerIcons(BiConsumer<List<Long>, String> callback) { public CompletableFuture<List<Long>> requestServerIcons() {
run(callback, channels::listIcons); return request(channels::listIcons);
} }
/** Uploads an image as a server icon and reports the new icon's id. */ /** Uploads an image as a server icon and reports the new icon's id. */
public void uploadIcon(File source, BiConsumer<Long, String> callback) { public CompletableFuture<Long> uploadIcon(File source) {
run(callback, () -> channels.uploadIcon(source)); return request(() -> channels.uploadIcon(source));
} }
/** Deletes a server icon; {@code callback} is given {@code null} on success. */ /** Deletes a server icon. */
public void deleteIcon(long iconId, Consumer<String> callback) { public CompletableFuture<Void> deleteIcon(long iconId) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> channels.deleteIcon(iconId));
channels.deleteIcon(iconId);
return null;
});
} }
/** A request made on the socket of the connection it was issued on. */ /** 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 * Runs a blocking server request in the background. The future completes there, so
* failure message — to {@code callback}, which therefore never runs on the UI thread. * whatever is chained onto it does not run on the UI thread; it fails with a
* {@link RequestException}.
*/ */
private <T> void run(BiConsumer<T, String> callback, Job<T> job) { private <T> CompletableFuture<T> request(Job<T> job) {
CompletableFuture<T> result = new CompletableFuture<>();
ExecutorService pool = actions; ExecutorService pool = actions;
if (pool == null || client == null || !connected) { if (pool == null || client == null || !connected) {
callback.accept(null, "Not connected"); result.completeExceptionally(RequestException.notConnected());
return; return result;
} }
try { try {
pool.execute(() -> { pool.execute(() -> {
try { try {
callback.accept(job.call(), null); result.complete(job.call());
} catch (Exception e) { } catch (Exception e) {
callback.accept(null, connected ? rootMessage(e) : "Not connected"); result.completeExceptionally(connected ? RequestException.of(e) : RequestException.notConnected());
} }
}); });
} catch (RejectedExecutionException e) { } catch (RejectedExecutionException e) {
callback.accept(null, "Not connected"); result.completeExceptionally(RequestException.notConnected());
} }
return result;
}
private CompletableFuture<Void> requestVoid(VoidJob job) {
return request(() -> {
job.call();
return null;
});
} }
/** The live socket. Package-private for {@link ChannelAdmin}. */ /** 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. * 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<String> callback) { public CompletableFuture<Void> setAvatar(File source) {
run((flag, error) -> { return requestVoid(() -> {
if (error == null) updateSelf(self -> self.avatarFlag = flag); String flag = avatarAdmin.upload(source);
callback.accept(error); updateSelf(self -> self.avatarFlag = flag);
}, () -> avatarAdmin.upload(source)); });
} }
/** Withdraws our avatar; {@code callback} is given {@code null} on success. */ /** Withdraws our avatar. */
public void removeAvatar(Consumer<String> callback) { public CompletableFuture<Void> removeAvatar() {
run((ignored, error) -> { return requestVoid(() -> {
if (error == null) updateSelf(self -> self.avatarFlag = "");
callback.accept(error);
}, () -> {
avatarAdmin.remove(); avatarAdmin.remove();
return null; updateSelf(self -> self.avatarFlag = "");
}); });
} }
/** Deletes another client's avatar; {@code callback} is given {@code null} on success. */ /** Deletes another client's avatar. */
public void removeAvatarOf(ClientEntry client, Consumer<String> callback) { public CompletableFuture<Void> removeAvatarOf(ClientEntry client) {
run((ignored, error) -> callback.accept(error), () -> { return requestVoid(() -> avatarAdmin.removeOther(client.uniqueId));
avatarAdmin.removeOther(client.uniqueId);
return null;
});
} }
/** Reads a client's avatar out of the virtual server's file repository (channel 0). */ /** 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)"); + " (" + serverHistory.size() + " server, " + channelHistory.size() + " channel)");
} catch (Exception e) { } catch (Exception e) {
chatLogs = null; 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, ui.onPrivateChatHistory(clientId, c != null ? c.nickname : "Client " + clientId,
logs.privateHtmlHistory(uniqueId)); logs.privateHtmlHistory(uniqueId));
} catch (IOException e) { } 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 { try {
logs.appendMessage(toLogScope(scope), false, fromClientId, fromUniqueId, fromName, message); logs.appendMessage(toLogScope(scope), false, fromClientId, fromUniqueId, fromName, message);
} catch (IOException e) { } 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); logs.appendMessage(toLogScope(scope), true, selfClientId, uid, name, message);
} }
} catch (IOException e) { } 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)); ui.onServerLogHtml(logs.appendServerEvent(message));
} catch (IOException e) { } catch (IOException e) {
ui.onServerLog(message); 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. */ /** Reports a failure to the UI and plays the matching server sound. */
private void error(String prefix, Exception e) { private void error(String prefix, Exception e) {
sound(isPermissionError(e) sound(RequestException.isPermissionError(e)
? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS ? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS
: SoundEvent.SERVER_ERROR, serverVars()); : SoundEvent.SERVER_ERROR, serverVars());
ui.onError(prefix + rootMessage(e)); ui.onError(prefix + RequestException.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;
} }
/** Whether the client is in the channel we are in ourselves. Package-private: also /** 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(); 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();
}
} }
@@ -12,7 +12,7 @@ import eu.lixko.ts3j.client.contacts.ContactStore;
import eu.lixko.ts3j.client.net.ChannelNode; import eu.lixko.ts3j.client.net.ChannelNode;
import eu.lixko.ts3j.client.net.ClientEntry; import eu.lixko.ts3j.client.net.ClientEntry;
import eu.lixko.ts3j.client.net.ConnectionListener; 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.TeamspeakConnection;
import eu.lixko.ts3j.client.net.Whisper; import eu.lixko.ts3j.client.net.Whisper;
import eu.lixko.ts3j.client.recording.VoiceRecorder; import eu.lixko.ts3j.client.recording.VoiceRecorder;
@@ -804,8 +804,9 @@ public final class ServerSession {
tokenLink = null; tokenLink = null;
Target target = lastTarget; Target target = lastTarget;
if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return; if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return;
conn.usePrivilegeKey(link.token, error -> listener.onSystemMessage(error == null Replies.handle(conn.usePrivilegeKey(link.token), Runnable::run,
? "Privilege key used." : "Could not use the privilege key: " + error)); () -> listener.onSystemMessage("Privilege key used."),
failure -> listener.onSystemMessage("Could not use the privilege key: " + failure.getMessage()));
} }
private void checkServerIcon() { private void checkServerIcon() {
@@ -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<RequestException> seen = new AtomicReference<>();
Replies.handle(CompletableFuture.<String>failedFuture(notConnected).thenApply(String::trim), Runnable::run,
value -> {
}, seen::set);
assertSame(notConnected, seen.get());
}
}
@@ -6,12 +6,12 @@ import eu.lixko.ts3j.client.net.avatar.Avatar;
import javax.swing.JFileChooser; import javax.swing.JFileChooser;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Component; import java.awt.Component;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;
/** Sets, takes and deletes our avatar on one server, reporting failures in a dialog. */ /** Sets, takes and deletes our avatar on one server, reporting failures in a dialog. */
final class AvatarActions { final class AvatarActions {
@@ -36,7 +36,7 @@ final class AvatarActions {
if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return; if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return;
File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile();
lastDirectory = file.getParentFile(); 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. */ /** Uploads someone else's avatar as ours. */
@@ -47,30 +47,26 @@ final class AvatarActions {
file = Files.createTempFile("avatar", "." + avatar.format().extension).toFile(); file = Files.createTempFile("avatar", "." + avatar.format().extension).toFile();
Files.write(file.toPath(), avatar.data()); Files.write(file.toPath(), avatar.data());
} catch (IOException e) { } catch (IOException e) {
fail("Error uploading avatar: ", e.getMessage()); show("Error uploading avatar: " + e.getMessage());
return; return;
} }
conn.setAvatar(file, error -> { CompletableFuture<Void> upload = conn.setAvatar(file);
file.delete(); upload.whenComplete((ignored, failure) -> file.delete());
fail("Error uploading avatar: ", error); Edt.onFailure(upload, failure -> show("Error uploading avatar: " + failure.getMessage()));
});
} }
void delete() { void delete() {
if (!conn.isConnected()) return; 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. */ /** Deletes another client's avatar for everyone. */
void deleteOf(ClientEntry client) { void deleteOf(ClientEntry client) {
if (!conn.isConnected()) return; 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 show(String message) {
private void fail(String what, String error) { JOptionPane.showMessageDialog(owner, message, "Error", JOptionPane.ERROR_MESSAGE);
if (error == null) return;
SwingUtilities.invokeLater(() ->
JOptionPane.showMessageDialog(owner, what + error, "Error", JOptionPane.ERROR_MESSAGE));
} }
} }
@@ -55,6 +55,7 @@ import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -373,26 +374,21 @@ final class BanListDialog extends JDialog {
if (loading) return; if (loading) return;
loading = true; loading = true;
status.setText("Loading…"); status.setText("Loading…");
conn.requestBanList((bans, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestBanList(), bans -> {
loading = false; loading = false;
if (!isDisplayable()) return; 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); tableModel.setBans(bans);
status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans");
updateButtons(); updateButtons();
})); }, failure -> {
} loading = false;
if (!isDisplayable()) return;
private static boolean isPermissionError(String message) { tableModel.setBans(List.of());
String m = message.toLowerCase(Locale.ROOT); status.setText(failure.permissionDenied()
return m.contains("insufficient") || m.contains("permission"); ? "You have insufficient permissions to view the ban list."
: "Failed to request ban list: " + failure.getMessage());
updateButtons();
});
} }
private void applyFilter() { private void applyFilter() {
@@ -448,9 +444,9 @@ final class BanListDialog extends JDialog {
dialog.setVisible(true); dialog.setVisible(true);
BanRule rule = dialog.getRule(); BanRule rule = dialog.getRule();
if (rule == null) return; 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.showMessageDialog(this, "Your ban was successfully added.", "Ban List",
JOptionPane.INFORMATION_MESSAGE))); JOptionPane.INFORMATION_MESSAGE));
} }
private void editBan() { private void editBan() {
@@ -460,7 +456,7 @@ final class BanListDialog extends JDialog {
dialog.setVisible(true); dialog.setVisible(true);
BanRule rule = dialog.getRule(); BanRule rule = dialog.getRule();
if (rule == null) return; 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() { private void removeBans() {
@@ -470,18 +466,23 @@ final class BanListDialog extends JDialog {
"Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); "Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return; if (answer != JOptionPane.YES_OPTION) return;
List<Integer> ids = bans.stream().map(b -> b.id).collect(Collectors.toList()); List<Integer> 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. */ /** 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) { private void afterChange(CompletableFuture<Void> change, String errorPrefix) {
SwingUtilities.invokeLater(() -> { afterChange(change, errorPrefix, () -> {
});
}
private void afterChange(CompletableFuture<Void> change, String errorPrefix, Runnable onSuccess) {
Edt.handle(change, () -> {
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) { onSuccess.run();
JOptionPane.showMessageDialog(this, errorPrefix + error, "Ban List", JOptionPane.ERROR_MESSAGE); reload();
} else if (onSuccess != null) { }, failure -> {
onSuccess.run(); if (!isDisplayable()) return;
} JOptionPane.showMessageDialog(this, errorPrefix + failure.getMessage(), "Ban List", JOptionPane.ERROR_MESSAGE);
reload(); reload();
}); });
} }
@@ -19,7 +19,6 @@ import javax.swing.JScrollPane;
import javax.swing.JTabbedPane; import javax.swing.JTabbedPane;
import javax.swing.JTextArea; import javax.swing.JTextArea;
import javax.swing.JTextField; import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer; import javax.swing.Timer;
import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener; import javax.swing.event.DocumentListener;
@@ -33,6 +32,7 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
/** /**
* TeamSpeak's channel editor: the channel's name, icon, password, topic and description * TeamSpeak's channel editor: the channel's name, icon, password, topic and description
@@ -286,19 +286,13 @@ final class ChannelDialog extends JDialog {
// ---- loading ---- // ---- loading ----
private void load() { private void load() {
conn.requestChannelSettings(channel.id, (settings, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestChannelSettings(channel.id), this::apply, failure -> {
if (error != null) { JOptionPane.showMessageDialog(this, "Could not read the channel: " + failure.getMessage(),
JOptionPane.showMessageDialog(this, "Could not read the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE); dispose();
dispose(); });
return; Edt.handle(conn.requestChannelPermissions(channel.id), permissionsPanel::read,
} failure -> permissionsPanel.showUnavailable("No permission to view channel permissions."));
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);
}));
} }
/** /**
@@ -403,9 +397,8 @@ final class ChannelDialog extends JDialog {
if (channel == null) { if (channel == null) {
ok.setEnabled(false); ok.setEnabled(false);
conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed(), finish(conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed()),
(channelId, error) -> SwingUtilities.invokeLater( "Could not create the channel: ");
() -> finish(error, "Could not create the channel: ")));
return; return;
} }
@@ -418,17 +411,15 @@ final class ChannelDialog extends JDialog {
} }
ok.setEnabled(false); ok.setEnabled(false);
conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions, finish(conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions),
error -> SwingUtilities.invokeLater(() -> finish(error, "Could not save the channel: "))); "Could not save the channel: ");
} }
/** Closes the dialog, or reports why the server would not have it and lets the user retry. */ /** Closes the dialog, or reports why the server would not have it and lets the user retry. */
private void finish(String error, String errorPrefix) { private void finish(CompletableFuture<?> request, String errorPrefix) {
if (error == null) { Edt.handle(request, ignored -> dispose(), failure -> {
dispose(); ok.setEnabled(true);
return; JOptionPane.showMessageDialog(this, errorPrefix + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} });
ok.setEnabled(true);
JOptionPane.showMessageDialog(this, errorPrefix + error, "Error", JOptionPane.ERROR_MESSAGE);
} }
} }
@@ -256,17 +256,17 @@ final class ComplaintsDialog extends JDialog {
if (loading) return; if (loading) return;
loading = true; loading = true;
status.setText("Loading…"); status.setText("Loading…");
conn.requestComplaints((complaints, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestComplaints(), complaints -> {
loading = false; loading = false;
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) { setTargets(groupByTarget(complaints));
setTargets(List.of()); status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints");
status.setText("Failed to request complaint list: " + error); }, failure -> {
} else { loading = false;
setTargets(groupByTarget(complaints)); if (!isDisplayable()) return;
status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); setTargets(List.of());
} status.setText("Failed to request complaint list: " + failure.getMessage());
})); });
} }
private static List<Target> groupByTarget(List<Complaint> complaints) { private static List<Target> groupByTarget(List<Complaint> complaints) {
@@ -384,14 +384,14 @@ final class ComplaintsDialog extends JDialog {
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return; if (answer != JOptionPane.YES_OPTION) return;
List<Integer> whole = sel.whole().stream().map(Target::dbId).toList(); List<Integer> 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 (!isDisplayable()) return;
if (error != null) { JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + failure.getMessage(), getTitle(),
JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + error, getTitle(), JOptionPane.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
}
reload(); reload();
})); });
} }
private void banSelected() { private void banSelected() {
@@ -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 <T> void handle(CompletableFuture<T> request, Consumer<T> onSuccess, Consumer<RequestException> onFailure) {
Replies.handle(request, SwingUtilities::invokeLater, onSuccess, onFailure);
}
static void handle(CompletableFuture<Void> request, Runnable onSuccess, Consumer<RequestException> onFailure) {
Replies.handle(request, SwingUtilities::invokeLater, onSuccess, onFailure);
}
static void onFailure(CompletableFuture<?> request, Consumer<RequestException> onFailure) {
Replies.onFailure(request, SwingUtilities::invokeLater, onFailure);
}
}
@@ -18,7 +18,6 @@ import javax.swing.JPanel;
import javax.swing.JScrollPane; import javax.swing.JScrollPane;
import javax.swing.JSplitPane; import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel; import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.Timer; import javax.swing.Timer;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.BorderLayout; import java.awt.BorderLayout;
@@ -179,15 +178,11 @@ final class IconChooserDialog extends JDialog {
private void loadRemoteIcons() { private void loadRemoteIcons() {
status.setText("Loading icons…"); status.setText("Loading icons…");
conn.requestServerIcons((ids, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestServerIcons(), ids -> {
if (error != null) {
status.setText("Could not list the server's icons: " + error);
return;
}
status.setText(" "); status.setText(" ");
remoteModel.clear(); remoteModel.clear();
for (Long id : ids) remoteModel.addElement(id); for (Long id : ids) remoteModel.addElement(id);
})); }, failure -> status.setText("Could not list the server's icons: " + failure.getMessage()));
} }
private void uploadIcon() { private void uploadIcon() {
@@ -197,16 +192,14 @@ final class IconChooserDialog extends JDialog {
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile();
status.setText("Uploading " + file.getName() + "…"); status.setText("Uploading " + file.getName() + "…");
conn.uploadIcon(file, (iconId, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.uploadIcon(file), iconId -> {
if (error != null) {
status.setText(" ");
JOptionPane.showMessageDialog(this, "Error uploading icon: " + error,
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
loadRemoteIcons(); loadRemoteIcons();
startRefreshing(); startRefreshing();
})); }, failure -> {
status.setText(" ");
JOptionPane.showMessageDialog(this, "Error uploading icon: " + failure.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
});
} }
private void deleteSelectedIcon() { private void deleteSelectedIcon() {
@@ -216,14 +209,9 @@ final class IconChooserDialog extends JDialog {
"Permanently delete this icon from the server?", "Confirmation", "Permanently delete this icon from the server?", "Confirmation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return; if (answer != JOptionPane.YES_OPTION) return;
conn.deleteIcon(id, error -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.deleteIcon(id), () -> remoteModel.removeElement(id),
if (error != null) { failure -> JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + failure.getMessage(),
JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + error, "Error", JOptionPane.ERROR_MESSAGE));
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
remoteModel.removeElement(id);
}));
} }
/** /**
@@ -54,6 +54,7 @@ import java.util.Comparator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
@@ -361,11 +362,10 @@ final class OfflineMessageComposeDialog extends JDialog {
String typed = recipientField.getText().trim(); String typed = recipientField.getText().trim();
if (typed.isEmpty()) return; if (typed.isEmpty()) return;
if (UNIQUE_ID.matcher(typed).matches()) { if (UNIQUE_ID.matcher(typed).matches()) {
conn.lookupDatabaseClient(typed, (client, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.lookupDatabaseClient(typed),
if (error != null) showRecipientError(error); client -> client.ifPresentOrElse(this::accept,
else if (client == null) showRecipientError("The unique ID is unknown on this server."); () -> showRecipientError("The unique ID is unknown on this server.")),
else accept(client); failure -> showRecipientError(failure.getMessage()));
}));
return; return;
} }
for (int i = 0; i < available.size(); i++) { for (int i = 0; i < available.size(); i++) {
@@ -374,18 +374,18 @@ final class OfflineMessageComposeDialog extends JDialog {
return; return;
} }
} }
conn.searchDatabaseClients(typed, (found, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.searchDatabaseClients(typed), found -> {
if (error != null) { if (found.isEmpty()) {
showRecipientError(error);
} else if (found.isEmpty()) {
showRecipientError("The nickname is unknown on this server."); showRecipientError("The nickname is unknown on this server.");
} else { return;
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);
} }
})); 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) { private void accept(DatabaseClient client) {
@@ -431,18 +431,17 @@ final class OfflineMessageComposeDialog extends JDialog {
if (!sendButton.isEnabled()) return; if (!sendButton.isEnabled()) return;
sending = true; sending = true;
updateSendButton(); updateSendButton();
conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText(), Edt.handle(conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText()),
error -> SwingUtilities.invokeLater(() -> { () -> {
sending = false;
if (isDisplayable()) dispose();
}, failure -> {
sending = false; sending = false;
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error == null) {
dispose();
return;
}
updateSendButton(); updateSendButton();
JOptionPane.showMessageDialog(this, "Failed to send offline message: " + error, getTitle(), JOptionPane.showMessageDialog(this, "Failed to send offline message: " + failure.getMessage(),
JOptionPane.ERROR_MESSAGE); getTitle(), JOptionPane.ERROR_MESSAGE);
})); });
} }
private void cancel() { private void cancel() {
@@ -27,7 +27,6 @@ import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel; import javax.swing.ListSelectionModel;
import javax.swing.RowSorter; import javax.swing.RowSorter;
import javax.swing.SortOrder; import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.UIManager; import javax.swing.UIManager;
import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkEvent;
import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuEvent;
@@ -328,16 +327,15 @@ final class OfflineMessagesDialog extends JDialog {
if (loading) return; if (loading) return;
loading = true; loading = true;
status.setText("Loading…"); status.setText("Loading…");
conn.requestOfflineMessages((messages, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestOfflineMessages(), messages -> {
loading = false; loading = false;
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) {
status.setText("Failed to list offline messages: " + error);
return;
}
setMessages(messages); setMessages(messages);
status.setText(messages.isEmpty() ? "No 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<OfflineMessage> messages) { private void setMessages(List<OfflineMessage> messages) {
@@ -390,15 +388,15 @@ final class OfflineMessagesDialog extends JDialog {
return; return;
} }
bodyPane.setText(""); bodyPane.setText("");
conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> {
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) {
if (shownId == message.id()) status.setText("Failed to get offline message: " + error);
return;
}
bodies.put(message.id(), text); bodies.put(message.id(), text);
if (shownId == message.id()) showBody(message, 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) { private void showBody(OfflineMessage message, String body) {
@@ -421,15 +419,13 @@ final class OfflineMessagesDialog extends JDialog {
composer.reply(message, body); composer.reply(message, body);
return; return;
} }
conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> {
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) {
status.setText("Failed to get offline message: " + error);
return;
}
bodies.put(message.id(), text); bodies.put(message.id(), text);
composer.reply(message, text); composer.reply(message, text);
})); }, failure -> {
if (isDisplayable()) status.setText("Failed to get offline message: " + failure.getMessage());
});
} }
private void markSelected(boolean read) { private void markSelected(boolean read) {
@@ -440,12 +436,11 @@ final class OfflineMessagesDialog extends JDialog {
private void mark(List<OfflineMessage> messages, boolean read) { private void mark(List<OfflineMessage> messages, boolean read) {
if (messages.isEmpty()) return; if (messages.isEmpty()) return;
for (OfflineMessage m : messages) tableModel.replace(m.withRead(read)); for (OfflineMessage m : messages) tableModel.replace(m.withRead(read));
conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read, Edt.onFailure(conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read), failure -> {
error -> SwingUtilities.invokeLater(() -> { if (!isDisplayable()) return;
if (error == null || !isDisplayable()) return; status.setText("Failed to update offline message: " + failure.getMessage());
status.setText("Failed to update offline message: " + error); reload();
reload(); });
}));
} }
private void deleteSelected() { private void deleteSelected() {
@@ -461,16 +456,18 @@ final class OfflineMessagesDialog extends JDialog {
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return; if (answer != JOptionPane.YES_OPTION) return;
} }
conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList(), Runnable deleted = () -> {
error -> SwingUtilities.invokeLater(() -> { for (OfflineMessage m : selected) bodies.remove(m.id());
if (!isDisplayable()) return; reload();
if (error != null) { };
JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + error, Edt.handle(conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList()), () -> {
getTitle(), JOptionPane.ERROR_MESSAGE); if (isDisplayable()) deleted.run();
} }, failure -> {
for (OfflineMessage m : selected) bodies.remove(m.id()); if (!isDisplayable()) return;
reload(); JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + failure.getMessage(),
})); getTitle(), JOptionPane.ERROR_MESSAGE);
deleted.run();
});
} }
private static String subjectOrPlaceholder(OfflineMessage m) { private static String subjectOrPlaceholder(OfflineMessage m) {
@@ -19,7 +19,6 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JRadioButton; import javax.swing.JRadioButton;
import javax.swing.JTextField; import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Component; import java.awt.Component;
import java.awt.FlowLayout; import java.awt.FlowLayout;
@@ -149,20 +148,20 @@ final class PrivilegeKeyCreateDialog extends JDialog {
Group group = (Group) groupBox.getSelectedItem(); Group group = (Group) groupBox.getSelectedItem();
ChannelNode channel = (ChannelNode) channelBox.getSelectedItem(); ChannelNode channel = (ChannelNode) channelBox.getSelectedItem();
create.setEnabled(false); create.setEnabled(false);
conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id, Edt.handle(conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id,
descriptionField.getText().trim(), (key, error) -> SwingUtilities.invokeLater(() -> { descriptionField.getText().trim()), key -> {
if (!isDisplayable()) return; if (!isDisplayable()) return;
updateCreate(); updateCreate();
if (error != null) { keyField.setText(key);
JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + error, keyField.selectAll();
getTitle(), JOptionPane.ERROR_MESSAGE); keyField.requestFocusInWindow();
return; copy.setEnabled(true);
} onCreated.run();
keyField.setText(key); }, failure -> {
keyField.selectAll(); if (!isDisplayable()) return;
keyField.requestFocusInWindow(); updateCreate();
copy.setEnabled(true); JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + failure.getMessage(),
onCreated.run(); getTitle(), JOptionPane.ERROR_MESSAGE);
})); });
} }
} }
@@ -22,7 +22,6 @@ import javax.swing.JScrollPane;
import javax.swing.JTable; import javax.swing.JTable;
import javax.swing.KeyStroke; import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel; import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel; import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter; import javax.swing.table.TableRowSorter;
@@ -213,18 +212,19 @@ final class PrivilegeKeysDialog extends JDialog {
if (loading) return; if (loading) return;
loading = true; loading = true;
status.setText("Loading…"); status.setText("Loading…");
conn.requestPrivilegeKeys((keys, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestPrivilegeKeys(), keys -> {
loading = false; loading = false;
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) { tableModel.setKeys(keys);
tableModel.setKeys(List.of()); status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys");
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");
}
updateButtons(); updateButtons();
})); }, failure -> {
loading = false;
if (!isDisplayable()) return;
tableModel.setKeys(List.of());
status.setText("Failed to request Privilege Key list: " + failure.getMessage());
updateButtons();
});
} }
private List<PrivilegeKey> selectedKeys() { private List<PrivilegeKey> selectedKeys() {
@@ -252,14 +252,14 @@ final class PrivilegeKeysDialog extends JDialog {
"Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); "Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return; if (answer != JOptionPane.YES_OPTION) return;
List<String> tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList()); List<String> 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 (!isDisplayable()) return;
if (error != null) { JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + failure.getMessage(), getTitle(),
JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + error, getTitle(), JOptionPane.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
}
reload(); reload();
})); });
} }
private void copyKeys() { private void copyKeys() {
@@ -5,6 +5,7 @@ import com.formdev.flatlaf.util.UIScale;
import eu.lixko.ts3j.client.config.ServerLogSettings; import eu.lixko.ts3j.client.config.ServerLogSettings;
import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight;
import eu.lixko.ts3j.client.config.Settings; 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;
import eu.lixko.ts3j.client.net.ServerLogEntry.Level; import eu.lixko.ts3j.client.net.ServerLogEntry.Level;
import eu.lixko.ts3j.client.net.ServerLogPage; import eu.lixko.ts3j.client.net.ServerLogPage;
@@ -263,16 +264,15 @@ final class ServerLogDialog extends JDialog {
loading = true; loading = true;
olderButton.setEnabled(false); olderButton.setEnabled(false);
showStatus("Loading…", Theme.chatEvent()); 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; loading = false;
if (!isDisplayable()) return; if (!isDisplayable()) return;
if (error != null) { failed(failure);
failed(error); olderButton.setEnabled(olderFrom > 0);
olderButton.setEnabled(olderFrom > 0); });
return;
}
received(page, from > 0);
}));
} }
private void received(ServerLogPage page, boolean older) { private void received(ServerLogPage page, boolean older) {
@@ -284,10 +284,10 @@ final class ServerLogDialog extends JDialog {
if (older) log.setCaretPosition(0); if (older) log.setCaretPosition(0);
} }
private void failed(String error) { private void failed(RequestException failure) {
showStatus(error.toLowerCase(Locale.ROOT).contains("insufficient") showStatus(failure.permissionDenied()
? "Insufficient permissions to view Server Log" ? "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)); Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000));
} }
@@ -19,7 +19,6 @@ import eu.lixko.ts3j.client.text.TsLink;
import javax.swing.JComponent; import javax.swing.JComponent;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.JSplitPane; import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import java.awt.Component; import java.awt.Component;
import java.awt.Window; import java.awt.Window;
@@ -255,11 +254,8 @@ final class ServerTab {
String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key", String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key",
JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null); JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null);
if (key == null || key.isBlank()) return; if (key == null || key.isBlank()) return;
conn.usePrivilegeKey(key.trim(), error -> { Edt.onFailure(conn.usePrivilegeKey(key.trim()), failure -> JOptionPane.showMessageDialog(host,
if (error == null) return; failure.getMessage(), "Error using Privilege Key", JOptionPane.ERROR_MESSAGE));
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, error,
"Error using Privilege Key", JOptionPane.ERROR_MESSAGE));
});
} }
/** Opens the server's privilege keys, or brings the already open window forward. */ /** Opens the server's privilege keys, or brings the already open window forward. */
@@ -10,7 +10,6 @@ import eu.lixko.ts3j.client.net.TeamspeakConnection;
import eu.lixko.ts3j.client.text.TsLink; import eu.lixko.ts3j.client.text.TsLink;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import java.awt.Component; import java.awt.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -251,23 +250,15 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
@Override @Override
public void changeClientDescription(ClientEntry client) { public void changeClientDescription(ClientEntry client) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
conn.requestClientDescription(client.id, (description, error) -> SwingUtilities.invokeLater(() -> { Edt.handle(conn.requestClientDescription(client.id), description -> {
if (error != null) {
JOptionPane.showMessageDialog(host, "Could not read the description: " + error,
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
String edited = (String) JOptionPane.showInputDialog(host, String edited = (String) JOptionPane.showInputDialog(host,
"Description for " + client.nickname + ":", "Change Description", "Description for " + client.nickname + ":", "Change Description",
JOptionPane.PLAIN_MESSAGE, Icons.of("EDIT"), null, description); JOptionPane.PLAIN_MESSAGE, Icons.of("EDIT"), null, description);
if (edited == null || edited.equals(description)) return; if (edited == null || edited.equals(description)) return;
conn.setClientDescription(client.id, edited, failure -> SwingUtilities.invokeLater(() -> { Edt.onFailure(conn.setClientDescription(client.id, edited), failure -> JOptionPane.showMessageDialog(host,
if (failure != null) { "Could not change the description: " + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE));
JOptionPane.showMessageDialog(host, "Could not change the description: " + failure, }, failure -> JOptionPane.showMessageDialog(host, "Could not read the description: " + failure.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE); "Error", JOptionPane.ERROR_MESSAGE));
}
}));
}));
} }
@Override @Override
@@ -323,10 +314,8 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) { JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
return; return;
} }
conn.deleteChannel(channel.id, true, error -> { Edt.onFailure(conn.deleteChannel(channel.id, true), failure -> JOptionPane.showMessageDialog(host,
if (error != null) SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, "Could not delete the channel: " + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE));
"Could not delete the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE));
});
} }
@Override @Override