Frontends call the admin helpers directly, not through the connection

The channel, ban, privilege key, complaint, server log, offline message
and avatar helpers are public, each method running in the background and
answering a future; only the connection creates them. TeamspeakConnection
and ServerSession hand them out, which drops 30 one-line forwarders from
the connection. What the forwarders added moves into the helpers: the
stop-at-the-first-refusal loops, the "sent" log lines, re-reading an
edited channel's description and showing our own new avatar. The
complaint and offline message length limits move with them.

The icon chooser and the offline message composer take only their
helper; the other dialogs still need the connection for the model.

The connection's request runner is renamed Uplink, since
session.ServerLink is the ts3server:// link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 18:45:21 +00:00
co-authored by Claude Opus 5.5
parent da908f77bd
commit 959f7ed97a
25 changed files with 546 additions and 581 deletions
@@ -248,17 +248,17 @@ class ServerController internal constructor(
if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId)
/** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = conn.requestChannelSettings(channelId).result()
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = session.channels().settings(channelId).result()
suspend fun editChannel(channelId: Int, changes: Map<String, String>): Result<Unit> =
if (changes.isEmpty()) Result.success(Unit)
else conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()).done()
else session.channels().edit(channelId, changes, emptyMap(), emptyList()).done()
suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result<Unit> =
conn.createChannel(parentId, settings.creationParameters(), emptyMap()).result().map { }
session.channels().create(parentId, settings.creationParameters(), emptyMap()).result().map { }
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): Result<Unit> = conn.deleteChannel(channelId, true).done()
suspend fun deleteChannel(channelId: Int): Result<Unit> = session.channels().delete(channelId, true).done()
// ---- files ----
@@ -325,13 +325,13 @@ class ServerController internal constructor(
else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } }
/** The server's bans, or why they could not be read. */
suspend fun banList(): Result<List<BanEntry>> = conn.requestBanList().result()
suspend fun banList(): Result<List<BanEntry>> = session.bans().list().result()
suspend fun addBan(rule: BanRule): Result<Unit> = conn.addBan(rule).done()
suspend fun addBan(rule: BanRule): Result<Unit> = session.bans().add(rule).done()
suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = conn.replaceBan(banId, rule).done()
suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = session.bans().replace(banId, rule).done()
suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = conn.deleteBans(banIds).done()
suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = session.bans().delete(banIds).done()
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = permissions.canDeleteBans(bans, conn.selfUniqueId)
@@ -346,7 +346,7 @@ class ServerController internal constructor(
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) }
}
return try {
conn.setAvatar(file).done()
session.avatarAdmin().set(file).done()
} finally {
file.delete()
}
+2 -2
View File
@@ -13,8 +13,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo
| 3 | What we may do is answered in five places: `ServerSession.can*`, `ServerModel.can*/permits/mayHavePower`, `TeamspeakConnection.canSendOfflineMessages/canTransferFiles`, and raw permission names in Swing dialogs and `ServerController.canCreateBans` | done (`13e3a62`): `Permissions` owns the table, the rules and one named question per capability; `ServerSession.permissions()` is `NONE` while disconnected; no permission names outside core except channel-permission editing |
| 4 | `TeamspeakConnection` (2,157 lines) still does lifecycle, mic/speaker, recording, chat logs, log/sound text, contacts, avatars, icons, file transfers, myTeamSpeak and job plumbing. The `*Admin` helpers take the whole connection, which forwards ~90 methods to them | in progress, in sub-steps: |
| 4a | … chat log and what we tell the user (log lines, sounds, links and sound variables) | done (`1bc7eb5`): `ChatLog`, `Announcer` |
| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | done (uncommitted): `ServerLink` owns the socket, event and request threads and file transfers, and runs requests; the helpers take it (plus the model, permissions or avatars where they need them) |
| 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | open |
| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | done (`da908f7`; renamed `Uplink` in 4c, as `session.ServerLink` is the `ts3server://` link): `ServerLink` owns the socket, event and request threads and file transfers, and runs requests; the helpers take it (plus the model, permissions or avatars where they need them) |
| 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | done (uncommitted): the helpers are public with non-blocking methods, reached through `ServerSession`/`TeamspeakConnection` getters; 30 forwarders gone, and what they added (stop-at-first-refusal loops, log lines, description refresh, own avatar flag) moved into the helpers. Swing dialogs still take the whole connection for the model and our ids (item 5) |
| 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | open |
| 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | open |
| 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 |
@@ -10,8 +10,10 @@ import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
import java.io.File;
import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
@@ -19,29 +21,62 @@ import java.util.function.Supplier;
* it: the picture goes into channel 0's file repository as {@code /avatar_<name>} and
* {@code client_flag_avatar} is then set to its MD5, which is what other clients key
* their downloads on.
*
* <p>Requests run in the background and fail with a {@link RequestException}.
*/
final class AvatarAdmin {
public final class AvatarAdmin {
/** The largest avatar we are willing to download, whatever a server allows. */
static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024;
private static final long UPLOAD_TIMEOUT_MS = 60_000;
private final ServerLink link;
private final Uplink uplink;
private final Permissions permissions;
private final AvatarRepository avatars;
/** Our unique id, which names our avatar file. */
private final Supplier<String> selfUniqueId;
/** Shows our new avatar flag on our own entry; the server tells only the other clients. */
private final Consumer<String> ownFlagChanged;
AvatarAdmin(ServerLink link, Permissions permissions, AvatarRepository avatars, Supplier<String> selfUniqueId) {
this.link = link;
AvatarAdmin(Uplink uplink, Permissions permissions, AvatarRepository avatars,
Supplier<String> selfUniqueId, Consumer<String> ownFlagChanged) {
this.uplink = uplink;
this.permissions = permissions;
this.avatars = avatars;
this.selfUniqueId = selfUniqueId;
this.ownFlagChanged = ownFlagChanged;
}
/** Uploads an image as our avatar and publishes it to the other clients. */
public CompletableFuture<Void> set(File source) {
return uplink.requestVoid(() -> ownFlagChanged.accept(upload(source)));
}
/** Withdraws our avatar. */
public CompletableFuture<Void> remove() {
return uplink.requestVoid(() -> {
setFlag("");
ownFlagChanged.accept("");
try {
deleteFile(selfUniqueId.get());
} catch (Exception ignored) {
// The flag is what other clients go by; a leftover file only wastes space.
// Servers refuse the deletion unless we may delete others' avatars too.
}
});
}
/**
* Deletes another client's avatar, which needs {@code b_client_avatar_delete_other};
* the server then clears their flag for everyone.
*/
public CompletableFuture<Void> removeOf(ClientEntry client) {
return uplink.requestVoid(() -> deleteFile(client.uniqueId));
}
/** Uploads {@code source} as our avatar and announces it; returns its flag. */
String upload(File source) throws Exception {
private String upload(File source) throws Exception {
byte[] data = Files.readAllBytes(source.toPath());
if (data.length == 0) throw new IllegalArgumentException("That file is empty");
if (ImageFormat.detect(data) == null) {
@@ -54,7 +89,7 @@ final class AvatarAdmin {
String name = ownFileName();
CountDownLatch done = new CountDownLatch(1);
FileTransfer transfer = link.files().upload(0, "", "/" + name, source, true, t -> {
FileTransfer transfer = uplink.files().upload(0, "", "/" + name, source, true, t -> {
if (t.isDone()) done.countDown();
});
if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
@@ -70,37 +105,18 @@ final class AvatarAdmin {
return flag;
}
/** Clears our avatar flag and removes the file from the server. */
void remove() throws Exception {
setFlag("");
try {
deleteFile(selfUniqueId.get());
} catch (Exception ignored) {
// The flag is what other clients go by; a leftover file only wastes space.
// Servers refuse the deletion unless we may delete others' avatars too.
}
}
/**
* Deletes another client's avatar, which needs {@code b_client_avatar_delete_other};
* the server then clears their flag for everyone.
*/
void removeOther(String uniqueId) throws Exception {
deleteFile(uniqueId);
}
/**
* Deleting names the avatar by its owner's unique id, {@code /avatar_<uid>}, which the
* server maps to the stored file itself; the stored name is refused ("convert error").
*/
private void deleteFile(String uniqueId) throws Exception {
link.files().delete(0, "", "/avatar_" + uniqueId);
uplink.files().delete(0, "", "/avatar_" + uniqueId);
}
private void setFlag(String flag) throws Exception {
SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT,
new CommandSingleParameter("client_flag_avatar", flag));
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
}
private String ownFileName() {
@@ -9,24 +9,22 @@ import eu.lixko.ts3j.client.net.ban.BanEntry;
import eu.lixko.ts3j.client.net.ban.BanRule;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* The server's ban list: reading it and adding, replacing and deleting entries.
*
* <p>Split out of {@link TeamspeakConnection} like {@link ChannelAdmin}, and for the same
* reason: it is a self-contained request/response corner of the protocol that only the
* ban list window uses. Every call here blocks and must run off the UI thread; the
* connection's public wrappers do that.
* <p>Requests run in the background and fail with a {@link RequestException}.
*/
final class BanAdmin {
public final class BanAdmin {
/** What {@code banlist} answers when there are no bans at all. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
private final ServerLink link;
private final Uplink uplink;
/**
* The {@code banlist} reply in progress. The server answers the command with a burst
@@ -36,19 +34,51 @@ final class BanAdmin {
*/
private volatile List<BanEntry> listing;
BanAdmin(ServerLink link) {
this.link = link;
BanAdmin(Uplink uplink) {
this.uplink = uplink;
}
/** Reads every ban on the server. */
List<BanEntry> list() throws Exception {
public CompletableFuture<List<BanEntry>> list() {
return uplink.request(this::readList);
}
public CompletableFuture<Void> add(BanRule rule) {
return uplink.requestVoid(() -> addNow(rule));
}
/**
* Replaces a ban with a re-written one. The server has no way to edit a ban in place,
* so the new one is added before the old is removed: a failure half-way leaves the
* client banned twice rather than not at all.
*/
public CompletableFuture<Void> replace(int banId, BanRule rule) {
return uplink.requestVoid(() -> {
addNow(rule);
try {
deleteNow(banId);
} catch (Exception e) {
throw new IllegalStateException("The edited ban was added, but the original could not be"
+ " removed: " + e.getMessage(), e);
}
});
}
/** Deletes bans one by one, stopping at the first the server refuses. */
public CompletableFuture<Void> delete(Collection<Integer> banIds) {
return uplink.requestVoid(() -> {
for (int id : banIds) deleteNow(id);
});
}
private List<BanEntry> readList() throws Exception {
List<BanEntry> entries = Collections.synchronizedList(new ArrayList<>());
listing = entries;
try {
link.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete();
uplink.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete();
// The entries were queued on the event thread before the command's own reply
// was read, so draining that thread is what guarantees they have all landed.
link.awaitEventsProcessed();
uplink.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
@@ -65,12 +95,7 @@ final class BanAdmin {
if (entry.id >= 0) entries.add(entry);
}
/**
* Adds a ban.
*
* @return the new ban's id, or -1 where the server did not name it
*/
int add(BanRule rule) throws Exception {
private void addNow(BanRule rule) throws Exception {
if (!rule.hasTarget()) throw new IllegalArgumentException("A ban needs something to match");
SingleCommand cmd = new SingleCommand("banadd", ProtocolRole.CLIENT);
addIfSet(cmd, "ip", rule.ipRegex);
@@ -79,34 +104,13 @@ final class BanAdmin {
addIfSet(cmd, "mytsid", rule.mytsid);
if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds)));
addIfSet(cmd, "banreason", rule.reason);
for (SingleCommand answer : link.socket().executeCommand(cmd).get()) {
Map<String, String> fields = answer.toMap();
if (fields.containsKey("banid")) {
return BanEntry.from(fields).id;
}
}
return -1;
uplink.socket().executeCommand(cmd).complete();
}
/**
* Replaces a ban with a re-written one. The server has no way to edit a ban in place,
* so the new one is added before the old is removed: a failure half-way leaves the
* client banned twice rather than not at all.
*/
void replace(int banId, BanRule rule) throws Exception {
add(rule);
try {
delete(banId);
} catch (Exception e) {
throw new IllegalStateException("The edited ban was added, but the original could not be"
+ " removed: " + e.getMessage(), e);
}
}
void delete(int banId) throws Exception {
private void deleteNow(int banId) throws Exception {
SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT,
new CommandSingleParameter("banid", Integer.toString(banId)));
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
}
private static void addIfSet(SingleCommand cmd, String key, String value) {
@@ -16,6 +16,7 @@ import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -25,11 +26,9 @@ import java.util.zip.CRC32;
* Everything the channel editor needs of the server: reading and writing a channel's
* properties and its needed-power permissions, plus the virtual server's icon store.
*
* <p>Split out of {@link TeamspeakConnection} because it is a self-contained request/
* response corner of the protocol that only the editor uses. Every call here blocks and
* must run off the UI thread; the connection's public wrappers do that.
* <p>Requests run in the background and fail with a {@link RequestException}.
*/
final class ChannelAdmin {
public final class ChannelAdmin {
/** The directory a server's icons live in, where the server has one. */
private static final String ICON_DIRECTORY = "icons";
@@ -37,7 +36,7 @@ final class ChannelAdmin {
/** How long to wait for a whole icon to travel over the file connection. */
private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000;
private final ServerLink link;
private final Uplink uplink;
private final ServerModel model;
/**
@@ -48,72 +47,121 @@ final class ChannelAdmin {
*/
private volatile PermRequest permRequest;
ChannelAdmin(ServerLink link, ServerModel model) {
this.link = link;
ChannelAdmin(Uplink uplink, ServerModel model) {
this.uplink = uplink;
this.model = model;
}
// ---- channel properties ----
/** Reads a channel's full property set. */
ChannelSettings readSettings(int channelId) throws Exception {
Channel info = link.socket().getChannelInfo(channelId);
if (info == null) throw new IllegalStateException("The server did not describe that channel");
return ChannelSettings.from(channelId, info.getMap());
public CompletableFuture<ChannelSettings> settings(int channelId) {
return uplink.request(() -> {
Channel info = uplink.socket().getChannelInfo(channelId);
if (info == null) throw new IllegalStateException("The server did not describe that channel");
return ChannelSettings.from(channelId, info.getMap());
});
}
/**
* Creates a channel below {@code parentId} (0 being the top level).
* Creates a channel below {@code parentId} (0 being the top level) and gives it the
* channel permissions it was created with.
*
* @param properties the new channel's properties, as {@link ChannelSettings#creationParameters}
* @return the new channel's id
* @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.
*/
int create(int parentId, Map<String, String> properties) throws Exception {
public CompletableFuture<Integer> create(int parentId, Map<String, String> properties,
Map<String, Integer> permissions) {
return uplink.request(() -> {
int channelId = createNow(parentId, properties);
try {
writePermissions(channelId, permissions, List.of());
} catch (Exception e) {
throw new IllegalStateException("The channel was created, but its permissions"
+ " could not be set: " + RequestException.rootMessage(e));
}
return channelId;
});
}
/** Applies an edited channel: its changed properties first, then its needed-power permissions. */
public CompletableFuture<Void> edit(int channelId, Map<String, String> changes,
Map<String, Integer> setPermissions, Collection<String> removePermissions) {
return uplink.requestVoid(() -> {
editProperties(channelId, changes);
writePermissions(channelId, setPermissions, removePermissions);
if (changes.containsKey("channel_description")) refreshDescription(channelId);
});
}
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */
public CompletableFuture<Void> delete(int channelId, boolean force) {
return uplink.requestVoid(() -> uplink.socket().executeCommand(new SingleCommand("channeldelete",
ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)),
new CommandSingleParameter("force", force ? "1" : "0"))).complete());
}
private int createNow(int parentId, Map<String, String> properties) throws Exception {
SingleCommand cmd = new SingleCommand("channelcreate", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cpid", Integer.toString(parentId)));
for (Map.Entry<String, String> property : properties.entrySet()) {
cmd.add(new CommandSingleParameter(property.getKey(), property.getValue()));
}
for (SingleCommand answer : link.socket().executeCommand(cmd).get()) {
for (SingleCommand answer : uplink.socket().executeCommand(cmd).get()) {
int cid = parseInt(answer.toMap().get("cid"), -1);
if (cid > 0) return cid;
}
// Some servers acknowledge the command without naming the channel; the
// notifychannelcreated they also send does name it, so read it off the model
// once that event has been handled.
link.awaitEventsProcessed();
uplink.awaitEventsProcessed();
ChannelNode created = model.findChannelByName(parentId, properties.get("channel_name"));
if (created == null) throw new IllegalStateException("The server did not report the new channel");
return created.id;
}
/** Applies {@code changes} (property name to value) with a single {@code channeledit}. */
void edit(int channelId, Map<String, String> changes) throws Exception {
private void editProperties(int channelId, Map<String, String> changes) throws Exception {
if (changes.isEmpty()) return;
SingleCommand cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
for (Map.Entry<String, String> change : changes.entrySet()) {
cmd.add(new CommandSingleParameter(change.getKey(), change.getValue()));
}
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
}
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */
void delete(int channelId, boolean force) throws Exception {
link.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)),
new CommandSingleParameter("force", force ? "1" : "0"))).complete();
/**
* The server does not tell the invoker about their own description change, so a
* description already shown is read again. Refused, the old one stays.
*/
private void refreshDescription(int channelId) {
ChannelNode node = model.getChannel(channelId);
if (node == null || !node.descriptionLoaded) return;
node.descriptionLoaded = false;
try {
uplink.socket().executeCommand(new SingleCommand("channelgetdescription", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)))).complete();
} catch (Exception ignored) {
}
}
// ---- channel permissions ----
/**
* Reads the permissions set directly on a channel.
* Reads the permissions set directly on a channel. Fails when the server does not let
* us look at them.
*
* @return permission name to value, holding only the permissions the channel itself
* carries — anything inherited from a group is absent
*/
Map<String, Integer> readPermissions(int channelId) throws Exception {
public CompletableFuture<Map<String, Integer>> permissions(int channelId) {
return uplink.request(() -> readPermissions(channelId));
}
private Map<String, Integer> readPermissions(int channelId) throws Exception {
if (!model.permissions().hasNames()) {
// channelpermlist reports numeric ids, which only the permissionlist response
// gives names to; without it the values could not be told apart.
@@ -124,10 +172,10 @@ final class ChannelAdmin {
try {
SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)));
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
// The entries were queued on the event thread before the command's own reply
// was read, so draining that thread is what guarantees they have all landed.
link.awaitEventsProcessed();
uplink.awaitEventsProcessed();
} finally {
permRequest = null;
}
@@ -154,7 +202,7 @@ final class ChannelAdmin {
* Sets and clears channel permissions by name. A permission set to a value is added or
* updated; one that is cleared is removed so the channel inherits it again.
*/
void writePermissions(int channelId, Map<String, Integer> set, Collection<String> remove)
private void writePermissions(int channelId, Map<String, Integer> set, Collection<String> remove)
throws Exception {
if (!set.isEmpty()) {
List<SingleCommand> parts = new ArrayList<>(set.size());
@@ -178,7 +226,7 @@ final class ChannelAdmin {
private void send(String name, int channelId, List<SingleCommand> parts) throws Exception {
MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
}
// ---- the server's icon store ----
@@ -187,10 +235,14 @@ final class ChannelAdmin {
* The ids of the icons uploaded to this virtual server, which live in channel 0's file
* repository as {@code /icon_<id>}.
*/
List<Long> listIcons() throws Exception {
public CompletableFuture<List<Long>> icons() {
return uplink.request(this::listIcons);
}
private List<Long> listIcons() throws Exception {
List<Long> ids = new ArrayList<>();
boolean hasIconDirectory = false;
for (RemoteFile file : link.files().list(0, "", "/")) {
for (RemoteFile file : uplink.files().list(0, "", "/")) {
if (file.isDirectory()) {
hasIconDirectory |= file.getName().equals(ICON_DIRECTORY);
continue;
@@ -200,7 +252,7 @@ final class ChannelAdmin {
// Newer servers keep the icons in their own directory rather than loose in the
// repository's root; both layouts exist, so whichever this server uses is read.
if (hasIconDirectory) {
for (RemoteFile file : link.files().list(0, "", "/" + ICON_DIRECTORY)) {
for (RemoteFile file : uplink.files().list(0, "", "/" + ICON_DIRECTORY)) {
if (!file.isDirectory()) addIcon(ids, file);
}
}
@@ -218,7 +270,11 @@ final class ChannelAdmin {
*
* @return the icon's id, which TeamSpeak derives from the file's CRC32
*/
long uploadIcon(File source) throws Exception {
public CompletableFuture<Long> uploadIcon(File source) {
return uplink.request(() -> upload(source));
}
private long upload(File source) throws Exception {
byte[] data = Files.readAllBytes(source.toPath());
if (data.length == 0) throw new IllegalArgumentException("That file is empty");
if (data.length > TeamspeakConnection.MAX_ICON_BYTES) {
@@ -230,7 +286,7 @@ final class ChannelAdmin {
long id = crc.getValue();
CountDownLatch done = new CountDownLatch(1);
FileTransfer transfer = link.files().upload(0, "", "/icon_" + id, source, true, t -> {
FileTransfer transfer = uplink.files().upload(0, "", "/icon_" + id, source, true, t -> {
if (t.isDone()) done.countDown();
});
if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
@@ -243,8 +299,8 @@ final class ChannelAdmin {
return id;
}
void deleteIcon(long iconId) throws Exception {
link.files().delete(0, "", "/icon_" + iconId);
public CompletableFuture<Void> deleteIcon(long iconId) {
return uplink.requestVoid(() -> uplink.files().delete(0, "", "/icon_" + iconId));
}
// ---- helpers ----
@@ -7,45 +7,53 @@ import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The server's complaints: filing, listing and removing them.
*
* <p>Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same
* way: {@code complainlist} replies with {@code notifycomplainlist} events ahead of the
* command's own completion. Every call here blocks and must run off the UI thread; the
* connection's public wrappers do that.
* <p>Answered like {@link BanAdmin}: {@code complainlist} replies with
* {@code notifycomplainlist} events ahead of the command's own completion. Requests run in
* the background and fail with a {@link RequestException}.
*/
final class ComplaintAdmin {
public final class ComplaintAdmin {
/** The longest reason a complaint may carry. */
public static final int REASON_LIMIT = 200;
/** What {@code complainlist} answers when there are no complaints at all. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
/** What {@code complainadd} answers when we already complained about that client. */
private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502;
private final ServerLink link;
private final Uplink uplink;
private final Announcer announce;
/** The {@code complainlist} reply in progress; one request may be in flight at a time. */
private volatile List<Complaint> listing;
ComplaintAdmin(ServerLink link) {
this.link = link;
ComplaintAdmin(Uplink uplink, Announcer announce) {
this.uplink = uplink;
this.announce = announce;
}
List<Complaint> list() throws Exception {
List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>());
listing = complaints;
try {
link.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete();
link.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
listing = null;
}
return new ArrayList<>(complaints);
public CompletableFuture<List<Complaint>> list() {
return uplink.request(() -> {
List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>());
listing = complaints;
try {
uplink.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete();
uplink.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
listing = null;
}
return new ArrayList<>(complaints);
});
}
void onListEntry(UnknownTeamspeakEvent e) {
@@ -53,27 +61,39 @@ final class ComplaintAdmin {
if (complaints != null) complaints.add(Complaint.from(e.getMap()));
}
/** Files a complaint about a client; the server takes one per client from each of us. */
void add(int targetDbId, String message) throws Exception {
try {
link.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)),
new CommandSingleParameter("message", message))).complete();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e;
throw new IllegalStateException("Cannot add multiple complaints about the same client.");
}
/**
* Complains about an online client to the server's admins; the server takes one per
* client from each of us. The outcome goes to the server tab's log.
*/
public void complain(ClientEntry client, String reason) {
uplink.submit(sock -> {
try {
sock.executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(client.databaseId)),
new CommandSingleParameter("message", reason))).complete();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e;
throw new IllegalStateException("Cannot add multiple complaints about the same client.");
}
announce.log("Complaint sent.");
}, e -> announce.error("Failed to send complaint: ", e));
}
void delete(Complaint complaint) throws Exception {
link.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())),
new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete();
}
/** Removes every complaint about one client. */
void deleteAll(int targetDbId) throws Exception {
link.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete();
/**
* Removes every complaint about each of {@code targetDbIds}, then each of {@code single},
* stopping at the first the server refuses.
*/
public CompletableFuture<Void> delete(Collection<Integer> targetDbIds, Collection<Complaint> single) {
return uplink.requestVoid(() -> {
for (int target : targetDbIds) {
uplink.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(target)))).complete();
}
for (Complaint complaint : single) {
uplink.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())),
new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete();
}
});
}
}
@@ -102,7 +102,7 @@ final class ConnectionStatsCollector {
}
private void awaitReports(ConnectionStats s, int expected) {
LocalTeamspeakClientSocket client = conn.link.currentSocket();
LocalTeamspeakClientSocket client = conn.uplink.currentSocket();
if (client == null) return;
Pending p = new Pending(s, expected);
pending.put(s.clientId, p);
@@ -133,7 +133,7 @@ final class ConnectionStatsCollector {
long connectedAt = conn.connectedAtMs;
if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt;
LocalTeamspeakClientSocket c = conn.link.currentSocket();
LocalTeamspeakClientSocket c = conn.uplink.currentSocket();
if (c == null) return;
try {
Pair<Double, Double> ping = c.getPing();
@@ -158,7 +158,7 @@ final class ConnectionStatsCollector {
/** Our file transfer rate since the previous poll; the server reports it only for others. */
private synchronized void applyTransferRate(ConnectionStats s) {
FileTransferManager ft = conn.link.currentFiles();
FileTransferManager ft = conn.uplink.currentFiles();
if (ft == null) return;
long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()};
long[] last = lastTransferSample;
@@ -8,20 +8,27 @@ import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
/**
* Our offline message inbox on the server, sending offline messages, and finding the
* database clients to send them to.
*
* <p>Split out of {@link TeamspeakConnection} like {@link ComplaintAdmin}. Every reply comes as
* notifications ahead of the command's completion, collected into {@link #replies}; calls are
* serialised so two requests never share it. Every call blocks and must run off the UI thread.
* <p>Every reply comes as notifications ahead of the command's completion, collected into
* {@link #replies}; commands are serialised so two requests never share it. Requests run in
* the background and fail with a {@link RequestException}.
*/
final class OfflineMessageAdmin {
public final class OfflineMessageAdmin {
/** The longest subject and body an offline message may carry, in characters. */
public static final int SUBJECT_LIMIT = 200;
public static final int BODY_LIMIT = 4096;
/** What a listing answers when it has nothing to list. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
@@ -30,7 +37,8 @@ final class OfflineMessageAdmin {
/** The most matches a nickname search names; each costs a lookup, and lookups flood quickly. */
private static final int MAX_SEARCH_RESULTS = 10;
private final ServerLink link;
private final Uplink uplink;
private final Announcer announce;
/** Senders' nicknames by unique id; they cost a lookup each, so a connection asks once. */
private final Map<String, String> names = new ConcurrentHashMap<>();
@@ -38,8 +46,9 @@ final class OfflineMessageAdmin {
private volatile String awaited;
private volatile List<Map<String, String>> replies;
OfflineMessageAdmin(ServerLink link) {
this.link = link;
OfflineMessageAdmin(Uplink uplink, Announcer announce) {
this.uplink = uplink;
this.announce = announce;
}
/** Forgets what the last server told us; a reconnect may be to another server. */
@@ -59,8 +68,8 @@ final class OfflineMessageAdmin {
awaited = notification;
replies = collected;
try {
link.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
link.awaitEventsProcessed();
uplink.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
uplink.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
@@ -71,7 +80,7 @@ final class OfflineMessageAdmin {
}
private synchronized void execute(String command, CommandParameter... params) throws Exception {
link.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
uplink.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
}
private static CommandSingleParameter param(String key, Object value) {
@@ -80,48 +89,69 @@ final class OfflineMessageAdmin {
// ---- inbox ----
List<OfflineMessage> list() throws Exception {
List<OfflineMessage> messages = new ArrayList<>();
for (Map<String, String> row : query("notifymessagelist", "messagelist")) {
String sender = OfflineMessage.orEmpty(row.get("cluid"));
messages.add(OfflineMessage.from(row, senderName(sender)));
}
return messages;
public CompletableFuture<List<OfflineMessage>> list() {
return uplink.request(() -> {
List<OfflineMessage> messages = new ArrayList<>();
for (Map<String, String> row : query("notifymessagelist", "messagelist")) {
String sender = OfflineMessage.orEmpty(row.get("cluid"));
messages.add(OfflineMessage.from(row, senderName(sender)));
}
return messages;
});
}
private String senderName(String uniqueId) throws Exception {
if (uniqueId.isEmpty()) return "";
String known = names.get(uniqueId);
if (known != null) return known;
DatabaseClient client = lookupUid(uniqueId);
DatabaseClient client = lookup(uniqueId);
String name = client != null ? client.nickname() : uniqueId;
names.put(uniqueId, name);
return name;
}
/** Reads a message's body; this does not mark it read. */
String body(int messageId) throws Exception {
List<Map<String, String>> rows = query("notifymessage", "messageget", param("msgid", messageId));
if (rows.isEmpty()) throw new IllegalStateException("The message is gone.");
return OfflineMessage.orEmpty(rows.get(0).get("message"));
public CompletableFuture<String> body(int messageId) {
return uplink.request(() -> {
List<Map<String, String>> rows = query("notifymessage", "messageget", param("msgid", messageId));
if (rows.isEmpty()) throw new IllegalStateException("The message is gone.");
return OfflineMessage.orEmpty(rows.get(0).get("message"));
});
}
void setRead(int messageId, boolean read) throws Exception {
execute("messageupdateflag", param("msgid", messageId), param("flag", read ? 1 : 0));
/** Marks messages read or unread, stopping at the first the server refuses. */
public CompletableFuture<Void> markRead(Collection<Integer> messageIds, boolean read) {
return uplink.requestVoid(() -> {
for (int id : messageIds) execute("messageupdateflag", param("msgid", id), param("flag", read ? 1 : 0));
});
}
void delete(int messageId) throws Exception {
execute("messagedel", param("msgid", messageId));
/** Deletes messages, stopping at the first the server refuses. */
public CompletableFuture<Void> delete(Collection<Integer> messageIds) {
return uplink.requestVoid(() -> {
for (int id : messageIds) execute("messagedel", param("msgid", id));
});
}
void send(String recipientUid, String subject, String message) throws Exception {
execute("messageadd", param("cluid", recipientUid), param("subject", subject), param("message", message));
/** Sends one offline message to each recipient, stopping at the first the server refuses. */
public CompletableFuture<Void> send(Collection<String> recipientUids, String subject, String message) {
return uplink.requestVoid(() -> {
for (String uid : recipientUids) {
execute("messageadd", param("cluid", uid), param("subject", subject), param("message", message));
}
announce.log("Offline message sent.");
});
}
// ---- recipients ----
/** Looks a client up by unique id; empty when the server has never seen them. */
public CompletableFuture<Optional<DatabaseClient>> lookupUid(String uniqueId) {
return uplink.request(() -> Optional.ofNullable(lookup(uniqueId)));
}
/** @return the client with this unique id, or {@code null} when the server has never seen them */
DatabaseClient lookupUid(String uniqueId) throws Exception {
private DatabaseClient lookup(String uniqueId) throws Exception {
try {
List<Map<String, String>> rows = query("notifyclientnamefromuid", "clientgetnamefromuid",
param("cluid", uniqueId));
@@ -136,7 +166,11 @@ final class OfflineMessageAdmin {
* Clients whose last nickname contains {@code nickname}. Needs
* {@code b_virtualserver_client_dbsearch}, which the server never reports to us up front.
*/
List<DatabaseClient> search(String nickname) throws Exception {
public CompletableFuture<List<DatabaseClient>> search(String nickname) {
return uplink.request(() -> searchNow(nickname));
}
private List<DatabaseClient> searchNow(String nickname) throws Exception {
List<Map<String, String>> found = query("notifyclientdbfind", "clientdbfind",
param("pattern", "%" + nickname + "%"));
List<DatabaseClient> clients = new ArrayList<>();
@@ -7,45 +7,48 @@ import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The server's privilege keys: listing, creating, deleting and redeeming them.
*
* <p>Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same
* way: {@code tokenlist} and {@code tokenadd} reply with notifications ahead of the
* command's own completion. Every call here blocks and must run off the UI thread; the
* connection's public wrappers do that.
* <p>Answered like {@link BanAdmin}: {@code tokenlist} and {@code tokenadd} reply with
* notifications ahead of the command's own completion. Requests run in the background and
* fail with a {@link RequestException}.
*/
final class PrivilegeKeyAdmin {
public final class PrivilegeKeyAdmin {
/** What {@code tokenlist} answers when there are no keys at all. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
private final ServerLink link;
private final Uplink uplink;
/** The {@code tokenlist} reply in progress; one request may be in flight at a time. */
private volatile List<PrivilegeKey> listing;
/** The key the {@code tokenadd} in flight was answered with. */
private volatile String created;
PrivilegeKeyAdmin(ServerLink link) {
this.link = link;
PrivilegeKeyAdmin(Uplink uplink) {
this.uplink = uplink;
}
List<PrivilegeKey> list() throws Exception {
List<PrivilegeKey> keys = Collections.synchronizedList(new ArrayList<>());
listing = keys;
try {
link.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete();
link.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
listing = null;
}
return new ArrayList<>(keys);
public CompletableFuture<List<PrivilegeKey>> list() {
return uplink.request(() -> {
List<PrivilegeKey> keys = Collections.synchronizedList(new ArrayList<>());
listing = keys;
try {
uplink.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete();
uplink.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
listing = null;
}
return new ArrayList<>(keys);
});
}
void onListEntry(UnknownTeamspeakEvent e) {
@@ -59,32 +62,41 @@ final class PrivilegeKeyAdmin {
* @param channelId the channel a channel group key applies in; ignored for a server group
* @return the new key
*/
synchronized String add(boolean channelGroup, int groupId, int channelId, String description) throws Exception {
public CompletableFuture<String> add(boolean channelGroup, int groupId, int channelId, String description) {
SingleCommand cmd = new SingleCommand("tokenadd", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("tokentype", channelGroup ? "1" : "0"));
cmd.add(new CommandSingleParameter("tokenid1", Integer.toString(groupId)));
cmd.add(new CommandSingleParameter("tokenid2", channelGroup ? Integer.toString(channelId) : "0"));
cmd.add(new CommandSingleParameter("tokendescription", description));
created = null;
link.socket().executeCommand(cmd).complete();
link.awaitEventsProcessed();
String token = created;
if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key");
return token;
return uplink.request(() -> {
synchronized (this) {
created = null;
uplink.socket().executeCommand(cmd).complete();
uplink.awaitEventsProcessed();
String token = created;
if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key");
return token;
}
});
}
void onAdded(UnknownTeamspeakEvent e) {
created = e.get("token");
}
void delete(String token) throws Exception {
link.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT,
new CommandSingleParameter("token", token))).complete();
/** Deletes keys one by one, stopping at the first the server refuses. */
public CompletableFuture<Void> delete(Collection<String> tokens) {
return uplink.requestVoid(() -> {
for (String token : tokens) {
uplink.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT,
new CommandSingleParameter("token", token))).complete();
}
});
}
/** Redeems a key; the server announces the resulting group change itself. */
void use(String token) throws Exception {
link.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT,
new CommandSingleParameter("token", token))).complete();
public CompletableFuture<Void> use(String token) {
return uplink.requestVoid(() -> uplink.socket().executeCommand(new SingleCommand("tokenuse",
ProtocolRole.CLIENT, new CommandSingleParameter("token", token))).complete());
}
}
@@ -9,16 +9,16 @@ import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Reads the virtual server's log with {@code logview}, which answers with one
* {@code notifyserverlog} per line, newest first, each also carrying {@code last_pos}: where
* the lines it returned begin in the log file, and so where the older ones end.
*
* <p>Split out of {@link TeamspeakConnection} like {@link BanAdmin}. Every call here blocks
* and must run off the UI thread; the connection's public wrapper does that.
* <p>Requests run in the background and fail with a {@link RequestException}.
*/
final class ServerLogAdmin {
public final class ServerLogAdmin {
/** The most lines {@code logview} returns at once. */
static final int PAGE_LINES = 100;
@@ -26,7 +26,7 @@ final class ServerLogAdmin {
/** What {@code logview} may answer for an empty log. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
private final ServerLink link;
private final Uplink uplink;
/** The {@code logview} reply in progress; one request may be in flight at a time. */
private volatile Reply reply;
@@ -36,25 +36,33 @@ final class ServerLogAdmin {
volatile long lastPos;
}
ServerLogAdmin(ServerLink link) {
this.link = link;
ServerLogAdmin(Uplink uplink) {
this.uplink = uplink;
}
/**
* Reads the newest lines, or with {@code olderFrom} > 0 those ending there (from an
* earlier {@link ServerLogPage#olderFrom()}).
*/
synchronized ServerLogPage read(long olderFrom) throws Exception {
public CompletableFuture<ServerLogPage> read(long olderFrom) {
SingleCommand cmd = new SingleCommand("logview", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("lines", Integer.toString(PAGE_LINES)));
if (olderFrom > 0) cmd.add(new CommandSingleParameter("begin_pos", Long.toString(olderFrom)));
cmd.add(new CommandSingleParameter("reverse", "1"));
cmd.add(new CommandSingleParameter("instance", "0"));
return uplink.request(() -> {
synchronized (this) {
return read(cmd);
}
});
}
private ServerLogPage read(SingleCommand cmd) throws Exception {
Reply r = new Reply();
reply = r;
try {
link.socket().executeCommand(cmd).complete();
link.awaitEventsProcessed();
uplink.socket().executeCommand(cmd).complete();
uplink.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
@@ -58,11 +58,6 @@ public final class TeamspeakConnection implements TS3Listener {
/** The longest reason the protocol carries with a kick. */
public static final int KICK_REASON_LIMIT = 40;
/** The longest reason a complaint may carry. */
public static final int COMPLAINT_REASON_LIMIT = 200;
/** 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;
/** The protocol's reason ids for the two flavours of <b>clientkick</b>. */
private static final int REASON_KICK_CHANNEL = 4;
@@ -85,7 +80,7 @@ public final class TeamspeakConnection implements TS3Listener {
private final AudioBackend audio;
private final ServerModel model = new ServerModel();
/** The socket and the threads requests run on; package-private for {@link ConnectionStatsCollector}. */
final ServerLink link = new ServerLink();
final Uplink uplink = new Uplink();
/** Package-private: read directly by {@link ConnectionEventHandler}. */
final ConnectionListener ui;
private final IconRepository icons;
@@ -100,15 +95,13 @@ public final class TeamspeakConnection implements TS3Listener {
private final ConnectionEventHandler events;
/** Builds {@code getconnectioninfo} snapshots; also package-private for {@link ConnectionEventHandler}. */
final ConnectionStatsCollector stats = new ConnectionStatsCollector(this);
/** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */
/** The server administration helpers; package-private for {@link ConnectionEventHandler}, which feeds them replies. */
final ChannelAdmin channels;
/** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */
final BanAdmin bans = new BanAdmin(link);
final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(link);
final ComplaintAdmin complaints = new ComplaintAdmin(link);
final ServerLogAdmin serverLog = new ServerLogAdmin(link);
/** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */
final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(link);
final BanAdmin bans = new BanAdmin(uplink);
final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(uplink);
final ComplaintAdmin complaints;
final ServerLogAdmin serverLog = new ServerLogAdmin(uplink);
final OfflineMessageAdmin offlineMessages;
private final AvatarAdmin avatarAdmin;
/*
@@ -169,11 +162,11 @@ public final class TeamspeakConnection implements TS3Listener {
/** Refreshes account authentication after sign-in/out while connected. */
public void updateMyTeamSpeak() {
link.submit(socket -> {
uplink.submit(socket -> {
synchronized (myTeamSpeakUpdateLock) {
var login = myTeamSpeak;
var account = myTeamSpeakFeatures && login != null ? login.serverIdentity() : null;
if (link.currentSocket() != socket || !link.isUp()) return;
if (uplink.currentSocket() != socket || !uplink.isUp()) return;
socket.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate);
SingleCommand command = new SingleCommand("updatemytsid", ProtocolRole.CLIENT);
socket.addMyTeamSpeakParameters(command);
@@ -193,12 +186,15 @@ public final class TeamspeakConnection implements TS3Listener {
this.ui = ui;
this.contacts = contacts;
this.chatLog = new ChatLog(settings, ui);
this.announce = new Announcer(model, sounds, ui, chatLog, () -> deafened, link::isUp);
this.announce = new Announcer(model, sounds, ui, chatLog, () -> deafened, uplink::isUp);
this.events = new ConnectionEventHandler(this);
this.icons = new IconRepository(this::fetchIcon, ui::onIconsUpdated);
this.avatars = new AvatarRepository(this::fetchAvatar, ui::onInfoUpdated);
this.channels = new ChannelAdmin(link, model);
this.avatarAdmin = new AvatarAdmin(link, model.permissions(), avatars, this::getSelfUniqueId);
this.channels = new ChannelAdmin(uplink, model);
this.complaints = new ComplaintAdmin(uplink, announce);
this.offlineMessages = new OfflineMessageAdmin(uplink, announce);
this.avatarAdmin = new AvatarAdmin(uplink, model.permissions(), avatars, this::getSelfUniqueId,
flag -> updateSelf(self -> self.avatarFlag = flag));
}
public ServerModel getModel() {
@@ -206,7 +202,7 @@ public final class TeamspeakConnection implements TS3Listener {
}
public boolean isConnected() {
return link.isUp();
return uplink.isUp();
}
public int getSelfClientId() {
@@ -269,7 +265,7 @@ public final class TeamspeakConnection implements TS3Listener {
/** Starts or stops capture to match {@link #microphoneActive}. */
private synchronized void applyMicrophoneState() {
VoiceInput mic = microphone;
if (mic == null || !link.isUp()) return;
if (mic == null || !uplink.isUp()) return;
try {
if (microphoneActive) mic.start();
else mic.stop();
@@ -360,7 +356,7 @@ public final class TeamspeakConnection implements TS3Listener {
});
microphone.setMutedTalkListener(this::onTalkingWhileMuted);
LocalTeamspeakClientSocket client = link.open();
LocalTeamspeakClientSocket client = uplink.open();
client.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate);
client.setIdentity(identity);
client.setNickname(nickname);
@@ -400,7 +396,7 @@ public final class TeamspeakConnection implements TS3Listener {
model.enteredChannel(ourselves.channelId);
}
client.setMicrophone(microphone);
link.established(new FileTransferManager(client, () -> serverHost));
uplink.established(new FileTransferManager(client, () -> serverHost));
icons.retryFailed();
avatars.retryFailed();
if (login != null && login.revision() != loginRevision) updateMyTeamSpeak();
@@ -428,7 +424,7 @@ public final class TeamspeakConnection implements TS3Listener {
// Whoever took over reports on their own; cleaning up here would tear down what a newer
// connect has set up in the meantime.
if (connectAttempt != attempt) return;
link.markDown();
uplink.markDown();
connectErrorId = refusalId(e);
String failure = "Connection failed: " + RequestException.rootMessage(e) + versionHint(e);
ui.onError(failure);
@@ -501,8 +497,8 @@ public final class TeamspeakConnection implements TS3Listener {
*/
private void joinDefaultChannelIfNeeded(String channel, String channelPassword) {
if (normaliseChannelRef(channel) == null) return;
LocalTeamspeakClientSocket sock = link.currentSocket();
if (sock == null || !link.isUp()) return; // already left again
LocalTeamspeakClientSocket sock = uplink.currentSocket();
if (sock == null || !uplink.isUp()) return; // already left again
ChannelNode target = model.findChannelByPath(channel);
if (target == null) {
ui.onError("Channel \"" + channel.trim() + "\" not found on this server.");
@@ -513,7 +509,7 @@ public final class TeamspeakConnection implements TS3Listener {
sock.joinChannel(target.id, (channelPassword == null || channelPassword.isEmpty())
? null : channelPassword);
} catch (Exception e) {
if (!link.isUp()) return;
if (!uplink.isUp()) return;
announce.error("Could not join channel \"" + target.name + "\": ", e);
}
}
@@ -528,7 +524,7 @@ public final class TeamspeakConnection implements TS3Listener {
ClientEntry self = model.getClient(selfClientId);
if (self != null) return self.channelId;
try {
return link.socket().getClientInfo(selfClientId).getChannelId();
return uplink.socket().getClientInfo(selfClientId).getChannelId();
} catch (Exception e) {
return -1;
}
@@ -581,7 +577,7 @@ public final class TeamspeakConnection implements TS3Listener {
leaving = true;
disconnectReasonId = -1;
try {
LocalTeamspeakClientSocket client = link.currentSocket();
LocalTeamspeakClientSocket client = uplink.currentSocket();
if (client != null) client.disconnect(reason);
} catch (Exception ignored) {
} finally {
@@ -640,7 +636,7 @@ public final class TeamspeakConnection implements TS3Listener {
} catch (Exception ignored) {
}
}
link.close();
uplink.close();
}
// ---- self actions ----
@@ -831,7 +827,7 @@ public final class TeamspeakConnection implements TS3Listener {
for (String name : Permissions.UNREPORTED) {
rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name)));
}
link.submit(sock -> {
uplink.submit(sock -> {
Map<String, Integer> powers = new HashMap<>();
for (SingleCommand answer : sock.executeCommand(new MultiCommand("permget", ProtocolRole.CLIENT, rows)).get()) {
Map<String, String> fields = answer.toMap();
@@ -1001,7 +997,7 @@ public final class TeamspeakConnection implements TS3Listener {
public synchronized VoiceRecorder startRecording(VoiceRecorder.Mode mode, Path file) throws IOException {
VoiceOutput out = playback;
VoiceInput mic = microphone;
if (!link.isUp() || out == null || mic == null) throw new IllegalStateException("Not connected");
if (!uplink.isUp() || out == null || mic == null) throw new IllegalStateException("Not connected");
if (recorder != null) throw new IllegalStateException("Already recording");
Map<String, String> names = new HashMap<>();
@@ -1047,7 +1043,7 @@ public final class TeamspeakConnection implements TS3Listener {
if (recorder != rec) return false;
detachRecorder();
}
if (announce && link.isUp()) publishRecording(false);
if (announce && uplink.isUp()) publishRecording(false);
return true;
}
@@ -1091,7 +1087,7 @@ public final class TeamspeakConnection implements TS3Listener {
public double getPingMillis() {
try {
LocalTeamspeakClientSocket sock = link.currentSocket();
LocalTeamspeakClientSocket sock = uplink.currentSocket();
return sock != null ? sock.getPing().getKey() * 1000.0 : -1;
} catch (Exception e) {
return -1;
@@ -1135,8 +1131,8 @@ public final class TeamspeakConnection implements TS3Listener {
* live text instead of whatever an earlier info request cached.
*/
public CompletableFuture<String> requestClientDescription(int clientId) {
return link.request(() -> {
Client c = link.socket().getClientInfo(clientId);
return uplink.request(() -> {
Client c = uplink.socket().getClientInfo(clientId);
String description = c == null ? "" : orEmpty(c.get("client_description"));
ClientEntry e = model.getClient(clientId);
if (e != null) e.description = description;
@@ -1151,11 +1147,11 @@ public final class TeamspeakConnection implements TS3Listener {
*/
public CompletableFuture<Void> setClientDescription(int clientId, String description) {
boolean self = clientId == selfClientId;
return link.requestVoid(() -> {
return uplink.requestVoid(() -> {
SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId)));
cmd.add(new CommandSingleParameter("client_description", description));
link.socket().executeCommand(cmd).complete();
uplink.socket().executeCommand(cmd).complete();
// Only the other clients are told about our own update, so the local entry
// (and the info panel showing it) has to be caught up here.
if (self) {
@@ -1166,59 +1162,37 @@ public final class TeamspeakConnection implements TS3Listener {
});
}
// ---- privilege keys ----
// ---- server administration ----
/** Reads the server's privilege keys. */
public CompletableFuture<List<PrivilegeKey>> requestPrivilegeKeys() {
return link.request(privilegeKeys::list);
/** Channel editing and the server's icon store. */
public ChannelAdmin channels() {
return channels;
}
/**
* Creates a privilege key for a server group, or for a channel group in {@code channelId}.
*
* @return the new key
*/
public CompletableFuture<String> addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) {
return link.request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description));
public BanAdmin bans() {
return bans;
}
/**
* Deletes privilege keys one by one, stopping at the first the server refuses.
*/
public CompletableFuture<Void> deletePrivilegeKeys(Collection<String> tokens) {
return link.requestVoid(() -> {
for (String token : tokens) privilegeKeys.delete(token);
});
public PrivilegeKeyAdmin privilegeKeys() {
return privilegeKeys;
}
public CompletableFuture<Void> usePrivilegeKey(String token) {
return link.requestVoid(() -> privilegeKeys.use(token));
public ComplaintAdmin complaints() {
return complaints;
}
// ---- complaints ----
/** Complains about an online client to the server's admins. */
public void complain(ClientEntry client, String reason) {
act("Failed to send complaint: ", sock -> {
complaints.add(client.databaseId, reason);
announce.log("Complaint sent.");
});
public ServerLogAdmin serverLog() {
return serverLog;
}
/** Reads the server's complaints. */
public CompletableFuture<List<Complaint>> requestComplaints() {
return link.request(complaints::list);
/** Our offline message inbox, sending offline messages and finding their recipients. */
public OfflineMessageAdmin offlineMessages() {
return offlineMessages;
}
/**
* Removes every complaint about each of {@code targetDbIds}, then each of {@code single},
* stopping at the first the server refuses.
*/
public CompletableFuture<Void> deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> single) {
return link.requestVoid(() -> {
for (int target : targetDbIds) complaints.deleteAll(target);
for (Complaint complaint : single) complaints.delete(complaint);
});
/** Setting and removing our avatar, and deleting others'. */
public AvatarAdmin avatarAdmin() {
return avatarAdmin;
}
// ---- offline messages ----
@@ -1239,96 +1213,6 @@ public final class TeamspeakConnection implements TS3Listener {
ui.onUnreadMessagesChanged(unread);
}
/** Lists our offline message inbox. */
public CompletableFuture<List<OfflineMessage>> requestOfflineMessages() {
return link.request(offlineMessages::list);
}
/** Reads a message's body. */
public CompletableFuture<String> requestOfflineMessageBody(int messageId) {
return link.request(() -> offlineMessages.body(messageId));
}
/**
* Marks messages read or unread, stopping at the first the server refuses.
*/
public CompletableFuture<Void> markOfflineMessages(Collection<Integer> messageIds, boolean read) {
return link.requestVoid(() -> {
for (int id : messageIds) offlineMessages.setRead(id, read);
});
}
public CompletableFuture<Void> deleteOfflineMessages(Collection<Integer> messageIds) {
return link.requestVoid(() -> {
for (int id : messageIds) offlineMessages.delete(id);
});
}
/**
* Sends one offline message to each recipient, stopping at the first the server refuses.
*/
public CompletableFuture<Void> sendOfflineMessage(Collection<String> recipientUids, String subject, String message) {
return link.requestVoid(() -> {
for (String uid : recipientUids) offlineMessages.send(uid, subject, message);
announce.log("Offline message sent.");
});
}
/** Looks a client up by unique id; empty when the server has never seen them. */
public CompletableFuture<Optional<DatabaseClient>> lookupDatabaseClient(String uniqueId) {
return link.request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId)));
}
/**
* Finds clients whose last nickname contains {@code nickname}.
*
* A server that will not let us search refuses for lack of permission.
*/
public CompletableFuture<List<DatabaseClient>> searchDatabaseClients(String nickname) {
return link.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.
*/
public CompletableFuture<ServerLogPage> requestServerLog(long olderFrom) {
return link.request(() -> serverLog.read(olderFrom));
}
// ---- bans ----
/** Reads the server's ban list. */
public CompletableFuture<List<BanEntry>> requestBanList() {
return link.request(bans::list);
}
public CompletableFuture<Void> addBan(BanRule rule) {
return link.requestVoid(() -> bans.add(rule));
}
/**
* Rewrites an existing ban.
*/
public CompletableFuture<Void> replaceBan(int banId, BanRule rule) {
return link.requestVoid(() -> bans.replace(banId, rule));
}
/**
* Deletes bans one by one, stopping at the first the server refuses.
*/
public CompletableFuture<Void> deleteBans(Collection<Integer> banIds) {
return link.requestVoid(() -> {
for (int id : banIds) bans.delete(id);
});
}
/**
* Our own unique identifier on this server, which is how the server names us as a
* ban's creator; empty while not connected.
*/
// ---- contacts ----
public ContactStore getContacts() {
@@ -1382,7 +1266,7 @@ public final class TeamspeakConnection implements TS3Listener {
* own server, which is a change that triggers the other's re-application, and so on.
*/
public void applyContacts() {
if (!link.isUp()) return;
if (!uplink.isUp()) return;
for (ClientEntry c : model.allClients()) {
Contact contact = applyContactPlayback(c);
if (contact != null && contact.lastSeen == null) {
@@ -1416,95 +1300,16 @@ public final class TeamspeakConnection implements TS3Listener {
return id == null ? "" : id.getUid().toBase64();
}
// ---- channel administration ----
/**
* Reads a channel's editable properties.
*/
public CompletableFuture<ChannelSettings> requestChannelSettings(int channelId) {
return link.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 CompletableFuture<Map<String, Integer>> requestChannelPermissions(int channelId) {
return link.request(() -> channels.readPermissions(channelId));
}
/**
* Applies an edited channel: its changed properties first, then its needed-power
* permissions.
*/
public CompletableFuture<Void> applyChannelEdit(int channelId, Map<String, String> changes,
Map<String, Integer> setPermissions,
Collection<String> removePermissions) {
return link.requestVoid(() -> {
channels.edit(channelId, changes);
channels.writePermissions(channelId, setPermissions, removePermissions);
if (changes.containsKey("channel_description")) {
ChannelNode node = model.getChannel(channelId);
// the server does not notify the invoker of their own description change
if (node != null && node.descriptionLoaded) {
node.descriptionLoaded = false;
requestChannelInfo(channelId);
}
}
});
}
/**
* Creates a channel below {@code parentId} (0 being the top level) and gives it the
* channel permissions it was created with.
*
* @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 CompletableFuture<Integer> createChannel(int parentId, Map<String, String> properties,
Map<String, Integer> permissions) {
return link.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: " + RequestException.rootMessage(e));
}
return channelId;
});
}
/**
* Deletes a channel; with {@code force}, also one that has sub-channels or clients in it.
*/
public CompletableFuture<Void> deleteChannel(int channelId, boolean force) {
return link.requestVoid(() -> channels.delete(channelId, force));
}
/** The ids of the icons uploaded to this virtual server. */
public CompletableFuture<List<Long>> requestServerIcons() {
return link.request(channels::listIcons);
}
/** Uploads an image as a server icon and reports the new icon's id. */
public CompletableFuture<Long> uploadIcon(File source) {
return link.request(() -> channels.uploadIcon(source));
}
/** Deletes a server icon. */
public CompletableFuture<Void> deleteIcon(long iconId) {
return link.requestVoid(() -> channels.deleteIcon(iconId));
}
// ---- requests ----
/** Sends a request in the background, reporting a failure as {@code errorPrefix} and the reason. */
private void act(String errorPrefix, ServerLink.Action action) {
link.submit(action, e -> announce.error(errorPrefix, e));
private void act(String errorPrefix, Uplink.Action action) {
uplink.submit(action, e -> announce.error(errorPrefix, e));
}
/** Sends a request in the background whose failure nobody needs to hear about. */
private void attempt(ServerLink.Action action) {
link.submit(action, e -> {
private void attempt(Uplink.Action action) {
uplink.submit(action, e -> {
});
}
@@ -1517,7 +1322,7 @@ public final class TeamspeakConnection implements TS3Listener {
/** Reads an icon out of the virtual server's file repository (channel 0). */
private byte[] fetchIcon(long iconId) throws Exception {
return link.files().downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES);
return uplink.files().downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES);
}
// ---- avatars ----
@@ -1532,46 +1337,18 @@ public final class TeamspeakConnection implements TS3Listener {
return client == null ? null : avatars.get(client.uniqueId, client.avatarFlag);
}
/** How large an avatar this server lets us upload, in bytes. */
public int maxAvatarBytes() {
return model.permissions().maxAvatarBytes();
}
/**
* Uploads an image as our avatar and publishes it to the other clients.
*/
public CompletableFuture<Void> setAvatar(File source) {
return link.requestVoid(() -> {
String flag = avatarAdmin.upload(source);
updateSelf(self -> self.avatarFlag = flag);
});
}
/** Withdraws our avatar. */
public CompletableFuture<Void> removeAvatar() {
return link.requestVoid(() -> {
avatarAdmin.remove();
updateSelf(self -> self.avatarFlag = "");
});
}
/** Deletes another client's avatar. */
public CompletableFuture<Void> removeAvatarOf(ClientEntry client) {
return link.requestVoid(() -> avatarAdmin.removeOther(client.uniqueId));
}
/** Reads a client's avatar out of the virtual server's file repository (channel 0). */
private byte[] fetchAvatar(String uniqueId) throws Exception {
String name = AvatarNaming.fileName(uniqueId);
if (name == null) throw new IllegalArgumentException("Not a client unique id: " + uniqueId);
return link.files().downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES);
return uplink.files().downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES);
}
// ---- whisper ----
/** Sends the microphone's voice to {@code targets} as a whisper, or to our channel again with null. */
public void setWhisperTargets(Whisper.Targets targets) {
LocalTeamspeakClientSocket sock = link.currentSocket();
LocalTeamspeakClientSocket sock = uplink.currentSocket();
if (sock == null) return;
if (targets == null) {
sock.setWhisperTarget(null);
@@ -1593,7 +1370,7 @@ public final class TeamspeakConnection implements TS3Listener {
/** Whether a live connection capable of file transfers is available. */
public boolean canTransferFiles() {
return link.canTransferFiles();
return uplink.canTransferFiles();
}
/**
@@ -1602,32 +1379,32 @@ public final class TeamspeakConnection implements TS3Listener {
*/
public java.util.List<RemoteFile> listFiles(int channelId, String channelPassword, String path)
throws Exception {
return link.files().list(channelId, channelPassword, path);
return uplink.files().list(channelId, channelPassword, path);
}
public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception {
link.files().createDirectory(channelId, channelPassword, dirPath);
uplink.files().createDirectory(channelId, channelPassword, dirPath);
}
public void deleteFile(int channelId, String channelPassword, String fullPath) throws Exception {
link.files().delete(channelId, channelPassword, fullPath);
uplink.files().delete(channelId, channelPassword, fullPath);
}
public void renameFile(int channelId, String channelPassword, String oldFullPath, String newFullPath)
throws Exception {
link.files().rename(channelId, channelPassword, oldFullPath, newFullPath);
uplink.files().rename(channelId, channelPassword, oldFullPath, newFullPath);
}
/** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */
public FileTransfer downloadFile(int channelId, String channelPassword, String remoteFullPath,
File target, FileTransfer.Listener listener) {
return link.files().download(channelId, channelPassword, remoteFullPath, target, announcing(listener));
return uplink.files().download(channelId, channelPassword, remoteFullPath, target, announcing(listener));
}
/** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */
public FileTransfer uploadFile(int channelId, String channelPassword, String remoteFullPath,
File source, boolean overwrite, FileTransfer.Listener listener) {
return link.files().upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener));
return uplink.files().upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener));
}
/**
@@ -1659,7 +1436,7 @@ public final class TeamspeakConnection implements TS3Listener {
* version, platform and idle time. May be called repeatedly to poll.
*/
public void requestConnectionInfo(int clientId, Consumer<ConnectionStats> callback) {
if (!link.isUp()) return;
if (!uplink.isUp()) return;
stats.request(clientId, callback);
}
@@ -1673,7 +1450,7 @@ public final class TeamspeakConnection implements TS3Listener {
*/
@Override
public void onDisconnected(DisconnectedEvent e) {
link.markDown();
uplink.markDown();
disconnectReasonId = e.getReasonId();
safeCleanup();
announceDisconnect(false);
@@ -1689,7 +1466,7 @@ public final class TeamspeakConnection implements TS3Listener {
* never told it); {@code null} before the server has introduced itself.
*/
public String serverUniqueId() {
LocalTeamspeakClientSocket client = link.currentSocket();
LocalTeamspeakClientSocket client = uplink.currentSocket();
if (client == null) return null;
Uid uid = client.getServerUid();
return uid == null ? null : uid.toBase64();
@@ -18,7 +18,7 @@ import java.util.function.Consumer;
* <p>Set up by the connect thread and torn down by whichever thread notices the end; read
* from the UI, event and action threads, so each reader copies a field before using it.
*/
final class ServerLink {
final class Uplink {
/** A request made on the socket it was issued on. */
interface Action {
@@ -9,11 +9,18 @@ import eu.lixko.ts3j.client.myts.ChatAttachment;
import eu.lixko.ts3j.client.myts.ChatAttachments;
import eu.lixko.ts3j.client.myts.MyTsException;
import eu.lixko.ts3j.client.contacts.ContactStore;
import eu.lixko.ts3j.client.net.AvatarAdmin;
import eu.lixko.ts3j.client.net.BanAdmin;
import eu.lixko.ts3j.client.net.ChannelAdmin;
import eu.lixko.ts3j.client.net.ChannelNode;
import eu.lixko.ts3j.client.net.ClientEntry;
import eu.lixko.ts3j.client.net.ComplaintAdmin;
import eu.lixko.ts3j.client.net.ConnectionListener;
import eu.lixko.ts3j.client.net.OfflineMessageAdmin;
import eu.lixko.ts3j.client.net.Permissions;
import eu.lixko.ts3j.client.net.PrivilegeKeyAdmin;
import eu.lixko.ts3j.client.net.Replies;
import eu.lixko.ts3j.client.net.ServerLogAdmin;
import eu.lixko.ts3j.client.net.TeamspeakConnection;
import eu.lixko.ts3j.client.net.Whisper;
import eu.lixko.ts3j.client.recording.VoiceRecorder;
@@ -694,6 +701,36 @@ public final class ServerSession {
return permissions().canRequestTalkPower() && self != null && conn.getModel().lacksTalkPower(self);
}
// ---- server administration ----
public ChannelAdmin channels() {
return conn.channels();
}
public BanAdmin bans() {
return conn.bans();
}
public PrivilegeKeyAdmin privilegeKeys() {
return conn.privilegeKeys();
}
public ComplaintAdmin complaints() {
return conn.complaints();
}
public ServerLogAdmin serverLog() {
return conn.serverLog();
}
public OfflineMessageAdmin offlineMessages() {
return conn.offlineMessages();
}
public AvatarAdmin avatarAdmin() {
return conn.avatarAdmin();
}
// ---- connection events ----
private void setStatus(String text) {
@@ -713,7 +750,7 @@ public final class ServerSession {
tokenLink = null;
Target target = lastTarget;
if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return;
Replies.handle(conn.usePrivilegeKey(link.token), Runnable::run,
Replies.handle(conn.privilegeKeys().use(link.token), Runnable::run,
() -> listener.onSystemMessage("Privilege key used."),
failure -> listener.onSystemMessage("Could not use the privilege key: " + failure.getMessage()));
}
@@ -36,7 +36,7 @@ final class AvatarActions {
if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return;
File file = chooser.getSelectedFile();
lastDirectory = file.getParentFile();
Edt.onFailure(conn.setAvatar(file), failure -> show("Error uploading avatar: " + failure.getMessage()));
Edt.onFailure(conn.avatarAdmin().set(file), failure -> show("Error uploading avatar: " + failure.getMessage()));
}
/** Uploads someone else's avatar as ours. */
@@ -50,20 +50,20 @@ final class AvatarActions {
show("Error uploading avatar: " + e.getMessage());
return;
}
CompletableFuture<Void> upload = conn.setAvatar(file);
CompletableFuture<Void> upload = conn.avatarAdmin().set(file);
upload.whenComplete((ignored, failure) -> file.delete());
Edt.onFailure(upload, failure -> show("Error uploading avatar: " + failure.getMessage()));
}
void delete() {
if (!conn.isConnected()) return;
Edt.onFailure(conn.removeAvatar(), failure -> show("Error deleting avatar: " + failure.getMessage()));
Edt.onFailure(conn.avatarAdmin().remove(), failure -> show("Error deleting avatar: " + failure.getMessage()));
}
/** Deletes another client's avatar for everyone. */
void deleteOf(ClientEntry client) {
if (!conn.isConnected()) return;
Edt.onFailure(conn.removeAvatarOf(client), failure -> show("Error deleting avatar: " + failure.getMessage()));
Edt.onFailure(conn.avatarAdmin().removeOf(client), failure -> show("Error deleting avatar: " + failure.getMessage()));
}
private void show(String message) {
@@ -375,7 +375,7 @@ final class BanListDialog extends JDialog {
if (loading) return;
loading = true;
status.setText("Loading…");
Edt.handle(conn.requestBanList(), bans -> {
Edt.handle(conn.bans().list(), bans -> {
loading = false;
if (!isDisplayable()) return;
tableModel.setBans(bans);
@@ -438,7 +438,7 @@ final class BanListDialog extends JDialog {
dialog.setVisible(true);
BanRule rule = dialog.getRule();
if (rule == null) return;
afterChange(conn.addBan(rule), "Error adding ban: ",
afterChange(conn.bans().add(rule), "Error adding ban: ",
() -> JOptionPane.showMessageDialog(this, "Your ban was successfully added.", "Ban List",
JOptionPane.INFORMATION_MESSAGE));
}
@@ -450,7 +450,7 @@ final class BanListDialog extends JDialog {
dialog.setVisible(true);
BanRule rule = dialog.getRule();
if (rule == null) return;
afterChange(conn.replaceBan(ban.id, rule), "Error editing ban: ");
afterChange(conn.bans().replace(ban.id, rule), "Error editing ban: ");
}
private void removeBans() {
@@ -460,7 +460,7 @@ final class BanListDialog extends JDialog {
"Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
List<Integer> ids = bans.stream().map(b -> b.id).collect(Collectors.toList());
afterChange(conn.deleteBans(ids), "Error deleting ban: ");
afterChange(conn.bans().delete(ids), "Error deleting ban: ");
}
/** Reports a failed change, or re-reads the list so the table shows what the server now holds. */
@@ -286,12 +286,12 @@ final class ChannelDialog extends JDialog {
// ---- loading ----
private void load() {
Edt.handle(conn.requestChannelSettings(channel.id), this::apply, failure -> {
Edt.handle(conn.channels().settings(channel.id), this::apply, failure -> {
JOptionPane.showMessageDialog(this, "Could not read the channel: " + failure.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
dispose();
});
Edt.handle(conn.requestChannelPermissions(channel.id), permissionsPanel::read,
Edt.handle(conn.channels().permissions(channel.id), permissionsPanel::read,
failure -> permissionsPanel.showUnavailable("No permission to view channel permissions."));
}
@@ -352,7 +352,7 @@ final class ChannelDialog extends JDialog {
}
private void chooseIcon() {
IconChooserDialog chooser = new IconChooserDialog(this, conn, groupIcons);
IconChooserDialog chooser = new IconChooserDialog(this, conn.channels(), groupIcons);
chooser.setVisible(true);
if (chooser.isAccepted()) setIconId(chooser.getIconId());
}
@@ -397,7 +397,7 @@ final class ChannelDialog extends JDialog {
if (channel == null) {
ok.setEnabled(false);
finish(conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed()),
finish(conn.channels().create(parentId, edited.creationParameters(), permissionsPanel.changed()),
"Could not create the channel: ");
return;
}
@@ -411,7 +411,7 @@ final class ChannelDialog extends JDialog {
}
ok.setEnabled(false);
finish(conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions),
finish(conn.channels().edit(channel.id, changes, setPermissions, clearedPermissions),
"Could not save the channel: ");
}
@@ -256,7 +256,7 @@ final class ComplaintsDialog extends JDialog {
if (loading) return;
loading = true;
status.setText("Loading…");
Edt.handle(conn.requestComplaints(), complaints -> {
Edt.handle(conn.complaints().list(), complaints -> {
loading = false;
if (!isDisplayable()) return;
setTargets(groupByTarget(complaints));
@@ -384,7 +384,7 @@ final class ComplaintsDialog extends JDialog {
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
List<Integer> whole = sel.whole().stream().map(Target::dbId).toList();
Edt.handle(conn.deleteComplaints(whole, sel.single()), () -> {
Edt.handle(conn.complaints().delete(whole, sel.single()), () -> {
if (isDisplayable()) reload();
}, failure -> {
if (!isDisplayable()) return;
@@ -3,7 +3,7 @@ package eu.lixko.ts3j.client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import eu.lixko.ts3j.client.net.IconRepository;
import eu.lixko.ts3j.client.net.TeamspeakConnection;
import eu.lixko.ts3j.client.net.ChannelAdmin;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
@@ -42,7 +42,7 @@ final class IconChooserDialog extends JDialog {
/** Give up repainting once nothing has arrived for this long. */
private static final int REFRESH_TIMEOUT_MS = 20_000;
private final TeamspeakConnection conn;
private final ChannelAdmin channels;
private final GroupIcons groupIcons;
private final DefaultListModel<Long> remoteModel = new DefaultListModel<>();
@@ -55,9 +55,9 @@ final class IconChooserDialog extends JDialog {
private long chosenIconId;
private boolean accepted;
IconChooserDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons) {
IconChooserDialog(Window owner, ChannelAdmin channels, GroupIcons groupIcons) {
super(owner, "Icons", ModalityType.APPLICATION_MODAL);
this.conn = conn;
this.channels = channels;
this.groupIcons = groupIcons;
configure(remoteList);
@@ -178,7 +178,7 @@ final class IconChooserDialog extends JDialog {
private void loadRemoteIcons() {
status.setText("Loading icons…");
Edt.handle(conn.requestServerIcons(), ids -> {
Edt.handle(channels.icons(), ids -> {
status.setText(" ");
remoteModel.clear();
for (Long id : ids) remoteModel.addElement(id);
@@ -192,7 +192,7 @@ final class IconChooserDialog extends JDialog {
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
File file = chooser.getSelectedFile();
status.setText("Uploading " + file.getName() + "…");
Edt.handle(conn.uploadIcon(file), iconId -> {
Edt.handle(channels.uploadIcon(file), iconId -> {
loadRemoteIcons();
startRefreshing();
}, failure -> {
@@ -209,7 +209,7 @@ final class IconChooserDialog extends JDialog {
"Permanently delete this icon from the server?", "Confirmation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
Edt.handle(conn.deleteIcon(id), () -> remoteModel.removeElement(id),
Edt.handle(channels.deleteIcon(id), () -> remoteModel.removeElement(id),
failure -> JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + failure.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE));
}
@@ -252,8 +252,8 @@ final class IconChooserDialog extends JDialog {
}
/** Convenience for callers that only need the picked id. */
static long pick(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, long current) {
IconChooserDialog dialog = new IconChooserDialog(owner, conn, groupIcons);
static long pick(Window owner, ChannelAdmin channels, GroupIcons groupIcons, long current) {
IconChooserDialog dialog = new IconChooserDialog(owner, channels, groupIcons);
dialog.setVisible(true);
return dialog.isAccepted() ? dialog.getIconId() : current;
}
@@ -8,7 +8,7 @@ import eu.lixko.ts3j.client.contacts.ContactStore;
import eu.lixko.ts3j.client.contacts.ContactType;
import eu.lixko.ts3j.client.net.DatabaseClient;
import eu.lixko.ts3j.client.net.OfflineMessage;
import eu.lixko.ts3j.client.net.TeamspeakConnection;
import eu.lixko.ts3j.client.net.OfflineMessageAdmin;
import eu.lixko.ts3j.client.text.BBCode;
import javax.swing.BorderFactory;
@@ -71,7 +71,7 @@ final class OfflineMessageComposeDialog extends JDialog {
/** The client property naming the recipient a chip stands for. */
private static final String CHIP_UID = "ts3.recipientUid";
private final TeamspeakConnection conn;
private final OfflineMessageAdmin messages;
/** Recipients by unique id, in the order they were added. */
private final Map<String, DatabaseClient> recipients = new LinkedHashMap<>();
@@ -86,19 +86,19 @@ final class OfflineMessageComposeDialog extends JDialog {
private final JButton sendButton = new JButton("Send");
private boolean sending;
static OfflineMessageComposeDialog compose(Window owner, TeamspeakConnection conn, ContactStore contacts) {
return new OfflineMessageComposeDialog(owner, "New Offline Message", conn, contacts);
static OfflineMessageComposeDialog compose(Window owner, OfflineMessageAdmin messages, ContactStore contacts) {
return new OfflineMessageComposeDialog(owner, "New Offline Message", messages, contacts);
}
/** A reply to {@code message}, quoting {@code body}. */
static OfflineMessageComposeDialog reply(Window owner, TeamspeakConnection conn, ContactStore contacts,
static OfflineMessageComposeDialog reply(Window owner, OfflineMessageAdmin messages, ContactStore contacts,
OfflineMessage message, String body) {
OfflineMessageComposeDialog d = new OfflineMessageComposeDialog(owner, "Reply Offline Message", conn, contacts);
OfflineMessageComposeDialog d = new OfflineMessageComposeDialog(owner, "Reply Offline Message", messages, contacts);
d.addRecipient(new DatabaseClient(message.senderUid(), 0, message.senderName()));
String subject = message.subject().regionMatches(true, 0, "Re:", 0, 3)
? message.subject() : "Re: " + message.subject();
d.subjectField.setText(subject.length() > TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT
? subject.substring(0, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT) : subject);
d.subjectField.setText(subject.length() > OfflineMessageAdmin.SUBJECT_LIMIT
? subject.substring(0, OfflineMessageAdmin.SUBJECT_LIMIT) : subject);
d.bodyArea.setText(quote(message.senderName(), body));
d.bodyArea.setCaretPosition(d.bodyArea.getDocument().getLength());
return d;
@@ -111,12 +111,12 @@ final class OfflineMessageComposeDialog extends JDialog {
return out.toString();
}
private OfflineMessageComposeDialog(Window owner, String title, TeamspeakConnection conn, ContactStore contacts) {
private OfflineMessageComposeDialog(Window owner, String title, OfflineMessageAdmin messages, ContactStore contacts) {
super(owner, title, ModalityType.MODELESS);
this.conn = conn;
this.messages = messages;
limit(subjectField, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT);
limit(bodyArea, TeamspeakConnection.OFFLINE_MESSAGE_LIMIT);
limit(subjectField, OfflineMessageAdmin.SUBJECT_LIMIT);
limit(bodyArea, OfflineMessageAdmin.BODY_LIMIT);
for (Contact c : contacts.all()) {
if (c.type != ContactType.BLOCKED) {
available.addElement(new DatabaseClient(c.uniqueId, 0, c.nickname.isEmpty() ? c.uniqueId : c.nickname));
@@ -362,7 +362,7 @@ final class OfflineMessageComposeDialog extends JDialog {
String typed = recipientField.getText().trim();
if (typed.isEmpty()) return;
if (UNIQUE_ID.matcher(typed).matches()) {
Edt.handle(conn.lookupDatabaseClient(typed),
Edt.handle(messages.lookupUid(typed),
client -> client.ifPresentOrElse(this::accept,
() -> showRecipientError("The unique ID is unknown on this server.")),
failure -> showRecipientError(failure.getMessage()));
@@ -374,7 +374,7 @@ final class OfflineMessageComposeDialog extends JDialog {
return;
}
}
Edt.handle(conn.searchDatabaseClients(typed), found -> {
Edt.handle(messages.search(typed), found -> {
if (found.isEmpty()) {
showRecipientError("The nickname is unknown on this server.");
return;
@@ -431,7 +431,7 @@ final class OfflineMessageComposeDialog extends JDialog {
if (!sendButton.isEnabled()) return;
sending = true;
updateSendButton();
Edt.handle(conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText()),
Edt.handle(messages.send(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText()),
() -> {
sending = false;
if (isDisplayable()) dispose();
@@ -327,7 +327,7 @@ final class OfflineMessagesDialog extends JDialog {
if (loading) return;
loading = true;
status.setText("Loading…");
Edt.handle(conn.requestOfflineMessages(), messages -> {
Edt.handle(conn.offlineMessages().list(), messages -> {
loading = false;
if (!isDisplayable()) return;
setMessages(messages);
@@ -388,7 +388,7 @@ final class OfflineMessagesDialog extends JDialog {
return;
}
bodyPane.setText("");
Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> {
Edt.handle(conn.offlineMessages().body(message.id()), text -> {
if (!isDisplayable()) return;
bodies.put(message.id(), text);
if (shownId == message.id()) showBody(message, text);
@@ -419,7 +419,7 @@ final class OfflineMessagesDialog extends JDialog {
composer.reply(message, body);
return;
}
Edt.handle(conn.requestOfflineMessageBody(message.id()), text -> {
Edt.handle(conn.offlineMessages().body(message.id()), text -> {
if (!isDisplayable()) return;
bodies.put(message.id(), text);
composer.reply(message, text);
@@ -436,7 +436,7 @@ final class OfflineMessagesDialog extends JDialog {
private void mark(List<OfflineMessage> messages, boolean read) {
if (messages.isEmpty()) return;
for (OfflineMessage m : messages) tableModel.replace(m.withRead(read));
Edt.onFailure(conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read), failure -> {
Edt.onFailure(conn.offlineMessages().markRead(messages.stream().map(OfflineMessage::id).toList(), read), failure -> {
if (!isDisplayable()) return;
status.setText("Failed to update offline message: " + failure.getMessage());
reload();
@@ -460,7 +460,7 @@ final class OfflineMessagesDialog extends JDialog {
for (OfflineMessage m : selected) bodies.remove(m.id());
reload();
};
Edt.handle(conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList()), () -> {
Edt.handle(conn.offlineMessages().delete(selected.stream().map(OfflineMessage::id).toList()), () -> {
if (isDisplayable()) deleted.run();
}, failure -> {
if (!isDisplayable()) return;
@@ -148,7 +148,7 @@ final class PrivilegeKeyCreateDialog extends JDialog {
Group group = (Group) groupBox.getSelectedItem();
ChannelNode channel = (ChannelNode) channelBox.getSelectedItem();
create.setEnabled(false);
Edt.handle(conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id,
Edt.handle(conn.privilegeKeys().add(forChannelGroup(), group.id, channel == null ? 0 : channel.id,
descriptionField.getText().trim()), key -> {
if (!isDisplayable()) return;
updateCreate();
@@ -212,7 +212,7 @@ final class PrivilegeKeysDialog extends JDialog {
if (loading) return;
loading = true;
status.setText("Loading…");
Edt.handle(conn.requestPrivilegeKeys(), keys -> {
Edt.handle(conn.privilegeKeys().list(), keys -> {
loading = false;
if (!isDisplayable()) return;
tableModel.setKeys(keys);
@@ -252,7 +252,7 @@ final class PrivilegeKeysDialog extends JDialog {
"Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
List<String> tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList());
Edt.handle(conn.deletePrivilegeKeys(tokens), () -> {
Edt.handle(conn.privilegeKeys().delete(tokens), () -> {
if (isDisplayable()) reload();
}, failure -> {
if (!isDisplayable()) return;
@@ -264,7 +264,7 @@ final class ServerLogDialog extends JDialog {
loading = true;
olderButton.setEnabled(false);
showStatus("Loading…", Theme.chatEvent());
Edt.handle(conn.requestServerLog(from), page -> {
Edt.handle(conn.serverLog().read(from), page -> {
loading = false;
if (isDisplayable()) received(page, from > 0);
}, failure -> {
@@ -227,7 +227,7 @@ final class ServerTab {
@Override
public void reply(OfflineMessage message, String body) {
if (!session.isConnected()) return;
OfflineMessageComposeDialog.reply(offlineMessages, conn, contacts, message, body).setVisible(true);
OfflineMessageComposeDialog.reply(offlineMessages, conn.offlineMessages(), contacts, message, body).setVisible(true);
}
});
}
@@ -238,7 +238,7 @@ final class ServerTab {
void composeOfflineMessage() {
if (!session.permissions().canSendOfflineMessages()) return;
Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host;
OfflineMessageComposeDialog.compose(owner, conn, contacts).setVisible(true);
OfflineMessageComposeDialog.compose(owner, conn.offlineMessages(), contacts).setVisible(true);
}
/** New mail refreshes an open inbox; a message being read does not need to. */
@@ -254,7 +254,7 @@ final class ServerTab {
String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key",
JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null);
if (key == null || key.isBlank()) return;
Edt.onFailure(conn.usePrivilegeKey(key.trim()), failure -> JOptionPane.showMessageDialog(host,
Edt.onFailure(conn.privilegeKeys().use(key.trim()), failure -> JOptionPane.showMessageDialog(host,
failure.getMessage(), "Error using Privilege Key", JOptionPane.ERROR_MESSAGE));
}
@@ -5,6 +5,7 @@ import eu.lixko.ts3j.client.net.ChannelNode;
import eu.lixko.ts3j.client.net.Spacers;
import eu.lixko.ts3j.client.net.ChannelSettings;
import eu.lixko.ts3j.client.net.ClientEntry;
import eu.lixko.ts3j.client.net.ComplaintAdmin;
import eu.lixko.ts3j.client.net.Group;
import eu.lixko.ts3j.client.net.TeamspeakConnection;
import eu.lixko.ts3j.client.text.TsLink;
@@ -140,8 +141,8 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
public void complainAboutClient(ClientEntry client) {
if (!conn.isConnected()) return;
String reason = ReasonDialog.prompt(host, "Make a Complaint", "Enter the reason for your complaint:",
TeamspeakConnection.COMPLAINT_REASON_LIMIT);
if (reason != null) conn.complain(client, reason);
ComplaintAdmin.REASON_LIMIT);
if (reason != null) conn.complaints().complain(client, reason);
}
@Override
@@ -314,7 +315,7 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
return;
}
Edt.onFailure(conn.deleteChannel(channel.id, true), failure -> JOptionPane.showMessageDialog(host,
Edt.onFailure(conn.channels().delete(channel.id, true), failure -> JOptionPane.showMessageDialog(host,
"Could not delete the channel: " + failure.getMessage(), "Error", JOptionPane.ERROR_MESSAGE));
}