diff --git a/CLAUDE.md b/CLAUDE.md index c57e4df..4ffeead 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,13 +8,17 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho | --- | --- | | `src/index.ts` | Gateway startup, SQLite, master secret, admin service and shutdown; also supports relay mode | | `src/server/server.ts` | HTTP or HTTPS, public configuration, skins, join tickets, admin routes and static frontend | -| `src/server/voice-bridge.ts` | `/ws/voice`, session orchestration, control commands, voice and screen-sharing signaling | +| `src/server/voice-bridge.ts` | `/ws/voice`, admission, connection/reconnection orchestration and voice transport assembly | +| `src/server/voice-commands.ts`, `directory-view.ts`, `audio-stats.ts` | Command execution, public directory projection and diagnostic snapshots | +| `src/server/screen-share-coordinator.ts` | Server/channel-scoped sharing membership and browser/native signaling | +| `src/shared/` | Browser-safe wire types and runtime parsers shared by both endpoints | | `src/server/ts-client.ts` and `teamspeak-adapter.ts` | SDK integration, TS3/TS6 negotiation, identity, chat, voice and client events | | `src/server/session-manager.ts` and `directory-sync.ts` | Connection state, teardown, admission limits and directory reconciliation | | `src/server/webrtc-audio.ts` and `opus-codec.ts` | WebRTC audio mixing and platform-specific Opus codecs | | `src/admin/`, `src/security/`, `src/persistence/` | Administration, access policies, credentials and persistent settings | | `src/relay.ts` and `src/server/acceleration-relay.ts` | Standalone relay and gateway-side relay transport | | `web/src/views/` and `web/src/composables/` | Vue pages, connection state, audio controls, chat and screen sharing | +| `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics | | `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations | | `src/mobile/`, `mobile/`, `web/android/` | Android loopback gateway, asset packaging and Capacitor container | @@ -29,6 +33,8 @@ Channel and member data come from SDK directory snapshots and client-protocol co Session teardown must remain safe when requested more than once or when sockets and codec resources are already closed. Reconnection is governed by `reconnect-policy.ts`; preserve terminal error handling, bounded retries and the previous-channel fallback. +Late socket messages and media permission/negotiation results must not mutate a replacement session. Screen-sharing ownership is scoped to both the TeamSpeak target and channel; another member moving channels must not stop the current user's share. Preserve these invariants when extracting the remaining audio responsibilities. + ## Audio and screen sharing The compatibility voice path captures 48 kHz mono PCM using an AudioWorklet, with a ScriptProcessor fallback. The browser assembles 960-sample, 20 ms frames and sends 1,920-byte Int16 payloads over WebSocket. The gateway encodes them as Opus for TeamSpeak. Incoming Opus uses a three-byte header containing codec and client ID, then browser WebCodecs decoding and playback. diff --git a/docs/CODE_REFACTOR_PLAN.zh-CN.md b/docs/CODE_REFACTOR_PLAN.zh-CN.md index 2b61367..2a32ebd 100644 --- a/docs/CODE_REFACTOR_PLAN.zh-CN.md +++ b/docs/CODE_REFACTOR_PLAN.zh-CN.md @@ -21,6 +21,7 @@ | --- | --- | --- | | 网关启动与 HTTP | `src/index.ts`、`src/server/server.ts` | 初始化服务、公共接口、加入凭证、静态页面和管理路由 | | 实时会话与协议桥接 | `src/server/voice-bridge.ts`、`session-manager.ts`、`voice-protocol.ts` | 会话生命周期、命令分发、语音、事件同步和屏幕共享信令 | +| 服务端桥接子模块 | `voice-commands.ts`、`directory-view.ts`、`audio-stats.ts`、`screen-share-coordinator.ts` | 命令执行、目录展示、诊断快照及屏幕共享协调 | | 共享协议 | `src/shared/` | 前后端消息模型、命令载荷、屏幕共享解析、服务端消息校验和皮肤目录类型 | | TeamSpeak 接入 | `src/server/ts-client.ts`、`teamspeak-adapter.ts`、`directory-sync.ts` | SDK 适配、连接、目录同步、聊天及语音收发 | | 管理与持久化 | `src/admin/`、`src/persistence/`、`src/security/` | 认证、配置、邀请、中继节点、审计和 SQLite 存储 | @@ -40,7 +41,7 @@ | 02 | P1 | 补齐会话与媒体关键行为测试 | 测试缺口 | 基础测试已补,媒体及完整连接验证待补 | | 03 | P2 | 集中前后端协议契约 | 重构建议 | 已迁移,本地构建及协议测试通过;真实联调待补 | | 04 | P2 | 拆分前端语音核心模块 | 重构建议及生命周期修复 | 进行中;屏幕共享已拆分,连接与采集竞态已修复 | -| 05 | P2 | 拆分服务端实时桥接模块 | 重构建议 | 待实施 | +| 05 | P2 | 拆分服务端实时桥接模块 | 重构建议及行为修复 | 已拆出命令、目录展示、统计和共享协调;音频转发及集成验证待继续 | | 06 | P2 | 拆分页面组件与管理页逻辑 | 重构建议 | 待实施 | | 07 | P2 | 明确 Android 平台边界与验证范围 | 预览功能的整理与验证 | 预览已提交,启动逻辑拆分及设备验证待完成 | | 08 | P1 | 修正文档与实现不一致的说明 | 文档维护 | 旧说明已修正,后续随模块调整同步 | @@ -60,7 +61,7 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性 ### 02 补齐会话与媒体关键行为测试 -**现状与位置:** 当前根目录 `test` 脚本显式列出 18 个测试文件。凭证、身份占用、会话清理、目录合并和重连策略已有基础测试;协议、前端实际 composable 及屏幕共享控制器已有补充测试。本地共 69 项测试通过。尚缺真实浏览器到 TeamSpeak 的完整连接验证和 WebRTC 语音回退验证;模拟浏览器边界的生命周期测试不能替代真实媒体测试。尚未测量覆盖率。 +**现状与位置:** 当前根目录 `test` 脚本显式列出 22 个测试文件。凭证、身份占用、会话清理、目录合并和重连策略已有基础测试;协议、前端实际 composable、屏幕共享控制器和服务端桥接子模块已有补充测试。本地共 89 项测试通过。尚缺真实浏览器到 TeamSpeak 的完整连接验证和 WebRTC 语音回退验证;模拟浏览器边界的生命周期测试不能替代真实媒体测试。尚未测量覆盖率。 **修改方向:** 优先为即将拆分的模块建立行为基线。覆盖加入凭证过期及重复消费、会话重复清理、目录快照与实时事件合并、重连成功与失败、WebRTC 失败回退、屏幕共享退出后的资源释放。通过可替换的时钟、传输和 SDK 边界验证正常与异常路径;真实 TeamSpeak、浏览器媒体和 Android 行为另设可重复执行的集成验证步骤。 @@ -98,12 +99,14 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性 ### 05 拆分服务端实时桥接模块 -**现状与位置:** [voice-bridge.ts](../src/server/voice-bridge.ts) 当前为 2,135 行,同时承担连接接入、会话编排、事件同步、命令处理、音频统计和跨端屏幕共享协调。项目已经存在 `SessionManager`、`DirectorySynchronizer`、协议解析和 WebRTC 音频模块,工作区也已接入公共发送消息类型。 +**现状与位置:** [voice-bridge.ts](../src/server/voice-bridge.ts) 从 2,135 行降至约 1,096 行。命令执行、目录展示转换、统计快照和屏幕共享协调已分别拆至独立模块。主模块仍负责接入、会话编排、SDK 事件与音频转发;后续继续明确音频热路径及目录事件编排的边界。 **修改方向:** 保留 `VoiceBridge` 的接入与组装职责,沿现有边界提取命令处理、目录与成员事件协调、音频转发、屏幕共享协调。复用现有状态机和清理机制,明确断开、踢出、管理员终止和网关关闭等路径的责任归属。 **建议切入顺序:** 先提取目录展示转换、错误分类及统计快照等输入输出明确的函数;再提取命令处理;最后迁移涉及服务器、频道和参与者状态的屏幕共享协调。会话准入与清理继续由现有 `SessionManager` 管理,避免拆出第二套会话状态。音频转发的拆分需要同时验证队列上限和节拍行为。 +上述前三项提取已完成。新增测试验证频道及服务器隔离、共享者与观看者信令权限、目录大整数标识、成员移动和命令回执;真实 SDK 会话和媒体集成验收仍待完成。 + **验收标准:** 一次性凭证、身份占用限制、并发会话上限和重连策略保持原有行为;清理操作可安全重复执行;屏幕共享仍遵守所属服务器、频道及参与者校验;语音热路径保留有界缓冲,不新增逐帧持久化日志。 ### 06 拆分页面组件与管理页逻辑 @@ -183,10 +186,18 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性 ### 共享协议与前端生命周期实施记录 +- 对应提交 `ab4ad48` 已推送至 `dev`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36799503102) 的验证、Docker 构建和容器健康检查均通过。 - 共享命令、服务端消息、屏幕共享模型和皮肤目录类型集中到 `src/shared/`;服务端发送与前端接收均接入公共契约。 - 屏幕共享控制器只依赖传输状态与发送接口,自行管理采集音轨、PeerConnection、ICE 配置、协商计时器和统计。 - 新增 11 项前端测试。其中 9 项先复现了失败:旧 socket 污染新成员列表、异常断开未停止共享、断开后获批的共享采集未释放、取消后协商仍发送信令、旧开始确认干扰新采集、旧授权结果覆盖新采集参数、缺少视频轨时其他轨道未释放,以及麦克风授权迟到和旧授权阻塞新会话。 - 本地 `npm run verify` 通过:69 项测试、后端编译、前端类型检查及生产构建;开发服务器实际请求确认共享协议与屏幕共享模块可返回成功响应。Vite 依赖扫描限定为网页入口,避免扫描 Android 生成页面。 - 尚未完成真实 TeamSpeak 双向音频、WebRTC 语音回退、浏览器实际媒体连接、Android 真机及各平台发布包验证。此处的模拟边界测试只证明相应状态和资源生命周期行为。 -事项 02 和 04 继续实施,03 仍需真实联调,05 至 07 及 09 尚有未完成项;不能根据当前测试通过将整个清单标记为完成。 +### 服务端桥接拆分实施记录 + +- 拆出命令处理、目录展示、音频统计和屏幕共享协调四个模块,入口保留会话组装职责;原有统计类型导出保持兼容。 +- 新增 20 项测试,其中 7 项先复现失败后修复:统计快照共享实时对象、结构化权限错误映射遗漏、其他成员换频道误停共享、跨服务器客户端 ID 混用、重复或迟到的原生发布通知生成多余共享、最后会话离开后发现状态未重置,以及旧加入失败移除新观看关系。 +- TeamSpeak 连接中断时清理共享关系;原生源频道从当前服务器目录确定,无法确认所属频道时不猜测广播范围。 +- 本地 `npm run verify` 通过:89 项测试、后端编译、前端类型检查及生产构建。新增服务端改动尚待对应提交的远端 CI 和真实媒体联调验证。 + +事项 02、04、05 继续实施,03 仍需真实联调,06、07、09 尚有未完成项;不能根据当前测试通过将整个清单标记为完成。 diff --git a/package.json b/package.json index ddeaf09..bc341ba 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/reconnect-policy.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/screen-share.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/screen-share.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts", "verify": "npm test && npm run build && npm run web:build", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", diff --git a/src/server/audio-stats.test.ts b/src/server/audio-stats.test.ts new file mode 100644 index 0000000..910b3b1 --- /dev/null +++ b/src/server/audio-stats.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createAudioFlowStats, snapshotAudioStats, snapshotAudioStatus } from "./audio-stats.js"; +import type { WebRtcAudioStats } from "./webrtc-audio.js"; + +test("diagnostic snapshots remain stable while new traffic changes live counters", () => { + const audio = createAudioFlowStats(); + audio.egressFramesByClient[2] = 3; + const snapshot = snapshotAudioStats({ audio, webrtc: null }); + audio.egressFramesByClient[2]++; + assert.equal(snapshot.egressFramesByClient[2], 3); + snapshot.egressFramesByClient[2] = 10; + assert.equal(audio.egressFramesByClient[2], 4); +}); + +test("public audio status includes live WebRTC counters without losing gateway counters", () => { + const audio = createAudioFlowStats(); + audio.ingressFrames = 12; + const rtc: WebRtcAudioStats = { + webrtcIngressRtpFrames: 7, webrtcIngressRtpFirstAt: 100, webrtcIngressRtpLastAt: 220, webrtcIngressRtpMaxGapMs: 20, + webrtcEgressRtpFrames: 3, webrtcEgressRtpFirstAt: 100, webrtcEgressRtpLastAt: 140, webrtcEgressRtpMaxGapMs: 20, + webrtcQueuePeakFrames: 2, webrtcQueueDroppedFrames: 1, webrtcQueueUnderrunTicks: 0, webrtcPacerLateTicks: 0, + webrtcQueueCurrentFrames: 1, webrtcIngressQuietFrames: 0, webrtcIngressDecodeErrors: 0, + webrtcDownlinkDecodedFrames: 3, webrtcDownlinkDecodeErrors: 0, webrtcDownlinkShortFrames: 0, + }; + const source = { audio, webrtc: { getStats: () => rtc } }; + const status = snapshotAudioStatus(source); + assert.equal(status.transport, "webrtc"); + assert.equal(status.ingressFrames, 12); + assert.equal(status.webrtcIngressRtpFrames, 7); + assert.equal(snapshotAudioStatus({ audio, webrtc: null }).transport, "websocket"); +}); diff --git a/src/server/audio-stats.ts b/src/server/audio-stats.ts new file mode 100644 index 0000000..1214ae2 --- /dev/null +++ b/src/server/audio-stats.ts @@ -0,0 +1,119 @@ +import type { VoiceAudioBridgeStats } from "../shared/voice-models.js"; +import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js"; + +export interface AudioFlowStats extends WebRtcAudioStats { + ingressFrames: number; + ingressDroppedFrames: number; + ingressFirstAt: number | null; + ingressLastAt: number | null; + ingressMaxGapMs: number; + tsSendFrames: number; + tsSendErrors: number; + tsSendFirstAt: number | null; + tsSendLastAt: number | null; + tsSendMaxGapMs: number; + tsEncodeMaxMs: number; + tsReceiveFrames: number; + tsReceiveFirstAt: number | null; + tsReceiveLastAt: number | null; + tsReceiveMaxGapMs: number; + egressFrames: number; + egressDroppedFrames: number; + egressFirstAt: number | null; + egressLastAt: number | null; + egressMaxGapMs: number; + egressSentFirstAt: number | null; + egressSentLastAt: number | null; + egressSentMaxGapMs: number; + egressPeakBufferedBytes: number; + egressFramesByClient: Record; + +} + +export interface AudioStatsSource { + audio: AudioFlowStats; + webrtc: Pick | null; +} + +export function createAudioFlowStats(): AudioFlowStats { + return { + ingressFrames: 0, + ingressDroppedFrames: 0, + ingressFirstAt: null, + ingressLastAt: null, + ingressMaxGapMs: 0, + tsSendFrames: 0, + tsSendErrors: 0, + tsSendFirstAt: null, + tsSendLastAt: null, + tsSendMaxGapMs: 0, + tsEncodeMaxMs: 0, + tsReceiveFrames: 0, + tsReceiveFirstAt: null, + tsReceiveLastAt: null, + tsReceiveMaxGapMs: 0, + egressFrames: 0, + egressDroppedFrames: 0, + egressFirstAt: null, + egressLastAt: null, + egressMaxGapMs: 0, + egressSentFirstAt: null, + egressSentLastAt: null, + egressSentMaxGapMs: 0, + egressPeakBufferedBytes: 0, + egressFramesByClient: {}, + webrtcIngressRtpFrames: 0, + webrtcIngressRtpFirstAt: null, + webrtcIngressRtpLastAt: null, + webrtcIngressRtpMaxGapMs: 0, + webrtcEgressRtpFrames: 0, + webrtcEgressRtpFirstAt: null, + webrtcEgressRtpLastAt: null, + webrtcEgressRtpMaxGapMs: 0, + webrtcQueuePeakFrames: 0, + webrtcQueueDroppedFrames: 0, + webrtcQueueUnderrunTicks: 0, + webrtcPacerLateTicks: 0, + webrtcQueueCurrentFrames: 0, + webrtcIngressQuietFrames: 0, + webrtcIngressDecodeErrors: 0, + webrtcDownlinkDecodedFrames: 0, + webrtcDownlinkDecodeErrors: 0, + webrtcDownlinkShortFrames: 0, + }; +} + +export function snapshotAudioStats(entry: AudioStatsSource): AudioFlowStats { + const stats = { ...entry.audio, egressFramesByClient: { ...entry.audio.egressFramesByClient } }; + const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats(); + if (webRtcStats) Object.assign(stats, webRtcStats); + return stats; +} + +export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeStats { + const stats = snapshotAudioStats(entry); + return { + transport: entry.webrtc ? "webrtc" : "websocket", + ingressFrames: stats.ingressFrames, + ingressDroppedFrames: stats.ingressDroppedFrames, + ingressMaxGapMs: stats.ingressMaxGapMs, + tsSendFrames: stats.tsSendFrames, + tsSendErrors: stats.tsSendErrors, + tsSendMaxGapMs: stats.tsSendMaxGapMs, + tsReceiveFrames: stats.tsReceiveFrames, + tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs, + egressFrames: stats.egressFrames, + egressDroppedFrames: stats.egressDroppedFrames, + egressMaxGapMs: stats.egressMaxGapMs, + webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames, + webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs, + webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames, + webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs, + webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames, + webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks, + webrtcPacerLateTicks: stats.webrtcPacerLateTicks, + webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors, + webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors, + }; +} + diff --git a/src/server/directory-view.test.ts b/src/server/directory-view.test.ts new file mode 100644 index 0000000..a7d05dc --- /dev/null +++ b/src/server/directory-view.test.ts @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { TSDirectorySnapshot } from "./ts-client.js"; +import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js"; +import { parseServerMessage } from "../shared/server-messages.js"; + +const directory = (): TSDirectorySnapshot => ({ + channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }], + clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }], +}); + +test("self restoration uses the connected channel before a snapshot or requested channel", () => { + const source = directory(); + const result = normalizeDirectorySnapshot(source, 2, 18446744073709551615n, "Self", "Lobby"); + assert.equal(result.clients[0]?.channelID, 18446744073709551615n); + assert.equal(result.clients[0]?.uid, "uid-2"); + assert.equal(source.clients[0]?.channelID, 1n); + assert.equal(normalizeDirectorySnapshot(source, 0, 1n, "Unknown"), source); +}); + +test("partial welcome data can restore self by channel name without duplicating existing members", () => { + const source = directory(); + const result = normalizeDirectorySnapshot(source, 3, 0n, "Self", " room "); + assert.equal(result.clients.length, 2); + assert.equal(result.clients[1]?.channelID, 18446744073709551615n); + assert.equal(normalizeDirectorySnapshot(result, 3, 0n, "Self").clients.length, 2); + assert.equal(source.clients.length, 1); +}); + +test("directory presentation survives JSON transport with large IDs, member flags and cached avatars", () => { + const source = directory(); + const channels = mapChannelTree(source, new Map([["uid-2", "data:image/png;base64,test"]])); + const decoded = parseServerMessage(JSON.parse(JSON.stringify({ type: "channelList", channels }))); + assert.ok(decoded?.type === "channelList"); + assert.equal(decoded.channels[1]?.id, "18446744073709551615"); + assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true); + assert.equal(decoded.channels[0]?.members?.[0]?.away, true); + assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test"); + assert.deepEqual(decoded.channels[1]?.members, []); +}); diff --git a/src/server/directory-view.ts b/src/server/directory-view.ts new file mode 100644 index 0000000..9d20e0c --- /dev/null +++ b/src/server/directory-view.ts @@ -0,0 +1,67 @@ +import type { ChannelInfo } from "../shared/voice-models.js"; +import type { TSDirectorySnapshot } from "./ts-client.js"; + +export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map()): ChannelInfo[] { + return snapshot.channels.map((channel) => ({ + id: String(channel.id), + parentID: String(channel.parentID), + order: String(channel.order), + name: channel.name || "未命名频道", + description: channel.description || "", + members: snapshot.clients + .filter((client) => client.channelID === channel.id) + .map((client) => { + const avatar = client.uid ? avatarCache.get(client.uid) : undefined; + return { + id: client.id, + nickname: client.nickname || "未知用户", + uid: client.uid, + ...(avatar ? { avatar } : {}), + away: client.away, + awayMessage: client.awayMessage, + inputMuted: client.inputMuted, + outputMuted: client.outputMuted, + channelCommander: client.channelCommander, + }; + }), + })); +} + +export function avatarDataUrl(data: Buffer): string | null { + if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return `data:image/png;base64,${data.toString("base64")}`; + if (data.length >= 3 && data.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return `data:image/jpeg;base64,${data.toString("base64")}`; + if (data.length >= 6 && (data.subarray(0, 6).toString("ascii") === "GIF87a" || data.subarray(0, 6).toString("ascii") === "GIF89a")) return `data:image/gif;base64,${data.toString("base64")}`; + if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return `data:image/webp;base64,${data.toString("base64")}`; + return null; +} + +export function normalizeDirectorySnapshot( + snapshot: TSDirectorySnapshot, + selfId: number, + selfChannelId: bigint, + nickname: string, + requestedChannelName?: string, +): TSDirectorySnapshot { + if (selfId <= 0) return snapshot; + + const clients = snapshot.clients.slice(); + const selfIndex = clients.findIndex((client) => client.id === selfId); + const snapshotChannelId = selfIndex >= 0 ? clients[selfIndex]!.channelID : 0n; + const requestedName = requestedChannelName?.trim().toLocaleLowerCase(); + const requestedChannel = requestedName + ? snapshot.channels.find((channel) => channel.name.trim().toLocaleLowerCase() === requestedName) + : undefined; + const resolvedChannelId = selfChannelId !== 0n + ? selfChannelId + : snapshotChannelId !== 0n + ? snapshotChannelId + : requestedChannel?.id ?? snapshot.channels[0]?.id ?? 0n; + if (selfIndex >= 0) { + const current = clients[selfIndex]!; + if (resolvedChannelId !== 0n) clients[selfIndex] = { ...current, channelID: resolvedChannelId }; + } else if (resolvedChannelId !== 0n) { + clients.push({ id: selfId, nickname, uid: "", channelID: resolvedChannelId, type: 1, serverGroups: [] }); + } + + return { ...snapshot, clients }; +} diff --git a/src/server/screen-share-coordinator.test.ts b/src/server/screen-share-coordinator.test.ts new file mode 100644 index 0000000..8c2940c --- /dev/null +++ b/src/server/screen-share-coordinator.test.ts @@ -0,0 +1,163 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { ScreenShareCoordinator, type ScreenShareParticipant } from "./screen-share-coordinator.js"; +import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js"; +import type { ScreenShareClientMessage } from "../shared/screen-share.js"; + +function fixture() { + const entries = new Map(); + const messages: Array<{ to: string; message: ServerMessage }> = []; + const commands: Array<{ from: string; command: string }> = []; + const send = (to: string, message: ServerMessage) => { + assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid message: ${message.type}`); + messages.push({ to, message }); + }; + const coordinator = new ScreenShareCoordinator(entries, send, { debug() {}, warn() {} }); + function participant(id: string, clientId: number, channel = 1n, host = "first.example") { + const entry: ScreenShareParticipant = { + id, nickname: id, screenPeerId: `peer-${id}`, target: { host, port: 9987 }, members: new Map([[clientId, {}]]), + channelTree: [{ id: String(channel), parentID: "0", name: "Room", members: [{ id: clientId, nickname: id }] }], + tsClient: { + getClientId: () => clientId, getChannelId: () => channel, isConnected: () => true, + sendProtocolCommand: async command => { commands.push({ from: id, command }); }, + }, + }; + entries.set(id, entry); + return entry; + } + function handle(entry: ScreenShareParticipant, command: ScreenShareClientMessage) { + coordinator.handleMessage(entry, command, message => send(entry.id, message)); + } + function list(entry: ScreenShareParticipant) { + handle(entry, { type: "screenShareList" }); + const message = messages.at(-1)?.message; + assert.ok(message?.type === "screenShareList"); + return message.streams; + } + function start(entry: ScreenShareParticipant) { + handle(entry, { type: "screenShareStart", requestId: "start", name: "Screen", audio: false }); + const share = list(entry)[0]; + assert.ok(share); + return share.streamId; + } + return { entries, messages, commands, coordinator, participant, handle, list, start }; +} + +test("sharing is isolated by server and channel, and only its owner can stop it", () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const viewer = f.participant("viewer", 2); + const otherChannel = f.participant("other-channel", 3, 2n); + const otherServer = f.participant("other-server", 1, 1n, "second.example"); + const streamId = f.start(owner); + assert.equal(f.messages.some(({ to }) => to === otherChannel.id || to === otherServer.id), false); + for (const [entry, code] of [[otherServer, "SCREEN_SHARE_NOT_FOUND"], [otherChannel, "SCREEN_SHARE_TARGET_MISMATCH"]] as const) { + f.handle(entry, { type: "screenShareJoin", streamId }); + const reply = f.messages.at(-1)?.message; + assert.ok(reply?.type === "screenShareError"); + assert.equal(reply.code, code); + } + f.handle(viewer, { type: "screenShareStop", streamId }); + assert.equal(f.list(owner).length, 1); + f.handle(owner, { type: "screenShareStop", streamId }); + assert.equal(f.list(owner).length, 0); +}); + +test("signaling permits owner-viewer pairs but rejects viewer-to-viewer injection", () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const left = f.participant("left", 2); + const right = f.participant("right", 3); + const streamId = f.start(owner); + for (const viewer of [left, right]) f.handle(viewer, { type: "screenShareJoin", streamId }); + f.messages.length = 0; + f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: right.screenPeerId, signal: { kind: "offer", sdp: "invalid-peer" } }); + assert.equal(f.messages.some(({ to }) => to === right.id), false); + assert.equal(f.messages[0]?.message.type, "screenShareError"); + f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: owner.screenPeerId, signal: { kind: "offer", sdp: "offer" } }); + assert.equal(f.messages.at(-1)?.to, owner.id); + assert.equal(f.messages.at(-1)?.message.type, "screenShareSignal"); +}); + +test("another member moving channels cannot stop the owner's share or evict its viewer", () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const viewer = f.participant("viewer", 2); + const streamId = f.start(owner); + f.handle(viewer, { type: "screenShareJoin", streamId }); + f.coordinator.onClientMove(owner, 99, 2n); + f.coordinator.onClientMove(viewer, 99, 2n); + assert.equal(f.list(owner)[0]?.viewerCount, 1); + f.coordinator.onClientMove(viewer, 2, 2n); + assert.equal(f.list(owner)[0]?.viewerCount, 0); + f.coordinator.onClientMove(owner, 1, 2n); + assert.equal(f.list(owner).length, 0); +}); + +test("native source lookup cannot use another server's colliding client ID", () => { + const f = fixture(); + f.participant("collision", 17, 99n, "second.example"); + const observer = f.participant("observer", 1); + const viewer = f.participant("viewer", 2, 3n); + observer.channelTree.push({ id: "3", parentID: "0", name: "Source", members: [{ id: 17, nickname: "Native" }] }); + f.coordinator.handleNotification(observer, { name: "notifystreamstarted", params: { id: "native", clid: "17", name: "Native" } }); + assert.equal(f.list(observer).length, 0); + assert.equal(f.list(viewer)[0]?.streamId, "native"); +}); + +test("a gateway publisher's repeated native notification cannot create a duplicate stream", () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const streamId = f.start(owner); + f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native-copy", clid: "1" } }); + f.coordinator.handleNotification(owner, { name: "notifystreaminfo", params: { id: "native-copy", clid: "1" } }); + assert.deepEqual(f.list(owner).map(stream => stream.streamId), [streamId]); + f.handle(owner, { type: "screenShareStop", streamId }); + f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "late-copy", clid: "1" } }); + assert.equal(f.list(owner).length, 0); + assert.ok(f.commands.some(({ command }) => command.startsWith("stopstream id=late-copy "))); +}); + +test("native discovery runs again when the last session on a target has left", async () => { + const f = fixture(); + const first = f.participant("first", 1); + await f.coordinator.discoverExistingStreams(first); + f.coordinator.removePeer(first.id); + f.entries.delete(first.id); + const second = f.participant("second", 2); + await f.coordinator.discoverExistingStreams(second); + assert.ok(f.commands.some(({ from, command }) => from === second.id && command === "requeststreaminfo clid=2")); +}); + +test("owner removal is idempotent and clears the stream from remaining viewers", async () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const viewer = f.participant("viewer", 2); + const streamId = f.start(owner); + f.handle(viewer, { type: "screenShareJoin", streamId }); + f.messages.length = 0; + f.coordinator.removePeer(owner.id); + f.coordinator.removePeer(owner.id); + await nextTurn(); + assert.equal(f.messages.filter(({ to, message }) => to === viewer.id && message.type === "screenShareStopped").length, 1); + assert.equal(f.list(viewer).length, 0); +}); + +test("a failed old native join cannot remove a newer membership", async () => { + const f = fixture(); + const viewer = f.participant("viewer", 2); + viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" }); + f.coordinator.handleNotification(viewer, { name: "notifystreamstarted", params: { id: "native", clid: "17" } }); + let rejectOld!: (error: Error) => void; + const old = new Promise((_, reject) => { rejectOld = reject; }); + let joins = 0; + viewer.tsClient.sendProtocolCommand = command => command.startsWith("joinstreamrequest") && ++joins === 1 ? old : Promise.resolve(); + f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "old" }); + f.handle(viewer, { type: "screenShareLeave", streamId: "native" }); + f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "new" }); + rejectOld(new Error("old request failed")); + await nextTurn(); + assert.equal(f.list(viewer)[0]?.viewerCount, 1); + assert.equal(f.messages.some(({ message }) => message.type === "screenShareError" && message.requestId === "old"), false); +}); diff --git a/src/server/screen-share-coordinator.ts b/src/server/screen-share-coordinator.ts new file mode 100644 index 0000000..5e2719c --- /dev/null +++ b/src/server/screen-share-coordinator.ts @@ -0,0 +1,746 @@ +import { randomUUID } from "node:crypto"; +import type { Logger } from "../logger.js"; +import type { TSClient, TSRawNotification } from "./ts-client.js"; +import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js"; +import type { ServerMessage } from "../shared/server-messages.js"; +import type { ChannelInfo } from "../shared/voice-models.js"; +import type { ScreenShareClientMessage, ScreenSharePeerSignal, ScreenShareStreamDescription, ScreenShareViewerDescription } from "../shared/screen-share.js"; + +export interface ScreenShareParticipant { + id: string; + screenPeerId: string; + nickname: string; + target: TeamSpeakTarget; + members: ReadonlyMap; + channelTree: ChannelInfo[]; + tsClient: Pick; +} + +interface ScreenStreamRecord extends ScreenShareStreamDescription { + targetKey: string; + channelId: bigint; + ownerEntryId: string; + viewerEntryIds: Map; + sourceClientId?: number; + /** The gateway TS client that publishes a browser-owned stream to TS6. */ + teamSpeakPublisherEntryId?: string; + /** The TS6 stream id paired with a browser-owned WebSpeak stream. */ + teamSpeakStreamId?: string; + /** Native TS6 viewer client ids paired with a browser-owned stream. */ + nativeViewerClids: Set; +} + +// Stream ids are scoped to a TeamSpeak server. Keep the target in the key so +// two unrelated servers cannot overwrite each other's native stream record. +function screenStreamKey(targetKey: string, streamId: string): string { + return `${targetKey}\u0000${streamId}`; +} + +/** Coordinates channel-scoped browser/native sharing; media stays peer-to-peer. */ +export class ScreenShareCoordinator { + private readonly screenStreams = new Map(); + private readonly discoveredClients = new Map>(); + + constructor( + private readonly entries: ReadonlyMap, + private readonly sendToEntry: (entryId: string, message: ServerMessage) => void, + private readonly logger: Pick, + ) {} + + handleMessage( + entry: ScreenShareParticipant, + message: ScreenShareClientMessage, + sendJson: (message: ServerMessage) => void, + ): void { + if (message.type === "screenShareList") { + sendJson({ type: "screenShareList", streams: this.listScreenStreamsFor(entry) }); + return; + } + + if (message.type === "screenShareStart") { + if ([...this.screenStreams.values()].some((stream) => stream.source === "browser" && stream.ownerEntryId === entry.id)) { + sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_ALREADY_ACTIVE", message: "你已经在共享屏幕" }); + return; + } + const stream: ScreenStreamRecord = { + streamId: `screen-${randomUUID()}`, + source: "browser", + ownerPeerId: entry.screenPeerId, + ownerClientId: entry.tsClient.getClientId() || undefined, + ownerNickname: entry.nickname, + name: message.name?.trim() || `${entry.nickname} 的屏幕`, + audio: message.audio === true, + createdAt: Date.now(), + viewerCount: 0, + viewers: [], + targetKey: teamSpeakTargetKey(entry.target), + channelId: entry.tsClient.getChannelId(), + ownerEntryId: entry.id, + viewerEntryIds: new Map(), + teamSpeakPublisherEntryId: entry.id, + nativeViewerClids: new Set(), + }; + this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream); + sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true }); + this.broadcastScreenMessage(stream, { + type: "screenShareStarted", + stream: this.describeScreenStream(stream), + owner: false, + }, entry.id); + void this.publishBrowserScreenStream(entry, stream); + return; + } + + const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId)); + if (!stream) { + sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" }); + return; + } + if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) { + sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" }); + return; + } + + if (message.type === "screenShareStop") { + if (stream.ownerEntryId !== entry.id) { + sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_NOT_OWNER", message: "只有共享者可以结束共享" }); + return; + } + this.stopScreenStream(stream, "owner-stopped"); + if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId }); + return; + } + + if (message.type === "screenShareJoin") { + if (stream.ownerEntryId === entry.id) { + sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_OWNER_CANNOT_JOIN", message: "共享者不能作为观看者加入自己的共享" }); + return; + } + const alreadyJoined = stream.viewerEntryIds.has(entry.id); + if (!alreadyJoined) stream.viewerEntryIds.set(entry.id, Symbol("screen-membership")); + stream.viewerCount = this.screenShareViewerCount(stream); + sendJson({ + type: "screenShareJoined", + requestId: message.requestId, + stream: this.describeScreenStream(stream), + ownerPeerId: stream.ownerPeerId, + mode: stream.source, + }); + if (stream.source === "browser" && !alreadyJoined) { + this.sendToEntry(stream.ownerEntryId, { + type: "screenShareViewerJoined", + streamId: stream.streamId, + viewerPeerId: entry.screenPeerId, + viewerNickname: entry.nickname, + }); + } else if (stream.source === "teamspeak" && !alreadyJoined) { + void this.joinNativeScreenStream(entry, stream, sendJson, message.requestId); + } + if (!alreadyJoined) { + this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); + } + return; + } + + if (message.type === "screenShareLeave") { + this.leaveScreenStream(entry, stream); + if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId }); + return; + } + + if (message.type === "screenShareSignal") { + this.relayScreenShareSignal(entry, stream, message.targetPeerId, message.signal, sendJson); + } + } + + private listScreenStreamsFor(entry: ScreenShareParticipant): ScreenShareStreamDescription[] { + const targetKey = teamSpeakTargetKey(entry.target); + return [...this.screenStreams.values()] + .filter((stream) => stream.targetKey === targetKey && stream.channelId === entry.tsClient.getChannelId()) + .map((stream) => this.describeScreenStream(stream)); + } + + /** + * A gateway session can connect after a native TeamSpeak stream has already + * started. TS6 does not replay that stream in the normal welcome snapshot; + * requeststreaminfo is the official client-protocol query for this case. + * Query each visible client once per TeamSpeak target, then let the normal + * raw notification path announce the discovered stream to web viewers. + */ + async discoverExistingStreams(entry: ScreenShareParticipant): Promise { + const targetKey = teamSpeakTargetKey(entry.target); + let discovered = this.discoveredClients.get(targetKey); + if (!discovered) this.discoveredClients.set(targetKey, discovered = new Set()); + const clientIds = [...entry.members.keys()].filter((clientId) => Number.isInteger(clientId) && clientId > 0); + for (const clientId of clientIds) { + if (this.entries.get(entry.id) !== entry || !entry.tsClient.isConnected()) return; + if (discovered.has(clientId)) continue; + discovered.add(clientId); + try { + await entry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`); + } catch (error: unknown) { + discovered.delete(clientId); + this.logger.debug({ + target: formatTeamSpeakTarget(entry.target), + clientId, + err: error instanceof Error ? error.message : String(error), + }, "Could not query existing TeamSpeak screen stream"); + } + } + } + + private describeScreenStream(stream: ScreenStreamRecord): ScreenShareStreamDescription { + return { + streamId: stream.streamId, + source: stream.source, + ownerPeerId: stream.ownerPeerId, + ...(typeof stream.ownerClientId === "number" ? { ownerClientId: stream.ownerClientId } : {}), + ownerNickname: stream.ownerNickname, + name: stream.name, + audio: stream.audio, + createdAt: stream.createdAt, + viewerCount: stream.viewerCount, + viewers: this.describeScreenViewers(stream), + }; + } + + private describeScreenViewers(stream: ScreenStreamRecord): ScreenShareViewerDescription[] { + return [...stream.viewerEntryIds.keys()] + .map((entryId) => this.entries.get(entryId)) + .filter((entry): entry is ScreenShareParticipant => Boolean(entry)) + .slice(0, 64) + .map((entry) => { + const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar; + return { + peerId: entry.screenPeerId, + nickname: entry.nickname, + ...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}), + }; + }); + } + + private screenShareViewerCountMessage(stream: ScreenStreamRecord): ServerMessage { + return { + type: "screenShareViewerCount", + streamId: stream.streamId, + viewerCount: stream.viewerCount, + viewers: this.describeScreenViewers(stream), + }; + } + + private screenShareViewerCount(stream: ScreenStreamRecord): number { + return stream.viewerEntryIds.size + stream.nativeViewerClids.size; + } + + private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void { + for (const candidate of this.entries.values()) { + if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue; + // A stream is scoped to the source channel. Do not leak its card or + // viewer roster to users who are connected to another channel on the + // same TeamSpeak target. + if (candidate.id !== stream.ownerEntryId) { + try { + if (candidate.tsClient.getChannelId() !== stream.channelId) continue; + } catch { + continue; + } + } + this.sendToEntry(candidate.id, message); + } + } + + private stopScreenStream(stream: ScreenStreamRecord, reason: string): void { + if (!this.screenStreams.delete(screenStreamKey(stream.targetKey, stream.streamId))) return; + if (stream.source === "browser" && stream.teamSpeakStreamId && stream.teamSpeakPublisherEntryId) { + const publisher = this.entries.get(stream.teamSpeakPublisherEntryId); + if (publisher) { + void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { + id: stream.teamSpeakStreamId, + reason: "1", + })).catch(() => undefined); + } + } + const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason }; + this.broadcastScreenMessage(stream, message); + stream.viewerEntryIds.clear(); + stream.nativeViewerClids.clear(); + stream.viewerCount = 0; + } + + private leaveScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): void { + if (!stream.viewerEntryIds.delete(entry.id)) return; + stream.viewerCount = this.screenShareViewerCount(stream); + if (stream.source === "browser") this.sendToEntry(stream.ownerEntryId, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: entry.screenPeerId }); + else { + void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", { + id: stream.streamId, + clid: String(entry.tsClient.getClientId()), + })).catch(() => undefined); + } + this.sendToEntry(entry.id, { type: "screenShareLeft", streamId: stream.streamId }); + this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); + } + + private relayScreenShareSignal( + entry: ScreenShareParticipant, + stream: ScreenStreamRecord, + targetPeerId: string, + signal: ScreenSharePeerSignal, + sendJson: (message: ServerMessage) => void, + ): void { + if (stream.source === "teamspeak") { + if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" }); + return; + } + const sourceClientId = stream.sourceClientId; + if (!sourceClientId) { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" }); + return; + } + if (signal.kind === "close") { + this.leaveScreenStream(entry, stream); + return; + } + if (signal.kind === "offer") { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "观看端不能向 TeamSpeak 来源发送 offer" }); + return; + } + const payload = signal.kind === "iceCandidate" + ? { cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } } + : { cmd: "answer", args: { answer: signal.sdp } }; + void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("streamsignaling", { + id: stream.streamId, + clid: String(sourceClientId), + json: JSON.stringify(payload), + })).catch((error: unknown) => { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" }); + }); + return; + } + + if (stream.source === "browser" && entry.id === stream.ownerEntryId && targetPeerId.startsWith("ts-viewer-")) { + const viewerClid = parseNativeViewerPeerId(targetPeerId); + const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined; + if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" }); + return; + } + if (signal.kind === "close") { + void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", { + id: stream.teamSpeakStreamId, + clid: String(viewerClid), + })).catch(() => undefined); + stream.nativeViewerClids.delete(viewerClid); + stream.viewerCount = this.screenShareViewerCount(stream); + this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId }); + this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); + return; + } + if (signal.kind === "answer") { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "TeamSpeak 观看端不能先发送 answer" }); + return; + } + let command: string; + if (signal.kind === "offer") { + command = buildTeamSpeakCommand("respondjoinstreamrequest", { + id: stream.teamSpeakStreamId, + clid: String(viewerClid), + msg: "", + offer: signal.sdp, + decision: "1", + }); + } else if (signal.kind === "iceCandidate") { + command = buildTeamSpeakCommand("streamsignaling", { + id: stream.teamSpeakStreamId, + clid: String(viewerClid), + json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }), + }); + } else { + return; + } + void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" }); + }); + return; + } + + const owner = this.entries.get(stream.ownerEntryId); + const isOwner = entry.id === stream.ownerEntryId; + const isViewer = stream.viewerEntryIds.has(entry.id); + if (!owner || (!isOwner && !isViewer)) { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" }); + return; + } + // Keep the browser P2P graph bipartite: the owner may signal only an + // active viewer, and a viewer may signal only the owner. Without this + // check one viewer could inject SDP/ICE into another viewer's peer. + const targetEntry = isOwner + ? [...stream.viewerEntryIds.keys()] + .map((id) => this.entries.get(id)) + .find((candidate) => candidate?.screenPeerId === targetPeerId) + : targetPeerId === owner.screenPeerId ? owner : undefined; + if (!targetEntry || targetEntry.id === entry.id) { + sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "观看者已离开" }); + return; + } + this.sendToEntry(targetEntry.id, { type: "screenShareSignal", streamId: stream.streamId, fromPeerId: entry.screenPeerId, signal }); + } + + private async publishBrowserScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): Promise { + try { + await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("setupstream", { + name: stream.name, + type: "3", + bitrate: "4608", + accessibility: "1", + mode: "1", + viewer_limit: "0", + audio: stream.audio ? "1" : "0", + })); + } catch (error: unknown) { + this.logger.warn({ + target: formatTeamSpeakTarget(entry.target), + streamId: stream.streamId, + err: error instanceof Error ? error.message : String(error), + }, "Could not publish browser screen share to TeamSpeak"); + } + } + + private async joinNativeScreenStream( + entry: ScreenShareParticipant, + stream: ScreenStreamRecord, + sendJson: (message: ServerMessage) => void, + requestId?: string, + ): Promise { + const membership = stream.viewerEntryIds.get(entry.id); + const sourceClientId = stream.sourceClientId; + if (!entry.tsClient.getClientId() || !sourceClientId) { + sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" }); + return; + } + try { + await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("joinstreamrequest", { + id: stream.streamId, + // TS6 uses the source client id on joinstreamrequest. The requesting + // gateway session is identified later by the response/signaling + // notification delivered to this TS connection. + clid: String(sourceClientId), + msg: "", + is_remove: "0", + muted: "0", + volume: "0", + hidden: "0", + })); + } catch (error: unknown) { + if (this.entries.get(entry.id) !== entry + || this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream + || stream.viewerEntryIds.get(entry.id) !== membership) return; + this.leaveScreenStream(entry, stream); + sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_JOIN_FAILED", message: error instanceof Error ? error.message : "无法加入屏幕共享" }); + } + } + + removePeer(entryId: string): void { + for (const stream of [...this.screenStreams.values()]) { + if (stream.ownerEntryId === entryId) { + this.stopScreenStream(stream, "owner-disconnected"); + continue; + } + const entry = this.entries.get(entryId); + if (entry && stream.viewerEntryIds.has(entryId)) this.leaveScreenStream(entry, stream); + } + const departing = this.entries.get(entryId); + if (!departing) return; + const targetKey = teamSpeakTargetKey(departing.target); + if (![...this.entries.values()].some(entry => entry.id !== entryId && teamSpeakTargetKey(entry.target) === targetKey)) { + this.discoveredClients.delete(targetKey); + // Native notifications are not observed while no session is attached. + // Rediscover on the next connection instead of retaining stale cards. + for (const stream of [...this.screenStreams.values()]) { + if (stream.targetKey === targetKey) this.stopScreenStream(stream, "target-disconnected"); + } + } + } + + onClientMove(entry: ScreenShareParticipant, movedClientId: number, targetChannelId: bigint): void { + const targetKey = teamSpeakTargetKey(entry.target); + const selfMoved = movedClientId === entry.tsClient.getClientId(); + for (const stream of [...this.screenStreams.values()]) { + if (stream.targetKey !== targetKey) continue; + // A browser share belongs to the gateway user's current channel. Stop + // it when that user moves so existing viewers cannot keep a cross- + // channel peer alive. + if (selfMoved && stream.source === "browser" && stream.ownerEntryId === entry.id && stream.channelId !== targetChannelId) { + this.stopScreenStream(stream, "owner-moved-channel"); + continue; + } + // Native TS6 shares are channel-scoped as well. The notification is + // observed by every gateway session, so stop the shared record once the + // native source changes channels. + if (stream.source === "teamspeak" && stream.sourceClientId === movedClientId && stream.channelId !== targetChannelId) { + this.stopScreenStream(stream, "source-moved-channel"); + continue; + } + if (selfMoved && stream.viewerEntryIds.has(entry.id) && stream.channelId !== targetChannelId) { + this.leaveScreenStream(entry, stream); + } + } + } + + onClientLeave(entry: ScreenShareParticipant, clientId: number): void { + const targetKey = teamSpeakTargetKey(entry.target); + this.discoveredClients.get(targetKey)?.delete(clientId); + for (const stream of [...this.screenStreams.values()]) { + if (stream.targetKey === targetKey && stream.source === "teamspeak" && stream.sourceClientId === clientId) { + this.stopScreenStream(stream, "source-left"); + } + } + } + + handleNotification(entry: ScreenShareParticipant, notification: TSRawNotification): void { + if (this.entries.get(entry.id) !== entry) return; + const params = notification.params; + if (notification.name === "notifyjoinstreamrequest") { + const streamId = params.id || params.stream_id; + const viewerClientId = parseNumber(params.clid); + if (!streamId || !viewerClientId) return; + const targetKey = teamSpeakTargetKey(entry.target); + const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey + && candidate.source === "browser" + && candidate.teamSpeakPublisherEntryId === entry.id + && candidate.teamSpeakStreamId === streamId); + if (!stream) return; + stream.nativeViewerClids.add(viewerClientId); + stream.viewerCount = this.screenShareViewerCount(stream); + this.sendToEntry(stream.ownerEntryId, { + type: "screenShareNativeViewerJoined", + streamId: stream.streamId, + viewerPeerId: nativeViewerPeerId(viewerClientId), + viewerClientId, + }); + this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); + return; + } + if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") { + const streamId = params.id || params.stream_id; + const sourceClientId = parseNumber(params.clid); + if (!streamId || !sourceClientId) return; + const targetKey = teamSpeakTargetKey(entry.target); + const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target + && teamSpeakTargetKey(candidate.target) === targetKey + && candidate.tsClient.getClientId() === sourceClientId); + const browserStream = publisherEntry + ? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey + && candidate.source === "browser" + && candidate.teamSpeakPublisherEntryId === publisherEntry.id + && (!candidate.teamSpeakStreamId || candidate.teamSpeakStreamId === streamId)) + : undefined; + if (browserStream) { + browserStream.teamSpeakStreamId = streamId; + return; + } + if (publisherEntry) { + // A delayed setup acknowledgement can arrive after the browser stopped. + // A gateway-owned publication is never a second native source. + void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined); + return; + } + const sourceChannel = entry.channelTree.find(channel => channel.members?.some(member => member.id === sourceClientId)); + // Do not guess a channel from the observer, or from a colliding client id + // on another server. Discovery will retry after the directory is ready. + if (!sourceChannel) return; + const key = screenStreamKey(targetKey, streamId); + const current = this.screenStreams.get(key); + const stream: ScreenStreamRecord = current ?? { + streamId, + source: "teamspeak", + ownerPeerId: `ts-${sourceClientId}`, + ownerClientId: sourceClientId, + ownerNickname: params.name || `TeamSpeak 用户 ${sourceClientId}`, + name: params.name || "TeamSpeak 屏幕共享", + audio: params.audio === "1", + createdAt: Date.now(), + viewerCount: 0, + viewers: [], + targetKey, + channelId: BigInt(sourceChannel.id), + ownerEntryId: "", + viewerEntryIds: new Map(), + nativeViewerClids: new Set(), + sourceClientId, + }; + stream.sourceClientId = sourceClientId; + stream.ownerNickname = params.name || stream.ownerNickname; + stream.name = params.name || stream.name; + stream.audio = params.audio === "1"; + this.screenStreams.set(key, stream); + // Every gateway session attached to the same TS target sees the same + // raw notification. Only the first one should announce a new stream to + // browsers; otherwise each connected user receives duplicate cards. + if (!current) { + this.broadcastScreenMessage(stream, { type: "screenShareStarted", stream: this.describeScreenStream(stream), owner: false }); + } + return; + } + if (notification.name === "notifystreamstopped") { + const streamId = params.id || params.stream_id; + if (!streamId) return; + const targetKey = teamSpeakTargetKey(entry.target); + const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId)); + if (stream) { + this.stopScreenStream(stream, "source-stopped"); + return; + } + const browserStream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey + && candidate.source === "browser" + && candidate.teamSpeakStreamId === streamId); + if (browserStream) { + browserStream.teamSpeakStreamId = undefined; + browserStream.nativeViewerClids.clear(); + browserStream.viewerCount = this.screenShareViewerCount(browserStream); + this.sendToEntry(browserStream.ownerEntryId, { + type: "screenShareError", + code: "SCREEN_SHARE_NATIVE_PUBLISHER_STOPPED", + message: "TeamSpeak 客户端屏幕共享通道已停止,网页共享仍可继续", + }); + this.broadcastScreenMessage(browserStream, this.screenShareViewerCountMessage(browserStream)); + } + return; + } + if (notification.name === "notifystreamclientleft") { + const streamId = params.id || params.stream_id; + const viewerClientId = parseNumber(params.clid); + if (!streamId || !viewerClientId) return; + const targetKey = teamSpeakTargetKey(entry.target); + const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey + && candidate.source === "browser" + && candidate.teamSpeakStreamId === streamId + && candidate.nativeViewerClids.has(viewerClientId)); + if (!stream) return; + stream.nativeViewerClids.delete(viewerClientId); + stream.viewerCount = this.screenShareViewerCount(stream); + this.sendToEntry(stream.ownerEntryId, { + type: "screenShareViewerLeft", + streamId: stream.streamId, + viewerPeerId: nativeViewerPeerId(viewerClientId), + }); + this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); + return; + } + if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") { + const streamId = params.id || params.stream_id; + if (!streamId) return; + const targetKey = teamSpeakTargetKey(entry.target); + const browserStream = notification.name === "notifystreamsignaling" + ? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey + && candidate.source === "browser" + && candidate.teamSpeakPublisherEntryId === entry.id + && candidate.teamSpeakStreamId === streamId) + : undefined; + if (browserStream) { + const viewerClientId = parseNumber(params.clid); + if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return; + const payload = parseStreamSignalPayload(params.json || params.data || ""); + if (!payload) return; + const signal = toBrowserScreenSignal(payload); + if (!signal) return; + this.sendToEntry(browserStream.ownerEntryId, { + type: "screenShareSignal", + streamId: browserStream.streamId, + fromPeerId: nativeViewerPeerId(viewerClientId), + signal, + }); + return; + } + const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId)); + if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return; + const payload = notification.name === "notifyrespondjoinstreamrequest" + ? { cmd: "offer", args: { offer: params.offer || "" } } + : parseStreamSignalPayload(params.json || params.data || ""); + if (!payload) return; + const signal = toBrowserScreenSignal(payload); + if (!signal) return; + this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal }); + } + } + +} + +function parseNumber(value: string | undefined): number | undefined { + if (!value || !/^\d+$/.test(value)) return undefined; + const parsed = Number(value); + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined; +} + +function nativeViewerPeerId(clientId: number): string { + return `ts-viewer-${clientId}`; +} + +function parseNativeViewerPeerId(peerId: string): number | undefined { + const match = /^ts-viewer-(\d+)$/.exec(peerId); + if (!match) return undefined; + return parseNumber(match[1]); +} + +function buildTeamSpeakCommand(command: string, params: Record): string { + return [command, ...Object.entries(params).map(([key, value]) => `${key}=${escapeTeamSpeakValue(value)}`)].join(" "); +} + +function parseStreamSignalPayload(raw: string): { cmd: string; args: Record } | null { + try { + const value: unknown = JSON.parse(raw); + if (!isRecord(value) || typeof value.cmd !== "string" || !isRecord(value.args)) return null; + return { cmd: value.cmd, args: value.args }; + } catch { + return null; + } +} + +function toBrowserScreenSignal(payload: { cmd: string; args: Record }): ScreenSharePeerSignal | null { + const args = payload.args; + // TeamSpeak's native screen-share source wraps the initial SDP in a + // `joinResponse` message after it accepts a viewer's join request. The + // browser-side protocol uses the regular offer shape, so normalize it here + // before forwarding it. Without this mapping the native source can accept a + // viewer while the browser waits forever for its first SDP. + if (payload.cmd === "joinResponse") { + const decision = args.decision; + if (decision === false || decision === 0 || decision === "0") return { kind: "close" }; + const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : ""; + return sdp ? { kind: "offer", sdp } : null; + } + if (payload.cmd === "offer" || payload.cmd === "reconnectOffer") { + const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : ""; + return sdp ? { kind: "offer", sdp } : null; + } + if (payload.cmd === "answer") { + const sdp = typeof args.answer === "string" ? args.answer : typeof args.sdp === "string" ? args.sdp : ""; + return sdp ? { kind: "answer", sdp } : null; + } + if (payload.cmd === "iceCandidate") { + const candidate = typeof args.sdp === "string" ? args.sdp : typeof args.candidate === "string" ? args.candidate : ""; + if (!candidate) return null; + return { + kind: "iceCandidate", + candidate, + ...(typeof args.mid === "string" ? { sdpMid: args.mid } : {}), + ...(typeof args.mLine === "number" ? { sdpMLineIndex: args.mLine } : {}), + }; + } + return null; +} + +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"); +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 7b2192d..e3f47e5 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -1,5 +1,10 @@ +import { ScreenShareCoordinator } from "./screen-share-coordinator.js"; +import { handleCommand } from "./voice-commands.js"; +import { createAudioFlowStats, snapshotAudioStats, type AudioFlowStats } from "./audio-stats.js"; +export type { AudioFlowStats } from "./audio-stats.js"; +import { mapChannelTree, normalizeDirectorySnapshot, avatarDataUrl } from "./directory-view.js"; import type { ServerMessage } from "../shared/server-messages.js"; -import type { ChannelInfo, VoiceAudioBridgeStats } from "../shared/voice-models.js"; +import type { ChannelInfo } from "../shared/voice-models.js"; import type { ChannelMember as SharedChannelMember, ServerEvent as SharedServerEvent } from "../shared/voice-models.js"; import { WebSocketServer, WebSocket } from "ws"; import type { IncomingMessage, Server } from "node:http"; @@ -9,17 +14,16 @@ import { identityFromString } from "@echosixhiya/teamspeak-client"; import { DirectorySynchronizer } from "./directory-sync.js"; import { TSClient, type TSDirectorySnapshot, type TSVoiceData, type TSRawNotification } from "./ts-client.js"; import type { Logger as LoggerType } from "../logger.js"; -import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, teamSpeakServerErrorCode, type WebSpeakError } from "../errors.js"; +import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, type WebSpeakError } from "../errors.js"; import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js"; import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; import { IdentityLeaseStore } from "./identity-lease.js"; import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js"; -import { parseClientCommand, type ClientCommand } from "./voice-protocol.js"; +import { parseClientCommand } from "./voice-protocol.js"; import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js"; -import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js"; -import { pingTeamSpeakSession } from "./network-probe.js"; +import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.js"; import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js"; -import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareClientMessage, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js"; +import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js"; import { OpusEncoder } from "./opus-codec.js"; const HEARTBEAT_INTERVAL_MS = 30_000; @@ -61,52 +65,6 @@ export interface AdminSessionSummary { audio: AudioFlowStats; } -export interface AudioFlowStats { - ingressFrames: number; - ingressDroppedFrames: number; - ingressFirstAt: number | null; - ingressLastAt: number | null; - ingressMaxGapMs: number; - tsSendFrames: number; - tsSendErrors: number; - tsSendFirstAt: number | null; - tsSendLastAt: number | null; - tsSendMaxGapMs: number; - tsEncodeMaxMs: number; - tsReceiveFrames: number; - tsReceiveFirstAt: number | null; - tsReceiveLastAt: number | null; - tsReceiveMaxGapMs: number; - egressFrames: number; - egressDroppedFrames: number; - egressFirstAt: number | null; - egressLastAt: number | null; - egressMaxGapMs: number; - egressSentFirstAt: number | null; - egressSentLastAt: number | null; - egressSentMaxGapMs: number; - egressPeakBufferedBytes: number; - egressFramesByClient: Record; - webrtcIngressRtpFrames: number; - webrtcIngressRtpFirstAt: number | null; - webrtcIngressRtpLastAt: number | null; - webrtcIngressRtpMaxGapMs: number; - webrtcEgressRtpFrames: number; - webrtcEgressRtpFirstAt: number | null; - webrtcEgressRtpLastAt: number | null; - webrtcEgressRtpMaxGapMs: number; - webrtcQueuePeakFrames: number; - webrtcQueueDroppedFrames: number; - webrtcQueueUnderrunTicks: number; - webrtcPacerLateTicks: number; - webrtcQueueCurrentFrames: number; - webrtcIngressQuietFrames: number; - webrtcIngressDecodeErrors: number; - webrtcDownlinkDecodedFrames: number; - webrtcDownlinkDecodeErrors: number; - webrtcDownlinkShortFrames: number; -} - type ChannelMember = SharedChannelMember & { uid: string }; type ServerEvent = SharedServerEvent & { kind: "joined" | "left" | "moved" | "poke" | "connection" }; @@ -141,31 +99,10 @@ interface WebClientEntry { screenPeerId: string; } -interface ScreenStreamRecord extends ScreenShareStreamDescription { - targetKey: string; - channelId: bigint; - ownerEntryId: string; - viewerEntryIds: Set; - sourceClientId?: number; - /** The gateway TS client that publishes a browser-owned stream to TS6. */ - teamSpeakPublisherEntryId?: string; - /** The TS6 stream id paired with a browser-owned WebSpeak stream. */ - teamSpeakStreamId?: string; - /** Native TS6 viewer client ids paired with a browser-owned stream. */ - nativeViewerClids: Set; -} - -// Stream ids are scoped to a TeamSpeak server. Keep the target in the key so -// two unrelated servers cannot overwrite each other's native stream record. -function screenStreamKey(targetKey: string, streamId: string): string { - return `${targetKey}\u0000${streamId}`; -} - export class VoiceBridge { private readonly sessionManager = new SessionManager(); private readonly entries = new Map(); - private readonly screenStreams = new Map(); - private readonly screenStreamDiscoveryTargets = new Set(); + private readonly screenShares: ScreenShareCoordinator; private readonly identityLeases = new IdentityLeaseStore(); private wss: WebSocketServer | null = null; private heartbeatTimer: ReturnType | null = null; @@ -176,6 +113,10 @@ export class VoiceBridge { logger: LoggerType, ) { this.logger = logger.child({ component: "voice-bridge" }); + this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => { + const entry = this.entries.get(entryId); + if (entry?.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify(message)); + }, this.logger); } attach(server: Server): void { @@ -526,7 +467,7 @@ export class VoiceBridge { refreshDirectory(); } sendInitialState(); - void this.discoverExistingTeamSpeakStreams(entry!); + void this.screenShares.discoverExistingStreams(entry!); } catch (error: unknown) { const normalized = normalizeTeamSpeakError(error); const failureCode = clientConnectionFailureCode(normalized, serverPassword); @@ -596,7 +537,7 @@ export class VoiceBridge { }); tsClient.on("clientLeave", (info) => { - this.reconcileNativeScreenShareAfterClientLeave(entry!, info.id); + this.screenShares.onClientLeave(entry!, info.id); const wasKnown = entry!.members.has(info.id); const leavingMember = entry!.members.get(info.id); entry!.webrtc?.setMemberVolume(info.id, 1); @@ -611,7 +552,7 @@ export class VoiceBridge { tsClient.on("clientMoved", (info) => { if (info.targetChannelID === undefined || info.targetChannelID === 0n) return; - this.reconcileScreenShareAfterClientMove(entry!, info.id, info.targetChannelID); + this.screenShares.onClientMove(entry!, info.id, info.targetChannelID); const movedMember = entry!.members.get(info.id); if (info.id === selfId) selfChannelId = info.targetChannelID; directory.applyClientMoved(info.id, info.targetChannelID); @@ -629,7 +570,7 @@ export class VoiceBridge { }); tsClient.on("rawNotification", (notification: TSRawNotification) => { - this.handleRawScreenNotification(entry!, notification); + this.screenShares.handleNotification(entry!, notification); }); tsClient.on("voiceData", (data: TSVoiceData) => { @@ -721,6 +662,7 @@ export class VoiceBridge { tsClient.on("disconnected", (error?: Error) => { if (!hasConnectedOnce || session.state !== "connected") return; + this.screenShares.removePeer(entryId); resetDirectoryForReconnect(); // Prefer a kick reason over the generic transport error that follows it, // regardless of which of the two events arrives first. @@ -809,7 +751,7 @@ export class VoiceBridge { sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪"); return; } - this.handleScreenShareMessage(entry!, screenShareMessage, sendJson); + this.screenShares.handleMessage(entry!, screenShareMessage, sendJson); return; } const command = parseClientCommand(rawMessage); @@ -916,7 +858,7 @@ export class VoiceBridge { } private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise { - this.removeScreenSharePeer(entry.id); + this.screenShares.removePeer(entry.id); if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id); if (entry.reconnectTimer) { clearTimeout(entry.reconnectTimer); @@ -997,599 +939,6 @@ export class VoiceBridge { return selected; } - private handleScreenShareMessage( - entry: WebClientEntry, - message: ScreenShareClientMessage, - sendJson: (message: ServerMessage) => void, - ): void { - if (message.type === "screenShareList") { - sendJson({ type: "screenShareList", streams: this.listScreenStreamsFor(entry) }); - return; - } - - if (message.type === "screenShareStart") { - if ([...this.screenStreams.values()].some((stream) => stream.source === "browser" && stream.ownerEntryId === entry.id)) { - sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_ALREADY_ACTIVE", message: "你已经在共享屏幕" }); - return; - } - const stream: ScreenStreamRecord = { - streamId: `screen-${randomUUID()}`, - source: "browser", - ownerPeerId: entry.screenPeerId, - ownerClientId: entry.tsClient.getClientId() || undefined, - ownerNickname: entry.nickname, - name: message.name?.trim() || `${entry.nickname} 的屏幕`, - audio: message.audio === true, - createdAt: Date.now(), - viewerCount: 0, - viewers: [], - targetKey: teamSpeakTargetKey(entry.target), - channelId: entry.tsClient.getChannelId(), - ownerEntryId: entry.id, - viewerEntryIds: new Set(), - teamSpeakPublisherEntryId: entry.id, - nativeViewerClids: new Set(), - }; - this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream); - sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true }); - this.broadcastScreenMessage(stream, { - type: "screenShareStarted", - stream: this.describeScreenStream(stream), - owner: false, - }, entry.id); - void this.publishBrowserScreenStream(entry, stream); - return; - } - - const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId)); - if (!stream) { - sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" }); - return; - } - if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) { - sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" }); - return; - } - - if (message.type === "screenShareStop") { - if (stream.ownerEntryId !== entry.id) { - sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_NOT_OWNER", message: "只有共享者可以结束共享" }); - return; - } - this.stopScreenStream(stream, "owner-stopped"); - if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId }); - return; - } - - if (message.type === "screenShareJoin") { - if (stream.ownerEntryId === entry.id) { - sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_OWNER_CANNOT_JOIN", message: "共享者不能作为观看者加入自己的共享" }); - return; - } - const alreadyJoined = stream.viewerEntryIds.has(entry.id); - if (!alreadyJoined) stream.viewerEntryIds.add(entry.id); - stream.viewerCount = this.screenShareViewerCount(stream); - sendJson({ - type: "screenShareJoined", - requestId: message.requestId, - stream: this.describeScreenStream(stream), - ownerPeerId: stream.ownerPeerId, - mode: stream.source, - }); - if (stream.source === "browser" && !alreadyJoined) { - this.sendToEntry(stream.ownerEntryId, { - type: "screenShareViewerJoined", - streamId: stream.streamId, - viewerPeerId: entry.screenPeerId, - viewerNickname: entry.nickname, - }); - } else if (stream.source === "teamspeak" && !alreadyJoined) { - void this.joinNativeScreenStream(entry, stream, sendJson, message.requestId); - } - if (!alreadyJoined) { - this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); - } - return; - } - - if (message.type === "screenShareLeave") { - this.leaveScreenStream(entry, stream); - if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId }); - return; - } - - if (message.type === "screenShareSignal") { - this.relayScreenShareSignal(entry, stream, message.targetPeerId, message.signal, sendJson); - } - } - - private listScreenStreamsFor(entry: WebClientEntry): ScreenShareStreamDescription[] { - const targetKey = teamSpeakTargetKey(entry.target); - return [...this.screenStreams.values()] - .filter((stream) => stream.targetKey === targetKey && stream.channelId === entry.tsClient.getChannelId()) - .map((stream) => this.describeScreenStream(stream)); - } - - /** - * A gateway session can connect after a native TeamSpeak stream has already - * started. TS6 does not replay that stream in the normal welcome snapshot; - * requeststreaminfo is the official client-protocol query for this case. - * Query each visible client once per TeamSpeak target, then let the normal - * raw notification path announce the discovered stream to web viewers. - */ - private async discoverExistingTeamSpeakStreams(entry: WebClientEntry): Promise { - const targetKey = teamSpeakTargetKey(entry.target); - if (this.screenStreamDiscoveryTargets.has(targetKey)) return; - this.screenStreamDiscoveryTargets.add(targetKey); - const clientIds = [...entry.members.keys()].filter((clientId) => Number.isInteger(clientId) && clientId > 0); - for (const clientId of clientIds) { - if (!entry.tsClient.isConnected()) return; - try { - await entry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`); - } catch (error: unknown) { - this.logger.debug({ - target: formatTeamSpeakTarget(entry.target), - clientId, - err: error instanceof Error ? error.message : String(error), - }, "Could not query existing TeamSpeak screen stream"); - } - } - } - - private describeScreenStream(stream: ScreenStreamRecord): ScreenShareStreamDescription { - return { - streamId: stream.streamId, - source: stream.source, - ownerPeerId: stream.ownerPeerId, - ...(typeof stream.ownerClientId === "number" ? { ownerClientId: stream.ownerClientId } : {}), - ownerNickname: stream.ownerNickname, - name: stream.name, - audio: stream.audio, - createdAt: stream.createdAt, - viewerCount: stream.viewerCount, - viewers: this.describeScreenViewers(stream), - }; - } - - private describeScreenViewers(stream: ScreenStreamRecord): ScreenShareViewerDescription[] { - return [...stream.viewerEntryIds] - .map((entryId) => this.entries.get(entryId)) - .filter((entry): entry is WebClientEntry => Boolean(entry)) - .slice(0, 64) - .map((entry) => { - const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar; - return { - peerId: entry.screenPeerId, - nickname: entry.nickname, - ...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}), - }; - }); - } - - private screenShareViewerCountMessage(stream: ScreenStreamRecord): ServerMessage { - return { - type: "screenShareViewerCount", - streamId: stream.streamId, - viewerCount: stream.viewerCount, - viewers: this.describeScreenViewers(stream), - }; - } - - private screenShareViewerCount(stream: ScreenStreamRecord): number { - return stream.viewerEntryIds.size + stream.nativeViewerClids.size; - } - - private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void { - for (const candidate of this.entries.values()) { - if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue; - // A stream is scoped to the source channel. Do not leak its card or - // viewer roster to users who are connected to another channel on the - // same TeamSpeak target. - if (candidate.id !== stream.ownerEntryId) { - try { - if (candidate.tsClient.getChannelId() !== stream.channelId) continue; - } catch { - continue; - } - } - this.sendToEntry(candidate.id, message); - } - } - - private sendToEntry(entryId: string, message: ServerMessage): void { - const candidate = this.entries.get(entryId); - if (candidate?.ws.readyState === WebSocket.OPEN) candidate.ws.send(JSON.stringify(message)); - } - - private stopScreenStream(stream: ScreenStreamRecord, reason: string): void { - if (stream.source === "browser" && stream.teamSpeakStreamId && stream.teamSpeakPublisherEntryId) { - const publisher = this.entries.get(stream.teamSpeakPublisherEntryId); - if (publisher) { - void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { - id: stream.teamSpeakStreamId, - reason: "1", - })).catch(() => undefined); - } - } - if (!this.screenStreams.delete(screenStreamKey(stream.targetKey, stream.streamId))) return; - const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason }; - this.broadcastScreenMessage(stream, message); - stream.viewerEntryIds.clear(); - stream.nativeViewerClids.clear(); - stream.viewerCount = 0; - } - - private leaveScreenStream(entry: WebClientEntry, stream: ScreenStreamRecord): void { - if (!stream.viewerEntryIds.delete(entry.id)) return; - stream.viewerCount = this.screenShareViewerCount(stream); - if (stream.source === "browser") this.sendToEntry(stream.ownerEntryId, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: entry.screenPeerId }); - else { - void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", { - id: stream.streamId, - clid: String(entry.tsClient.getClientId()), - })).catch(() => undefined); - } - this.sendToEntry(entry.id, { type: "screenShareLeft", streamId: stream.streamId }); - this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); - } - - private relayScreenShareSignal( - entry: WebClientEntry, - stream: ScreenStreamRecord, - targetPeerId: string, - signal: ScreenSharePeerSignal, - sendJson: (message: ServerMessage) => void, - ): void { - if (stream.source === "teamspeak") { - if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" }); - return; - } - const sourceClientId = stream.sourceClientId; - if (!sourceClientId) { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" }); - return; - } - if (signal.kind === "close") { - this.leaveScreenStream(entry, stream); - return; - } - if (signal.kind === "offer") { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "观看端不能向 TeamSpeak 来源发送 offer" }); - return; - } - const payload = signal.kind === "iceCandidate" - ? { cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } } - : { cmd: "answer", args: { answer: signal.sdp } }; - void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("streamsignaling", { - id: stream.streamId, - clid: String(sourceClientId), - json: JSON.stringify(payload), - })).catch((error: unknown) => { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" }); - }); - return; - } - - if (stream.source === "browser" && entry.id === stream.ownerEntryId && targetPeerId.startsWith("ts-viewer-")) { - const viewerClid = parseNativeViewerPeerId(targetPeerId); - const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined; - if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" }); - return; - } - if (signal.kind === "close") { - void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", { - id: stream.teamSpeakStreamId, - clid: String(viewerClid), - })).catch(() => undefined); - stream.nativeViewerClids.delete(viewerClid); - stream.viewerCount = this.screenShareViewerCount(stream); - this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId }); - this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); - return; - } - if (signal.kind === "answer") { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "TeamSpeak 观看端不能先发送 answer" }); - return; - } - let command: string; - if (signal.kind === "offer") { - command = buildTeamSpeakCommand("respondjoinstreamrequest", { - id: stream.teamSpeakStreamId, - clid: String(viewerClid), - msg: "", - offer: signal.sdp, - decision: "1", - }); - } else if (signal.kind === "iceCandidate") { - command = buildTeamSpeakCommand("streamsignaling", { - id: stream.teamSpeakStreamId, - clid: String(viewerClid), - json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }), - }); - } else { - return; - } - void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" }); - }); - return; - } - - const owner = this.entries.get(stream.ownerEntryId); - const isOwner = entry.id === stream.ownerEntryId; - const isViewer = stream.viewerEntryIds.has(entry.id); - if (!owner || (!isOwner && !isViewer)) { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" }); - return; - } - // Keep the browser P2P graph bipartite: the owner may signal only an - // active viewer, and a viewer may signal only the owner. Without this - // check one viewer could inject SDP/ICE into another viewer's peer. - const targetEntry = isOwner - ? [...stream.viewerEntryIds] - .map((id) => this.entries.get(id)) - .find((candidate) => candidate?.screenPeerId === targetPeerId) - : targetPeerId === owner.screenPeerId ? owner : undefined; - if (!targetEntry || targetEntry.id === entry.id) { - sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "观看者已离开" }); - return; - } - this.sendToEntry(targetEntry.id, { type: "screenShareSignal", streamId: stream.streamId, fromPeerId: entry.screenPeerId, signal }); - } - - private async publishBrowserScreenStream(entry: WebClientEntry, stream: ScreenStreamRecord): Promise { - try { - await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("setupstream", { - name: stream.name, - type: "3", - bitrate: "4608", - accessibility: "1", - mode: "1", - viewer_limit: "0", - audio: stream.audio ? "1" : "0", - })); - } catch (error: unknown) { - this.logger.warn({ - target: formatTeamSpeakTarget(entry.target), - streamId: stream.streamId, - err: error instanceof Error ? error.message : String(error), - }, "Could not publish browser screen share to TeamSpeak"); - } - } - - private async joinNativeScreenStream( - entry: WebClientEntry, - stream: ScreenStreamRecord, - sendJson: (message: ServerMessage) => void, - requestId?: string, - ): Promise { - const sourceClientId = stream.sourceClientId; - if (!entry.tsClient.getClientId() || !sourceClientId) { - sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" }); - return; - } - try { - await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("joinstreamrequest", { - id: stream.streamId, - // TS6 uses the source client id on joinstreamrequest. The requesting - // gateway session is identified later by the response/signaling - // notification delivered to this TS connection. - clid: String(sourceClientId), - msg: "", - is_remove: "0", - muted: "0", - volume: "0", - hidden: "0", - })); - } catch (error: unknown) { - this.leaveScreenStream(entry, stream); - sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_JOIN_FAILED", message: error instanceof Error ? error.message : "无法加入屏幕共享" }); - } - } - - private removeScreenSharePeer(entryId: string): void { - for (const stream of [...this.screenStreams.values()]) { - if (stream.ownerEntryId === entryId) { - this.stopScreenStream(stream, "owner-disconnected"); - continue; - } - const entry = this.entries.get(entryId); - if (entry && stream.viewerEntryIds.has(entryId)) this.leaveScreenStream(entry, stream); - } - } - - private reconcileScreenShareAfterClientMove(entry: WebClientEntry, movedClientId: number, targetChannelId: bigint): void { - const targetKey = teamSpeakTargetKey(entry.target); - for (const stream of [...this.screenStreams.values()]) { - if (stream.targetKey !== targetKey) continue; - // A browser share belongs to the gateway user's current channel. Stop - // it when that user moves so existing viewers cannot keep a cross- - // channel peer alive. - if (stream.source === "browser" && stream.ownerEntryId === entry.id && stream.channelId !== targetChannelId) { - this.stopScreenStream(stream, "owner-moved-channel"); - continue; - } - // Native TS6 shares are channel-scoped as well. The notification is - // observed by every gateway session, so stop the shared record once the - // native source changes channels. - if (stream.source === "teamspeak" && stream.sourceClientId === movedClientId) { - this.stopScreenStream(stream, "source-moved-channel"); - continue; - } - if (stream.viewerEntryIds.has(entry.id) && stream.channelId !== targetChannelId) { - this.leaveScreenStream(entry, stream); - } - } - } - - private reconcileNativeScreenShareAfterClientLeave(entry: WebClientEntry, clientId: number): void { - const targetKey = teamSpeakTargetKey(entry.target); - for (const stream of [...this.screenStreams.values()]) { - if (stream.targetKey === targetKey && stream.source === "teamspeak" && stream.sourceClientId === clientId) { - this.stopScreenStream(stream, "source-left"); - } - } - } - - private handleRawScreenNotification(entry: WebClientEntry, notification: TSRawNotification): void { - const params = notification.params; - if (notification.name === "notifyjoinstreamrequest") { - const streamId = params.id || params.stream_id; - const viewerClientId = parseNumber(params.clid); - if (!streamId || !viewerClientId) return; - const targetKey = teamSpeakTargetKey(entry.target); - const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey - && candidate.source === "browser" - && candidate.teamSpeakPublisherEntryId === entry.id - && candidate.teamSpeakStreamId === streamId); - if (!stream) return; - stream.nativeViewerClids.add(viewerClientId); - stream.viewerCount = this.screenShareViewerCount(stream); - this.sendToEntry(stream.ownerEntryId, { - type: "screenShareNativeViewerJoined", - streamId: stream.streamId, - viewerPeerId: nativeViewerPeerId(viewerClientId), - viewerClientId, - }); - this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); - return; - } - if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") { - const streamId = params.id || params.stream_id; - const sourceClientId = parseNumber(params.clid); - if (!streamId || !sourceClientId) return; - const targetKey = teamSpeakTargetKey(entry.target); - const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target - && teamSpeakTargetKey(candidate.target) === targetKey - && candidate.tsClient.getClientId() === sourceClientId); - const browserStream = publisherEntry - ? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey - && candidate.source === "browser" - && candidate.teamSpeakPublisherEntryId === publisherEntry.id - && !candidate.teamSpeakStreamId) - : undefined; - if (browserStream) { - browserStream.teamSpeakStreamId = streamId; - return; - } - const sourceEntry = [...this.entries.values()].find((candidate) => candidate.tsClient.getClientId() === sourceClientId); - const key = screenStreamKey(targetKey, streamId); - const current = this.screenStreams.get(key); - const stream: ScreenStreamRecord = current ?? { - streamId, - source: "teamspeak", - ownerPeerId: `ts-${sourceClientId}`, - ownerClientId: sourceClientId, - ownerNickname: params.name || `TeamSpeak 用户 ${sourceClientId}`, - name: params.name || "TeamSpeak 屏幕共享", - audio: params.audio === "1", - createdAt: Date.now(), - viewerCount: 0, - viewers: [], - targetKey, - channelId: sourceEntry?.tsClient.getChannelId() ?? entry.tsClient.getChannelId(), - ownerEntryId: "", - viewerEntryIds: new Set(), - nativeViewerClids: new Set(), - sourceClientId, - }; - stream.sourceClientId = sourceClientId; - stream.ownerNickname = params.name || stream.ownerNickname; - stream.name = params.name || stream.name; - stream.audio = params.audio === "1"; - this.screenStreams.set(key, stream); - // Every gateway session attached to the same TS target sees the same - // raw notification. Only the first one should announce a new stream to - // browsers; otherwise each connected user receives duplicate cards. - if (!current) { - this.broadcastScreenMessage(stream, { type: "screenShareStarted", stream: this.describeScreenStream(stream), owner: false }); - } - return; - } - if (notification.name === "notifystreamstopped") { - const streamId = params.id || params.stream_id; - if (!streamId) return; - const targetKey = teamSpeakTargetKey(entry.target); - const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId)); - if (stream) { - this.stopScreenStream(stream, "source-stopped"); - return; - } - const browserStream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey - && candidate.source === "browser" - && candidate.teamSpeakStreamId === streamId); - if (browserStream) { - browserStream.teamSpeakStreamId = undefined; - browserStream.nativeViewerClids.clear(); - browserStream.viewerCount = this.screenShareViewerCount(browserStream); - this.sendToEntry(browserStream.ownerEntryId, { - type: "screenShareError", - code: "SCREEN_SHARE_NATIVE_PUBLISHER_STOPPED", - message: "TeamSpeak 客户端屏幕共享通道已停止,网页共享仍可继续", - }); - this.broadcastScreenMessage(browserStream, this.screenShareViewerCountMessage(browserStream)); - } - return; - } - if (notification.name === "notifystreamclientleft") { - const streamId = params.id || params.stream_id; - const viewerClientId = parseNumber(params.clid); - if (!streamId || !viewerClientId) return; - const targetKey = teamSpeakTargetKey(entry.target); - const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey - && candidate.source === "browser" - && candidate.teamSpeakStreamId === streamId - && candidate.nativeViewerClids.has(viewerClientId)); - if (!stream) return; - stream.nativeViewerClids.delete(viewerClientId); - stream.viewerCount = this.screenShareViewerCount(stream); - this.sendToEntry(stream.ownerEntryId, { - type: "screenShareViewerLeft", - streamId: stream.streamId, - viewerPeerId: nativeViewerPeerId(viewerClientId), - }); - this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream)); - return; - } - if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") { - const streamId = params.id || params.stream_id; - if (!streamId) return; - const targetKey = teamSpeakTargetKey(entry.target); - const browserStream = notification.name === "notifystreamsignaling" - ? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey - && candidate.source === "browser" - && candidate.teamSpeakPublisherEntryId === entry.id - && candidate.teamSpeakStreamId === streamId) - : undefined; - if (browserStream) { - const viewerClientId = parseNumber(params.clid); - if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return; - const payload = parseStreamSignalPayload(params.json || params.data || ""); - if (!payload) return; - const signal = toBrowserScreenSignal(payload); - if (!signal) return; - this.sendToEntry(browserStream.ownerEntryId, { - type: "screenShareSignal", - streamId: browserStream.streamId, - fromPeerId: nativeViewerPeerId(viewerClientId), - signal, - }); - return; - } - const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId)); - if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return; - const payload = notification.name === "notifyrespondjoinstreamrequest" - ? { cmd: "offer", args: { offer: params.offer || "" } } - : parseStreamSignalPayload(params.json || params.data || ""); - if (!payload) return; - const signal = toBrowserScreenSignal(payload); - if (!signal) return; - this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal }); - } - } - private async handleWebRtcOffer( entry: WebClientEntry, offer: WebRtcSessionDescription, @@ -1709,173 +1058,6 @@ function normalizeWebRtcHost(value: string | undefined): string | undefined { } } -async function handleCommand( - entry: WebClientEntry, - command: ClientCommand, - sendJson: (message: ServerMessage) => void, -): Promise { - if (command.type === "latencyProbe") { - // Keep the control-path probe for already-open older browser clients. The - // current voice status panel exclusively requests actual audio counters. - const sequence = command.payload.sequence as string; - const now = Date.now(); - if (now - entry.lastLatencyProbeAt < 150) return; - entry.lastLatencyProbeAt = now; - const result = await pingTeamSpeakSession( - (request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs), - ); - sendJson({ - type: "latencyPong", - sequence, - teamSpeakLatencyMs: result.latencyMs, - teamSpeakReachable: result.ok, - teamSpeakErrorCode: result.errorCode ?? null, - }); - return; - } - - if (command.type === "audioStatsProbe") { - const sequence = command.payload.sequence as string; - const now = Date.now(); - if (now - entry.lastAudioStatsProbeAt < 750) return; - entry.lastAudioStatsProbeAt = now; - sendJson({ - type: "audioStats", - sequence, - stats: snapshotAudioStatus(entry), - }); - return; - } - - if (command.type === "switchChannel") { - const rawId = command.payload.channelId as string; - const channelPassword = typeof command.payload.password === "string" ? command.payload.password : ""; - try { - await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined); - } catch (error: unknown) { - const rawMessage = error instanceof Error ? error.message : String(error); - if (/already member/i.test(rawMessage)) { - sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); - return; - } - const operation = classifyOperationError(error, "CHANNEL_SWITCH_FAILED", "频道切换失败"); - sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); - return; - } - sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); - sendJson({ type: "channelList", channels: entry.channelTree }); - return; - } - - try { - if (command.type === "moveClient") { - const clientId = command.payload.clientId as number; - const channelId = command.payload.channelId as string; - if (clientId === entry.tsClient.getClientId()) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CANNOT_MOVE_SELF", message: "不能移动自己的客户端", recoverable: false } }); - return; - } - if (!entry.members.has(clientId)) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线或当前不可见", recoverable: false } }); - return; - } - const targetExists = entry.channelTree.some((channel) => isRecord(channel) && channel.id === channelId); - if (!targetExists) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_NOT_FOUND", message: "目标频道不可用", recoverable: false } }); - return; - } - // TeamSpeak evaluates i_client_move_power against the target's - // i_client_needed_move_power inside clientmove. Do not duplicate that - // policy in the gateway; forwarding the authoritative command keeps TS3 - // and TS6 permission behavior aligned. - // Moving another visible client is an administrator operation. It must - // not prompt for or depend on the target channel's join password. - await entry.tsClient.moveClient(clientId, BigInt(channelId)); - } else if (command.type === "sendTextMessage") { - const message = (command.payload.message as string).trim(); - if (message) await entry.tsClient.sendTextMessage("channel", message, entry.tsClient.getChannelId()); - } else if (command.type === "sendServerMessage") { - const message = (command.payload.message as string).trim(); - if (message) await entry.tsClient.sendTextMessage("server", message); - } else if (command.type === "sendPrivateMessage") { - const clientId = command.payload.clientId as number; - if (!entry.members.has(clientId)) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); - return; - } - const message = (command.payload.message as string).trim(); - if (message) await entry.tsClient.sendTextMessage("private", message, BigInt(clientId)); - } else if (command.type === "poke") { - const clientId = command.payload.clientId as number; - if (!entry.members.has(clientId)) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); - return; - } - await entry.tsClient.poke(clientId, (command.payload.message as string).trim()); - } else if (command.type === "setAway") { - await entry.tsClient.setAway(command.payload.away as boolean, typeof command.payload.message === "string" ? command.payload.message.trim() : ""); - } else if (command.type === "setWhisperTargets") { - const targetIds = command.payload.targetIds as number[]; - const selfId = entry.tsClient.getClientId(); - if (targetIds.some((clientId) => clientId === selfId || !entry.members.has(clientId))) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "私语目标已离线", recoverable: false } }); - return; - } - entry.whisperTargetIds = new Set(targetIds); - if (!entry.whisperTargetIds.size) entry.whisperActive = false; - sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive }); - } else if (command.type === "setWhisperActive") { - const active = command.payload.active as boolean; - if (active && !entry.whisperTargetIds.size) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "NO_WHISPER_TARGETS", message: "请先选择私语目标", recoverable: false } }); - return; - } - entry.whisperActive = active; - sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive }); - } else if (command.type === "setMicrophoneMuted") { - const muted = command.payload.muted as boolean; - await entry.tsClient.setInputMuted(muted); - entry.webrtc?.setMicrophoneMuted(muted); - } else if (command.type === "setAccompanimentActive") { - entry.webrtc?.setAccompanimentActive(command.payload.active as boolean); - } else if (command.type === "setMemberVolume") { - const clientId = command.payload.clientId as number; - entry.webrtc?.setMemberVolume(clientId, command.payload.volume as number); - } - if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId }); - } catch (error: unknown) { - const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败"); - sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); - } -} - -function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } { - const text = error instanceof Error ? error.message : String(error); - const normalized = text.toLocaleLowerCase(); - // A TeamSpeak server error id is authoritative when the SDK preserved it, so it - // is consulted before the keyword rules: 781 (channel password), 2568 - // (permissions), 515/2817 (server or slot limit) and friends keep their exact - // meaning instead of being guessed from prose. - const serverCode = - teamSpeakServerErrorCode(isRecord(error) ? (error.id ?? error.code) : undefined) ?? - teamSpeakServerErrorCode(/\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1]); - if (serverCode) { - if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; - if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; - if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" }; - if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" }; - if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" }; - if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" }; - if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" }; - } - if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; - if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|781/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; - if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" }; - if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" }; - if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" }; - return { code: fallbackCode, message: fallbackMessage }; -} - function sendProtocolError(sendJson: (message: ServerMessage) => void, code: string, message: string): void { sendJson({ type: "error", error: { code, message, recoverable: false } }); } @@ -1905,80 +1087,6 @@ function isWebRtcStopMessage(raw: string): boolean { } } -function parseNumber(value: string | undefined): number | undefined { - if (!value || !/^\d+$/.test(value)) return undefined; - const parsed = Number(value); - return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined; -} - -function nativeViewerPeerId(clientId: number): string { - return `ts-viewer-${clientId}`; -} - -function parseNativeViewerPeerId(peerId: string): number | undefined { - const match = /^ts-viewer-(\d+)$/.exec(peerId); - if (!match) return undefined; - return parseNumber(match[1]); -} - -function buildTeamSpeakCommand(command: string, params: Record): string { - return [command, ...Object.entries(params).map(([key, value]) => `${key}=${escapeTeamSpeakValue(value)}`)].join(" "); -} - -function parseStreamSignalPayload(raw: string): { cmd: string; args: Record } | null { - try { - const value: unknown = JSON.parse(raw); - if (!isRecord(value) || typeof value.cmd !== "string" || !isRecord(value.args)) return null; - return { cmd: value.cmd, args: value.args }; - } catch { - return null; - } -} - -function toBrowserScreenSignal(payload: { cmd: string; args: Record }): ScreenSharePeerSignal | null { - const args = payload.args; - // TeamSpeak's native screen-share source wraps the initial SDP in a - // `joinResponse` message after it accepts a viewer's join request. The - // browser-side protocol uses the regular offer shape, so normalize it here - // before forwarding it. Without this mapping the native source can accept a - // viewer while the browser waits forever for its first SDP. - if (payload.cmd === "joinResponse") { - const decision = args.decision; - if (decision === false || decision === 0 || decision === "0") return { kind: "close" }; - const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : ""; - return sdp ? { kind: "offer", sdp } : null; - } - if (payload.cmd === "offer" || payload.cmd === "reconnectOffer") { - const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : ""; - return sdp ? { kind: "offer", sdp } : null; - } - if (payload.cmd === "answer") { - const sdp = typeof args.answer === "string" ? args.answer : typeof args.sdp === "string" ? args.sdp : ""; - return sdp ? { kind: "answer", sdp } : null; - } - if (payload.cmd === "iceCandidate") { - const candidate = typeof args.sdp === "string" ? args.sdp : typeof args.candidate === "string" ? args.candidate : ""; - if (!candidate) return null; - return { - kind: "iceCandidate", - candidate, - ...(typeof args.mid === "string" ? { sdpMid: args.mid } : {}), - ...(typeof args.mLine === "number" ? { sdpMLineIndex: args.mLine } : {}), - }; - } - return null; -} - -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"); -} - function isRecord(value: unknown): value is Record { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } @@ -1986,150 +1094,3 @@ function isRecord(value: unknown): value is Record { function isChannelRecord(value: unknown): value is { id: string; name: string } { return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string"; } - -function createAudioFlowStats(): AudioFlowStats { - return { - ingressFrames: 0, - ingressDroppedFrames: 0, - ingressFirstAt: null, - ingressLastAt: null, - ingressMaxGapMs: 0, - tsSendFrames: 0, - tsSendErrors: 0, - tsSendFirstAt: null, - tsSendLastAt: null, - tsSendMaxGapMs: 0, - tsEncodeMaxMs: 0, - tsReceiveFrames: 0, - tsReceiveFirstAt: null, - tsReceiveLastAt: null, - tsReceiveMaxGapMs: 0, - egressFrames: 0, - egressDroppedFrames: 0, - egressFirstAt: null, - egressLastAt: null, - egressMaxGapMs: 0, - egressSentFirstAt: null, - egressSentLastAt: null, - egressSentMaxGapMs: 0, - egressPeakBufferedBytes: 0, - egressFramesByClient: {}, - webrtcIngressRtpFrames: 0, - webrtcIngressRtpFirstAt: null, - webrtcIngressRtpLastAt: null, - webrtcIngressRtpMaxGapMs: 0, - webrtcEgressRtpFrames: 0, - webrtcEgressRtpFirstAt: null, - webrtcEgressRtpLastAt: null, - webrtcEgressRtpMaxGapMs: 0, - webrtcQueuePeakFrames: 0, - webrtcQueueDroppedFrames: 0, - webrtcQueueUnderrunTicks: 0, - webrtcPacerLateTicks: 0, - webrtcQueueCurrentFrames: 0, - webrtcIngressQuietFrames: 0, - webrtcIngressDecodeErrors: 0, - webrtcDownlinkDecodedFrames: 0, - webrtcDownlinkDecodeErrors: 0, - webrtcDownlinkShortFrames: 0, - }; -} - -function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats { - const stats = { ...entry.audio }; - const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats(); - if (webRtcStats) Object.assign(stats, webRtcStats); - return stats; -} - -function snapshotAudioStatus(entry: WebClientEntry): VoiceAudioBridgeStats { - const stats = snapshotAudioStats(entry); - return { - transport: entry.webrtc ? "webrtc" : "websocket", - ingressFrames: stats.ingressFrames, - ingressDroppedFrames: stats.ingressDroppedFrames, - ingressMaxGapMs: stats.ingressMaxGapMs, - tsSendFrames: stats.tsSendFrames, - tsSendErrors: stats.tsSendErrors, - tsSendMaxGapMs: stats.tsSendMaxGapMs, - tsReceiveFrames: stats.tsReceiveFrames, - tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs, - egressFrames: stats.egressFrames, - egressDroppedFrames: stats.egressDroppedFrames, - egressMaxGapMs: stats.egressMaxGapMs, - webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames, - webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs, - webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames, - webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs, - webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames, - webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks, - webrtcPacerLateTicks: stats.webrtcPacerLateTicks, - webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors, - webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors, - }; -} - -function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map()): ChannelInfo[] { - return snapshot.channels.map((channel) => ({ - id: String(channel.id), - parentID: String(channel.parentID), - order: String(channel.order), - name: channel.name || "未命名频道", - description: channel.description || "", - members: snapshot.clients - .filter((client) => client.channelID === channel.id) - .map((client) => { - const avatar = client.uid ? avatarCache.get(client.uid) : undefined; - return { - id: client.id, - nickname: client.nickname || "未知用户", - uid: client.uid, - ...(avatar ? { avatar } : {}), - away: client.away, - awayMessage: client.awayMessage, - inputMuted: client.inputMuted, - outputMuted: client.outputMuted, - channelCommander: client.channelCommander, - }; - }), - })); -} - -function avatarDataUrl(data: Buffer): string | null { - if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return `data:image/png;base64,${data.toString("base64")}`; - if (data.length >= 3 && data.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return `data:image/jpeg;base64,${data.toString("base64")}`; - if (data.length >= 6 && (data.subarray(0, 6).toString("ascii") === "GIF87a" || data.subarray(0, 6).toString("ascii") === "GIF89a")) return `data:image/gif;base64,${data.toString("base64")}`; - if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return `data:image/webp;base64,${data.toString("base64")}`; - return null; -} - -function normalizeDirectorySnapshot( - snapshot: TSDirectorySnapshot, - selfId: number, - selfChannelId: bigint, - nickname: string, - requestedChannelName?: string, -): TSDirectorySnapshot { - if (selfId <= 0) return snapshot; - - const clients = snapshot.clients.slice(); - const selfIndex = clients.findIndex((client) => client.id === selfId); - const snapshotChannelId = selfIndex >= 0 ? clients[selfIndex]!.channelID : 0n; - const requestedName = requestedChannelName?.trim().toLocaleLowerCase(); - const requestedChannel = requestedName - ? snapshot.channels.find((channel) => channel.name.trim().toLocaleLowerCase() === requestedName) - : undefined; - const resolvedChannelId = selfChannelId !== 0n - ? selfChannelId - : snapshotChannelId !== 0n - ? snapshotChannelId - : requestedChannel?.id ?? snapshot.channels[0]?.id ?? 0n; - if (selfIndex >= 0) { - const current = clients[selfIndex]!; - if (resolvedChannelId !== 0n) clients[selfIndex] = { ...current, channelID: resolvedChannelId }; - } else if (resolvedChannelId !== 0n) { - clients.push({ id: selfId, nickname, uid: "", channelID: resolvedChannelId, type: 1, serverGroups: [] }); - } - - return { ...snapshot, clients }; -} diff --git a/src/server/voice-commands.test.ts b/src/server/voice-commands.test.ts new file mode 100644 index 0000000..751b413 --- /dev/null +++ b/src/server/voice-commands.test.ts @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { parseClientCommand, type ClientCommand } from "../shared/client-commands.js"; +import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js"; +import { createAudioFlowStats } from "./audio-stats.js"; +import { handleCommand, type VoiceCommandContext } from "./voice-commands.js"; + +function fixture() { + const calls: Array<[string, ...unknown[]]> = []; + const messages: ServerMessage[] = []; + const context: VoiceCommandContext = { + tsClient: { + execCommandWithResponse: async request => { calls.push(["exec", request]); return []; }, + switchChannel: async (...args) => { calls.push(["switch", ...args]); }, + getClientId: () => 1, getChannelId: () => 5n, + moveClient: async (...args) => { calls.push(["move", ...args]); }, + sendTextMessage: async (...args) => { calls.push(["text", ...args]); }, + poke: async (...args) => { calls.push(["poke", ...args]); }, + setAway: async (...args) => { calls.push(["away", ...args]); }, + setInputMuted: async (...args) => { calls.push(["mute", ...args]); }, + }, + channelTree: [{ id: "18446744073709551615", parentID: "0", name: "Large ID" }], + members: new Map([[1, {}], [2, {}]]), + whisperTargetIds: new Set(), whisperActive: false, + lastAudioStatsProbeAt: 0, lastLatencyProbeAt: 0, + audio: createAudioFlowStats(), webrtc: null, + }; + async function run(command: ClientCommand, now = 10_000) { + // The same parsers used at both ends must accept the command and reply. + const parsed = parseClientCommand(JSON.stringify(command)); + assert.ok(!("error" in parsed)); + await handleCommand(context, parsed, message => { + assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid response: ${message.type}`); + messages.push(message); + }, () => now); + } + return { context, calls, messages, run }; +} + +test("moving a visible member preserves bigint channel IDs and request correlation", async () => { + const f = fixture(); + await f.run({ type: "moveClient", payload: { clientId: 2, channelId: "18446744073709551615", password: "ignored-for-admin-move" }, requestId: "move-1" }); + assert.deepEqual(f.calls, [["move", 2, 18446744073709551615n]]); + assert.deepEqual(f.messages, [{ type: "commandCompleted", requestId: "move-1" }]); +}); + +test("invalid move targets are rejected before invoking the SDK", async () => { + const f = fixture(); + for (const [clientId, channelId, code] of [[1, "18446744073709551615", "CANNOT_MOVE_SELF"], [3, "18446744073709551615", "CLIENT_NOT_FOUND"], [2, "9", "CHANNEL_NOT_FOUND"]] as const) { + await f.run({ type: "moveClient", payload: { clientId, channelId }, requestId: code }); + const reply = f.messages.at(-1); + assert.ok(reply?.type === "error"); + assert.equal(reply.error?.code, code); + assert.equal(reply.requestId, code); + } + assert.deepEqual(f.calls, []); +}); + +test("channel switching preserves already-member success and authoritative password errors", async () => { + const f = fixture(); + f.context.tsClient.switchChannel = async () => { throw new Error("already member"); }; + await f.run({ type: "switchChannel", payload: { channelId: "2" }, requestId: "same" }); + assert.deepEqual(f.messages, [{ type: "channelSwitched", requestId: "same", channelId: "2" }]); + f.context.tsClient.switchChannel = async () => { throw Object.assign(new Error("generic failure"), { id: 781 }); }; + await f.run({ type: "switchChannel", payload: { channelId: "3" }, requestId: "password" }); + const failure = f.messages.at(-1); + assert.ok(failure?.type === "error"); + assert.equal(failure.error?.code, "CHANNEL_PASSWORD_REQUIRED"); + assert.equal(failure.requestId, "password"); +}); + +test("whisper transitions reject unavailable targets and deactivate when targets are cleared", async () => { + const f = fixture(); + await f.run({ type: "setWhisperActive", payload: { active: true } }); + assert.equal(f.context.whisperActive, false); + await f.run({ type: "setWhisperTargets", payload: { targetIds: [1] } }); + assert.equal(f.context.whisperTargetIds.size, 0); + await f.run({ type: "setWhisperTargets", payload: { targetIds: [2] } }); + await f.run({ type: "setWhisperActive", payload: { active: true } }); + assert.equal(f.context.whisperActive, true); + await f.run({ type: "setWhisperTargets", payload: { targetIds: [] } }); + assert.equal(f.context.whisperActive, false); + assert.deepEqual(f.messages.at(-1), { type: "whisperTargets", targetIds: [], active: false }); +}); + +test("mute state reaches the mixer only after TeamSpeak accepts the change", async () => { + const f = fixture(); + f.context.webrtc = { + getStats: createAudioFlowStats, + setMicrophoneMuted: value => { f.calls.push(["mixer-mute", value]); }, + setAccompanimentActive() {}, setMemberVolume() {}, + }; + await f.run({ type: "setMicrophoneMuted", payload: { muted: true }, requestId: "mute" }); + assert.deepEqual(f.calls, [["mute", true], ["mixer-mute", true]]); + f.context.tsClient.setInputMuted = async () => { throw Object.assign(new Error("denied"), { id: 2568 }); }; + await f.run({ type: "setMicrophoneMuted", payload: { muted: false }, requestId: "unmute" }); + assert.equal(f.calls.length, 2); + const reply = f.messages.at(-1); + assert.ok(reply?.type === "error"); + assert.equal(reply.error?.code, "PERMISSION_DENIED"); +}); + +test("chat routing uses the current channel, server scope, and private target independently", async () => { + const f = fixture(); + await f.run({ type: "sendTextMessage", payload: { message: " channel " } }); + await f.run({ type: "sendServerMessage", payload: { message: " server " } }); + await f.run({ type: "sendPrivateMessage", payload: { clientId: 2, message: " private " } }); + await f.run({ type: "sendTextMessage", payload: { message: " " }, requestId: "empty" }); + assert.deepEqual(f.calls, [["text", "channel", "channel", 5n], ["text", "server", "server"], ["text", "private", "private", 2n]]); + assert.deepEqual(f.messages.at(-1), { type: "commandCompleted", requestId: "empty" }); +}); + +test("audio probing is bounded per session and accepts the next request at the interval boundary", async () => { + const f = fixture(); + f.context.audio.ingressFrames = 8; + const request = (sequence: string): ClientCommand => ({ type: "audioStatsProbe", payload: { sequence } }); + await f.run(request("first"), 1000); + await f.run(request("early"), 1749); + await f.run(request("next"), 1750); + assert.equal(f.messages.length, 2); + assert.ok(f.messages[1]?.type === "audioStats"); + assert.equal(f.messages[1].sequence, "next"); + assert.equal(f.messages[1].stats.ingressFrames, 8); +}); diff --git a/src/server/voice-commands.ts b/src/server/voice-commands.ts new file mode 100644 index 0000000..e4a4c1d --- /dev/null +++ b/src/server/voice-commands.ts @@ -0,0 +1,197 @@ +import type { ServerMessage } from "../shared/server-messages.js"; +import type { ChannelInfo } from "../shared/voice-models.js"; +import type { ClientCommand } from "../shared/client-commands.js"; +import type { TSClient } from "./ts-client.js"; +import type { WebRtcAudioSession } from "./webrtc-audio.js"; +import { snapshotAudioStatus, type AudioStatsSource } from "./audio-stats.js"; +import { pingTeamSpeakSession } from "./network-probe.js"; +import { teamSpeakServerErrorCode } from "../errors.js"; + +/** Only the session capabilities used by control commands cross this boundary. */ +export interface VoiceCommandContext extends AudioStatsSource { + tsClient: Pick; + channelTree: ChannelInfo[]; + members: ReadonlyMap; + whisperTargetIds: Set; + whisperActive: boolean; + lastLatencyProbeAt: number; + lastAudioStatsProbeAt: number; + webrtc: Pick | null; +} + +export async function handleCommand( + entry: VoiceCommandContext, + command: ClientCommand, + sendJson: (message: ServerMessage) => void, + clock: () => number = Date.now, +): Promise { + if (command.type === "latencyProbe") { + // Keep the control-path probe for already-open older browser clients. The + // current voice status panel exclusively requests actual audio counters. + const sequence = command.payload.sequence; + const now = clock(); + if (now - entry.lastLatencyProbeAt < 150) return; + entry.lastLatencyProbeAt = now; + const result = await pingTeamSpeakSession( + (request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs), + ); + sendJson({ + type: "latencyPong", + sequence, + teamSpeakLatencyMs: result.latencyMs, + teamSpeakReachable: result.ok, + teamSpeakErrorCode: result.errorCode ?? null, + }); + return; + } + + if (command.type === "audioStatsProbe") { + const sequence = command.payload.sequence; + const now = clock(); + if (now - entry.lastAudioStatsProbeAt < 750) return; + entry.lastAudioStatsProbeAt = now; + sendJson({ + type: "audioStats", + sequence, + stats: snapshotAudioStatus(entry), + }); + return; + } + + if (command.type === "switchChannel") { + const rawId = command.payload.channelId; + const channelPassword = typeof command.payload.password === "string" ? command.payload.password : ""; + try { + await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined); + } catch (error: unknown) { + const rawMessage = error instanceof Error ? error.message : String(error); + if (/already member/i.test(rawMessage)) { + sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); + return; + } + const operation = classifyOperationError(error, "CHANNEL_SWITCH_FAILED", "频道切换失败"); + sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); + return; + } + sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); + sendJson({ type: "channelList", channels: entry.channelTree }); + return; + } + + try { + if (command.type === "moveClient") { + const clientId = command.payload.clientId; + const channelId = command.payload.channelId; + if (clientId === entry.tsClient.getClientId()) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CANNOT_MOVE_SELF", message: "不能移动自己的客户端", recoverable: false } }); + return; + } + if (!entry.members.has(clientId)) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线或当前不可见", recoverable: false } }); + return; + } + const targetExists = entry.channelTree.some((channel) => channel.id === channelId); + if (!targetExists) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_NOT_FOUND", message: "目标频道不可用", recoverable: false } }); + return; + } + // TeamSpeak evaluates i_client_move_power against the target's + // i_client_needed_move_power inside clientmove. Do not duplicate that + // policy in the gateway; forwarding the authoritative command keeps TS3 + // and TS6 permission behavior aligned. + // Moving another visible client is an administrator operation. It must + // not prompt for or depend on the target channel's join password. + await entry.tsClient.moveClient(clientId, BigInt(channelId)); + } else if (command.type === "sendTextMessage") { + const message = command.payload.message.trim(); + if (message) await entry.tsClient.sendTextMessage("channel", message, entry.tsClient.getChannelId()); + } else if (command.type === "sendServerMessage") { + const message = command.payload.message.trim(); + if (message) await entry.tsClient.sendTextMessage("server", message); + } else if (command.type === "sendPrivateMessage") { + const clientId = command.payload.clientId; + if (!entry.members.has(clientId)) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); + return; + } + const message = command.payload.message.trim(); + if (message) await entry.tsClient.sendTextMessage("private", message, BigInt(clientId)); + } else if (command.type === "poke") { + const clientId = command.payload.clientId; + if (!entry.members.has(clientId)) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); + return; + } + await entry.tsClient.poke(clientId, command.payload.message.trim()); + } else if (command.type === "setAway") { + await entry.tsClient.setAway(command.payload.away, typeof command.payload.message === "string" ? command.payload.message.trim() : ""); + } else if (command.type === "setWhisperTargets") { + const targetIds = command.payload.targetIds; + const selfId = entry.tsClient.getClientId(); + if (targetIds.some((clientId) => clientId === selfId || !entry.members.has(clientId))) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "私语目标已离线", recoverable: false } }); + return; + } + entry.whisperTargetIds = new Set(targetIds); + if (!entry.whisperTargetIds.size) entry.whisperActive = false; + sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive }); + } else if (command.type === "setWhisperActive") { + const active = command.payload.active; + if (active && !entry.whisperTargetIds.size) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "NO_WHISPER_TARGETS", message: "请先选择私语目标", recoverable: false } }); + return; + } + entry.whisperActive = active; + sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive }); + } else if (command.type === "setMicrophoneMuted") { + const muted = command.payload.muted; + await entry.tsClient.setInputMuted(muted); + entry.webrtc?.setMicrophoneMuted(muted); + } else if (command.type === "setAccompanimentActive") { + entry.webrtc?.setAccompanimentActive(command.payload.active); + } else if (command.type === "setMemberVolume") { + const clientId = command.payload.clientId; + entry.webrtc?.setMemberVolume(clientId, command.payload.volume); + } + if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId }); + } catch (error: unknown) { + const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败"); + sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); + } +} + +function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } { + const text = error instanceof Error ? error.message : String(error); + const normalized = text.toLocaleLowerCase(); + // A TeamSpeak server error id is authoritative when the SDK preserved it, so it + // is consulted before the keyword rules: 781 (channel password), 2568 + // (permissions), 515/2817 (server or slot limit) and friends keep their exact + // meaning instead of being guessed from prose. + const rawId = isRecord(error) ? (error.id ?? error.code) : undefined; + const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1]; + // Operation permissions are distinct from connection/identity failures. + // Preserve the existing 2568 mapping even when the SDK only exposes an id. + if (["2568", "0x0a08", "0a08"].includes(String(rawId ?? inlineId).trim().toLowerCase())) { + return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; + } + const serverCode = teamSpeakServerErrorCode(rawId) ?? teamSpeakServerErrorCode(inlineId); + if (serverCode) { + if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; + if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; + if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" }; + if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" }; + if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" }; + if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" }; + if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" }; + } + if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; + if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|781/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; + if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" }; + if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" }; + if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" }; + return { code: fallbackCode, message: fallbackMessage }; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +}