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,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.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 <b>clientkick</b>. */
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<String, String> callback) {
run(callback, () -> {
public CompletableFuture<String> 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<String> callback) {
public CompletableFuture<Void> 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<List<PrivilegeKey>, String> callback) {
run(callback, privilegeKeys::list);
/** Reads the server's privilege keys. */
public CompletableFuture<List<PrivilegeKey>> 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<String, String> callback) {
run(callback, () -> privilegeKeys.add(channelGroup, groupId, channelId, description));
public CompletableFuture<String> 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<String> tokens, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> deletePrivilegeKeys(Collection<String> 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<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
privilegeKeys.use(token);
return null;
});
public CompletableFuture<Void> 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<List<Complaint>, String> callback) {
run(callback, complaints::list);
/** Reads the server's complaints. */
public CompletableFuture<List<Complaint>> 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<Integer> targetDbIds, Collection<Complaint> single,
Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> 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<List<OfflineMessage>, String> callback) {
run(callback, offlineMessages::list);
/** Lists our offline message inbox. */
public CompletableFuture<List<OfflineMessage>> 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<String, String> callback) {
run(callback, () -> offlineMessages.body(messageId));
/** Reads a message's body. */
public CompletableFuture<String> 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<Integer> messageIds, boolean read, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> markOfflineMessages(Collection<Integer> 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<Integer> messageIds, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> deleteOfflineMessages(Collection<Integer> 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<String> recipientUids, String subject, String message,
Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> sendOfflineMessage(Collection<String> 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<DatabaseClient, String> callback) {
run(callback, () -> offlineMessages.lookupUid(uniqueId));
/** Looks a client up by unique id; empty when the server has never seen them. */
public CompletableFuture<Optional<DatabaseClient>> 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<List<DatabaseClient>, 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<List<DatabaseClient>> 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<ServerLogPage, String> callback) {
run(callback, () -> serverLog.read(olderFrom));
public CompletableFuture<ServerLogPage> 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<List<BanEntry>, String> callback) {
run(callback, bans::list);
/** Reads the server's ban list. */
public CompletableFuture<List<BanEntry>> requestBanList() {
return request(bans::list);
}
/** @param callback given {@code null} on success, or the failure message */
public void addBan(BanRule rule, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
bans.add(rule);
return null;
});
public CompletableFuture<Void> 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<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
bans.replace(banId, rule);
return null;
});
public CompletableFuture<Void> 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<Integer> banIds, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
public CompletableFuture<Void> deleteBans(Collection<Integer> 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<ChannelSettings, String> callback) {
run(callback, () -> channels.readSettings(channelId));
public CompletableFuture<ChannelSettings> 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<Map<String, Integer>, String> callback) {
run(callback, () -> channels.readPermissions(channelId));
public CompletableFuture<Map<String, Integer>> 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<String, String> changes,
public CompletableFuture<Void> applyChannelEdit(int channelId, Map<String, String> changes,
Map<String, Integer> setPermissions,
Collection<String> removePermissions,
Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
Collection<String> 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<String, String> properties,
Map<String, Integer> permissions,
BiConsumer<Integer, String> callback) {
run(callback, () -> {
public CompletableFuture<Integer> createChannel(int parentId, Map<String, String> properties,
Map<String, Integer> 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<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
channels.delete(channelId, force);
return null;
});
public CompletableFuture<Void> 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<List<Long>, String> callback) {
run(callback, channels::listIcons);
public CompletableFuture<List<Long>> 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<Long, String> callback) {
run(callback, () -> channels.uploadIcon(source));
public CompletableFuture<Long> 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<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
channels.deleteIcon(iconId);
return null;
});
/** Deletes a server icon. */
public CompletableFuture<Void> 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 <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;
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<Void> 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<String> callback) {
run((flag, error) -> {
if (error == null) updateSelf(self -> self.avatarFlag = flag);
callback.accept(error);
}, () -> avatarAdmin.upload(source));
public CompletableFuture<Void> 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<String> callback) {
run((ignored, error) -> {
if (error == null) updateSelf(self -> self.avatarFlag = "");
callback.accept(error);
}, () -> {
/** Withdraws our avatar. */
public CompletableFuture<Void> 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<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
avatarAdmin.removeOther(client.uniqueId);
return null;
});
/** Deletes another client's avatar. */
public CompletableFuture<Void> 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();
}
}
@@ -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() {
@@ -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());
}
}