diff --git a/connector/src/main.rs b/connector/src/main.rs index 36026ca..df1d395 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -17,9 +17,9 @@ use tsclientlib::messages::c2s::{ OutChannelAddPermPart, OutChannelClientAddPermPart, OutChannelClientDelPermPart, OutChannelClientPermListRequestPart, OutChannelDelPermPart, OutChannelGroupAddPermPart, OutChannelGroupDelPermPart, OutChannelGroupPermListRequestPart, OutChannelPermListRequestPart, - OutClientAddPermPart, OutClientDelPermPart, OutClientPermListRequestPart, OutClientPokeRequestPart, - OutCreateDirectoryPart, OutDeleteFilePart, OutFileListRequestPart, OutRenameFilePart, - OutSendTextMessagePart, OutServerGroupAddPermPart, OutServerGroupDelPermPart, + OutClientAddPermPart, OutClientDelPermPart, OutClientMovePart, OutClientPermListRequestPart, + OutClientPokeRequestPart, OutCreateDirectoryPart, OutDeleteFilePart, OutFileListRequestPart, + OutRenameFilePart, OutSendTextMessagePart, OutServerGroupAddPermPart, OutServerGroupDelPermPart, OutServerGroupPermListRequestPart, }; use tsclientlib::prelude::*; @@ -103,6 +103,9 @@ struct ClientInfo { /// haven't been individually granted talk power. Always `true` in a /// non-moderated channel. has_talk_power: bool, + /// ServerQuery client (`ClientType::Query`). Always included in the + /// snapshot; the UI hides these unless the user enables them per favorite. + is_query: bool, } /// Payload for the "serveredit " stdin command - every field is optional so @@ -573,13 +576,13 @@ fn snapshot(con: &data::Connection) -> Event { has_password: ch.has_password.unwrap_or(false), }) .collect::>(); - // Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them - // from the channel tree / client lists, and from the online-count fallback - // below too, so the number shown never counts a client the list doesn't. + // Bookkeeping includes ServerQuery clients (`ClientType::Query`). We always + // forward them (with `is_query`) so the UI can toggle visibility live from + // a favorite setting without reconnecting. Online counts below still exclude + // Query by default so the headline matches the default (hidden) tree. let clients = con .clients .values() - .filter(|c| !matches!(c.client_type, ClientType::Query { .. })) .map(|c| { // A channel with no talk power requirement at all (the common // case) is never moderated, so everyone can talk regardless of @@ -605,19 +608,20 @@ fn snapshot(con: &data::Connection) -> Event { channel_group: c.channel_group.0, server_groups: c.server_groups.iter().map(|g| g.0).collect(), has_talk_power, + is_query: matches!(c.client_type, ClientType::Query { .. }), } }) .collect::>(); // Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated) - // but never under-report vs. the visible (non-Query) client set (stale - // optional_data after joins would otherwise freeze the InfoPanel left number). - // `virtualserver_clientsonline` usually includes ServerQuery; subtract the - // Query clients we filtered from the list so the headline matches the tree. + // but never under-report vs. the non-Query client set (stale optional_data + // after joins would otherwise freeze the InfoPanel left number). + // `virtualserver_clientsonline` usually includes ServerQuery; subtract them + // so the default (Query-hidden) headline matches the default tree. let opt = con.server.optional_data.as_ref(); let visible_channels = channels.len() as u64; - let visible_clients_count = clients.len() as u16; - let query_count = (con.clients.len() as u16).saturating_sub(visible_clients_count); + let query_count = clients.iter().filter(|c| c.is_query).count() as u16; + let visible_clients_count = (clients.len() as u16).saturating_sub(query_count); let server_clients_online = opt .map(|d| { let without_query = d.client_count.saturating_sub(query_count); @@ -1094,6 +1098,72 @@ async fn run(args: Args) -> Result<()> { } Err(_) => emit(&Event::Error { message: format!("Invalid client id: {id}") }), } + } else if let Some(rest) = l.strip_prefix("moveclient ") { + // Move another client (or self) into a channel: clientmove clid=… cid=… + // Optional trailing base64 password, same as `switch`. + let mut move_args = rest.trim().splitn(3, ' '); + let clid_arg = move_args.next().unwrap_or(""); + let cid_arg = move_args.next().unwrap_or(""); + let password_arg = move_args.next(); + match (clid_arg.parse::(), cid_arg.parse::()) { + (Ok(clid), Ok(cid)) => { + let password = password_arg.and_then(|p| { + base64::engine::general_purpose::STANDARD + .decode(p) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + }); + let part = match con.get_state() { + Ok(state) => match state.clients.get(&ClientId(clid)) { + Some(client) => { + let mut part = client.client_move(ChannelId(cid)); + match &password { + Some(pwd) => { + part = part.set_password(pwd); + } + None => { + part.channel_password = + Some(std::borrow::Cow::Borrowed("")); + } + } + Some(part) + } + None => { + // Still try with raw ids if the client left our view. + // Carry through the already-decoded password instead of + // dropping it - this path is also used for self-moves + // via drag-and-drop, which still need the password to + // reach the server when the target channel requires one. + Some(OutClientMovePart { + client_id: ClientId(clid), + channel_id: ChannelId(cid), + channel_password: Some(match &password { + Some(pwd) => Cow::Owned(pwd.clone()), + None => Cow::Borrowed(""), + }), + }) + } + }, + Err(e) => { + emit(&Event::Error { + message: format!("Move client failed: {e}"), + }); + None + } + }; + if let Some(part) = part { + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Move client".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + } + _ => emit(&Event::Error { + message: format!("Malformed moveclient command: {rest}"), + }), + } } else if l == "away" || l.starts_with("away ") { let message = l.strip_prefix("away").unwrap_or("").trim(); let part = con.get_state()?.client_update().set_away(Some(message)); @@ -2292,6 +2362,23 @@ async fn run(args: Args) -> Result<()> { } } Some(Ok(StreamItem::MessageEvent(msg))) => { + // Defense in depth: TeaSpeak/GTS may surface notifyclientpoke as an + // unhandled MessageEvent if bookkeeping did not mark it handled. + if let InMessage::ClientPoke(poke) = &msg { + for part in poke.iter() { + emit(&Event::Poke { + from: part.invoker_name.clone(), + message: part.message.clone().unwrap_or_default(), + }); + } + } else if let InMessage::ClientPokeNormal(poke) = &msg { + for part in poke.iter() { + emit(&Event::Poke { + from: part.invoker_name.clone(), + message: part.message.clone().unwrap_or_default(), + }); + } + } if pending_server_log { if let InMessage::ServerLog(log) = &msg { let lines: Vec = log.iter().map(|part| part.log.clone()).collect(); diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 9767a63..eab8f3a 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -138,6 +138,14 @@ wss.on("connection", (socket: WebSocket) => { } break; } + case "moveClient": { + const clientId = Number(msg.clientId); + const channelId = Number(msg.channelId); + if (Number.isFinite(clientId) && Number.isFinite(channelId)) { + await connection?.moveClient(clientId, channelId, msg.channelPassword); + } + break; + } case "sendChatMessage": { await connection?.sendChatMessage(msg.message); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index e13bd1b..9796450 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -37,6 +37,8 @@ export interface ClientInfo { channelGroup: number; serverGroups: number[]; hasTalkPower: boolean; + /** ServerQuery client; UI may hide these unless enabled per favorite. */ + isQuery: boolean; } export interface GroupEntry { @@ -252,6 +254,7 @@ export class Ts3Connection { channel_group: number; server_groups: number[]; has_talk_power: boolean; + is_query?: boolean; } interface RawChannelInfo { @@ -424,6 +427,7 @@ export class Ts3Connection { channelGroup: c.channel_group, serverGroups: c.server_groups, hasTalkPower: c.has_talk_power, + isQuery: Boolean(c.is_query), })), ownClientId: event.own_client_id ?? 0, serverMaxClients: event.server_max_clients ?? 0, @@ -550,6 +554,14 @@ export class Ts3Connection { this.child?.stdin.write(`switch ${id}${passwordArg}\n`); } + async moveClient(clientId: number, channelId: number, channelPassword?: string): Promise { + const clid = Number(clientId); + const cid = Number(channelId); + if (!Number.isFinite(clid) || !Number.isFinite(cid)) return; + const passwordArg = channelPassword ? ` ${Buffer.from(channelPassword, "utf8").toString("base64")}` : ""; + this.child?.stdin.write(`moveclient ${clid} ${cid}${passwordArg}\n`); + } + async getClientConnectionInfo(clientId: number): Promise { this.child?.stdin.write(`clientconninfo ${clientId}\n`); } diff --git a/tsclientlib b/tsclientlib index 5fdf15c..a879f17 160000 --- a/tsclientlib +++ b/tsclientlib @@ -1 +1 @@ -Subproject commit 5fdf15cf5a6055a53ed2f186e3a2b6bf9b764a16 +Subproject commit a879f17fec733c2175674094ce3eb9b9c968e5e3 diff --git a/web/src/App.css b/web/src/App.css index e37018c..62e7db0 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1787,6 +1787,13 @@ background: var(--row-hover); } +.ts-channel-row.ts-drop-target, +.ts-channel-row.ts-spacer.ts-drop-target { + background: color-mix(in srgb, var(--accent) 22%, transparent); + outline: 1px dashed var(--accent); + outline-offset: -1px; +} + /* Channel spacers ([cspacer], [*spacer01], …) — GreenTeaSpeak / TS parity */ .ts-channel-row.ts-spacer { position: relative; @@ -1897,10 +1904,15 @@ } .ts-client-row { + cursor: grab; color: var(--client-text); padding-left: 0; } +.ts-client-row:active { + cursor: grabbing; +} + .ts-client-row.ts-self { font-weight: 700; color: var(--self-text); diff --git a/web/src/App.tsx b/web/src/App.tsx index 31c2fb3..ebbc653 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import "./App.css"; /** Only dismiss on a genuine backdrop click, not a text-selection drag that @@ -260,12 +260,33 @@ interface Favorite { serverPassword: string; defaultChannel: string; defaultChannelPassword: string; + /** When true, ServerQuery clients appear in the channel tree. Default: false. */ + showServerQueryClients: boolean; +} + +function normalizeFavorite(raw: Partial & Pick): Favorite { + return { + id: raw.id, + bookmarkName: typeof raw.bookmarkName === "string" ? raw.bookmarkName : "", + nickname: typeof raw.nickname === "string" ? raw.nickname : "", + host: typeof raw.host === "string" ? raw.host : "", + serverPassword: typeof raw.serverPassword === "string" ? raw.serverPassword : "", + defaultChannel: typeof raw.defaultChannel === "string" ? raw.defaultChannel : "", + defaultChannelPassword: + typeof raw.defaultChannelPassword === "string" ? raw.defaultChannelPassword : "", + showServerQueryClients: raw.showServerQueryClients === true, + }; } function loadFavorites(): Favorite[] { try { const raw = localStorage.getItem(FAVORITES_KEY); - return raw ? (JSON.parse(raw) as Favorite[]) : []; + if (!raw) return []; + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + return parsed + .filter((v): v is Partial & Pick => v && typeof v.id === "string") + .map(normalizeFavorite); } catch { return []; } @@ -448,6 +469,8 @@ interface ClientInfo { channelGroup: number; serverGroups: number[]; hasTalkPower: boolean; + /** ServerQuery client; filtered from the tree unless a favorite enables them. */ + isQuery?: boolean; } interface GroupEntry { @@ -666,6 +689,27 @@ function ServerIcon() { const lastChannelClickBySession = new Map(); let switchArmedUntil = 0; +const CLIENT_DRAG_MIME = "application/x-webspeak3-client"; + +type ClientDragPayload = { clientId: number; channelId: number }; + +function parseClientDragPayload(raw: string): ClientDragPayload | null { + try { + const data = JSON.parse(raw) as Partial; + if ( + typeof data.clientId === "number" && + Number.isFinite(data.clientId) && + typeof data.channelId === "number" && + Number.isFinite(data.channelId) + ) { + return { clientId: data.clientId, channelId: data.channelId }; + } + } catch { + /* ignore */ + } + return null; +} + function ChannelTree({ channels, clients, @@ -680,6 +724,7 @@ function ChannelTree({ onSwitchChannel, onOpenPrivateChat, onPokeClient, + onMoveClient, onClientContextMenu, onChannelContextMenu, }: { @@ -698,11 +743,13 @@ function ChannelTree({ onSwitchChannel: (channelId: number) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void; onPokeClient: (clientId: number, clientName: string) => void; + onMoveClient: (clientId: number, channelId: number) => void; onClientContextMenu: (e: React.MouseEvent, clientId: number, clientName: string, isSelf: boolean) => void; onChannelContextMenu: (e: React.MouseEvent, channelId: number, channelName: string) => void; }) { const t = useT(); const [collapsed, setCollapsed] = useState>(() => new Set()); + const [dragOverChannelId, setDragOverChannelId] = useState(null); // Module-level click tracking (see lastChannelClick) — refs alone are not // enough when Select re-renders remount nested ChannelTree instances. const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order); @@ -744,7 +791,7 @@ function ChannelTree({
{ onSelectItem({ type: "channel", id: channel.id }); // Manual double-click: native dblclick is often lost when the first @@ -765,6 +812,24 @@ function ChannelTree({ onSwitchChannel(channel.id); }} onContextMenu={(e) => onChannelContextMenu(e, channel.id, channel.name)} + onDragOver={(e) => { + if (![...e.dataTransfer.types].includes(CLIENT_DRAG_MIME)) return; + e.preventDefault(); + e.dataTransfer.dropEffect = "move"; + if (dragOverChannelId !== channel.id) setDragOverChannelId(channel.id); + }} + onDragLeave={(e) => { + const related = e.relatedTarget as Node | null; + if (related && e.currentTarget.contains(related)) return; + setDragOverChannelId((prev) => (prev === channel.id ? null : prev)); + }} + onDrop={(e) => { + e.preventDefault(); + setDragOverChannelId(null); + const payload = parseClientDragPayload(e.dataTransfer.getData(CLIENT_DRAG_MIME)); + if (!payload || payload.channelId === channel.id) return; + onMoveClient(payload.clientId, channel.id); + }} title={t("tree.clickToJoin")} > {!spacer.isSpacer && ( @@ -816,6 +881,18 @@ function ChannelTree({ ? " ts-talking" : "" }${selected?.type === "client" && selected.id === c.id ? " ts-row-selected" : ""}`} + draggable + onDragStart={(e) => { + const payload: ClientDragPayload = { + clientId: c.id, + channelId: c.channel, + }; + const raw = JSON.stringify(payload); + e.dataTransfer.setData(CLIENT_DRAG_MIME, raw); + e.dataTransfer.setData("text/plain", raw); + e.dataTransfer.effectAllowed = "move"; + }} + onDragEnd={() => setDragOverChannelId(null)} onClick={() => onSelectItem({ type: "client", id: c.id })} onDoubleClick={ c.id === ownClientId ? undefined : () => onOpenPrivateChat(c.id, c.name) @@ -904,6 +981,7 @@ function ChannelTree({ onSwitchChannel={onSwitchChannel} onOpenPrivateChat={onOpenPrivateChat} onPokeClient={onPokeClient} + onMoveClient={onMoveClient} onClientContextMenu={onClientContextMenu} onChannelContextMenu={onChannelContextMenu} /> @@ -1470,6 +1548,7 @@ function FavoritesDialog({ id: crypto.randomUUID(), bookmarkName: prefillNew.host || t("favorites.newFavoriteName"), ...prefillNew, + showServerQueryClients: prefillNew.showServerQueryClients === true, } : null ); @@ -1496,6 +1575,7 @@ function FavoritesDialog({ serverPassword: "", defaultChannel: "", defaultChannelPassword: "", + showServerQueryClients: false, }; setDraft((prev) => [...prev, nf]); setSelectedId(nf.id); @@ -1624,7 +1704,12 @@ function FavoritesDialog({