Run server requests through ServerLink, not the whole connection
ServerLink owns what lives from one connect to its teardown: the socket, the thread ts3j dispatches events on, the threads requests run on and the file transfer channel. It runs requests in the background and says whether we are connected. The *Admin helpers take it, plus the model, permissions or avatar store where they need them, instead of the whole TeamspeakConnection; the connection's file transfer calls share its "not connected" check instead of repeating it. A myTeamSpeak refresh that fails because we left meanwhile is no longer reported, as for every other request. Also corrects 4a's commit hash in AUDIT-STRUCTURE.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,8 +12,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo
|
|||||||
| 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | done (`e255a46`): one `applyClientProperties`. It also fixed a joining channel commander shown as none, and picks up the description a client enters with |
|
| 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | done (`e255a46`): one `applyClientProperties`. It also fixed a joining channel commander shown as none, and picks up the description a client enters with |
|
||||||
| 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 (`c28c2ce`): `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 | open |
|
| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | done (uncommitted): `ServerLink` owns the socket, event and request threads and file transfers, and runs requests; the helpers take it (plus the model, permissions or avatars where they need them) |
|
||||||
| 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | open |
|
| 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | open |
|
||||||
| 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 |
|
||||||
|
|||||||
@@ -4,14 +4,15 @@ import com.github.manevolent.ts3j.command.SingleCommand;
|
|||||||
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
|
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
|
||||||
import com.github.manevolent.ts3j.protocol.ProtocolRole;
|
import com.github.manevolent.ts3j.protocol.ProtocolRole;
|
||||||
import eu.lixko.ts3j.client.net.avatar.AvatarNaming;
|
import eu.lixko.ts3j.client.net.avatar.AvatarNaming;
|
||||||
|
import eu.lixko.ts3j.client.net.avatar.AvatarRepository;
|
||||||
import eu.lixko.ts3j.client.net.avatar.ImageFormat;
|
import eu.lixko.ts3j.client.net.avatar.ImageFormat;
|
||||||
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
|
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
|
||||||
import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Publishes and withdraws the local client's avatar, the way the official client does
|
* Publishes and withdraws the local client's avatar, the way the official client does
|
||||||
@@ -26,10 +27,17 @@ final class AvatarAdmin {
|
|||||||
|
|
||||||
private static final long UPLOAD_TIMEOUT_MS = 60_000;
|
private static final long UPLOAD_TIMEOUT_MS = 60_000;
|
||||||
|
|
||||||
private final TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
private final Permissions permissions;
|
||||||
|
private final AvatarRepository avatars;
|
||||||
|
/** Our unique id, which names our avatar file. */
|
||||||
|
private final Supplier<String> selfUniqueId;
|
||||||
|
|
||||||
AvatarAdmin(TeamspeakConnection conn) {
|
AvatarAdmin(ServerLink link, Permissions permissions, AvatarRepository avatars, Supplier<String> selfUniqueId) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
|
this.permissions = permissions;
|
||||||
|
this.avatars = avatars;
|
||||||
|
this.selfUniqueId = selfUniqueId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Uploads {@code source} as our avatar and announces it; returns its flag. */
|
/** Uploads {@code source} as our avatar and announces it; returns its flag. */
|
||||||
@@ -39,14 +47,14 @@ final class AvatarAdmin {
|
|||||||
if (ImageFormat.detect(data) == null) {
|
if (ImageFormat.detect(data) == null) {
|
||||||
throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images");
|
throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images");
|
||||||
}
|
}
|
||||||
int limit = conn.getModel().permissions().maxAvatarBytes();
|
int limit = permissions.maxAvatarBytes();
|
||||||
if (data.length > limit) {
|
if (data.length > limit) {
|
||||||
throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB");
|
throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB");
|
||||||
}
|
}
|
||||||
String name = ownFileName();
|
String name = ownFileName();
|
||||||
|
|
||||||
CountDownLatch done = new CountDownLatch(1);
|
CountDownLatch done = new CountDownLatch(1);
|
||||||
FileTransfer transfer = fileTransfers().upload(0, "", "/" + name, source, true, t -> {
|
FileTransfer transfer = link.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)) {
|
||||||
@@ -58,7 +66,7 @@ final class AvatarAdmin {
|
|||||||
}
|
}
|
||||||
String flag = AvatarNaming.flag(data);
|
String flag = AvatarNaming.flag(data);
|
||||||
setFlag(flag);
|
setFlag(flag);
|
||||||
conn.getAvatars().put(data);
|
avatars.put(data);
|
||||||
return flag;
|
return flag;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +74,7 @@ final class AvatarAdmin {
|
|||||||
void remove() throws Exception {
|
void remove() throws Exception {
|
||||||
setFlag("");
|
setFlag("");
|
||||||
try {
|
try {
|
||||||
deleteFile(conn.getSelfUniqueId());
|
deleteFile(selfUniqueId.get());
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
// The flag is what other clients go by; a leftover file only wastes space.
|
// 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.
|
// Servers refuse the deletion unless we may delete others' avatars too.
|
||||||
@@ -86,24 +94,18 @@ final class AvatarAdmin {
|
|||||||
* 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 {
|
||||||
fileTransfers().delete(0, "", "/avatar_" + uniqueId);
|
link.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));
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String ownFileName() {
|
private String ownFileName() {
|
||||||
String name = AvatarNaming.fileName(conn.getSelfUniqueId());
|
String name = AvatarNaming.fileName(selfUniqueId.get());
|
||||||
if (name == null) throw new IllegalStateException("Our identity has no usable unique id");
|
if (name == null) throw new IllegalStateException("Our identity has no usable unique id");
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
private FileTransferManager fileTransfers() {
|
|
||||||
FileTransferManager ft = conn.fileTransfers();
|
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ 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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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,8 +36,8 @@ final class BanAdmin {
|
|||||||
*/
|
*/
|
||||||
private volatile List<BanEntry> listing;
|
private volatile List<BanEntry> listing;
|
||||||
|
|
||||||
BanAdmin(TeamspeakConnection conn) {
|
BanAdmin(ServerLink link) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Reads every ban on the server. */
|
/** Reads every ban on the server. */
|
||||||
@@ -45,10 +45,10 @@ final class BanAdmin {
|
|||||||
List<BanEntry> entries = Collections.synchronizedList(new ArrayList<>());
|
List<BanEntry> entries = Collections.synchronizedList(new ArrayList<>());
|
||||||
listing = entries;
|
listing = entries;
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete();
|
link.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.
|
||||||
conn.awaitEventsProcessed();
|
link.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 {
|
||||||
@@ -79,7 +79,7 @@ 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 : conn.socket().executeCommand(cmd).get()) {
|
for (SingleCommand answer : link.socket().executeCommand(cmd).get()) {
|
||||||
Map<String, String> fields = answer.toMap();
|
Map<String, String> fields = answer.toMap();
|
||||||
if (fields.containsKey("banid")) {
|
if (fields.containsKey("banid")) {
|
||||||
return BanEntry.from(fields).id;
|
return BanEntry.from(fields).id;
|
||||||
@@ -106,7 +106,7 @@ final class BanAdmin {
|
|||||||
void delete(int banId) throws Exception {
|
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)));
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void addIfSet(SingleCommand cmd, String key, String value) {
|
private static void addIfSet(SingleCommand cmd, String key, String value) {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
|
|||||||
import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
|
import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
|
||||||
import com.github.manevolent.ts3j.protocol.ProtocolRole;
|
import com.github.manevolent.ts3j.protocol.ProtocolRole;
|
||||||
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
|
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
|
||||||
import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager;
|
|
||||||
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile;
|
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -38,7 +37,8 @@ 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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
private final ServerModel model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a
|
* The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a
|
||||||
@@ -48,15 +48,16 @@ final class ChannelAdmin {
|
|||||||
*/
|
*/
|
||||||
private volatile PermRequest permRequest;
|
private volatile PermRequest permRequest;
|
||||||
|
|
||||||
ChannelAdmin(TeamspeakConnection conn) {
|
ChannelAdmin(ServerLink link, ServerModel model) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
|
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 {
|
ChannelSettings readSettings(int channelId) throws Exception {
|
||||||
Channel info = conn.socket().getChannelInfo(channelId);
|
Channel info = link.socket().getChannelInfo(channelId);
|
||||||
if (info == null) throw new IllegalStateException("The server did not describe that channel");
|
if (info == null) throw new IllegalStateException("The server did not describe that channel");
|
||||||
return ChannelSettings.from(channelId, info.getMap());
|
return ChannelSettings.from(channelId, info.getMap());
|
||||||
}
|
}
|
||||||
@@ -73,15 +74,15 @@ final class ChannelAdmin {
|
|||||||
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 : conn.socket().executeCommand(cmd).get()) {
|
for (SingleCommand answer : link.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.
|
||||||
conn.awaitEventsProcessed();
|
link.awaitEventsProcessed();
|
||||||
ChannelNode created = conn.getModel().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;
|
||||||
}
|
}
|
||||||
@@ -94,12 +95,12 @@ final class ChannelAdmin {
|
|||||||
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()));
|
||||||
}
|
}
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */
|
/** 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 {
|
void delete(int channelId, boolean force) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||||
new CommandSingleParameter("force", force ? "1" : "0"))).complete();
|
new CommandSingleParameter("force", force ? "1" : "0"))).complete();
|
||||||
}
|
}
|
||||||
@@ -113,7 +114,7 @@ final class ChannelAdmin {
|
|||||||
* carries — anything inherited from a group is absent
|
* carries — anything inherited from a group is absent
|
||||||
*/
|
*/
|
||||||
Map<String, Integer> readPermissions(int channelId) throws Exception {
|
Map<String, Integer> readPermissions(int channelId) throws Exception {
|
||||||
if (!conn.getModel().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.
|
||||||
throw new IllegalStateException("The server did not send its permission list");
|
throw new IllegalStateException("The server did not send its permission list");
|
||||||
@@ -123,17 +124,17 @@ 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)));
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.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.
|
||||||
conn.awaitEventsProcessed();
|
link.awaitEventsProcessed();
|
||||||
} finally {
|
} finally {
|
||||||
permRequest = null;
|
permRequest = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Integer> byName = new LinkedHashMap<>();
|
Map<String, Integer> byName = new LinkedHashMap<>();
|
||||||
for (Map.Entry<Integer, Integer> entry : request.values.entrySet()) {
|
for (Map.Entry<Integer, Integer> entry : request.values.entrySet()) {
|
||||||
String name = conn.getModel().permissions().name(entry.getKey());
|
String name = model.permissions().name(entry.getKey());
|
||||||
if (name != null) byName.put(name, entry.getValue());
|
if (name != null) byName.put(name, entry.getValue());
|
||||||
}
|
}
|
||||||
return byName;
|
return byName;
|
||||||
@@ -177,7 +178,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)));
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- the server's icon store ----
|
// ---- the server's icon store ----
|
||||||
@@ -189,7 +190,7 @@ final class ChannelAdmin {
|
|||||||
List<Long> listIcons() throws Exception {
|
List<Long> listIcons() throws Exception {
|
||||||
List<Long> ids = new ArrayList<>();
|
List<Long> ids = new ArrayList<>();
|
||||||
boolean hasIconDirectory = false;
|
boolean hasIconDirectory = false;
|
||||||
for (RemoteFile file : fileTransfers().list(0, "", "/")) {
|
for (RemoteFile file : link.files().list(0, "", "/")) {
|
||||||
if (file.isDirectory()) {
|
if (file.isDirectory()) {
|
||||||
hasIconDirectory |= file.getName().equals(ICON_DIRECTORY);
|
hasIconDirectory |= file.getName().equals(ICON_DIRECTORY);
|
||||||
continue;
|
continue;
|
||||||
@@ -199,7 +200,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 : fileTransfers().list(0, "", "/" + ICON_DIRECTORY)) {
|
for (RemoteFile file : link.files().list(0, "", "/" + ICON_DIRECTORY)) {
|
||||||
if (!file.isDirectory()) addIcon(ids, file);
|
if (!file.isDirectory()) addIcon(ids, file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,7 +230,7 @@ final class ChannelAdmin {
|
|||||||
long id = crc.getValue();
|
long id = crc.getValue();
|
||||||
|
|
||||||
CountDownLatch done = new CountDownLatch(1);
|
CountDownLatch done = new CountDownLatch(1);
|
||||||
FileTransfer transfer = fileTransfers().upload(0, "", "/icon_" + id, source, true, t -> {
|
FileTransfer transfer = link.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,13 +244,7 @@ final class ChannelAdmin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void deleteIcon(long iconId) throws Exception {
|
void deleteIcon(long iconId) throws Exception {
|
||||||
fileTransfers().delete(0, "", "/icon_" + iconId);
|
link.files().delete(0, "", "/icon_" + iconId);
|
||||||
}
|
|
||||||
|
|
||||||
private FileTransferManager fileTransfers() {
|
|
||||||
FileTransferManager ft = conn.fileTransfers();
|
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- helpers ----
|
// ---- helpers ----
|
||||||
|
|||||||
@@ -25,21 +25,21 @@ final class ComplaintAdmin {
|
|||||||
/** 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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
|
||||||
/** 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(TeamspeakConnection conn) {
|
ComplaintAdmin(ServerLink link) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Complaint> list() throws Exception {
|
List<Complaint> list() throws Exception {
|
||||||
List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>());
|
List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>());
|
||||||
listing = complaints;
|
listing = complaints;
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete();
|
link.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete();
|
||||||
conn.awaitEventsProcessed();
|
link.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 {
|
||||||
@@ -56,7 +56,7 @@ final class ComplaintAdmin {
|
|||||||
/** Files a complaint about a client; the server takes one per client from each of us. */
|
/** Files a complaint about a client; the server takes one per client from each of us. */
|
||||||
void add(int targetDbId, String message) throws Exception {
|
void add(int targetDbId, String message) throws Exception {
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)),
|
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)),
|
||||||
new CommandSingleParameter("message", message))).complete();
|
new CommandSingleParameter("message", message))).complete();
|
||||||
} catch (CommandException e) {
|
} catch (CommandException e) {
|
||||||
@@ -66,14 +66,14 @@ final class ComplaintAdmin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void delete(Complaint complaint) throws Exception {
|
void delete(Complaint complaint) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())),
|
new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())),
|
||||||
new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete();
|
new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Removes every complaint about one client. */
|
/** Removes every complaint about one client. */
|
||||||
void deleteAll(int targetDbId) throws Exception {
|
void deleteAll(int targetDbId) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete();
|
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).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.client;
|
LocalTeamspeakClientSocket client = conn.link.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.client;
|
LocalTeamspeakClientSocket c = conn.link.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.fileTransfers();
|
FileTransferManager ft = conn.link.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;
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ 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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
/** 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 +38,8 @@ 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(TeamspeakConnection conn) {
|
OfflineMessageAdmin(ServerLink link) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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 +59,8 @@ final class OfflineMessageAdmin {
|
|||||||
awaited = notification;
|
awaited = notification;
|
||||||
replies = collected;
|
replies = collected;
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
|
link.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
|
||||||
conn.awaitEventsProcessed();
|
link.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 +71,7 @@ final class OfflineMessageAdmin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private synchronized void execute(String command, CommandParameter... params) throws Exception {
|
private synchronized void execute(String command, CommandParameter... params) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
|
link.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) {
|
||||||
|
|||||||
@@ -23,23 +23,23 @@ 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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
|
||||||
/** 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(TeamspeakConnection conn) {
|
PrivilegeKeyAdmin(ServerLink link) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<PrivilegeKey> list() throws Exception {
|
List<PrivilegeKey> list() throws Exception {
|
||||||
List<PrivilegeKey> keys = Collections.synchronizedList(new ArrayList<>());
|
List<PrivilegeKey> keys = Collections.synchronizedList(new ArrayList<>());
|
||||||
listing = keys;
|
listing = keys;
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete();
|
link.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete();
|
||||||
conn.awaitEventsProcessed();
|
link.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 {
|
||||||
@@ -66,8 +66,8 @@ final class PrivilegeKeyAdmin {
|
|||||||
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;
|
created = null;
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
conn.awaitEventsProcessed();
|
link.awaitEventsProcessed();
|
||||||
String token = created;
|
String token = created;
|
||||||
if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key");
|
if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key");
|
||||||
return token;
|
return token;
|
||||||
@@ -78,13 +78,13 @@ final class PrivilegeKeyAdmin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void delete(String token) throws Exception {
|
void delete(String token) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("token", token))).complete();
|
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 {
|
void use(String token) throws Exception {
|
||||||
conn.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT,
|
link.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT,
|
||||||
new CommandSingleParameter("token", token))).complete();
|
new CommandSingleParameter("token", token))).complete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
package eu.lixko.ts3j.client.net;
|
||||||
|
|
||||||
|
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.RejectedExecutionException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The live link to the server, from one connect to its teardown: the socket, the thread
|
||||||
|
* ts3j dispatches events on, the threads requests run on, and the file transfer channel.
|
||||||
|
* It runs requests in the background and is all the admin helpers need of a connection.
|
||||||
|
*
|
||||||
|
* <p>Set up by the connect thread and torn down by whichever thread notices the end; read
|
||||||
|
* from the UI, event and action threads, so each reader copies a field before using it.
|
||||||
|
*/
|
||||||
|
final class ServerLink {
|
||||||
|
|
||||||
|
/** A request made on the socket it was issued on. */
|
||||||
|
interface Action {
|
||||||
|
void run(LocalTeamspeakClientSocket sock) throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A request that produces a value. */
|
||||||
|
interface Job<T> {
|
||||||
|
T call() throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A request with no result. */
|
||||||
|
interface VoidJob {
|
||||||
|
void call() throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
private volatile LocalTeamspeakClientSocket socket;
|
||||||
|
/**
|
||||||
|
* Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make
|
||||||
|
* its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server
|
||||||
|
* has already sent has been handled.
|
||||||
|
*/
|
||||||
|
private volatile ExecutorService events;
|
||||||
|
private volatile ExecutorService actions;
|
||||||
|
private volatile FileTransferManager fileTransfers;
|
||||||
|
/** Past the handshake and not yet torn down. */
|
||||||
|
private volatile boolean up;
|
||||||
|
|
||||||
|
/** A fresh socket, dispatching its events on our event thread, for a connect to set up. */
|
||||||
|
LocalTeamspeakClientSocket open() {
|
||||||
|
LocalTeamspeakClientSocket sock = new LocalTeamspeakClientSocket();
|
||||||
|
ExecutorService eventThread = Executors.newSingleThreadExecutor(r -> daemon(r, "ts3j-events"));
|
||||||
|
sock.setCommandExecutorService(eventThread);
|
||||||
|
events = eventThread;
|
||||||
|
actions = Executors.newCachedThreadPool(r -> daemon(r, "ts3j-action"));
|
||||||
|
socket = sock;
|
||||||
|
return sock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The handshake is done: requests may go out, and files travel over {@code transfers}. */
|
||||||
|
void established(FileTransferManager transfers) {
|
||||||
|
fileTransfers = transfers;
|
||||||
|
up = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The connection is ending; requests are refused from now on, and failures go unreported. */
|
||||||
|
void markDown() {
|
||||||
|
up = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shuts everything down; there is no server left to tell. */
|
||||||
|
void close() {
|
||||||
|
up = false;
|
||||||
|
LocalTeamspeakClientSocket sock = socket;
|
||||||
|
FileTransferManager ft = fileTransfers;
|
||||||
|
ExecutorService eventThread = events;
|
||||||
|
ExecutorService pool = actions;
|
||||||
|
socket = null;
|
||||||
|
fileTransfers = null;
|
||||||
|
events = null;
|
||||||
|
actions = null;
|
||||||
|
if (ft != null) {
|
||||||
|
try {
|
||||||
|
ft.shutdown();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sock != null) {
|
||||||
|
try {
|
||||||
|
sock.close();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (eventThread != null) eventThread.shutdownNow();
|
||||||
|
if (pool != null) pool.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isUp() {
|
||||||
|
return up;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The socket, also while the handshake is under way; {@code null} once closed. */
|
||||||
|
LocalTeamspeakClientSocket currentSocket() {
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The live socket, for a request running in the background. */
|
||||||
|
LocalTeamspeakClientSocket socket() {
|
||||||
|
LocalTeamspeakClientSocket sock = socket;
|
||||||
|
if (sock == null || !up) throw new IllegalStateException("Not connected");
|
||||||
|
return sock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether files can travel now. */
|
||||||
|
boolean canTransferFiles() {
|
||||||
|
return up && fileTransfers != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The file transfer channel, for a request running in the background. */
|
||||||
|
FileTransferManager files() {
|
||||||
|
FileTransferManager ft = fileTransfers;
|
||||||
|
if (ft == null) throw new IllegalStateException("Not connected");
|
||||||
|
return ft;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The file transfer channel, or {@code null} while there is none. */
|
||||||
|
FileTransferManager currentFiles() {
|
||||||
|
return fileTransfers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks until ts3j has finished dispatching every event it had already queued, so a
|
||||||
|
* caller that just saw a command complete can be sure the notifications the server sent
|
||||||
|
* alongside it have been handled. Must not be called from the event thread itself.
|
||||||
|
*/
|
||||||
|
void awaitEventsProcessed() {
|
||||||
|
ExecutorService eventThread = events;
|
||||||
|
if (eventThread == null) return;
|
||||||
|
try {
|
||||||
|
eventThread.submit(() -> {
|
||||||
|
}).get(5, TimeUnit.SECONDS);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// A shutting-down or wedged event thread just means the caller gets what arrived.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a request in the background, handing a failure to {@code onFailure} unless the
|
||||||
|
* connection ended meanwhile: leaving fails whatever was still in flight.
|
||||||
|
*/
|
||||||
|
void submit(Action action, Consumer<Exception> onFailure) {
|
||||||
|
LocalTeamspeakClientSocket sock = socket;
|
||||||
|
ExecutorService pool = actions;
|
||||||
|
if (sock == null || pool == null || !up) return;
|
||||||
|
try {
|
||||||
|
pool.execute(() -> {
|
||||||
|
try {
|
||||||
|
action.run(sock);
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (socket == sock && up) onFailure.accept(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RejectedExecutionException ignored) {
|
||||||
|
// disconnected in the meantime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a blocking server request in the background. The future completes there, so
|
||||||
|
* whatever is chained onto it does not run on the UI thread; it fails with a
|
||||||
|
* {@link RequestException}.
|
||||||
|
*/
|
||||||
|
<T> CompletableFuture<T> request(Job<T> job) {
|
||||||
|
CompletableFuture<T> result = new CompletableFuture<>();
|
||||||
|
ExecutorService pool = actions;
|
||||||
|
if (pool == null || socket == null || !up) {
|
||||||
|
result.completeExceptionally(RequestException.notConnected());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
pool.execute(() -> {
|
||||||
|
try {
|
||||||
|
result.complete(job.call());
|
||||||
|
} catch (Exception e) {
|
||||||
|
result.completeExceptionally(up ? RequestException.of(e) : RequestException.notConnected());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RejectedExecutionException e) {
|
||||||
|
result.completeExceptionally(RequestException.notConnected());
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CompletableFuture<Void> requestVoid(VoidJob job) {
|
||||||
|
return request(() -> {
|
||||||
|
job.call();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Thread daemon(Runnable r, String name) {
|
||||||
|
Thread t = new Thread(r, name);
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 TeamspeakConnection conn;
|
private final ServerLink link;
|
||||||
|
|
||||||
/** 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,8 +36,8 @@ final class ServerLogAdmin {
|
|||||||
volatile long lastPos;
|
volatile long lastPos;
|
||||||
}
|
}
|
||||||
|
|
||||||
ServerLogAdmin(TeamspeakConnection conn) {
|
ServerLogAdmin(ServerLink link) {
|
||||||
this.conn = conn;
|
this.link = link;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,8 +53,8 @@ final class ServerLogAdmin {
|
|||||||
Reply r = new Reply();
|
Reply r = new Reply();
|
||||||
reply = r;
|
reply = r;
|
||||||
try {
|
try {
|
||||||
conn.socket().executeCommand(cmd).complete();
|
link.socket().executeCommand(cmd).complete();
|
||||||
conn.awaitEventsProcessed();
|
link.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 {
|
||||||
|
|||||||
@@ -44,10 +44,6 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.RejectedExecutionException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -88,6 +84,8 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
private final Settings settings;
|
private final Settings settings;
|
||||||
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}. */
|
||||||
|
final ServerLink link = new ServerLink();
|
||||||
/** 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;
|
||||||
@@ -103,40 +101,27 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
/** 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}. */
|
/** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */
|
||||||
final ChannelAdmin channels = new ChannelAdmin(this);
|
final ChannelAdmin channels;
|
||||||
/** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */
|
/** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */
|
||||||
final BanAdmin bans = new BanAdmin(this);
|
final BanAdmin bans = new BanAdmin(link);
|
||||||
final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this);
|
final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(link);
|
||||||
final ComplaintAdmin complaints = new ComplaintAdmin(this);
|
final ComplaintAdmin complaints = new ComplaintAdmin(link);
|
||||||
final ServerLogAdmin serverLog = new ServerLogAdmin(this);
|
final ServerLogAdmin serverLog = new ServerLogAdmin(link);
|
||||||
/** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */
|
/** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */
|
||||||
final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(this);
|
final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(link);
|
||||||
private final AvatarAdmin avatarAdmin = new AvatarAdmin(this);
|
private final AvatarAdmin avatarAdmin;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Set up by the connect thread and torn down by whichever thread notices the end; read from
|
* 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 the field before using it.
|
* the UI, event and action threads, so each reader copies the field before using it.
|
||||||
*/
|
*/
|
||||||
/** Package-private: read directly by {@link ConnectionStatsCollector}. */
|
|
||||||
volatile LocalTeamspeakClientSocket client;
|
|
||||||
/** The client whose whisper we heard last, to reply to; 0 for none yet. */
|
/** The client whose whisper we heard last, to reply to; 0 for none yet. */
|
||||||
private volatile int lastWhisperer;
|
private volatile int lastWhisperer;
|
||||||
private volatile VoiceInput microphone;
|
private volatile VoiceInput microphone;
|
||||||
private volatile VoiceOutput playback;
|
private volatile VoiceOutput playback;
|
||||||
private volatile LocalIdentity identity;
|
private volatile LocalIdentity identity;
|
||||||
private volatile FileTransferManager fileTransfers;
|
|
||||||
/** The recording in progress; guarded by this connection. */
|
/** The recording in progress; guarded by this connection. */
|
||||||
private VoiceRecorder recorder;
|
private VoiceRecorder recorder;
|
||||||
/**
|
|
||||||
* Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make
|
|
||||||
* its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server
|
|
||||||
* has already sent has been handled. Closed together with the socket.
|
|
||||||
*/
|
|
||||||
private volatile ExecutorService eventExecutor;
|
|
||||||
/** Runs this connection's requests to the server; created on connect, shut down with the socket. */
|
|
||||||
private volatile ExecutorService actions;
|
|
||||||
|
|
||||||
private volatile boolean connected;
|
|
||||||
/**
|
/**
|
||||||
* The connect in progress. A disconnect clears it and a newer connect replaces it, which
|
* The connect in progress. A disconnect clears it and a newer connect replaces it, which
|
||||||
* tells a superseded attempt that is still failing not to clean up after itself.
|
* tells a superseded attempt that is still failing not to clean up after itself.
|
||||||
@@ -184,16 +169,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() {
|
||||||
LocalTeamspeakClientSocket socket = client;
|
link.submit(socket -> {
|
||||||
ExecutorService executor = actions;
|
|
||||||
if (!connected || socket == null || executor == null) return;
|
|
||||||
try {
|
|
||||||
executor.execute(() -> {
|
|
||||||
synchronized (myTeamSpeakUpdateLock) {
|
synchronized (myTeamSpeakUpdateLock) {
|
||||||
try {
|
|
||||||
var login = myTeamSpeak;
|
var login = myTeamSpeak;
|
||||||
var account = myTeamSpeakFeatures && login != null ? login.serverIdentity() : null;
|
var account = myTeamSpeakFeatures && login != null ? login.serverIdentity() : null;
|
||||||
if (client != socket || !connected) return;
|
if (link.currentSocket() != socket || !link.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);
|
||||||
@@ -202,14 +182,8 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
command.add(new CommandSingleParameter(name, ""));
|
command.add(new CommandSingleParameter(name, ""));
|
||||||
}
|
}
|
||||||
socket.executeCommand(command).complete();
|
socket.executeCommand(command).complete();
|
||||||
} catch (Exception e) {
|
|
||||||
ui.onError("Could not update myTeamSpeak identity: " + messageChain(e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (RejectedExecutionException ignored) {
|
|
||||||
// The connection closed while scheduling the update.
|
|
||||||
}
|
}
|
||||||
|
}, e -> ui.onError("Could not update myTeamSpeak identity: " + messageChain(e)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public TeamspeakConnection(Settings settings, AudioBackend audio, ConnectionListener ui,
|
public TeamspeakConnection(Settings settings, AudioBackend audio, ConnectionListener ui,
|
||||||
@@ -219,10 +193,12 @@ 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, () -> connected);
|
this.announce = new Announcer(model, sounds, ui, chatLog, () -> deafened, link::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.avatarAdmin = new AvatarAdmin(link, model.permissions(), avatars, this::getSelfUniqueId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ServerModel getModel() {
|
public ServerModel getModel() {
|
||||||
@@ -230,7 +206,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isConnected() {
|
public boolean isConnected() {
|
||||||
return connected;
|
return link.isUp();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSelfClientId() {
|
public int getSelfClientId() {
|
||||||
@@ -293,7 +269,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 || !connected) return;
|
if (mic == null || !link.isUp()) return;
|
||||||
try {
|
try {
|
||||||
if (microphoneActive) mic.start();
|
if (microphoneActive) mic.start();
|
||||||
else mic.stop();
|
else mic.stop();
|
||||||
@@ -341,7 +317,6 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
connectErrorId = 0;
|
connectErrorId = 0;
|
||||||
disconnectReasonId = -1;
|
disconnectReasonId = -1;
|
||||||
// A socket or audio line an earlier connect left behind must not outlive it.
|
// A socket or audio line an earlier connect left behind must not outlive it.
|
||||||
connected = false;
|
|
||||||
safeCleanup();
|
safeCleanup();
|
||||||
try {
|
try {
|
||||||
var login = myTeamSpeak;
|
var login = myTeamSpeak;
|
||||||
@@ -385,22 +360,11 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
});
|
});
|
||||||
microphone.setMutedTalkListener(this::onTalkingWhileMuted);
|
microphone.setMutedTalkListener(this::onTalkingWhileMuted);
|
||||||
|
|
||||||
client = new LocalTeamspeakClientSocket();
|
LocalTeamspeakClientSocket client = link.open();
|
||||||
client.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate);
|
client.setMyTeamSpeakAuthenticator(account == null ? null : account::authenticate);
|
||||||
eventExecutor = Executors.newSingleThreadExecutor(r -> {
|
|
||||||
Thread t = new Thread(r, "ts3j-events");
|
|
||||||
t.setDaemon(true);
|
|
||||||
return t;
|
|
||||||
});
|
|
||||||
client.setCommandExecutorService(eventExecutor);
|
|
||||||
actions = Executors.newCachedThreadPool(r -> {
|
|
||||||
Thread t = new Thread(r, "ts3j-action");
|
|
||||||
t.setDaemon(true);
|
|
||||||
return t;
|
|
||||||
});
|
|
||||||
client.setIdentity(identity);
|
client.setIdentity(identity);
|
||||||
client.setNickname(nickname);
|
client.setNickname(nickname);
|
||||||
setIfPresent("client.nickname_phonetic", phoneticNickname);
|
setIfPresent(client, "client.nickname_phonetic", phoneticNickname);
|
||||||
client.setHWID("ts3jswing-" + Integer.toHexString(nickname.hashCode()));
|
client.setHWID("ts3jswing-" + Integer.toHexString(nickname.hashCode()));
|
||||||
client.addListener(this);
|
client.addListener(this);
|
||||||
client.addListener(events);
|
client.addListener(events);
|
||||||
@@ -417,8 +381,8 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
ui.onError("Network error: " + messageChain(t));
|
ui.onError("Network error: " + messageChain(t));
|
||||||
});
|
});
|
||||||
|
|
||||||
applyClientVersion();
|
applyClientVersion(client);
|
||||||
applyDefaultChannel(channel, channelPassword);
|
applyDefaultChannel(client, channel, channelPassword);
|
||||||
|
|
||||||
ui.onStatus("Connecting to " + address + ":" + port + "…");
|
ui.onStatus("Connecting to " + address + ":" + port + "…");
|
||||||
client.connect(new InetSocketAddress(address, port),
|
client.connect(new InetSocketAddress(address, port),
|
||||||
@@ -435,11 +399,10 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
ourselves.self = true;
|
ourselves.self = true;
|
||||||
model.enteredChannel(ourselves.channelId);
|
model.enteredChannel(ourselves.channelId);
|
||||||
}
|
}
|
||||||
fileTransfers = new FileTransferManager(client, () -> serverHost);
|
|
||||||
client.setMicrophone(microphone);
|
client.setMicrophone(microphone);
|
||||||
|
link.established(new FileTransferManager(client, () -> serverHost));
|
||||||
icons.retryFailed();
|
icons.retryFailed();
|
||||||
avatars.retryFailed();
|
avatars.retryFailed();
|
||||||
connected = true;
|
|
||||||
if (login != null && login.revision() != loginRevision) updateMyTeamSpeak();
|
if (login != null && login.revision() != loginRevision) updateMyTeamSpeak();
|
||||||
connectedAtMs = System.currentTimeMillis();
|
connectedAtMs = System.currentTimeMillis();
|
||||||
leaving = false;
|
leaving = false;
|
||||||
@@ -452,7 +415,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
requestSelfPowers();
|
requestSelfPowers();
|
||||||
|
|
||||||
ui.onStatus("Retrieving channels…");
|
ui.onStatus("Retrieving channels…");
|
||||||
syncAll();
|
syncAll(client);
|
||||||
ui.onModelChanged();
|
ui.onModelChanged();
|
||||||
joinDefaultChannelIfNeeded(channel, channelPassword);
|
joinDefaultChannelIfNeeded(channel, channelPassword);
|
||||||
ui.onStatus("Connected to " + model.getServerName());
|
ui.onStatus("Connected to " + model.getServerName());
|
||||||
@@ -465,7 +428,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;
|
||||||
connected = false;
|
link.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);
|
||||||
@@ -505,14 +468,14 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* built-in one when left empty; the signature has to match the version and
|
* built-in one when left empty; the signature has to match the version and
|
||||||
* platform it was issued for, or a server may refuse the connection.
|
* platform it was issued for, or a server may refuse the connection.
|
||||||
*/
|
*/
|
||||||
private void applyClientVersion() {
|
private void applyClientVersion(LocalTeamspeakClientSocket client) {
|
||||||
if (!settings.customVersion) return;
|
if (!settings.customVersion) return;
|
||||||
setIfPresent("client.version_string", settings.clientVersion);
|
setIfPresent(client, "client.version_string", settings.clientVersion);
|
||||||
setIfPresent("client.version_platform", settings.clientPlatform);
|
setIfPresent(client, "client.version_platform", settings.clientPlatform);
|
||||||
setIfPresent("client.version_sign", settings.clientVersionSign);
|
setIfPresent(client, "client.version_sign", settings.clientVersionSign);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setIfPresent(String option, String value) {
|
private static void setIfPresent(LocalTeamspeakClientSocket client, String option, String value) {
|
||||||
if (value != null && !value.isBlank()) client.setOption(option, value.trim());
|
if (value != null && !value.isBlank()) client.setOption(option, value.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -521,7 +484,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* channel right away instead of the default one. This is the path a real client
|
* channel right away instead of the default one. This is the path a real client
|
||||||
* takes for bookmarks, and it avoids being briefly visible in the wrong channel.
|
* takes for bookmarks, and it avoids being briefly visible in the wrong channel.
|
||||||
*/
|
*/
|
||||||
private void applyDefaultChannel(String channel, String channelPassword) {
|
private static void applyDefaultChannel(LocalTeamspeakClientSocket client, String channel, String channelPassword) {
|
||||||
String path = normaliseChannelRef(channel);
|
String path = normaliseChannelRef(channel);
|
||||||
if (path == null) return;
|
if (path == null) return;
|
||||||
client.setOption("client.default_channel", path);
|
client.setOption("client.default_channel", path);
|
||||||
@@ -538,8 +501,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 = client;
|
LocalTeamspeakClientSocket sock = link.currentSocket();
|
||||||
if (sock == null || !connected) return; // already left again
|
if (sock == null || !link.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.");
|
||||||
@@ -550,7 +513,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 (!connected) return;
|
if (!link.isUp()) return;
|
||||||
announce.error("Could not join channel \"" + target.name + "\": ", e);
|
announce.error("Could not join channel \"" + target.name + "\": ", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -565,7 +528,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 client.getClientInfo(selfClientId).getChannelId();
|
return link.socket().getClientInfo(selfClientId).getChannelId();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@@ -591,7 +554,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* them: their rows lack groups, unique ids and away state, and they count heavily
|
* them: their rows lack groups, unique ids and away state, and they count heavily
|
||||||
* against the server's flood protection.
|
* against the server's flood protection.
|
||||||
*/
|
*/
|
||||||
private void syncAll() {
|
private void syncAll(LocalTeamspeakClientSocket client) {
|
||||||
try {
|
try {
|
||||||
client.subscribeAll();
|
client.subscribeAll();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -618,11 +581,11 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
leaving = true;
|
leaving = true;
|
||||||
disconnectReasonId = -1;
|
disconnectReasonId = -1;
|
||||||
try {
|
try {
|
||||||
|
LocalTeamspeakClientSocket client = link.currentSocket();
|
||||||
if (client != null) client.disconnect(reason);
|
if (client != null) client.disconnect(reason);
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
} finally {
|
} finally {
|
||||||
safeCleanup();
|
safeCleanup();
|
||||||
connected = false;
|
|
||||||
announceDisconnect(true);
|
announceDisconnect(true);
|
||||||
ui.onDisconnected("You disconnected");
|
ui.onDisconnected("You disconnected");
|
||||||
ui.onStatus("Disconnected");
|
ui.onStatus("Disconnected");
|
||||||
@@ -659,27 +622,12 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
}
|
}
|
||||||
VoiceInput mic = microphone;
|
VoiceInput mic = microphone;
|
||||||
VoiceOutput out = playback;
|
VoiceOutput out = playback;
|
||||||
LocalTeamspeakClientSocket sock = client;
|
|
||||||
FileTransferManager ft = fileTransfers;
|
|
||||||
ExecutorService events = eventExecutor;
|
|
||||||
ExecutorService pool = actions;
|
|
||||||
eventExecutor = null;
|
|
||||||
actions = null;
|
|
||||||
microphone = null;
|
microphone = null;
|
||||||
playback = null;
|
playback = null;
|
||||||
client = null;
|
|
||||||
fileTransfers = null;
|
|
||||||
chatLog.close();
|
chatLog.close();
|
||||||
selfClientId = -1;
|
selfClientId = -1;
|
||||||
stats.clear();
|
stats.clear();
|
||||||
|
|
||||||
if (ft != null) {
|
|
||||||
try {
|
|
||||||
ft.shutdown();
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mic != null) {
|
if (mic != null) {
|
||||||
try {
|
try {
|
||||||
mic.stop();
|
mic.stop();
|
||||||
@@ -692,14 +640,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (sock != null) {
|
link.close();
|
||||||
try {
|
|
||||||
sock.close();
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (events != null) events.shutdownNow();
|
|
||||||
if (pool != null) pool.shutdownNow();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- self actions ----
|
// ---- self actions ----
|
||||||
@@ -890,7 +831,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)));
|
||||||
}
|
}
|
||||||
submit(sock -> {
|
link.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();
|
||||||
@@ -1060,7 +1001,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 (!connected || out == null || mic == null) throw new IllegalStateException("Not connected");
|
if (!link.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<>();
|
||||||
@@ -1106,7 +1047,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
if (recorder != rec) return false;
|
if (recorder != rec) return false;
|
||||||
detachRecorder();
|
detachRecorder();
|
||||||
}
|
}
|
||||||
if (announce && connected) publishRecording(false);
|
if (announce && link.isUp()) publishRecording(false);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1150,7 +1091,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
public double getPingMillis() {
|
public double getPingMillis() {
|
||||||
try {
|
try {
|
||||||
LocalTeamspeakClientSocket sock = client;
|
LocalTeamspeakClientSocket sock = link.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;
|
||||||
@@ -1194,8 +1135,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 request(() -> {
|
return link.request(() -> {
|
||||||
Client c = socket().getClientInfo(clientId);
|
Client c = link.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;
|
||||||
@@ -1210,11 +1151,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 requestVoid(() -> {
|
return link.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));
|
||||||
socket().executeCommand(cmd).complete();
|
link.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) {
|
||||||
@@ -1229,7 +1170,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Reads the server's privilege keys. */
|
/** Reads the server's privilege keys. */
|
||||||
public CompletableFuture<List<PrivilegeKey>> requestPrivilegeKeys() {
|
public CompletableFuture<List<PrivilegeKey>> requestPrivilegeKeys() {
|
||||||
return request(privilegeKeys::list);
|
return link.request(privilegeKeys::list);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1238,20 +1179,20 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* @return the new key
|
* @return the new key
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<String> addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) {
|
public CompletableFuture<String> addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description) {
|
||||||
return request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description));
|
return link.request(() -> privilegeKeys.add(channelGroup, groupId, channelId, description));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes privilege keys one by one, stopping at the first the server refuses.
|
* Deletes privilege keys one by one, stopping at the first the server refuses.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> deletePrivilegeKeys(Collection<String> tokens) {
|
public CompletableFuture<Void> deletePrivilegeKeys(Collection<String> tokens) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (String token : tokens) privilegeKeys.delete(token);
|
for (String token : tokens) privilegeKeys.delete(token);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public CompletableFuture<Void> usePrivilegeKey(String token) {
|
public CompletableFuture<Void> usePrivilegeKey(String token) {
|
||||||
return requestVoid(() -> privilegeKeys.use(token));
|
return link.requestVoid(() -> privilegeKeys.use(token));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- complaints ----
|
// ---- complaints ----
|
||||||
@@ -1266,7 +1207,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Reads the server's complaints. */
|
/** Reads the server's complaints. */
|
||||||
public CompletableFuture<List<Complaint>> requestComplaints() {
|
public CompletableFuture<List<Complaint>> requestComplaints() {
|
||||||
return request(complaints::list);
|
return link.request(complaints::list);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1274,7 +1215,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* stopping at the first the server refuses.
|
* stopping at the first the server refuses.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> single) {
|
public CompletableFuture<Void> deleteComplaints(Collection<Integer> targetDbIds, Collection<Complaint> single) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (int target : targetDbIds) complaints.deleteAll(target);
|
for (int target : targetDbIds) complaints.deleteAll(target);
|
||||||
for (Complaint complaint : single) complaints.delete(complaint);
|
for (Complaint complaint : single) complaints.delete(complaint);
|
||||||
});
|
});
|
||||||
@@ -1300,25 +1241,25 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Lists our offline message inbox. */
|
/** Lists our offline message inbox. */
|
||||||
public CompletableFuture<List<OfflineMessage>> requestOfflineMessages() {
|
public CompletableFuture<List<OfflineMessage>> requestOfflineMessages() {
|
||||||
return request(offlineMessages::list);
|
return link.request(offlineMessages::list);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Reads a message's body. */
|
/** Reads a message's body. */
|
||||||
public CompletableFuture<String> requestOfflineMessageBody(int messageId) {
|
public CompletableFuture<String> requestOfflineMessageBody(int messageId) {
|
||||||
return request(() -> offlineMessages.body(messageId));
|
return link.request(() -> offlineMessages.body(messageId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Marks messages read or unread, stopping at the first the server refuses.
|
* Marks messages read or unread, stopping at the first the server refuses.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> markOfflineMessages(Collection<Integer> messageIds, boolean read) {
|
public CompletableFuture<Void> markOfflineMessages(Collection<Integer> messageIds, boolean read) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (int id : messageIds) offlineMessages.setRead(id, read);
|
for (int id : messageIds) offlineMessages.setRead(id, read);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public CompletableFuture<Void> deleteOfflineMessages(Collection<Integer> messageIds) {
|
public CompletableFuture<Void> deleteOfflineMessages(Collection<Integer> messageIds) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (int id : messageIds) offlineMessages.delete(id);
|
for (int id : messageIds) offlineMessages.delete(id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1327,7 +1268,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* Sends one offline message to each recipient, stopping at the first the server refuses.
|
* Sends one offline message to each recipient, stopping at the first the server refuses.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> sendOfflineMessage(Collection<String> recipientUids, String subject, String message) {
|
public CompletableFuture<Void> sendOfflineMessage(Collection<String> recipientUids, String subject, String message) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (String uid : recipientUids) offlineMessages.send(uid, subject, message);
|
for (String uid : recipientUids) offlineMessages.send(uid, subject, message);
|
||||||
announce.log("Offline message sent.");
|
announce.log("Offline message sent.");
|
||||||
});
|
});
|
||||||
@@ -1335,7 +1276,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Looks a client up by unique id; empty when the server has never seen them. */
|
/** Looks a client up by unique id; empty when the server has never seen them. */
|
||||||
public CompletableFuture<Optional<DatabaseClient>> lookupDatabaseClient(String uniqueId) {
|
public CompletableFuture<Optional<DatabaseClient>> lookupDatabaseClient(String uniqueId) {
|
||||||
return request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId)));
|
return link.request(() -> Optional.ofNullable(offlineMessages.lookupUid(uniqueId)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1344,7 +1285,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* A server that will not let us search refuses for lack of permission.
|
* A server that will not let us search refuses for lack of permission.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<List<DatabaseClient>> searchDatabaseClients(String nickname) {
|
public CompletableFuture<List<DatabaseClient>> searchDatabaseClients(String nickname) {
|
||||||
return request(() -> offlineMessages.search(nickname));
|
return link.request(() -> offlineMessages.search(nickname));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- server log ----
|
// ---- server log ----
|
||||||
@@ -1354,32 +1295,32 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* earlier page's.
|
* earlier page's.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<ServerLogPage> requestServerLog(long olderFrom) {
|
public CompletableFuture<ServerLogPage> requestServerLog(long olderFrom) {
|
||||||
return request(() -> serverLog.read(olderFrom));
|
return link.request(() -> serverLog.read(olderFrom));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- bans ----
|
// ---- bans ----
|
||||||
|
|
||||||
/** Reads the server's ban list. */
|
/** Reads the server's ban list. */
|
||||||
public CompletableFuture<List<BanEntry>> requestBanList() {
|
public CompletableFuture<List<BanEntry>> requestBanList() {
|
||||||
return request(bans::list);
|
return link.request(bans::list);
|
||||||
}
|
}
|
||||||
|
|
||||||
public CompletableFuture<Void> addBan(BanRule rule) {
|
public CompletableFuture<Void> addBan(BanRule rule) {
|
||||||
return requestVoid(() -> bans.add(rule));
|
return link.requestVoid(() -> bans.add(rule));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rewrites an existing ban.
|
* Rewrites an existing ban.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> replaceBan(int banId, BanRule rule) {
|
public CompletableFuture<Void> replaceBan(int banId, BanRule rule) {
|
||||||
return requestVoid(() -> bans.replace(banId, rule));
|
return link.requestVoid(() -> bans.replace(banId, rule));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes bans one by one, stopping at the first the server refuses.
|
* Deletes bans one by one, stopping at the first the server refuses.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> deleteBans(Collection<Integer> banIds) {
|
public CompletableFuture<Void> deleteBans(Collection<Integer> banIds) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
for (int id : banIds) bans.delete(id);
|
for (int id : banIds) bans.delete(id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1441,7 +1382,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 (!connected) return;
|
if (!link.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) {
|
||||||
@@ -1481,7 +1422,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* Reads a channel's editable properties.
|
* Reads a channel's editable properties.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<ChannelSettings> requestChannelSettings(int channelId) {
|
public CompletableFuture<ChannelSettings> requestChannelSettings(int channelId) {
|
||||||
return request(() -> channels.readSettings(channelId));
|
return link.request(() -> channels.readSettings(channelId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1489,7 +1430,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* server does not let us look at them.
|
* server does not let us look at them.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Map<String, Integer>> requestChannelPermissions(int channelId) {
|
public CompletableFuture<Map<String, Integer>> requestChannelPermissions(int channelId) {
|
||||||
return request(() -> channels.readPermissions(channelId));
|
return link.request(() -> channels.readPermissions(channelId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1499,7 +1440,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
public CompletableFuture<Void> applyChannelEdit(int channelId, Map<String, String> changes,
|
public CompletableFuture<Void> applyChannelEdit(int channelId, Map<String, String> changes,
|
||||||
Map<String, Integer> setPermissions,
|
Map<String, Integer> setPermissions,
|
||||||
Collection<String> removePermissions) {
|
Collection<String> removePermissions) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
channels.edit(channelId, changes);
|
channels.edit(channelId, changes);
|
||||||
channels.writePermissions(channelId, setPermissions, removePermissions);
|
channels.writePermissions(channelId, setPermissions, removePermissions);
|
||||||
if (changes.containsKey("channel_description")) {
|
if (changes.containsKey("channel_description")) {
|
||||||
@@ -1522,7 +1463,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
*/
|
*/
|
||||||
public CompletableFuture<Integer> createChannel(int parentId, Map<String, String> properties,
|
public CompletableFuture<Integer> createChannel(int parentId, Map<String, String> properties,
|
||||||
Map<String, Integer> permissions) {
|
Map<String, Integer> permissions) {
|
||||||
return request(() -> {
|
return link.request(() -> {
|
||||||
int channelId = channels.create(parentId, properties);
|
int channelId = channels.create(parentId, properties);
|
||||||
try {
|
try {
|
||||||
channels.writePermissions(channelId, permissions, List.of());
|
channels.writePermissions(channelId, permissions, List.of());
|
||||||
@@ -1538,129 +1479,35 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* Deletes a channel; with {@code force}, also one that has sub-channels or clients in it.
|
* Deletes a channel; with {@code force}, also one that has sub-channels or clients in it.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> deleteChannel(int channelId, boolean force) {
|
public CompletableFuture<Void> deleteChannel(int channelId, boolean force) {
|
||||||
return requestVoid(() -> channels.delete(channelId, force));
|
return link.requestVoid(() -> channels.delete(channelId, force));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The ids of the icons uploaded to this virtual server. */
|
/** The ids of the icons uploaded to this virtual server. */
|
||||||
public CompletableFuture<List<Long>> requestServerIcons() {
|
public CompletableFuture<List<Long>> requestServerIcons() {
|
||||||
return request(channels::listIcons);
|
return link.request(channels::listIcons);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Uploads an image as a server icon and reports the new icon's id. */
|
/** Uploads an image as a server icon and reports the new icon's id. */
|
||||||
public CompletableFuture<Long> uploadIcon(File source) {
|
public CompletableFuture<Long> uploadIcon(File source) {
|
||||||
return request(() -> channels.uploadIcon(source));
|
return link.request(() -> channels.uploadIcon(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deletes a server icon. */
|
/** Deletes a server icon. */
|
||||||
public CompletableFuture<Void> deleteIcon(long iconId) {
|
public CompletableFuture<Void> deleteIcon(long iconId) {
|
||||||
return requestVoid(() -> channels.deleteIcon(iconId));
|
return link.requestVoid(() -> channels.deleteIcon(iconId));
|
||||||
}
|
|
||||||
|
|
||||||
/** A request made on the socket of the connection it was issued on. */
|
|
||||||
private interface Action {
|
|
||||||
void run(LocalTeamspeakClientSocket sock) throws Exception;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Work that produces a value or an error message. */
|
|
||||||
private interface Job<T> {
|
|
||||||
T call() throws Exception;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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, Action action) {
|
private void act(String errorPrefix, ServerLink.Action action) {
|
||||||
submit(action, e -> announce.error(errorPrefix, e));
|
link.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(Action action) {
|
private void attempt(ServerLink.Action action) {
|
||||||
submit(action, e -> {
|
link.submit(action, e -> {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void submit(Action action, Consumer<Exception> onFailure) {
|
|
||||||
LocalTeamspeakClientSocket sock = client;
|
|
||||||
ExecutorService pool = actions;
|
|
||||||
if (sock == null || pool == null || !connected) return;
|
|
||||||
try {
|
|
||||||
pool.execute(() -> {
|
|
||||||
try {
|
|
||||||
action.run(sock);
|
|
||||||
} catch (Exception e) {
|
|
||||||
// Leaving fails whatever was still in flight; that is no error to report.
|
|
||||||
if (client == sock && connected) onFailure.accept(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (RejectedExecutionException ignored) {
|
|
||||||
// disconnected in the meantime
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A request with no result. */
|
|
||||||
private interface VoidJob {
|
|
||||||
void call() throws Exception;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs a blocking server request in the background. The future completes there, so
|
|
||||||
* whatever is chained onto it does not run on the UI thread; it fails with a
|
|
||||||
* {@link RequestException}.
|
|
||||||
*/
|
|
||||||
private <T> CompletableFuture<T> request(Job<T> job) {
|
|
||||||
CompletableFuture<T> result = new CompletableFuture<>();
|
|
||||||
ExecutorService pool = actions;
|
|
||||||
if (pool == null || client == null || !connected) {
|
|
||||||
result.completeExceptionally(RequestException.notConnected());
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
pool.execute(() -> {
|
|
||||||
try {
|
|
||||||
result.complete(job.call());
|
|
||||||
} catch (Exception e) {
|
|
||||||
result.completeExceptionally(connected ? RequestException.of(e) : RequestException.notConnected());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (RejectedExecutionException e) {
|
|
||||||
result.completeExceptionally(RequestException.notConnected());
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private CompletableFuture<Void> requestVoid(VoidJob job) {
|
|
||||||
return request(() -> {
|
|
||||||
job.call();
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The live socket. Package-private for {@link ChannelAdmin}. */
|
|
||||||
LocalTeamspeakClientSocket socket() {
|
|
||||||
LocalTeamspeakClientSocket sock = client;
|
|
||||||
if (sock == null || !connected) throw new IllegalStateException("Not connected");
|
|
||||||
return sock;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */
|
|
||||||
FileTransferManager fileTransfers() {
|
|
||||||
return fileTransfers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Blocks until ts3j has finished dispatching every event it had already queued, so a
|
|
||||||
* caller that just saw a command complete can be sure the notifications the server sent
|
|
||||||
* alongside it have been handled. Must not be called from the event thread itself.
|
|
||||||
*/
|
|
||||||
void awaitEventsProcessed() {
|
|
||||||
ExecutorService events = eventExecutor;
|
|
||||||
if (events == null) return;
|
|
||||||
try {
|
|
||||||
events.submit(() -> {
|
|
||||||
}).get(5, TimeUnit.SECONDS);
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// A shutting-down or wedged event thread just means the caller gets what arrived.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- icons ----
|
// ---- icons ----
|
||||||
|
|
||||||
/** Group icons for this server: bundled defaults plus the server's own uploads. */
|
/** Group icons for this server: bundled defaults plus the server's own uploads. */
|
||||||
@@ -1670,9 +1517,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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
return link.files().downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES);
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft.downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- avatars ----
|
// ---- avatars ----
|
||||||
@@ -1696,7 +1541,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
* Uploads an image as our avatar and publishes it to the other clients.
|
* Uploads an image as our avatar and publishes it to the other clients.
|
||||||
*/
|
*/
|
||||||
public CompletableFuture<Void> setAvatar(File source) {
|
public CompletableFuture<Void> setAvatar(File source) {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
String flag = avatarAdmin.upload(source);
|
String flag = avatarAdmin.upload(source);
|
||||||
updateSelf(self -> self.avatarFlag = flag);
|
updateSelf(self -> self.avatarFlag = flag);
|
||||||
});
|
});
|
||||||
@@ -1704,7 +1549,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Withdraws our avatar. */
|
/** Withdraws our avatar. */
|
||||||
public CompletableFuture<Void> removeAvatar() {
|
public CompletableFuture<Void> removeAvatar() {
|
||||||
return requestVoid(() -> {
|
return link.requestVoid(() -> {
|
||||||
avatarAdmin.remove();
|
avatarAdmin.remove();
|
||||||
updateSelf(self -> self.avatarFlag = "");
|
updateSelf(self -> self.avatarFlag = "");
|
||||||
});
|
});
|
||||||
@@ -1712,23 +1557,21 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
|
|
||||||
/** Deletes another client's avatar. */
|
/** Deletes another client's avatar. */
|
||||||
public CompletableFuture<Void> removeAvatarOf(ClientEntry client) {
|
public CompletableFuture<Void> removeAvatarOf(ClientEntry client) {
|
||||||
return requestVoid(() -> avatarAdmin.removeOther(client.uniqueId));
|
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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
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 ft.downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES);
|
return link.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 = client;
|
LocalTeamspeakClientSocket sock = link.currentSocket();
|
||||||
if (sock == null) return;
|
if (sock == null) return;
|
||||||
if (targets == null) {
|
if (targets == null) {
|
||||||
sock.setWhisperTarget(null);
|
sock.setWhisperTarget(null);
|
||||||
@@ -1750,7 +1593,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 connected && fileTransfers != null;
|
return link.canTransferFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1759,44 +1602,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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
return link.files().list(channelId, channelPassword, path);
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft.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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
link.files().createDirectory(channelId, channelPassword, dirPath);
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
ft.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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
link.files().delete(channelId, channelPassword, fullPath);
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
ft.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 {
|
||||||
FileTransferManager ft = fileTransfers;
|
link.files().rename(channelId, channelPassword, oldFullPath, newFullPath);
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
ft.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) {
|
||||||
FileTransferManager ft = fileTransfers;
|
return link.files().download(channelId, channelPassword, remoteFullPath, target, announcing(listener));
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft.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) {
|
||||||
FileTransferManager ft = fileTransfers;
|
return link.files().upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener));
|
||||||
if (ft == null) throw new IllegalStateException("Not connected");
|
|
||||||
return ft.upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1828,7 +1659,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 (client == null || !connected) return;
|
if (!link.isUp()) return;
|
||||||
stats.request(clientId, callback);
|
stats.request(clientId, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1842,7 +1673,7 @@ public final class TeamspeakConnection implements TS3Listener {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onDisconnected(DisconnectedEvent e) {
|
public void onDisconnected(DisconnectedEvent e) {
|
||||||
connected = false;
|
link.markDown();
|
||||||
disconnectReasonId = e.getReasonId();
|
disconnectReasonId = e.getReasonId();
|
||||||
safeCleanup();
|
safeCleanup();
|
||||||
announceDisconnect(false);
|
announceDisconnect(false);
|
||||||
@@ -1858,7 +1689,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 = this.client;
|
LocalTeamspeakClientSocket client = link.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();
|
||||||
|
|||||||
Reference in New Issue
Block a user