import { EventEmitter } from "node:events"; import { Writable } from "node:stream"; import { Client as TS3FullClient, clientMove as tsClientMove, listChannels as tsListChannels, listClients as tsListClients, poke as tsPoke, sendTextMessage as tsSendTextMessage, generateIdentity, type Identity, type VoiceData, type DirectoryClientInfo, type DirectorySnapshot, type RawNotification, type TextMessage, } from "@echosixhiya/teamspeak-client"; import type { Logger } from "../logger.js"; import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js"; import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js"; import type { TeamSpeakTarget } from "../domain/teamspeak-target.js"; import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js"; export interface TSClientOptions { target: TeamSpeakTarget; nickname: string; serverPassword?: string; defaultChannel?: string; channelPassword?: string; identity?: Identity; acceleration?: AccelerationRelayOptions; } export interface TSVoiceData { clientId: number; codec: number; // 4 = voice, 5 = music data: Buffer; } export interface TSClientAvatar { /** TeamSpeak's avatar content marker, used to invalidate a cached avatar. */ cacheKey: string; data: Buffer; } // Keep enough room for avatars produced by the native client. The previous // 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account, // so every avatar silently fell back to its initial letter. const MAX_CLIENT_AVATAR_BYTES = 256 * 1024; export type TSDirectorySnapshot = DirectorySnapshot; export type TSDirectoryClient = DirectoryClientInfo; export type TSRawNotification = RawNotification; export type TSChatScope = "channel" | "server" | "private"; export interface TSChatMessage { invokerName: string; invokerId: number; invokerUid: string; message: string; targetMode: number; targetId: bigint; } /** * Keep the TeamSpeak target id when adapting SDK events for the gateway. * Private-message events include a bigint targetID; dropping it makes the * bridge dereference undefined while echoing the message to the browser. */ export function toTSChatMessage(msg: TextMessage): TSChatMessage { return { invokerName: msg.invokerName, invokerId: msg.invokerID, invokerUid: msg.invokerUID, message: msg.message, targetMode: msg.targetMode, targetId: msg.targetID, }; } export class TSClient extends EventEmitter { private client: TS3FullClient | null = null; private adapter: TeamSpeakAdapter | null = null; private logger: Logger; private readonly identity: Identity; private clientId = 0; private connected = false; private preferredChannelId = 0n; private accelerationClient: AccelerationRelayClient | null = null; // Reason id of the most recent self leave, kept so the SDK `kicked` event can // tell a plain kick (4) from a kick with ban (5). The SDK only forwards the // reason message to its `kicked` handler, not the reason id. private selfLeaveReasonId: number | null = null; constructor(private options: TSClientOptions, logger: Logger) { super(); this.logger = logger.child({ nickname: options.nickname }); this.identity = options.identity ?? generateIdentity(8); } async connect(): Promise { this.selfLeaveReasonId = null; if (!this.adapter || !this.client) { let transportTarget = this.options.target; if (this.options.acceleration && !this.accelerationClient) { this.accelerationClient = await createAccelerationRelayClient({ ...this.options.acceleration, host: this.options.target.host, port: this.options.target.port, }); transportTarget = { host: this.accelerationClient.localHost, port: this.accelerationClient.localPort }; } this.adapter = new TeamSpeakAdapter({ target: transportTarget, nickname: this.options.nickname, identity: this.identity, serverPassword: this.options.serverPassword, defaultChannel: this.options.defaultChannel, channelPassword: this.options.channelPassword, }, this.logger); this.client = this.adapter.client; this.attachClientListeners(this.client); } const adapter = this.adapter; const client = this.client; await adapter.connect(); this.clientId = client.clientID(); try { // A native TeamSpeak client subscribes to the complete channel tree // after the welcome sequence. Without this command the server only // exposes members in the current channel, so users disappear as soon as // they move elsewhere even though both clients are on the same server. await client.execCommand("channelsubscribeall", 5000); } catch (error: unknown) { this.logger.warn({ err: error instanceof Error ? error.message : String(error), }, "Could not subscribe to all TeamSpeak channels"); } // Directory snapshots are dispatched through two setImmediate layers in // the SDK. Let both flush before reconciling with a direct client-protocol // snapshot so the gateway's first connected state contains every member. await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve)); // TS6 can finish the welcome event stream before it has exposed every // existing client to a newly connected session. Pull one authoritative // snapshot through this same client protocol session so users who joined // earlier are visible immediately as well. Realtime events continue to // keep the snapshot current after this reconciliation. try { const [channels, clients] = await Promise.all([ tsListChannels(client), tsListClients(client), ]); this.emit("directorySnapshot", { channels, clients }); } catch (error: unknown) { this.logger.warn({ failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE", failureDetail: error instanceof Error ? error.message : String(error), }, "TeamSpeak directory snapshot unavailable"); } const connectedChannelId = client.channelID(); if (this.preferredChannelId === 0n) { this.preferredChannelId = connectedChannelId; } else if (connectedChannelId !== this.preferredChannelId) { try { await tsClientMove(client, this.clientId, this.preferredChannelId); } catch (error: unknown) { // The old channel may have been deleted or become inaccessible. The // SDK has already left us in the server/default channel, which is the // safe fallback required by the reconnect contract. this.logger.info({ channelId: this.preferredChannelId.toString(), err: error instanceof Error ? error.message : String(error), }, "Previous TeamSpeak channel could not be restored"); this.preferredChannelId = client.channelID(); } } this.connected = true; this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak"); this.emit("connected", this.clientId); } /** * Load a visible client's TeamSpeak avatar through the client protocol. * * TeamSpeak does not include the avatar bytes in directory notifications. * `clientinfo` exposes the avatar marker and the per-identity filename; the * file itself is then read through the normal TeamSpeak file-transfer port. * A missing permission, missing avatar, blocked file-transfer port, or an * oversized image is intentionally reported as `null` so the web client can * keep its generated initial avatar. */ async getClientAvatar(clientId: number, expectedUid = ""): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id"); const rows = await this.client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000); const info = rows.find((row) => { if (expectedUid && row.client_unique_identifier !== expectedUid) return false; return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string"; }); if (!info) return null; const cacheKey = info.client_flag_avatar?.trim() ?? ""; const avatarFileKey = info.client_base64HashClientUID?.trim() ?? ""; if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null; const transfer = await this.client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, ""); const size = Number(transfer.size); if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null; const chunks: Buffer[] = []; const destination = new Writable({ write(chunk: Buffer | string, _encoding, callback) { chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); callback(); }, }); await this.client.downloadFileData(this.options.target.host, transfer, destination); const data = Buffer.concat(chunks); if (data.length === 0 || data.length > MAX_CLIENT_AVATAR_BYTES) return null; return { cacheKey, data }; } private attachClientListeners(client: TS3FullClient): void { client.on("voiceData", (data: VoiceData) => { this.emit("voiceData", { clientId: data.clientId, codec: data.codec, data: Buffer.from(data.data), } as TSVoiceData); }); // The SDK exposes the directory that TeamSpeak sends during the normal // client welcome sequence. The connect path also reconciles this event // stream with a complete client-protocol snapshot. client.on("directorySnapshot", (snapshot) => { this.emit("directorySnapshot", { channels: snapshot.channels.slice(), clients: snapshot.clients.slice(), }); }); client.on("rawNotification", (notification: RawNotification) => { this.emit("rawNotification", { name: notification.name, params: { ...notification.params }, } satisfies TSRawNotification); }); client.on("textMessage", (msg) => { this.emit("textMessage", toTSChatMessage(msg)); }); client.on("poked", (event) => { this.emit("poked", event); }); client.on("disconnected", (err) => { if (err) { const normalized = normalizeTeamSpeakError(err); this.logger.warn({ failureCode: normalized.code.toUpperCase(), failureDetail: describeTeamSpeakError(normalized), }, "TeamSpeak transport disconnected unexpectedly"); } else { this.logger.info("TeamSpeak transport disconnected"); } this.connected = false; this.clientId = 0; this.emit("disconnected", err); }); client.on("clientEnter", (info) => { this.emit("clientEnter", info); }); client.on("clientLeave", (info) => { // 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁 if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID; this.emit("clientLeave", info); }); // 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器 // 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。 // The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5 // (kick with ban) and hands over the admin written reason message. Without // this listener the reason was dropped, so the browser degraded to a generic // "connection failed" right after the transport went away. client.on("kicked", (reasonMsg) => { const reasonId = this.selfLeaveReasonId; this.selfLeaveReasonId = null; this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId)); }); client.on("clientMoved", (info) => { if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID; this.emit("clientMoved", info); }); client.on("clientUpdated", (event) => { this.emit("clientUpdated", event.info); }); } sendVoice(data: Buffer, codec: number = 4): void { if (!this.client || !this.connected) return; this.client.sendVoice(data, codec); } sendWhisper(data: Buffer, clientIds: number[], codec: number = 4): void { if (!this.client || !this.connected) return; const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId()); if (!targets.length) throw new Error("Whisper requires at least one valid target"); this.client.sendWhisper(data, targets, codec); } async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); const targetMode = scope === "private" ? 1 : scope === "server" ? 3 : 2; await tsSendTextMessage(this.client, targetMode, targetId, message); } async poke(clientId: number, message: string): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); await tsPoke(this.client, clientId, message); } async setAway(away: boolean, message = ""): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); const escaped = escapeTeamSpeakValue(message); await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`); } async setInputMuted(muted: boolean): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); await this.client.execCommand(`clientupdate client_input_muted=${muted ? 1 : 0}`); } async switchChannel(channelId: bigint, password?: string): Promise { if (!this.client || !this.connected) return; await tsClientMove(this.client, this.clientId, channelId, password); this.preferredChannelId = channelId; } /** Move another visible TeamSpeak client; the server enforces both move powers. */ async moveClient(clientId: number, channelId: bigint, password?: string): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id"); await tsClientMove(this.client, clientId, channelId, password); } /** * Probe whether this identity may move a visible client into a channel. * * The browser client protocol does not expose ServerQuery's `permget`, so * the only authoritative capability check available through this session is * the same `clientmove` operation the UI will use. The bridge calls this * with the client's current channel, making the probe a no-op when accepted; * TeamSpeak still evaluates both move-power permissions. */ async probeMovePermission(clientId: number, channelId: bigint): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id"); await tsClientMove(this.client, clientId, channelId); } getClientId(): number { // The SDK learns the real client id during the welcome sequence, before // TSClient.connect() resumes. Reading it from the SDK prevents the first // directory snapshot from being built without the web client itself. return this.client?.clientID() ?? this.clientId; } getProtocol(): TeamSpeakProtocol | null { return this.adapter?.protocol ?? null; } async execCommandWithResponse(command: string, timeoutMs = 3000): Promise[]> { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); return this.client.execCommandWithResponse(command, timeoutMs); } /** * Send a TeamSpeak protocol command whose response is delivered later as a * notification (for example setupstream/streamsignaling). The command is * assembled by the trusted server-side stream adapter, never by the browser. */ async sendProtocolCommand(command: string): Promise { if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); await this.client.sendCommandNoWait(command); } getIdentityString(): string { return this.identity.toString(); } getChannelId(): bigint { if (!this.client) return 0n; const sdkClient = this.client as unknown as { channelID?: () => bigint }; return sdkClient.channelID?.() ?? 0n; } isConnected(): boolean { return this.connected; } async disconnect(): Promise { this.connected = false; this.selfLeaveReasonId = null; try { if (this.adapter) await this.adapter.disconnect(); } finally { this.accelerationClient?.close(); this.accelerationClient = null; this.adapter = null; this.client = null; this.clientId = 0; } } } function escapeTeamSpeakValue(value: string): string { return value .replace(/\\/g, "\\\\") .replace(/ /g, "\\s") .replace(/\//g, "\\/") .replace(/\|/g, "\\p") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r"); }