diff --git a/connector/src/main.rs b/connector/src/main.rs index 87c9a8c..69eb01c 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -13,14 +13,19 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tsclientlib::audio::AudioHandler; use tsclientlib::events::{Event as BookEvent, PropertyId, PropertyValue}; use tsclientlib::messages::c2s::{ - OutClientPokeRequestPart, OutCreateDirectoryPart, OutDeleteFilePart, OutFileListRequestPart, - OutRenameFilePart, OutSendTextMessagePart, + OutChannelAddPermPart, OutChannelClientAddPermPart, OutChannelClientDelPermPart, + OutChannelClientPermListRequestPart, OutChannelDelPermPart, OutChannelGroupAddPermPart, + OutChannelGroupDelPermPart, OutChannelGroupPermListRequestPart, OutChannelPermListRequestPart, + OutClientAddPermPart, OutClientDelPermPart, OutClientPermListRequestPart, OutClientPokeRequestPart, + OutCreateDirectoryPart, OutDeleteFilePart, OutFileListRequestPart, OutRenameFilePart, + OutSendTextMessagePart, OutServerGroupAddPermPart, OutServerGroupDelPermPart, + OutServerGroupPermListRequestPart, }; use tsclientlib::prelude::*; use tsclientlib::{ - data, ChannelId, ClientId, CodecEncryptionMode, Connection, DisconnectOptions, HostBannerMode, - HostMessageMode, Identity, InMessage, MaxClients, MessageHandle, MessageTarget, Reason, - StreamItem, TextMessageTargetMode, + data, ChannelGroupId, ChannelId, ClientDbId, ClientId, CodecEncryptionMode, Connection, + DisconnectOptions, HostBannerMode, HostMessageMode, Identity, InMessage, MaxClients, + MessageHandle, MessageTarget, Permission, Reason, ServerGroupId, StreamItem, TextMessageTargetMode, }; use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType}; @@ -285,6 +290,17 @@ enum Event { /// A requested file upload finished successfully. #[serde(rename = "fileUploadDone")] FileUploadDone { cid: u64, path: String }, + /// Reply to a "permlist ..." request - the permissions currently + /// assigned to one server group / channel group / channel / client / + /// channel+client combination. `scope` and `id1`/`id2` echo what was + /// requested, so the frontend can route the reply to the right editor tab. + #[serde(rename = "permList")] + PermList { scope: String, id1: u64, id2: Option, entries: Vec }, + /// Reply to a "permissionlist" request - the full catalog of every + /// permission the server knows about (not just ones actually assigned + /// anywhere), for populating an "add permission" picker. + #[serde(rename = "permissionCatalog")] + PermissionCatalog { entries: Vec }, } #[derive(Serialize)] @@ -333,6 +349,14 @@ struct PermissionOverviewEntry { skip: bool, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct PermissionCatalogEntry { + id: u32, + name: String, + description: String, +} + #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct GroupEntry { @@ -695,6 +719,17 @@ async fn run(args: Args) -> Result<()> { // request that stream belongs to. let mut pending_downloads: HashMap = HashMap::new(); let mut pending_uploads: HashMap)> = HashMap::new(); + // Set by "permissionlist" while waiting to emit the full permission + // catalog (name-resolution reuses the same permission_names cache/fetch + // as "permoverview" above). + let mut pending_permission_catalog = false; + // Set by "permlist ..." while one server-group/channel-group/ + // channel/client/channel+client permission listing is in flight - single + // request at a time, matching the editor UI only ever loading one + // selected target. (scope, id1, id2) echoes what was requested so the + // eventual emit can be routed back to it. + let mut pending_perm_list: Option<(String, u64, Option)> = None; + let mut pending_perm_list_raw: Option> = None; enum LoopOutcome { StdinLine(std::io::Result>), @@ -1508,6 +1543,216 @@ async fn run(args: Args) -> Result<()> { } _ => emit(&Event::Error { message: "Invalid ftupload args".into() }), } + } else if l == "permissionlist" { + if permission_names.is_empty() { + let packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "permissionlist", + ); + match packet.send_with_result(&mut con) { + Ok(handle) => { + pending_permission_list = true; + pending_permission_catalog = true; + pending_messages.insert(handle, "Permission list".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } else { + let entries: Vec = permission_names + .iter() + .map(|(id, (name, description))| PermissionCatalogEntry { + id: *id, + name: name.clone(), + description: description.clone(), + }) + .collect(); + emit(&Event::PermissionCatalog { entries }); + } + } else if let Some(rest) = l.strip_prefix("permlist ") { + let parts: Vec<&str> = rest.trim().split_whitespace().collect(); + let target = match parts.as_slice() { + ["server", sgid] => sgid.parse::().ok().map(|id| { + ("server".to_string(), id, None, OutServerGroupPermListRequestPart { + server_group_id: ServerGroupId(id), + }.to_packet()) + }), + ["channelgroup", cgid] => cgid.parse::().ok().map(|id| { + ("channelgroup".to_string(), id, None, OutChannelGroupPermListRequestPart { + channel_group: ChannelGroupId(id), + }.to_packet()) + }), + ["channel", cid] => cid.parse::().ok().map(|id| { + ("channel".to_string(), id, None, OutChannelPermListRequestPart { channel_id: ChannelId(id) }.to_packet()) + }), + ["client", cldbid] => cldbid.parse::().ok().map(|id| { + ("client".to_string(), id, None, OutClientPermListRequestPart { client_db_id: ClientDbId(id) }.to_packet()) + }), + ["channelclient", cid, cldbid] => match (cid.parse::(), cldbid.parse::()) { + (Ok(id1), Ok(id2)) => Some(( + "channelclient".to_string(), + id1, + Some(id2), + OutChannelClientPermListRequestPart { + channel_id: ChannelId(id1), + client_db_id: ClientDbId(id2), + } + .to_packet(), + )), + _ => None, + }, + _ => None, + }; + match target { + Some((scope, id1, id2, packet)) => { + if permission_names.is_empty() { + let names_packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "permissionlist", + ); + match names_packet.send_with_result(&mut con) { + Ok(handle) => { + pending_permission_list = true; + pending_messages.insert(handle, "Permission list".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + match packet.send_with_result(&mut con) { + Ok(handle) => { + pending_perm_list = Some((scope, id1, id2)); + pending_messages.insert(handle, "Permission list request".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + None => emit(&Event::Error { message: format!("Invalid permlist args: {rest}") }), + } + } else if let Some(rest) = l.strip_prefix("permadd ") { + let parts: Vec<&str> = rest.trim().split_whitespace().collect(); + let result = (|| -> Option { + match parts.as_slice() { + ["server", sgid, permid, value, negated, skip] => Some( + OutServerGroupAddPermPart { + server_group_id: ServerGroupId(sgid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + permission_value: value.parse().ok()?, + permission_negated: *negated == "1", + permission_skip: *skip == "1", + } + .to_packet(), + ), + ["channelgroup", cgid, permid, value] => Some( + OutChannelGroupAddPermPart { + channel_group: ChannelGroupId(cgid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + permission_value: value.parse().ok()?, + } + .to_packet(), + ), + ["channel", cid, permid, value] => Some( + OutChannelAddPermPart { + channel_id: ChannelId(cid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + permission_value: value.parse().ok()?, + } + .to_packet(), + ), + ["client", cldbid, permid, value, skip] => Some( + OutClientAddPermPart { + client_db_id: ClientDbId(cldbid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + permission_value: value.parse().ok()?, + permission_skip: *skip == "1", + } + .to_packet(), + ), + ["channelclient", cid, cldbid, permid, value] => Some( + OutChannelClientAddPermPart { + channel_id: ChannelId(cid.parse().ok()?), + client_db_id: ClientDbId(cldbid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + permission_value: value.parse().ok()?, + } + .to_packet(), + ), + _ => None, + } + })(); + match result { + Some(packet) => match packet.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Add permission".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + }, + None => emit(&Event::Error { message: format!("Invalid permadd args: {rest}") }), + } + } else if let Some(rest) = l.strip_prefix("permdel ") { + let parts: Vec<&str> = rest.trim().split_whitespace().collect(); + let result = (|| -> Option { + match parts.as_slice() { + ["server", sgid, permid] => Some( + OutServerGroupDelPermPart { + server_group_id: ServerGroupId(sgid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + } + .to_packet(), + ), + ["channelgroup", cgid, permid] => Some( + OutChannelGroupDelPermPart { + channel_group: ChannelGroupId(cgid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + } + .to_packet(), + ), + ["channel", cid, permid] => Some( + OutChannelDelPermPart { + channel_id: ChannelId(cid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + } + .to_packet(), + ), + ["client", cldbid, permid] => Some( + OutClientDelPermPart { + client_db_id: ClientDbId(cldbid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + } + .to_packet(), + ), + ["channelclient", cid, cldbid, permid] => Some( + OutChannelClientDelPermPart { + channel_id: ChannelId(cid.parse().ok()?), + client_db_id: ClientDbId(cldbid.parse().ok()?), + permission_id: Some(Permission(permid.parse().ok()?)), + permission_name_id: None, + } + .to_packet(), + ), + _ => None, + } + })(); + match result { + Some(packet) => match packet.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Remove permission".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + }, + None => emit(&Event::Error { message: format!("Invalid permdel args: {rest}") }), + } } else if let Some(b64) = l.strip_prefix("audio ") { match base64::engine::general_purpose::STANDARD.decode(b64.trim()) { Ok(bytes) => { @@ -1804,6 +2049,34 @@ async fn run(args: Args) -> Result<()> { .collect(); emit(&Event::PermissionOverview { entries }); } + if let Some(raw) = pending_perm_list_raw.take() { + if let Some((scope, id1, id2)) = pending_perm_list.clone() { + let entries: Vec = raw + .into_iter() + .map(|(id, value, negated, skip)| { + let (name, description) = permission_names + .get(&id) + .cloned() + .unwrap_or_else(|| (format!("#{id}"), String::new())); + PermissionOverviewEntry { name, description, value, negated, skip } + }) + .collect(); + emit(&Event::PermList { scope, id1, id2, entries }); + pending_perm_list = None; + } + } + if pending_permission_catalog { + pending_permission_catalog = false; + let entries: Vec = permission_names + .iter() + .map(|(id, (name, description))| PermissionCatalogEntry { + id: *id, + name: name.clone(), + description: description.clone(), + }) + .collect(); + emit(&Event::PermissionCatalog { entries }); + } } } if pending_perm_overview { @@ -1839,6 +2112,73 @@ async fn run(args: Args) -> Result<()> { } } } + if pending_perm_list.is_some() { + let raw: Option> = match &msg { + InMessage::ServerGroupPermList(list) => Some( + list.iter() + .filter_map(|part| { + part.permission_id.map(|id| { + (id.0, part.permission_value, part.permission_negated, part.permission_skip) + }) + }) + .collect(), + ), + InMessage::ChannelGroupPermList(list) => Some( + list.iter() + .filter_map(|part| { + part.permission_id.map(|id| { + (id.0, part.permission_value, part.permission_negated, part.permission_skip) + }) + }) + .collect(), + ), + InMessage::ChannelPermList(list) => Some( + list.iter() + .map(|part| { + (part.permission_id.0, part.permission_value, part.permission_negated, part.permission_skip) + }) + .collect(), + ), + InMessage::ClientPermList(list) => Some( + list.iter() + .filter_map(|part| { + part.permission_id.map(|id| { + (id.0, part.permission_value, part.permission_negated, part.permission_skip) + }) + }) + .collect(), + ), + InMessage::ChannelClientPermList(list) => Some( + list.iter() + .filter_map(|part| { + part.permission_id.map(|id| { + (id.0, part.permission_value, part.permission_negated, part.permission_skip) + }) + }) + .collect(), + ), + _ => None, + }; + if let Some(raw) = raw { + if pending_permission_list { + // The name lookup hasn't come back yet - buffer the raw + // values and resolve them once it does. + pending_perm_list_raw = Some(raw); + } else if let Some((scope, id1, id2)) = pending_perm_list.take() { + let entries: Vec = raw + .into_iter() + .map(|(id, value, negated, skip)| { + let (name, description) = permission_names + .get(&id) + .cloned() + .unwrap_or_else(|| (format!("#{id}"), String::new())); + PermissionOverviewEntry { name, description, value, negated, skip } + }) + .collect(); + emit(&Event::PermList { scope, id1, id2, entries }); + } + } + } if pending_file_list.is_some() { if let InMessage::FileList(list) = &msg { for part in list.iter() { diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 5ea932f..de5e76d 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -246,6 +246,22 @@ wss.on("connection", (socket: WebSocket) => { await connection?.uploadFile(msg.channelId, msg.path, msg.dataBase64); break; } + case "getPermissionCatalog": { + await connection?.getPermissionCatalog(); + break; + } + case "getPermList": { + await connection?.getPermList(msg.scope, msg.id1, msg.id2); + break; + } + case "addPermission": { + await connection?.addPermission(msg.scope, msg.ids, msg.permId, msg.value, msg.negated, msg.skip); + break; + } + case "removePermission": { + await connection?.removePermission(msg.scope, msg.ids, msg.permId); + break; + } case "disconnect": { await connection?.disconnect(msg.message ?? ""); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index abfdf2f..9b1c52a 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -51,6 +51,14 @@ export interface PermissionOverviewEntry { skip: boolean; } +export interface PermissionCatalogEntry { + id: number; + name: string; + description: string; +} + +export type PermScope = "server" | "channelgroup" | "channel" | "client" | "channelclient"; + export interface BanListEntry { banId: number; ip: string; @@ -162,7 +170,9 @@ export type Ts3ConnectionEvent = | { type: "permissionOverview"; entries: PermissionOverviewEntry[] } | { type: "fileList"; cid: number; path: string; entries: FileListEntry[] } | { type: "fileDownloadData"; cid: number; path: string; data: string } - | { type: "fileUploadDone"; cid: number; path: string }; + | { type: "fileUploadDone"; cid: number; path: string } + | { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] } + | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }; export interface Ts3ConnectOptions { host: string; @@ -334,7 +344,9 @@ export class Ts3Connection { } | { type: "fileList"; cid: number; path: string; entries: FileListEntry[] } | { type: "fileDownloadData"; cid: number; path: string; data: string } - | { type: "fileUploadDone"; cid: number; path: string }; + | { type: "fileUploadDone"; cid: number; path: string } + | { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] } + | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }; if (event.type === "connected") { this.emit({ @@ -610,6 +622,36 @@ export class Ts3Connection { this.child?.stdin.write(`permoverview\n`); } + async getPermissionCatalog(): Promise { + this.child?.stdin.write(`permissionlist\n`); + } + + async getPermList(scope: PermScope, id1: number, id2?: number): Promise { + const args = id2 !== undefined ? `${scope} ${id1} ${id2}` : `${scope} ${id1}`; + this.child?.stdin.write(`permlist ${args}\n`); + } + + /** `negated`/`skip` only apply to the "server" and "client" scopes - the + * connector ignores extra trailing args for scopes that don't use them, so + * it's safe to always pass through what the caller gave. */ + async addPermission( + scope: PermScope, + ids: number[], + permId: number, + value: number, + negated = false, + skip = false + ): Promise { + let args = `${scope} ${ids.join(" ")} ${permId} ${value}`; + if (scope === "server") args += ` ${negated ? 1 : 0} ${skip ? 1 : 0}`; + else if (scope === "client") args += ` ${skip ? 1 : 0}`; + this.child?.stdin.write(`permadd ${args}\n`); + } + + async removePermission(scope: PermScope, ids: number[], permId: number): Promise { + this.child?.stdin.write(`permdel ${scope} ${ids.join(" ")} ${permId}\n`); + } + async getFileList(channelId: number, path: string): Promise { const sanitized = (path || "/").replace(/[\r\n]+/g, " ").trim() || "/"; this.child?.stdin.write(`ftlist ${channelId} ${sanitized}\n`); diff --git a/web/src/App.css b/web/src/App.css index 5573d69..514df57 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1234,6 +1234,96 @@ border-radius: 2px; } +.ts-perms-editor-dialog { + width: 820px; + max-width: 95vw; +} + +.ts-perms-editor-tabs { + display: flex; + border-bottom: 1px solid var(--border-soft); + flex-wrap: wrap; +} + +.ts-perms-editor-tab { + background: none; + border: none; + padding: 0.5rem 0.8rem; + cursor: pointer; + color: var(--text-muted); + border-bottom: 2px solid transparent; +} + +.ts-perms-editor-tab-active { + color: var(--text); + border-bottom-color: var(--accent, #4a9eff); +} + +.ts-perms-editor-body { + display: flex; + gap: 0.75rem; + align-items: flex-start; +} + +.ts-perms-editor-picker { + width: 180px; + flex-shrink: 0; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.ts-perms-editor-list { + list-style: none; + margin: 0; + padding: 0; + max-height: 380px; + overflow-y: auto; + border: 1px solid var(--border-soft); + border-radius: 4px; +} + +.ts-perms-editor-list li { + padding: 0.3rem 0.5rem; + border-bottom: 1px solid var(--border-soft); +} + +.ts-perms-editor-list li:last-child { + border-bottom: none; +} + +.ts-perms-editor-list-empty { + color: var(--text-muted); + font-size: 12px; +} + +.ts-perms-editor-selected { + font-weight: bold; + color: var(--accent, #4a9eff); +} + +.ts-perms-editor-client-picker { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.ts-perms-editor-main { + flex: 1; + min-width: 0; +} + +.ts-perms-editor-add-form { + display: flex; + gap: 0.4rem; + align-items: center; + flex-wrap: wrap; + margin-bottom: 0.5rem; + padding: 0.4rem; + border: 1px solid var(--border-soft); + border-radius: 4px; +} + .ts-server-protocol-log-line { padding: 0.15rem 0.4rem; border-bottom: 1px solid var(--border-soft); diff --git a/web/src/App.tsx b/web/src/App.tsx index c5ecbe1..424ebbe 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -336,6 +336,14 @@ interface FileListEntry { timestamp: string; } +interface PermissionCatalogEntry { + id: number; + name: string; + description: string; +} + +type PermScope = "server" | "channelgroup" | "channel" | "client" | "channelclient"; + interface ClientConnectionInfoData { clientId: number; pingMs: number | null; @@ -1996,6 +2004,336 @@ function ServerIconsDialog({ ); } +/** The five permission-editor tabs from the real TS3 "Rechte" window - each + * is a different scope the ts3 protocol tracks assigned permissions under. */ +const PERM_SCOPES: { scope: PermScope; labelKey: string }[] = [ + { scope: "server", labelKey: "permsEditor.tab.server" }, + { scope: "client", labelKey: "permsEditor.tab.client" }, + { scope: "channel", labelKey: "permsEditor.tab.channel" }, + { scope: "channelgroup", labelKey: "permsEditor.tab.channelgroup" }, + { scope: "channelclient", labelKey: "permsEditor.tab.channelclient" }, +]; + +function PermissionsEditorDialog({ + initialScope, + channelGroups, + serverGroups, + channels, + clients, + entries, + catalog, + onSelectTarget, + onLoadCatalog, + onAdd, + onRemove, + onClose, +}: { + initialScope: PermScope; + channelGroups: GroupEntry[] | null; + serverGroups: GroupEntry[] | null; + channels: ChannelInfo[]; + clients: ClientInfo[]; + entries: PermissionOverviewEntry[] | null; + catalog: PermissionCatalogEntry[] | null; + onSelectTarget: (scope: PermScope, id1: number, id2?: number) => void; + onLoadCatalog: () => void; + onAdd: (scope: PermScope, ids: number[], permId: number, value: number, negated: boolean, skip: boolean) => void; + onRemove: (scope: PermScope, ids: number[], permId: number) => void; + onClose: () => void; +}) { + const t = useT(); + const backdrop = useBackdropDismiss(onClose); + const [scope, setScope] = useState(initialScope); + const [groupId, setGroupId] = useState(null); + const [channelId, setChannelId] = useState(null); + const [clientDbIdInput, setClientDbIdInput] = useState(""); + const [filter, setFilter] = useState(""); + const [showAddForm, setShowAddForm] = useState(false); + const [addPermSearch, setAddPermSearch] = useState(""); + const [addPermId, setAddPermId] = useState(null); + const [addValue, setAddValue] = useState("1"); + const [addNegated, setAddNegated] = useState(false); + const [addSkip, setAddSkip] = useState(false); + + const groupList = scope === "server" ? serverGroups : scope === "channelgroup" ? channelGroups : null; + + // (ids, ready) for the currently selected target under the active tab - + // ready is false while a required piece (channel/client) hasn't been picked yet. + const target: { id1: number; id2?: number } | null = (() => { + const clientDbId = parseInt(clientDbIdInput, 10); + switch (scope) { + case "server": + case "channelgroup": + return groupId !== null ? { id1: groupId } : null; + case "channel": + return channelId !== null ? { id1: channelId } : null; + case "client": + return !Number.isNaN(clientDbId) ? { id1: clientDbId } : null; + case "channelclient": + return channelId !== null && !Number.isNaN(clientDbId) ? { id1: channelId, id2: clientDbId } : null; + default: + return null; + } + })(); + + const load = (next: { scope: PermScope; groupId?: number | null; channelId?: number | null; clientDbId?: number }) => { + // The catalog doubles as the name->id lookup the delete button needs, so + // fetch it alongside the first load rather than only when "+ Hinzufügen" + // is opened - onLoadCatalog is idempotent (a no-op once already cached). + onLoadCatalog(); + const s = next.scope; + const gid = next.groupId !== undefined ? next.groupId : groupId; + const cid = next.channelId !== undefined ? next.channelId : channelId; + const cldbid = next.clientDbId !== undefined ? next.clientDbId : parseInt(clientDbIdInput, 10); + if ((s === "server" || s === "channelgroup") && gid !== null && gid !== undefined) { + onSelectTarget(s, gid); + } else if (s === "channel" && cid !== null && cid !== undefined) { + onSelectTarget(s, cid); + } else if (s === "client" && !Number.isNaN(cldbid)) { + onSelectTarget(s, cldbid); + } else if (s === "channelclient" && cid !== null && cid !== undefined && !Number.isNaN(cldbid)) { + onSelectTarget(s, cid, cldbid); + } + }; + + const filtered = entries?.filter((e) => e.name.toLowerCase().includes(filter.toLowerCase())) ?? null; + const showNegated = scope === "server"; + const showSkip = scope === "server" || scope === "client"; + + const catalogFiltered = (catalog ?? []) + .filter((p) => p.name.toLowerCase().includes(addPermSearch.toLowerCase())) + .slice(0, 200); // keep the setClientDbIdInput(e.target.value)} + onKeyDown={(e) => e.key === "Enter" && load({ scope })} + placeholder="1" + /> + + + {clients.length > 0 && ( + + )} + + )} + +
+ {!target ? ( +
{t("permsEditor.pickTarget")}
+ ) : ( + <> +
+ + +
+ {showAddForm && ( +
{ + e.preventDefault(); + if (addPermId === null || !target) return; + const value = parseInt(addValue, 10); + if (Number.isNaN(value)) return; + const ids = target.id2 !== undefined ? [target.id1, target.id2] : [target.id1]; + onAdd(scope, ids, addPermId, value, addNegated, addSkip); + setShowAddForm(false); + setAddPermSearch(""); + setAddPermId(null); + }} + > + setAddPermSearch(e.target.value)} + /> + + setAddValue(e.target.value)} + style={{ width: "5em" }} + /> + {showNegated && ( + + )} + {showSkip && ( + + )} + +
+ )} + {!entries ? ( +
{t("connectionInfo.loading")}
+ ) : filtered && filtered.length === 0 ? ( +
{t("permissionOverview.empty")}
+ ) : ( +
+ + + + + + {showNegated && } + {showSkip && } + + + + {filtered!.map((entry, i) => { + const catalogEntry = catalog?.find((p) => p.name === entry.name); + return ( + + + + {showNegated && } + {showSkip && } + + + ); + })} + +
{t("permissionOverview.name")}{t("permissionOverview.value")}{t("permissionOverview.negated")}{t("permissionOverview.skip")} +
{entry.name}{entry.value}{entry.negated ? "✔️" : ""}{entry.skip ? "✔️" : ""} + {catalogEntry && ( + + )} +
+
+ )} + + )} +
+ +
+ +
+ +
+
+ + + ); +} + function PermissionOverviewDialog({ entries, onClose, @@ -3572,6 +3910,14 @@ function AppInner() { } | null>(null); const [permissionOverviewOpen, setPermissionOverviewOpen] = useState(false); const [permissionOverview, setPermissionOverview] = useState(null); + const [permissionsEditorOpen, setPermissionsEditorOpen] = useState(false); + const [permissionsEditorScope, setPermissionsEditorScope] = useState("server"); + const [permissionsEditorEntries, setPermissionsEditorEntries] = useState(null); + const [permissionsEditorTarget, setPermissionsEditorTarget] = useState< + { scope: PermScope; id1: number; id2?: number } | null + >(null); + const [permissionCatalog, setPermissionCatalog] = useState(null); + const permissionCatalogRequestedRef = useRef(false); const [fileBrowserTarget, setFileBrowserTarget] = useState<{ channelId: number; channelName: string } | null>( null ); @@ -4213,6 +4559,12 @@ function AppInner() { if (data.cid === 0) handleServerIconsRefresh(); else handleFileBrowserRefresh(); break; + case "permList": + setPermissionsEditorEntries(data.entries); + break; + case "permissionCatalog": + setPermissionCatalog(data.entries); + break; } }; @@ -4996,6 +5348,53 @@ function AppInner() { socketRef.current?.send(JSON.stringify({ type: "getPermissionOverview" })); }; + const handleOpenPermissionsEditor = (scope: PermScope) => { + setPermissionsEditorScope(scope); + setPermissionsEditorEntries(null); + setPermissionsEditorTarget(null); + setPermissionsEditorOpen(true); + // Fetch both lists regardless of the initial tab - the dialog lets the + // user switch to any of the 5 tabs, including the group ones, later. + if (!serverGroups) socketRef.current?.send(JSON.stringify({ type: "getServerGroupList" })); + if (!channelGroups) socketRef.current?.send(JSON.stringify({ type: "getChannelGroupList" })); + }; + + const handlePermsLoadCatalog = () => { + if (permissionCatalogRequestedRef.current) return; + permissionCatalogRequestedRef.current = true; + socketRef.current?.send(JSON.stringify({ type: "getPermissionCatalog" })); + }; + + const handlePermsSelectTarget = (scope: PermScope, id1: number, id2?: number) => { + setPermissionsEditorEntries(null); + setPermissionsEditorTarget({ scope, id1, id2 }); + socketRef.current?.send(JSON.stringify({ type: "getPermList", scope, id1, id2 })); + }; + + const handlePermsRefresh = () => { + if (!permissionsEditorTarget) return; + const { scope, id1, id2 } = permissionsEditorTarget; + setPermissionsEditorEntries(null); + socketRef.current?.send(JSON.stringify({ type: "getPermList", scope, id1, id2 })); + }; + + const handlePermsAdd = ( + scope: PermScope, + ids: number[], + permId: number, + value: number, + negated: boolean, + skip: boolean + ) => { + socketRef.current?.send(JSON.stringify({ type: "addPermission", scope, ids, permId, value, negated, skip })); + window.setTimeout(handlePermsRefresh, 300); + }; + + const handlePermsRemove = (scope: PermScope, ids: number[], permId: number) => { + socketRef.current?.send(JSON.stringify({ type: "removePermission", scope, ids, permId })); + window.setTimeout(handlePermsRefresh, 300); + }; + const handleChannelContextMenu = (e: React.MouseEvent, channelId: number, channelName: string) => { e.preventDefault(); const x = Math.min(e.clientX, window.innerWidth - 220); @@ -5388,20 +5787,44 @@ function AppInner() { {rightsMenuOpen && (
- -
- - @@ -5966,6 +6389,23 @@ function AppInner() { /> )} + {permissionsEditorOpen && ( + setPermissionsEditorOpen(false)} + /> + )} + {fileBrowserTarget && ( ::" - the fake permission set currently +// assigned to one server group / channel group / channel / client / +// channel+client combination. +const DEMO_PERM_LISTS: Record = { + "server:1:-": [ + { name: "b_client_kick_from_server", description: "Kick client from server", value: 1, negated: false, skip: false }, + { name: "b_client_ban_client", description: "Ban client", value: 1, negated: false, skip: false }, + ], + "server:4:-": [ + { name: "i_channel_join_power", description: "Power to join channels", value: 25, negated: false, skip: false }, + ], + "channelgroup:1:-": [ + { name: "i_channel_create_modify_power", description: "Power to create/modify channels", value: 75, negated: false, skip: false }, + ], + "client:1:-": [ + { name: "b_client_info_view", description: "View own client info", value: 1, negated: false, skip: false }, + ], +}; + +function demoPermKey(scope: string, id1: number, id2?: number): string { + return `${scope}:${id1}:${id2 ?? "-"}`; +} + const SELF_ID = 101; /** @@ -423,6 +473,36 @@ export class DemoSocket { ); break; } + case "getPermissionCatalog": { + this.after(300, () => this.emit({ type: "permissionCatalog", entries: DEMO_PERMISSION_CATALOG })); + break; + } + case "getPermList": { + const key = demoPermKey(msg.scope, msg.id1, msg.id2); + this.after(300, () => + this.emit({ type: "permList", scope: msg.scope, id1: msg.id1, id2: msg.id2 ?? null, entries: DEMO_PERM_LISTS[key] ?? [] }) + ); + break; + } + case "addPermission": { + const [id1, id2] = msg.ids as number[]; + const key = demoPermKey(msg.scope, id1, id2); + const catalogEntry = DEMO_PERMISSION_CATALOG.find((p) => p.id === msg.permId); + const name = catalogEntry?.name ?? `#${msg.permId}`; + const description = catalogEntry?.description ?? ""; + const list = (DEMO_PERM_LISTS[key] ?? []).filter((e) => e.name !== name); + list.push({ name, description, value: msg.value, negated: !!msg.negated, skip: !!msg.skip }); + DEMO_PERM_LISTS[key] = list; + break; + } + case "removePermission": { + const [id1, id2] = msg.ids as number[]; + const key = demoPermKey(msg.scope, id1, id2); + const catalogEntry = DEMO_PERMISSION_CATALOG.find((p) => p.id === msg.permId); + const name = catalogEntry?.name ?? `#${msg.permId}`; + if (DEMO_PERM_LISTS[key]) DEMO_PERM_LISTS[key] = DEMO_PERM_LISTS[key].filter((e) => e.name !== name); + break; + } case "getFileList": { const key = demoFileKey(msg.channelId, msg.path); this.after(300, () => diff --git a/web/src/i18n.tsx b/web/src/i18n.tsx index abfc32f..04a76ec 100644 --- a/web/src/i18n.tsx +++ b/web/src/i18n.tsx @@ -411,6 +411,19 @@ const translations: Record> = { "permissionOverview.negated": "Negiert", "permissionOverview.skip": "Skip", + "permsEditor.title": "Rechte", + "permsEditor.tab.server": "Server Gruppen", + "permsEditor.tab.client": "Client Rechte", + "permsEditor.tab.channel": "Channel Rechte", + "permsEditor.tab.channelgroup": "Channel Gruppen", + "permsEditor.tab.channelclient": "Channel Client Rechte", + "permsEditor.clientDbId": "Eindeutige Client-DB-ID:", + "permsEditor.load": "Laden", + "permsEditor.pickOnlineClient": "Oder Online-Client wählen...", + "permsEditor.pickTarget": "Bitte links eine Gruppe/einen Channel wählen bzw. eine Client-ID eingeben.", + "permsEditor.addPermission": "Hinzufügen", + "permsEditor.searchPermission": "Recht suchen...", + "dialog.ok": "OK", "channelContext.files": "Dateien...", "fileBrowser.title": "Dateitransfers", @@ -889,6 +902,19 @@ const translations: Record> = { "permissionOverview.negated": "Negated", "permissionOverview.skip": "Skip", + "permsEditor.title": "Permissions", + "permsEditor.tab.server": "Server Groups", + "permsEditor.tab.client": "Client Permissions", + "permsEditor.tab.channel": "Channel Permissions", + "permsEditor.tab.channelgroup": "Channel Groups", + "permsEditor.tab.channelclient": "Channel Client Permissions", + "permsEditor.clientDbId": "Unique client DB ID:", + "permsEditor.load": "Load", + "permsEditor.pickOnlineClient": "Or pick an online client...", + "permsEditor.pickTarget": "Pick a group/channel on the left, or enter a client ID.", + "permsEditor.addPermission": "Add", + "permsEditor.searchPermission": "Search permission...", + "dialog.ok": "OK", "channelContext.files": "Files...", "fileBrowser.title": "File Transfers",