Add kick and ban to the client context menu

Wires up "Aus dem Channel kicken", "Vom Server kicken", and "Bannen"
(previously disabled placeholders). Kick uses tsclientlib's typed
Client::kick() builder; ban has no typed wrapper so it's built as a
raw "banclient" command (same OutCommand::write_arg approach used for
the connection-info requests). Both use send_with_result() so a
missing-permission rejection surfaces as a visible error.

"Channel-Gruppe zuweisen"/"Server-Gruppe zuweisen" remain disabled -
they need the server's group list threaded through first, left for a
follow-up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
MoepchiandClaude Sonnet 5 committed 2026-08-05 11:21:52 +02:00
1 parent 74f688aba8
commit 330ecccadb
6 files changed
+287 -3

No files matched your search

+80 -1
View File
@@ -18,7 +18,7 @@ use tsclientlib::{
data, ChannelId, ClientId, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle,
MessageTarget, Reason, StreamItem, TextMessageTargetMode,
};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio};
use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType};
/// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects.
const FRAME_SAMPLES: usize = 960;
@@ -662,6 +662,85 @@ async fn run(args: Args) -> Result<()> {
}
Err(_) => emit(&Event::Error { message: format!("Invalid client id: {rest}") }),
}
} else if let Some(rest) = l.strip_prefix("kickchannel ") {
let mut parts = rest.splitn(2, ' ');
let id_str = parts.next().unwrap_or("");
let reason = parts.next().unwrap_or("").trim();
match id_str.trim().parse::<u16>() {
Ok(id) => {
let client_id = ClientId(id);
let part = con.get_state()?.clients.get(&client_id).map(|c| {
let kick = c.kick(Reason::KickChannel);
if reason.is_empty() { kick } else { kick.set_reason_message(reason) }
});
match part {
Some(part) => match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Kick from channel".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
},
None => {
emit(&Event::Error { message: format!("Unknown client id: {id}") })
}
}
}
Err(_) => emit(&Event::Error { message: format!("Invalid client id: {id_str}") }),
}
} else if let Some(rest) = l.strip_prefix("kickserver ") {
let mut parts = rest.splitn(2, ' ');
let id_str = parts.next().unwrap_or("");
let reason = parts.next().unwrap_or("").trim();
match id_str.trim().parse::<u16>() {
Ok(id) => {
let client_id = ClientId(id);
let part = con.get_state()?.clients.get(&client_id).map(|c| {
let kick = c.kick(Reason::KickServer);
if reason.is_empty() { kick } else { kick.set_reason_message(reason) }
});
match part {
Some(part) => match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Kick from server".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
},
None => {
emit(&Event::Error { message: format!("Unknown client id: {id}") })
}
}
}
Err(_) => emit(&Event::Error { message: format!("Invalid client id: {id_str}") }),
}
} else if let Some(rest) = l.strip_prefix("banclient ") {
// Format: "banclient <id> <seconds> <reason...>" - seconds=0 means permanent.
// No typed builder exists for banclient, so this is built as a raw command
// (same approach used for the connection-info requests above).
let mut parts = rest.splitn(3, ' ');
let id_str = parts.next().unwrap_or("");
let seconds_str = parts.next().unwrap_or("0");
let reason = parts.next().unwrap_or("").trim();
match id_str.trim().parse::<u16>() {
Ok(id) => {
let seconds: u64 = seconds_str.trim().parse().unwrap_or(0);
let mut packet =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "banclient");
packet.write_arg("clid", &id);
if seconds > 0 {
packet.write_arg("time", &seconds);
}
if !reason.is_empty() {
packet.write_arg("banreason", &reason);
}
match packet.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Ban client".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
}
}
Err(_) => emit(&Event::Error { message: format!("Invalid client id: {id_str}") }),
}
} else if l == "serverconninfo" {
let part = con.get_state()?.server.connection_info();
match part.send_with_result(&mut con) {
+12
View File
@@ -130,6 +130,18 @@ wss.on("connection", (socket: WebSocket) => {
await connection?.getServerConnectionInfo();
break;
}
case "kickFromChannel": {
await connection?.kickFromChannel(msg.clientId, msg.reason ?? "");
break;
}
case "kickFromServer": {
await connection?.kickFromServer(msg.clientId, msg.reason ?? "");
break;
}
case "banClient": {
await connection?.banClient(msg.clientId, msg.seconds ?? 0, msg.reason ?? "");
break;
}
case "disconnect": {
await connection?.disconnect(msg.message ?? "");
break;
+15
View File
@@ -312,6 +312,21 @@ export class Ts3Connection {
this.child?.stdin.write(`serverconninfo\n`);
}
async kickFromChannel(clientId: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.child?.stdin.write(`kickchannel ${clientId} ${sanitized}\n`);
}
async kickFromServer(clientId: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.child?.stdin.write(`kickserver ${clientId} ${sanitized}\n`);
}
async banClient(clientId: number, seconds: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.child?.stdin.write(`banclient ${clientId} ${Math.max(0, Math.floor(seconds))} ${sanitized}\n`);
}
async sendChatMessage(message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`);
+21
View File
@@ -1632,6 +1632,27 @@
background: linear-gradient(var(--button-bg-hover-1), var(--button-bg-hover-2));
}
.ts-ban-compose {
flex-wrap: wrap;
max-width: 380px;
}
.ts-ban-duration-field {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 12px;
color: var(--text-muted);
}
.ts-ban-duration-field select {
background: var(--input-bg);
color: var(--input-text);
border: 1px solid var(--border);
border-radius: 3px;
padding: 0.2rem 0.4rem;
}
.ts-poke-notice {
display: flex;
align-items: center;
+127 -2
View File
@@ -2387,6 +2387,15 @@ function AppInner() {
const [pokeTarget, setPokeTarget] = useState<{ id: number; name: string } | null>(null);
const [pokeMessage, setPokeMessage] = useState("");
const pokeBackdrop = useBackdropDismiss(() => setPokeTarget(null));
const [kickTarget, setKickTarget] = useState<{ id: number; name: string; scope: "channel" | "server" } | null>(
null
);
const [kickReason, setKickReason] = useState("");
const kickBackdrop = useBackdropDismiss(() => setKickTarget(null));
const [banTarget, setBanTarget] = useState<{ id: number; name: string } | null>(null);
const [banReason, setBanReason] = useState("");
const [banSeconds, setBanSeconds] = useState("0");
const banBackdrop = useBackdropDismiss(() => setBanTarget(null));
const [demoForceMobile, setDemoForceMobile] = useState(false);
const [clientContextMenu, setClientContextMenu] = useState<{
x: number;
@@ -3517,6 +3526,36 @@ function AppInner() {
setPokeMessage("");
};
const handleConfirmKick = () => {
if (!kickTarget) return;
socketRef.current?.send(
JSON.stringify({
type: kickTarget.scope === "channel" ? "kickFromChannel" : "kickFromServer",
clientId: kickTarget.id,
reason: kickReason,
})
);
logClient("info", "Moderation", `Kicked ${kickTarget.name} from ${kickTarget.scope}`);
setKickTarget(null);
setKickReason("");
};
const handleConfirmBan = () => {
if (!banTarget) return;
socketRef.current?.send(
JSON.stringify({
type: "banClient",
clientId: banTarget.id,
seconds: Number(banSeconds) || 0,
reason: banReason,
})
);
logClient("info", "Moderation", `Banned ${banTarget.name}`);
setBanTarget(null);
setBanReason("");
setBanSeconds("0");
};
const handleClosePrivateChat = (clientId: number) => {
setPmThreads((prev) => {
const next = { ...prev };
@@ -4284,6 +4323,58 @@ function AppInner() {
</div>
)}
{kickTarget && (
<div className="ts-poke-compose-backdrop" {...kickBackdrop}>
<div className="ts-poke-compose" onClick={(e) => e.stopPropagation()}>
<span>
👢 {t("kick.title")} <strong>{kickTarget.name}</strong>
</span>
<input
autoFocus
value={kickReason}
onChange={(e) => setKickReason(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleConfirmKick();
if (e.key === "Escape") setKickTarget(null);
}}
placeholder={t("kick.reasonPlaceholder")}
/>
<button onClick={handleConfirmKick}>{t("kick.confirm")}</button>
<button onClick={() => setKickTarget(null)}>{t("kick.cancel")}</button>
</div>
</div>
)}
{banTarget && (
<div className="ts-poke-compose-backdrop" {...banBackdrop}>
<div className="ts-poke-compose ts-ban-compose" onClick={(e) => e.stopPropagation()}>
<span>
🚫 {t("ban.title")} <strong>{banTarget.name}</strong>
</span>
<label className="ts-ban-duration-field">
{t("ban.duration")}
<select value={banSeconds} onChange={(e) => setBanSeconds(e.target.value)}>
<option value="0">{t("ban.durationPermanent")}</option>
<option value="3600">{t("ban.duration1h")}</option>
<option value="86400">{t("ban.duration1d")}</option>
<option value="604800">{t("ban.duration1w")}</option>
</select>
</label>
<input
value={banReason}
onChange={(e) => setBanReason(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleConfirmBan();
if (e.key === "Escape") setBanTarget(null);
}}
placeholder={t("ban.reasonPlaceholder")}
/>
<button onClick={handleConfirmBan}>{t("ban.confirm")}</button>
<button onClick={() => setBanTarget(null)}>{t("ban.cancel")}</button>
</div>
</div>
)}
{pokes.map((poke) => (
<div key={poke.id} className="ts-poke-notice">
<span>
@@ -4372,11 +4463,45 @@ function AppInner() {
{!clientContextMenu.isSelf && (
<>
<div className="ts-menu-separator" />
<button className="ts-menu-item" disabled title={t("clientContext.notSupported")}>
<button
className="ts-menu-item"
onClick={() => {
setKickTarget({
id: clientContextMenu.clientId,
name: clientContextMenu.clientName,
scope: "channel",
});
setKickReason("");
setClientContextMenu(null);
}}
>
<span className="ts-menu-item-icon">🚪</span>
<span className="ts-menu-item-label">{t("clientContext.kickChannel")}</span>
</button>
<button
className="ts-menu-item"
onClick={() => {
setKickTarget({
id: clientContextMenu.clientId,
name: clientContextMenu.clientName,
scope: "server",
});
setKickReason("");
setClientContextMenu(null);
}}
>
<span className="ts-menu-item-icon">👢</span>
<span className="ts-menu-item-label">{t("clientContext.kick")}</span>
</button>
<button className="ts-menu-item" disabled title={t("clientContext.notSupported")}>
<button
className="ts-menu-item"
onClick={() => {
setBanTarget({ id: clientContextMenu.clientId, name: clientContextMenu.clientName });
setBanReason("");
setBanSeconds("0");
setClientContextMenu(null);
}}
>
<span className="ts-menu-item-icon">🚫</span>
<span className="ts-menu-item-label">{t("clientContext.ban")}</span>
</button>
+32
View File
@@ -303,6 +303,21 @@ const translations: Record<Lang, Record<string, string>> = {
"poke.pokedYou": "hat dich angestupst",
"poke.dismiss": "Schließen",
"kick.title": "Kicken:",
"kick.reasonPlaceholder": "Grund (optional)...",
"kick.confirm": "Kicken",
"kick.cancel": "Abbrechen",
"ban.title": "Bannen:",
"ban.reasonPlaceholder": "Grund (optional)...",
"ban.duration": "Dauer:",
"ban.durationPermanent": "Permanent",
"ban.duration1h": "1 Stunde",
"ban.duration1d": "1 Tag",
"ban.duration1w": "1 Woche",
"ban.confirm": "Bannen",
"ban.cancel": "Abbrechen",
"clientContext.privateChat": "Privater Chat",
"clientContext.poke": "Anstupsen",
"clientContext.copyName": "Namen kopieren",
@@ -311,6 +326,7 @@ const translations: Record<Lang, Record<string, string>> = {
"clientContext.removeWhisperTarget": "Als Whisper-Ziel entfernen",
"clientContext.assignChannelGroup": "Channel-Gruppe zuweisen",
"clientContext.assignServerGroup": "Server-Gruppe zuweisen",
"clientContext.kickChannel": "Aus dem Channel kicken",
"clientContext.kick": "Vom Server kicken",
"clientContext.ban": "Bannen",
"clientContext.notSupported": "Im Web-Client noch nicht unterstützt",
@@ -642,6 +658,21 @@ const translations: Record<Lang, Record<string, string>> = {
"poke.pokedYou": "poked you",
"poke.dismiss": "Dismiss",
"kick.title": "Kick:",
"kick.reasonPlaceholder": "Reason (optional)...",
"kick.confirm": "Kick",
"kick.cancel": "Cancel",
"ban.title": "Ban:",
"ban.reasonPlaceholder": "Reason (optional)...",
"ban.duration": "Duration:",
"ban.durationPermanent": "Permanent",
"ban.duration1h": "1 hour",
"ban.duration1d": "1 day",
"ban.duration1w": "1 week",
"ban.confirm": "Ban",
"ban.cancel": "Cancel",
"clientContext.privateChat": "Private chat",
"clientContext.poke": "Poke",
"clientContext.copyName": "Copy name",
@@ -650,6 +681,7 @@ const translations: Record<Lang, Record<string, string>> = {
"clientContext.removeWhisperTarget": "Remove as whisper target",
"clientContext.assignChannelGroup": "Assign channel group",
"clientContext.assignServerGroup": "Assign server group",
"clientContext.kickChannel": "Kick from channel",
"clientContext.kick": "Kick from server",
"clientContext.ban": "Ban",
"clientContext.notSupported": "Not yet supported in the web client",