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