diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt index f69a603..a16efd5 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -10,6 +10,7 @@ import eu.lixko.ts3j.client.net.ChannelSettings import eu.lixko.ts3j.client.net.ConnectionStats import eu.lixko.ts3j.client.net.Details import eu.lixko.ts3j.client.net.GroupChoice +import eu.lixko.ts3j.client.net.Permissions import eu.lixko.ts3j.client.net.RequestException import eu.lixko.ts3j.client.net.Whisper import eu.lixko.ts3j.client.net.ban.BanEntry @@ -194,7 +195,8 @@ class ServerController internal constructor( fun expand(channelIds: Collection) = _collapsed.update { it - channelIds.toSet() } - val canMoveClients: Boolean get() = session.canMoveClients() + /** What we may do on this server; nothing while not connected. */ + val permissions: Permissions get() = session.permissions() /** The channel kicked clients go back to; 0 until the server named it. */ val defaultChannelId: Int get() = conn.model.defaultChannelId() @@ -241,10 +243,6 @@ class ServerController internal constructor( // ---- channel administration ---- - val canCreateChannels: Boolean get() = session.canCreateChannels() - val canEditChannels: Boolean get() = session.canEditChannels() - val canDeleteChannels: Boolean get() = session.canDeleteChannels() - /** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */ fun sortChoices(channelId: Int, parentId: Int): List = if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId) @@ -283,17 +281,7 @@ class ServerController internal constructor( // ---- moderation ---- - val canKickFromChannel: Boolean get() = session.canKickFromChannel() - val canKickFromServer: Boolean get() = session.canKickFromServer() - val canBanClients: Boolean get() = session.canBanClients() - val canGrantTalkPower: Boolean get() = session.canGrantTalkPower() val canRequestTalkPower: Boolean get() = session.canRequestTalkPower() - val canViewBanList: Boolean get() = session.canViewBanList() - val canBrowseFiles: Boolean get() = session.canBrowseFiles() - val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create") - - /** The longest ban we may hand out in seconds; 0 or -1 for no limit. */ - val maxBanSeconds: Long get() = conn.model.maxBanSeconds() fun kickFromChannel(clientIds: Collection, reason: String) { if (session.isConnected) conn.kickFromChannel(clientIds, reason) @@ -345,9 +333,9 @@ class ServerController internal constructor( suspend fun deleteBans(banIds: Collection): Result = conn.deleteBans(banIds).done() - fun canDeleteBans(bans: Collection): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) + fun canDeleteBans(bans: Collection): Boolean = permissions.canDeleteBans(bans, conn.selfUniqueId) - fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId) + fun canEditBan(ban: BanEntry): Boolean = permissions.canEditBan(ban, conn.selfUniqueId) fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt index 8629a7e..2edf6da 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt @@ -102,7 +102,7 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: ( edit?.let { e -> val existing = (e as? BanEdit.Existing)?.ban - BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule -> + BanEditor(existing, presets, server.permissions.maxBanSeconds(), onBack = { edit = null }) { rule -> edit = null if (existing == null) change({ server.addBan(rule) }, "Error adding ban") else change({ server.replaceBan(existing.id, rule) }, "Error editing ban") @@ -113,7 +113,7 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: ( SubScreen( "Ban list", onBack, actions = { - if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") } + if (server.permissions.canCreateBans()) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") } IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") } }, snackbar = snackbar, diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt index 94015d9..3c1f9e2 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt @@ -190,10 +190,10 @@ fun GroupsDialog( fun clientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit): (@Composable () -> Unit)? { val serverGroups = remember(client) { server.serverGroupChoices(client.id) } val channelGroups = remember(client) { server.channelGroupChoices(client.id) } - val kickChannel = !client.self && server.canKickFromChannel - val kickServer = !client.self && server.canKickFromServer - val ban = !client.self && server.canBanClients - val talker = server.canGrantTalkPower && (client.talker || client.lacksTalkPower) + val kickChannel = !client.self && server.permissions.canKickFromChannel() + val kickServer = !client.self && server.permissions.canKickFromServer() + val ban = !client.self && server.permissions.canBanClients() + val talker = server.permissions.canGrantTalkPower() && (client.talker || client.lacksTalkPower) val showServerGroups = serverGroups.any { it.allowed() } val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() } if (!(talker || kickChannel || kickServer || ban || showServerGroups || showChannelGroups)) return null @@ -242,7 +242,7 @@ private fun ClientModeration( } } if (banning) { - BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason -> + BanPrompt(client.name, server.permissions.maxBanSeconds(), onDismiss = { banning = false }) { seconds, reason -> banning = false server.ban(client.id, seconds, reason) onDone() diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt index ba0d241..9e5d6e9 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -350,10 +350,10 @@ fun ServerScreen( val outside = tree.channel(state.channelId)?.clients.orEmpty().map { it.id }.let { selection - it.toSet() } SelectionBar( count = selection.size, - onMove = if (server.canMoveClients) ({ moving = selection }) else null, - onMoveHere = if (server.canMoveClients && outside.isNotEmpty()) ({ moveTo(state.channelId, outside) }) else null, - onKickChannel = if (server.canKickFromChannel && kickable(false).isNotEmpty()) ({ kickingSelection = false }) else null, - onKickServer = if (server.canKickFromServer && kickable(true).isNotEmpty()) ({ kickingSelection = true }) else null, + onMove = if (server.permissions.canMoveClients()) ({ moving = selection }) else null, + onMoveHere = if (server.permissions.canMoveClients() && outside.isNotEmpty()) ({ moveTo(state.channelId, outside) }) else null, + onKickChannel = if (server.permissions.canKickFromChannel() && kickable(false).isNotEmpty()) ({ kickingSelection = false }) else null, + onKickServer = if (server.permissions.canKickFromServer() && kickable(true).isNotEmpty()) ({ kickingSelection = true }) else null, onClear = { picked = emptySet() }, ) } @@ -402,7 +402,7 @@ fun ServerScreen( foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, listState = treeList, selected = selection, - onClientLongPress = if (server.canMoveClients || server.canKickFromChannel || server.canKickFromServer) { + onClientLongPress = if (server.permissions.canMoveClients() || server.permissions.canKickFromChannel() || server.permissions.canKickFromServer()) { { picked = selection + it.id } } else null, onShowSelf = { @@ -467,8 +467,8 @@ fun ServerScreen( clientSheet = null server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } }) else null, - onMove = if (server.canMoveClients) ({ clientSheet = null; moving = setOf(id) }) else null, - onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { + onMove = if (server.permissions.canMoveClients()) ({ clientSheet = null; moving = setOf(id) }) else null, + onMoveToOwnChannel = if (server.permissions.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { { server.moveClients(listOf(id), state.channelId); clientSheet = null } } else null, onFindInTree = if (clientSheetFromTree) null else ({ @@ -497,13 +497,13 @@ fun ServerScreen( channelSheet = null server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } } }) else null, - onFiles = if (server.canBrowseFiles) ({ + onFiles = if (server.permissions.canBrowseFiles()) ({ channelSheet = null if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "") }) else null, - onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null, - onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null, - onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null, + onCreateSub = if (server.permissions.canCreateChannels()) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null, + onEdit = if (server.permissions.canEditChannels()) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null, + onDelete = if (server.permissions.canDeleteChannels()) ({ channelSheet = null; deletingChannel = id }) else null, ) } } @@ -567,8 +567,8 @@ fun ServerScreen( remember(tree, infoUpdates) { server.serverDetails() }?.let { ServerSheet(it, onLink, onDismiss = { serverSheet = false }, onBookmark = { serverSheet = false; bookmarkHere(state.channelId) }, - onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null, - onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null) + onBanList = if (server.permissions.canViewBanList()) ({ serverSheet = false; banList = true }) else null, + onCreateChannel = if (server.permissions.canCreateChannels()) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null) } } } diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index 30e57d4..f058990 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -9,8 +9,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo | # | Finding | Status | |---|---|---| | 1 | Request failures reach frontends as strings, so they guess the kind by substring (`BanListDialog`, `ServerLogDialog`) and core needs a sentinel message (`SEARCH_NOT_PERMITTED`); success is signalled by a `null` error, here and in Android's `ServerController` (`String?`) | done (`0552ed8`): requests return `CompletableFuture`, failing with `RequestException` (kind + message); `Replies`/`Edt` split success and failure; Android uses `Result` | -| 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | done: 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` | open | +| 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: `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 | open | | 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | open | | 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | open | diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java index 5b572a8..2964c7e 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java @@ -21,8 +21,6 @@ import java.util.concurrent.TimeUnit; */ final class AvatarAdmin { - /** The server's own default for {@code i_client_max_avatar_filesize}. */ - static final int DEFAULT_MAX_AVATAR_BYTES = 200_000; /** The largest avatar we are willing to download, whatever a server allows. */ static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024; @@ -34,15 +32,6 @@ final class AvatarAdmin { this.conn = conn; } - /** - * How large an avatar this server lets us upload, from - * {@code i_client_max_avatar_filesize}, or the server default while unknown. - */ - int maxUploadBytes() { - int limit = conn.getModel().selfPermissionValue("i_client_max_avatar_filesize"); - return limit > 0 ? limit : DEFAULT_MAX_AVATAR_BYTES; - } - /** Uploads {@code source} as our avatar and announces it; returns its flag. */ String upload(File source) throws Exception { byte[] data = Files.readAllBytes(source.toPath()); @@ -50,7 +39,7 @@ final class AvatarAdmin { if (ImageFormat.detect(data) == null) { throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images"); } - int limit = maxUploadBytes(); + int limit = conn.getModel().permissions().maxAvatarBytes(); if (data.length > limit) { throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB"); } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java index 76e6d42..fa34f52 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java @@ -113,7 +113,7 @@ final class ChannelAdmin { * carries — anything inherited from a group is absent */ Map readPermissions(int channelId) throws Exception { - if (!conn.getModel().hasPermissionNames()) { + if (!conn.getModel().permissions().hasNames()) { // channelpermlist reports numeric ids, which only the permissionlist response // gives names to; without it the values could not be told apart. throw new IllegalStateException("The server did not send its permission list"); @@ -133,7 +133,7 @@ final class ChannelAdmin { Map byName = new LinkedHashMap<>(); for (Map.Entry entry : request.values.entrySet()) { - String name = conn.getModel().permissionName(entry.getKey()); + String name = conn.getModel().permissions().name(entry.getKey()); if (name != null) byName.put(name, entry.getValue()); } return byName; diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java index fa5823d..e86c9f9 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java @@ -633,12 +633,12 @@ final class ConnectionEventHandler implements TS3Listener { @Override public void onPermissionList(PermissionListEvent e) { - conn.getModel().putPermissionName(e.get("permname")); + conn.getModel().permissions().putName(e.get("permname")); } @Override public void onClientNeededPermissions(ClientNeededPermissionsEvent e) { - conn.getModel().putSelfPermissionValue(safeInt(e, "permid"), safeInt(e, "permvalue")); + conn.getModel().permissions().putValue(safeInt(e, "permid"), safeInt(e, "permvalue")); } @Override diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java index edbf5bd..0d0ddcd 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java @@ -89,9 +89,9 @@ final class ConnectionStatsCollector { s.monthBytesUploaded = entry.monthBytesUploaded; } if (s.self) { - ServerModel model = conn.getModel(); - s.downloadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_download_per_client", -1); - s.uploadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_upload_per_client", -1); + Permissions permissions = conn.getModel().permissions(); + s.downloadQuotaMb = permissions.downloadQuotaMb(); + s.uploadQuotaMb = permissions.uploadQuotaMb(); } VoiceOutput playback = conn.getPlayback(); if (playback != null) { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Permissions.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Permissions.java new file mode 100644 index 0000000..3283c2b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Permissions.java @@ -0,0 +1,298 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.net.ban.BanEntry; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * What the local client may do on a server, worked out from the permissions the server + * reports for it. Frontends ask the named questions; the permission names stay in here. + * + *

Until the server has said, an action is offered and the server is left to refuse, as + * the official client does. {@link #NONE} allows nothing, for while there is no connection. + * Thread-safe: filled from the event thread, asked from the UI. + */ +public final class Permissions { + + /** Allows nothing. */ + public static final Permissions NONE = new Permissions(false); + + /** + * The permissions {@code notifyclientneededpermissions} never carries, not even for an admin; + * they have to be asked for with {@code permget}. + */ + public static final List UNREPORTED = List.of("i_client_move_power", + "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power", + "b_client_complain_delete", "b_client_complain_delete_own"); + + /** The server's own default for {@code i_client_max_avatar_filesize}. */ + private static final int DEFAULT_MAX_AVATAR_BYTES = 200_000; + private static final int FIRST_PERMISSION_ID = 1; + + private final boolean live; + /** + * Permission id -> name, learned from the server's {@code permissionlist} response. + * Entries carry no id of their own: TS3 numbers them by position in the response, + * starting at 1, and the empty "group_id_end" separator records marking category + * boundaries don't count toward that position, so only {@link #putName} advances it. + */ + private final Map names = new LinkedHashMap<>(); + private final Map ids = new HashMap<>(); + private int nextId = FIRST_PERMISSION_ID; + /** Permission id -> the local client's resolved value, from {@code notifyclientneededpermissions}. */ + private final Map values = new LinkedHashMap<>(); + /** The local client's {@link #UNREPORTED} permissions; absent until known. */ + private final Map unreported = new HashMap<>(); + /** Whether the server answered for the {@link #UNREPORTED} permissions at all. */ + private boolean unreportedKnown; + + Permissions() { + this(true); + } + + private Permissions(boolean live) { + this.live = live; + } + + synchronized void clear() { + names.clear(); + ids.clear(); + nextId = FIRST_PERMISSION_ID; + values.clear(); + unreported.clear(); + unreportedKnown = false; + } + + // ---- what the server reports ---- + + /** Records the next named entry of a {@code permissionlist} response; ignores separators. */ + synchronized void putName(String name) { + if (name == null || name.isEmpty()) return; + names.put(nextId, name); + ids.putIfAbsent(name, nextId); + nextId++; + } + + synchronized void putValue(int permissionId, int value) { + values.put(permissionId, value); + } + + /** Takes on the answer to asking for the {@link #UNREPORTED} permissions; those it leaves out count as 0. */ + synchronized void setUnreported(Map values) { + unreported.clear(); + unreported.putAll(values); + unreportedKnown = true; + } + + /** + * The server would not say: asking needs {@code b_client_permissionoverview_own}, which + * moderator groups often lack although they hold the powers. + */ + synchronized void unreportedRefused() { + unreported.clear(); + unreportedKnown = false; + } + + /** Whether the server's {@code permissionlist} has arrived, so ids can be named at all. */ + synchronized boolean hasNames() { + return !names.isEmpty(); + } + + /** The name the server gave permission id {@code id}, or {@code null} if unknown. */ + synchronized String name(int id) { + return names.get(id); + } + + // ---- what we may do ---- + + public boolean canViewBanList() { + return permits("b_client_ban_list"); + } + + public boolean canCreateBans() { + return permits("b_client_ban_create"); + } + + /** + * Whether we may delete all of {@code bans}: any ban with {@code b_client_ban_delete}, + * only our own with {@code b_client_ban_delete_own}. + * + * @param selfUid our unique identifier, which is how a ban names its creator + */ + public synchronized boolean canDeleteBans(Collection bans, String selfUid) { + if (permits("b_client_ban_delete")) return true; + if (!permits("b_client_ban_delete_own")) return false; + return bans.stream().allMatch(b -> b.createdBy(selfUid)); + } + + /** Whether we may rewrite {@code ban}: that is deleting it and creating its replacement. */ + public synchronized boolean canEditBan(BanEntry ban, String selfUid) { + return canCreateBans() && canDeleteBans(List.of(ban), selfUid); + } + + /** {@code i_client_ban_max_bantime}: the longest ban we may hand out in seconds; 0 or -1 for no limit. */ + public synchronized long maxBanSeconds() { + return value("i_client_ban_max_bantime", 0); + } + + public boolean canViewComplaints() { + return permits("b_client_complain_list"); + } + + /** + * Whether we may remove all of {@code complaints}: any with {@code b_client_complain_delete}, + * only those we filed with {@code b_client_complain_delete_own}. + */ + public synchronized boolean canDeleteComplaints(Collection complaints, int selfDbId) { + if (power("b_client_complain_delete") > 0) return true; + if (power("b_client_complain_delete_own") <= 0) return false; + return complaints.stream().allMatch(c -> c.fromDbId() == selfDbId); + } + + public boolean canViewServerLog() { + return permits("b_virtualserver_log_view"); + } + + public boolean canListPrivilegeKeys() { + return permits("b_virtualserver_token_list"); + } + + public boolean canAddPrivilegeKeys() { + return permits("b_virtualserver_token_add"); + } + + public boolean canDeletePrivilegeKeys() { + return permits("b_virtualserver_token_delete"); + } + + public boolean canSendOfflineMessages() { + return permits("b_client_offline_textmessage_send"); + } + + /** Whether we may list channel files at all; a channel may still need more power than we have. */ + public boolean canBrowseFiles() { + return permits("i_ft_file_browse_power"); + } + + /** {@code i_ft_quota_mb_download_per_client}, or -1 while unknown. */ + public int downloadQuotaMb() { + return value("i_ft_quota_mb_download_per_client", -1); + } + + /** {@code i_ft_quota_mb_upload_per_client}, or -1 while unknown. */ + public int uploadQuotaMb() { + return value("i_ft_quota_mb_upload_per_client", -1); + } + + public boolean canSetAvatar() { + return permits("i_client_max_avatar_filesize"); + } + + /** How large an avatar we may upload, or the server default while unknown. */ + public int maxAvatarBytes() { + int limit = value("i_client_max_avatar_filesize", 0); + return limit > 0 ? limit : DEFAULT_MAX_AVATAR_BYTES; + } + + public boolean canDeleteOtherAvatars() { + return permits("b_client_avatar_delete_other"); + } + + /** Whether the server lets us ask for talk power; whether we need it is another matter. */ + public boolean canRequestTalkPower() { + return permits("b_client_request_talker"); + } + + public boolean canGrantTalkPower() { + return permits("b_client_set_flag_talker"); + } + + /* + * Whether we have any of a power; whether it beats the client's needed power only the + * server knows, so it is left to refuse. + */ + + public boolean canMoveClients() { + return mayHavePower("i_client_move_power"); + } + + public boolean canKickFromChannel() { + return mayHavePower("i_client_kick_from_channel_power"); + } + + public boolean canKickFromServer() { + return mayHavePower("i_client_kick_from_server_power"); + } + + public boolean canBanClients() { + return mayHavePower("i_client_ban_power"); + } + + public boolean canCreateChannels() { + return permitsAny("b_channel_create_temporary", "b_channel_create_semi_permanent", + "b_channel_create_permanent"); + } + + public boolean canEditChannels() { + return permitsAny("b_channel_modify_name", "b_channel_modify_topic", "b_channel_modify_description", + "b_channel_modify_password", "b_channel_modify_codec", "b_channel_modify_maxclients"); + } + + public boolean canDeleteChannels() { + return permitsAny("b_channel_delete_temporary", "b_channel_delete_semi_permanent", + "b_channel_delete_permanent"); + } + + /** + * Whether we have enough power to assign {@code group}, or to take it away when + * {@code assigned}: the add power always gates it, and the remove power additionally + * gates a group already held. {@code -1} is TS3's "unlimited" sentinel on either side: + * an unlimited own power always passes, and a group that needs unlimited power can only + * be touched by a client that has it. + */ + public synchronized boolean canToggleGroup(Group group, boolean assigned) { + if (!live) return false; + return beats(value("i_group_member_add_power", 0), group.neededMemberAddPower) + && (!assigned || beats(value("i_group_member_remove_power", 0), group.neededMemberRemovePower)); + } + + // ---- rules ---- + + /** Whether we hold a permission; offered until the server has named its permissions. */ + private synchronized boolean permits(String permission) { + return live && (!hasNames() || value(permission, 0) > 0); + } + + private boolean permitsAny(String... permissions) { + for (String p : permissions) { + if (permits(p)) return true; + } + return false; + } + + /** One of the {@link #UNREPORTED} powers: offered unless the server said we lack it. */ + private synchronized boolean mayHavePower(String name) { + return live && (!unreportedKnown || unreported.getOrDefault(name, 0) != 0); + } + + /** One of the {@link #UNREPORTED} powers; 0 until known, or when the server would not tell. */ + private synchronized int power(String name) { + return live ? unreported.getOrDefault(name, 0) : 0; + } + + private synchronized int value(String name, int absent) { + Integer id = ids.get(name); + Integer value = id == null ? null : values.get(id); + return value == null ? absent : value; + } + + private static boolean beats(int own, int needed) { + if (own == -1) return true; + if (needed == -1) return false; + return own >= needed; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java index eff383d..ee92dfc 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java @@ -22,23 +22,8 @@ public final class ServerModel { private final Map clients = new LinkedHashMap<>(); private final Map serverGroups = new LinkedHashMap<>(); private final Map channelGroups = new LinkedHashMap<>(); - /** - * Permission id -> name, learned from the server's {@code permissionlist} response. - * Entries carry no id of their own: TS3 numbers them by position in the response, - * starting at 1, and the empty "group_id_end" separator records marking category - * boundaries don't count toward that position, so only {@link #putPermissionName} - * advances it. - */ - private final Map permissionNames = new LinkedHashMap<>(); - private final Map permissionIds = new HashMap<>(); - private static final int FIRST_PERMISSION_ID = 1; - private int nextPermissionId = FIRST_PERMISSION_ID; - /** Permission id -> the local client's resolved value, from {@code notifyclientneededpermissions}. */ - private final Map selfPermissionValues = new LinkedHashMap<>(); - /** The local client's {@link #UNREPORTED_PERMISSIONS}, which the needed permissions leave out; absent until known. */ - private final Map unreportedValues = new HashMap<>(); - /** Whether the server answered for the {@link #UNREPORTED_PERMISSIONS} at all. */ - private boolean unreportedKnown; + /** What we may do here; cleared with the rest. */ + private final Permissions permissions = new Permissions(); private String serverName = "TeamSpeak Server"; /** The {@code virtualserver_*} properties from {@code initserver}, kept up to date by server edits. */ private final Map serverProperties = new HashMap<>(); @@ -52,12 +37,7 @@ public final class ServerModel { clients.clear(); serverGroups.clear(); channelGroups.clear(); - permissionNames.clear(); - permissionIds.clear(); - nextPermissionId = FIRST_PERMISSION_ID; - selfPermissionValues.clear(); - unreportedValues.clear(); - unreportedKnown = false; + permissions.clear(); serverProperties.clear(); defaultChannelGroupId = 0; defaultChannelId = 0; @@ -130,137 +110,8 @@ public final class ServerModel { return list; } - // ---- permissions ---- - - /** Records the next named entry of a {@code permissionlist} response; ignores separators. */ - public synchronized void putPermissionName(String name) { - if (name == null || name.isEmpty()) return; - permissionNames.put(nextPermissionId, name); - permissionIds.putIfAbsent(name, nextPermissionId); - nextPermissionId++; - } - - public synchronized void putSelfPermissionValue(int permId, int value) { - selfPermissionValues.put(permId, value); - } - - /** Whether the server's {@code permissionlist} has arrived, so ids can be named at all. */ - public synchronized boolean hasPermissionNames() { - return !permissionNames.isEmpty(); - } - - /** The name the server gave permission id {@code id}, or {@code null} if unknown. */ - public synchronized String permissionName(int id) { - return permissionNames.get(id); - } - - /** - * The local client's resolved value for a named permission (e.g. - * {@code "i_group_member_add_power"}), or {@code 0} if it isn't known - * yet (the {@code permissionlist} request is still in flight, or the server - * never reported a non-default value for it). - */ - public synchronized int selfPermissionValue(String name) { - return selfPermissionValue(name, 0); - } - - /** As {@link #selfPermissionValue(String)}, with {@code absent} for a permission not (yet) reported. */ - public synchronized int selfPermissionValue(String name, int absent) { - Integer id = permissionIds.get(name); - Integer value = id == null ? null : selfPermissionValues.get(id); - return value == null ? absent : value; - } - - /** - * The permissions {@code notifyclientneededpermissions} never carries, not even for an admin; - * they have to be asked for with {@code permget}. - */ - public static final List UNREPORTED_PERMISSIONS = List.of("i_client_move_power", - "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power", - "b_client_complain_delete", "b_client_complain_delete_own"); - - /** Takes on the answer to asking for {@link #UNREPORTED_PERMISSIONS}; those it leaves out count as 0. */ - public synchronized void setUnreportedPermissions(Map values) { - unreportedValues.clear(); - unreportedValues.putAll(values); - unreportedKnown = true; - } - - /** - * The server would not say: asking needs {@code b_client_permissionoverview_own}, which - * moderator groups often lack although they hold the powers. - */ - public synchronized void unreportedPermissionsRefused() { - unreportedValues.clear(); - unreportedKnown = false; - } - - /** - * Whether we may hold one of {@link #UNREPORTED_PERMISSIONS}: unless the server said we - * do not, the action is offered, as the official client always does, and the server judges. - */ - public synchronized boolean mayHavePower(String name) { - return !unreportedKnown || unreportedValues.getOrDefault(name, 0) != 0; - } - - /** One of {@link #UNREPORTED_PERMISSIONS}; 0 until known, or when the server would not tell. */ - public synchronized int selfPower(String name) { - return unreportedValues.getOrDefault(name, 0); - } - - // ---- what the local client may do ---- - - /** - * Whether we hold a permission. Until the server has named its permissions nothing can - * be resolved, so everything is offered and the server is left to refuse. - */ - public synchronized boolean permits(String permission) { - return !hasPermissionNames() || selfPermissionValue(permission) > 0; - } - - /** - * Whether we may delete all of {@code bans}: any ban with {@code b_client_ban_delete}, - * only our own with {@code b_client_ban_delete_own}. - * - * @param selfUid our unique identifier, which is how a ban names its creator - */ - public synchronized boolean canDeleteBans(Collection bans, String selfUid) { - if (permits("b_client_ban_delete")) return true; - if (!permits("b_client_ban_delete_own")) return false; - return bans.stream().allMatch(b -> b.createdBy(selfUid)); - } - - /** - * Whether we may remove all of {@code complaints}: any with {@code b_client_complain_delete}, - * only those we filed with {@code b_client_complain_delete_own}. - */ - public synchronized boolean canDeleteComplaints(Collection complaints, int selfDbId) { - if (selfPower("b_client_complain_delete") > 0) return true; - if (selfPower("b_client_complain_delete_own") <= 0) return false; - return complaints.stream().allMatch(c -> c.fromDbId() == selfDbId); - } - - /** Whether we may rewrite {@code ban}: that is deleting it and creating its replacement. */ - public synchronized boolean canEditBan(BanEntry ban, String selfUid) { - return permits("b_client_ban_create") && canDeleteBans(List.of(ban), selfUid); - } - - /** {@code i_client_ban_max_bantime}: the longest ban we may hand out in seconds; 0 or -1 for no limit. */ - public synchronized long maxBanSeconds() { - return selfPermissionValue("i_client_ban_max_bantime"); - } - - /** - * Whether the local client has enough power to assign {@code group}, or to take it - * away when {@code assigned}: the add power always gates it, and the remove power - * additionally gates a group already held. {@code -1} is TS3's "unlimited" sentinel on - * either side: an unlimited local power always passes, and a group that needs - * unlimited power can only be touched by a local client that has it. - */ - public synchronized boolean canToggleGroup(Group group, boolean assigned) { - return hasPower(group.neededMemberAddPower, selfPermissionValue("i_group_member_add_power")) - && (!assigned || hasPower(group.neededMemberRemovePower, - selfPermissionValue("i_group_member_remove_power"))); + public Permissions permissions() { + return permissions; } /** Every regular server group, with whether {@code client} is in it and whether we may change that. */ @@ -268,7 +119,7 @@ public final class ServerModel { List out = new ArrayList<>(); for (Group g : allServerGroups()) { boolean assigned = client.inServerGroup(g.id); - out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); + out.add(new GroupChoice(g, assigned, permissions.canToggleGroup(g, assigned))); } return out; } @@ -278,7 +129,7 @@ public final class ServerModel { List out = new ArrayList<>(); for (Group g : allChannelGroups()) { boolean assigned = client.channelGroupId == g.id; - out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); + out.add(new GroupChoice(g, assigned, permissions.canToggleGroup(g, assigned))); } return out; } @@ -287,16 +138,11 @@ public final class ServerModel { public synchronized List privilegeKeyGroups(boolean channelGroups) { List out = new ArrayList<>(); for (Group g : channelGroups ? allChannelGroups() : allServerGroups()) { - if (canToggleGroup(g, false)) out.add(g); + if (permissions.canToggleGroup(g, false)) out.add(g); } return out; } - private static boolean hasPower(int needed, int own) { - if (own == -1) return true; - if (needed == -1) return false; - return own >= needed; - } /** * Whether a channel shows in the tree at all — it doesn't while we are not subscribed diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java index fdaec2b..74c1e64 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -871,8 +871,8 @@ public final class TeamspeakConnection implements TS3Listener { * Asks the server to (re-)send its permission definitions, which arrive as a burst * of {@code notifypermissionlist} events — the only way to learn permission names, * since {@code notifyclientneededpermissions} (which resolves our own power for - * them) only ever reports numeric ids. Needed for {@link ServerModel#selfPermissionValue} - * to work; harmless if it's slow or fails, since group-assignment eligibility just + * them) only ever reports numeric ids. Needed for {@link Permissions} to resolve + * anything; harmless if it's slow or fails, since group-assignment eligibility just * won't be known yet. */ private void requestPermissionNames() { @@ -881,13 +881,13 @@ public final class TeamspeakConnection implements TS3Listener { } /** - * Asks for our own {@link ServerModel#UNREPORTED_PERMISSIONS}, which {@code notifyclientneededpermissions} - * never carries. Asking needs {@code b_client_permissionoverview_own}; refused, we take them - * as none, which is what the groups that lack the one usually have of the others. + * Asks for our own {@link Permissions#UNREPORTED} ones, which {@code notifyclientneededpermissions} + * never carries. Asking needs {@code b_client_permissionoverview_own}; refused, they stay + * unknown and the actions they gate stay offered. */ void requestSelfPowers() { List rows = new ArrayList<>(); - for (String name : ServerModel.UNREPORTED_PERMISSIONS) { + for (String name : Permissions.UNREPORTED) { rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name))); } submit(sock -> { @@ -898,8 +898,8 @@ public final class TeamspeakConnection implements TS3Listener { String value = fields.get("permvalue"); if (name != null && value != null) powers.put(name, Integer.parseInt(value)); } - model.setUnreportedPermissions(powers); - }, e -> model.unreportedPermissionsRefused()); + model.permissions().setUnreported(powers); + }, e -> model.permissions().unreportedRefused()); } /** Assigns or removes a server group for a client (by database id, as {@code servergroupaddclient} needs). */ @@ -1288,11 +1288,6 @@ public final class TeamspeakConnection implements TS3Listener { return self == null ? 0 : self.unreadMessages; } - /** Whether the server lets us send offline messages. */ - public boolean canSendOfflineMessages() { - return model.permits("b_client_offline_textmessage_send"); - } - /** Our unread count changed from {@code before}; more unread means new mail, which the log announces. */ void unreadMessagesChanged(int before) { int unread = unreadOfflineMessages(); @@ -1694,7 +1689,7 @@ public final class TeamspeakConnection implements TS3Listener { /** How large an avatar this server lets us upload, in bytes. */ public int maxAvatarBytes() { - return avatarAdmin.maxUploadBytes(); + return model.permissions().maxAvatarBytes(); } /** diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java index e555043..acd6e7c 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -12,6 +12,7 @@ import eu.lixko.ts3j.client.contacts.ContactStore; import eu.lixko.ts3j.client.net.ChannelNode; import eu.lixko.ts3j.client.net.ClientEntry; import eu.lixko.ts3j.client.net.ConnectionListener; +import eu.lixko.ts3j.client.net.Permissions; import eu.lixko.ts3j.client.net.Replies; import eu.lixko.ts3j.client.net.TeamspeakConnection; import eu.lixko.ts3j.client.net.Whisper; @@ -675,46 +676,9 @@ public final class ServerSession { // ---- permissions ---- - /** Whether the server grants us {@code b_client_ban_list}; offered while unknown. */ - public boolean canViewBanList() { - return permits("b_client_ban_list"); - } - - /** Whether the server grants us {@code b_client_complain_list}; offered while unknown. */ - public boolean canViewComplaints() { - return permits("b_client_complain_list"); - } - - /** Whether the server grants us {@code b_virtualserver_log_view}; offered while unknown. */ - public boolean canViewServerLog() { - return permits("b_virtualserver_log_view"); - } - - /** Whether the server grants us {@code b_virtualserver_token_list}; offered while unknown. */ - public boolean canListPrivilegeKeys() { - return permits("b_virtualserver_token_list"); - } - - /** - * Whether the server lets us list channel files ({@code i_ft_file_browse_power}); offered while - * unknown. A channel may still need more power than we have, which only the server knows. - */ - public boolean canBrowseFiles() { - return permits("i_ft_file_browse_power"); - } - - /** Whether the server lets us upload an avatar ({@code i_client_max_avatar_filesize}); offered while unknown. */ - public boolean canSetAvatar() { - return permits("i_client_max_avatar_filesize"); - } - - /** Whether the server lets us delete other clients' avatars; offered while unknown. */ - public boolean canDeleteOtherAvatars() { - return permits("b_client_avatar_delete_other"); - } - - private boolean permits(String permission) { - return conn.isConnected() && conn.getModel().permits(permission); + /** What we may do on this server; nothing while not connected. */ + public Permissions permissions() { + return conn.isConnected() ? conn.getModel().permissions() : Permissions.NONE; } /** Whether we publish an avatar on this server. */ @@ -724,65 +688,10 @@ public final class ServerSession { return self != null && !self.avatarFlag.isEmpty(); } - /** - * Whether we may ask for talk power: the server lets us ({@code b_client_request_talker}, offered - * while unknown), and we lack it in our channel, as it refuses the request otherwise. - */ + /** Whether we may ask for talk power: the server lets us, and we lack it in our channel, as it refuses otherwise. */ public boolean canRequestTalkPower() { ClientEntry self = self(); - return permits("b_client_request_talker") && self != null && conn.getModel().lacksTalkPower(self); - } - - /** Whether the server lets us grant and revoke talk power ({@code b_client_set_flag_talker}); offered while unknown. */ - public boolean canGrantTalkPower() { - return permits("b_client_set_flag_talker"); - } - - public boolean canMoveClients() { - return hasPower("i_client_move_power"); - } - - public boolean canKickFromChannel() { - return hasPower("i_client_kick_from_channel_power"); - } - - public boolean canKickFromServer() { - return hasPower("i_client_kick_from_server_power"); - } - - public boolean canBanClients() { - return hasPower("i_client_ban_power"); - } - - public boolean canCreateChannels() { - return permitsAny("b_channel_create_temporary", "b_channel_create_semi_permanent", - "b_channel_create_permanent"); - } - - public boolean canEditChannels() { - return permitsAny("b_channel_modify_name", "b_channel_modify_topic", "b_channel_modify_description", - "b_channel_modify_password", "b_channel_modify_codec", "b_channel_modify_maxclients"); - } - - public boolean canDeleteChannels() { - return permitsAny("b_channel_delete_temporary", "b_channel_delete_semi_permanent", - "b_channel_delete_permanent"); - } - - private boolean permitsAny(String... permissions) { - if (!conn.isConnected()) return false; - for (String p : permissions) { - if (conn.getModel().permits(p)) return true; - } - return false; - } - - /** - * Whether we have any of a power; whether it beats the client's needed power only the - * server knows, so it is left to refuse. - */ - private boolean hasPower(String power) { - return conn.isConnected() && conn.getModel().mayHavePower(power); + return permissions().canRequestTalkPower() && self != null && conn.getModel().lacksTalkPower(self); } // ---- connection events ---- diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/PermissionsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/PermissionsTest.java new file mode 100644 index 0000000..8e64808 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/PermissionsTest.java @@ -0,0 +1,76 @@ +package eu.lixko.ts3j.client.net; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PermissionsTest { + + private final Permissions permissions = new Permissions(); + + private void grant(String permission, int value) { + permissions.putName(permission); + permissions.putValue(permissionId(permission), value); + } + + private int permissionId(String name) { + for (int id = 0; ; id++) { + if (name.equals(permissions.name(id))) return id; + } + } + + private static Group group(int addPower, int removePower) { + return new Group(9, "Group", 0, 0, 1, addPower, removePower); + } + + @Test + void offeredUntilTheServerNamesItsPermissions() { + assertTrue(permissions.canViewBanList()); + + grant("b_client_complain_list", 1); + assertFalse(permissions.canViewBanList(), "named, and not ours"); + assertTrue(permissions.canViewComplaints()); + } + + @Test + void noneAllowsNothing() { + assertFalse(Permissions.NONE.canViewBanList()); + assertFalse(Permissions.NONE.canMoveClients()); + assertFalse(Permissions.NONE.canToggleGroup(group(0, 0), false)); + } + + @Test + void groupNeedsEnoughAddPowerAndRemovePowerToTakeAway() { + grant("i_group_member_add_power", 50); + grant("i_group_member_remove_power", 20); + + assertTrue(permissions.canToggleGroup(group(50, 0), false)); + assertFalse(permissions.canToggleGroup(group(51, 0), false)); + assertTrue(permissions.canToggleGroup(group(50, 20), true)); + assertFalse(permissions.canToggleGroup(group(50, 21), true)); + } + + @Test + void unlimitedPowerIsMinusOneOnEitherSide() { + grant("i_group_member_add_power", 75); + grant("i_group_member_remove_power", -1); + + assertFalse(permissions.canToggleGroup(group(-1, 0), false), "a group needing unlimited power"); + assertTrue(permissions.canToggleGroup(group(75, 1000), true), "unlimited remove power"); + } + + @Test + void unreportedPowerCountsOnlyWhenTheServerSaidNo() { + assertTrue(permissions.canMoveClients(), "not answered yet"); + + permissions.setUnreported(Map.of("i_client_move_power", 50)); + assertTrue(permissions.canMoveClients()); + assertFalse(permissions.canKickFromServer(), "answered without it"); + + permissions.unreportedRefused(); + assertTrue(permissions.canKickFromServer(), "refused: left to the server"); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java index 1986944..dd18064 100644 --- a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java @@ -9,41 +9,6 @@ class ServerModelRulesTest { private final ServerModel model = new ServerModel(); - private void grant(String permission, int value) { - model.putPermissionName(permission); - model.putSelfPermissionValue(permissionId(permission), value); - } - - private int permissionId(String name) { - for (int id = 0; ; id++) { - if (name.equals(model.permissionName(id))) return id; - } - } - - private static Group group(int addPower, int removePower) { - return new Group(9, "Group", 0, 0, 1, addPower, removePower); - } - - @Test - void groupNeedsEnoughAddPowerAndRemovePowerToTakeAway() { - grant("i_group_member_add_power", 50); - grant("i_group_member_remove_power", 20); - - assertTrue(model.canToggleGroup(group(50, 0), false)); - assertFalse(model.canToggleGroup(group(51, 0), false)); - assertTrue(model.canToggleGroup(group(50, 20), true)); - assertFalse(model.canToggleGroup(group(50, 21), true)); - } - - @Test - void unlimitedPowerIsMinusOneOnEitherSide() { - grant("i_group_member_add_power", 75); - grant("i_group_member_remove_power", -1); - - assertFalse(model.canToggleGroup(group(-1, 0), false), "a group needing unlimited power"); - assertTrue(model.canToggleGroup(group(75, 1000), true), "unlimited remove power"); - } - @Test void joiningNeedsAVisibleChannelWithRoom() { ChannelNode channel = model.putChannel(1, "Full", 0, 0); @@ -56,16 +21,4 @@ class ServerModelRulesTest { assertFalse(model.canJoinChannel(1), "full"); assertFalse(model.canJoinChannel(2), "unknown"); } - - @Test - void unreportedPowerCountsOnlyWhenTheServerSaidNo() { - assertTrue(model.mayHavePower("i_client_move_power"), "not answered yet"); - - model.setUnreportedPermissions(java.util.Map.of("i_client_move_power", 50)); - assertTrue(model.mayHavePower("i_client_move_power")); - assertFalse(model.mayHavePower("i_client_kick_from_server_power"), "answered without it"); - - model.unreportedPermissionsRefused(); - assertTrue(model.mayHavePower("i_client_kick_from_server_power"), "refused: left to the server"); - } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java index 0e78ddc..8f14e5b 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java @@ -4,6 +4,7 @@ import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; import eu.lixko.ts3j.client.config.BanReasonPresets; import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.Permissions; import eu.lixko.ts3j.client.net.TeamspeakConnection; import eu.lixko.ts3j.client.net.ban.BanEntry; import eu.lixko.ts3j.client.net.ban.BanRule; @@ -417,25 +418,18 @@ final class BanListDialog extends JDialog { // ---- permissions ---- - private boolean can(String permission) { - return conn.getModel().permits(permission); - } - - private boolean canDelete(List bans) { - return conn.getModel().canDeleteBans(bans, conn.getSelfUniqueId()); - } - private void updateButtons() { + Permissions permissions = conn.getModel().permissions(); List selected = selectedBans(); - addButton.setEnabled(can("b_client_ban_create")); - removeButton.setEnabled(!selected.isEmpty() && canDelete(selected)); - editButton.setEnabled(selected.size() == 1 && conn.getModel().canEditBan(selected.get(0), conn.getSelfUniqueId())); + addButton.setEnabled(permissions.canCreateBans()); + removeButton.setEnabled(!selected.isEmpty() && permissions.canDeleteBans(selected, conn.getSelfUniqueId())); + editButton.setEnabled(selected.size() == 1 && permissions.canEditBan(selected.get(0), conn.getSelfUniqueId())); } // ---- actions ---- private long maxBanSeconds() { - return conn.getModel().maxBanSeconds(); + return conn.getModel().permissions().maxBanSeconds(); } private void addBan() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java index b49aaf0..9ac8472 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java @@ -355,7 +355,7 @@ final class ComplaintsDialog extends JDialog { private void updateButtons() { Selection sel = selection(); - removeButton.setEnabled(!sel.isEmpty() && conn.getModel().canDeleteComplaints(sel.affected(), selfDbId())); + removeButton.setEnabled(!sel.isEmpty() && conn.getModel().permissions().canDeleteComplaints(sel.affected(), selfDbId())); } /** @@ -366,7 +366,7 @@ final class ComplaintsDialog extends JDialog { int[] rows = table.getSelectedRows(); if (rows.length != 1) return null; ServerModel model = conn.getModel(); - if (!model.mayHavePower("i_client_ban_power")) return null; + if (!model.permissions().canBanClients()) return null; Row row = tableModel.get(rows[0]); ClientEntry client = model.findClientByDatabaseId(row.isTarget() ? row.target().dbId() : row.complaint().fromDbId()); return client == null || client.id == conn.getSelfClientId() ? null : client; diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java index 1c3eece..be79b91 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java @@ -295,7 +295,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { @Override public boolean canSetAvatar() { - return selected != null && selected.session().canSetAvatar(); + return selected != null && selected.session().permissions().canSetAvatar(); } @Override @@ -350,7 +350,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { @Override public boolean canViewBanList() { - return selected != null && selected.session().canViewBanList(); + return selected != null && selected.session().permissions().canViewBanList(); } @Override @@ -360,7 +360,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { @Override public boolean canViewComplaints() { - return selected != null && selected.session().canViewComplaints(); + return selected != null && selected.session().permissions().canViewComplaints(); } @Override @@ -370,7 +370,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { @Override public boolean canViewServerLog() { - return selected != null && selected.session().canViewServerLog(); + return selected != null && selected.session().permissions().canViewServerLog(); } @Override @@ -380,7 +380,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { @Override public boolean canListPrivilegeKeys() { - return selected != null && selected.session().canListPrivilegeKeys(); + return selected != null && selected.session().permissions().canListPrivilegeKeys(); } @Override diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java index 9d813d4..304e843 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java @@ -363,7 +363,7 @@ final class OfflineMessagesDialog extends JDialog { } private void updateButtons() { - boolean canSend = conn.canSendOfflineMessages(); + boolean canSend = conn.getModel().permissions().canSendOfflineMessages(); composeButton.setEnabled(canSend); replyButton.setEnabled(canSend && singleSelected() != null); deleteButton.setEnabled(table.getSelectedRowCount() > 0); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java index 5e97049..d5fba91 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java @@ -235,8 +235,8 @@ final class PrivilegeKeysDialog extends JDialog { private void updateButtons() { ServerModel model = conn.getModel(); - createButton.setEnabled(model.permits("b_virtualserver_token_add")); - removeButton.setEnabled(!selectedKeys().isEmpty() && model.permits("b_virtualserver_token_delete")); + createButton.setEnabled(model.permissions().canAddPrivilegeKeys()); + removeButton.setEnabled(!selectedKeys().isEmpty() && model.permissions().canDeletePrivilegeKeys()); } // ---- actions ---- diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index da33246..71730da 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -129,12 +129,12 @@ final class ServerTab { @Override public boolean canSet() { - return session.canSetAvatar(); + return session.permissions().canSetAvatar(); } @Override public boolean canDeleteOthers() { - return session.canDeleteOtherAvatars(); + return session.permissions().canDeleteOtherAvatars(); } @Override @@ -236,7 +236,7 @@ final class ServerTab { } void composeOfflineMessage() { - if (!session.isConnected() || !conn.canSendOfflineMessages()) return; + if (!session.permissions().canSendOfflineMessages()) return; Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host; OfflineMessageComposeDialog.compose(owner, conn, contacts).setVisible(true); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java index 6edd2ac..d056c45 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java @@ -174,7 +174,7 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { public void banClient(ClientEntry client) { if (!conn.isConnected()) return; BanDialog dialog = new BanDialog(host, client.nickname, - conn.getModel().maxBanSeconds()); + conn.getModel().permissions().maxBanSeconds()); dialog.setVisible(true); if (dialog.isConfirmed()) conn.banClient(client.id, dialog.getSeconds(), dialog.getReason()); } @@ -229,12 +229,12 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { */ @Override public boolean canDeleteOtherAvatars() { - return tab.session().canDeleteOtherAvatars(); + return tab.session().permissions().canDeleteOtherAvatars(); } @Override public boolean canGrantTalkPower() { - return tab.session().canGrantTalkPower(); + return tab.session().permissions().canGrantTalkPower(); } @Override @@ -346,7 +346,7 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { @Override public boolean canBrowseFiles() { - return tab.session().canBrowseFiles(); + return tab.session().permissions().canBrowseFiles(); } @Override