refactor: scope SDK events and directory state to their session

This commit is contained in:
illusia committed 2026-10-01 13:42:57 +08:00
1 parent 2047e30984
commit 878e94a93a
9 files changed
+548 -241

No files matched your search

+3
View File
@@ -11,6 +11,7 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho
| `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/member-avatars.ts` | Generation-bound optional avatar downloads, bounded sequential batches, cached images and timer cleanup |
| `src/server/session-events.ts` | Session-owned SDK subscriptions, directory projection, self/channel state, chat mapping and avatar coordination |
| `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/shared/admin-inputs.ts`, `admin-responses.ts` | Shared admin request types and runtime-checked response projections |
@@ -42,6 +43,8 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho
Channel and member data come from SDK directory snapshots and client-protocol commands, followed by realtime notifications. WebQuery and its API key are not required. `DirectorySynchronizer` reconciles snapshots with membership events.
`SessionEventCoordinator` subscribes before SDK connection and closes before waiting for peer shutdown. Remove only its own listeners and guard captured callbacks as well as registered ones. Directory events are accepted during authentication, synchronization and the live connection, but not reconnect backoff. SDK adapter listeners must reject events from a replaced client before mutating state or forwarding them. A kick remains terminal if the disconnect notification already started recovery.
Avatar downloads belong to the connected directory generation. Reset them on SDK interruption and close them before awaiting session teardown. Old success or failure results cannot refill caches, publish images, start another download, or unlock newer work. `isAlive` is only the WebSocket heartbeat acknowledgement flag; it is not a lifecycle predicate. Keep avatar failure optional, the 50-member batch limit and 250 ms continuation delay.
The SDK avatar method captures its client and connection generation across metadata, transfer initialization and download. Recheck both after each await, including reconnects that reuse the same SDK object; never continue an old transfer through a replacement `this.client`. A retired SDK client's disconnect event must not clear the current connection.
+22 -9
View File
@@ -1,17 +1,18 @@
# WebSpeak 代码待修改清单与修改方向
本文聚焦 `webspeak-webclient`,记录当前代码结构、尚未完成的改动、建议优先级及验收条件。本轮按持续目标继续施工,已修复服务端 WebRTC 关闭流程、补齐测试入口、收尾音频转发提取,并提取与修复成员头像刷新;其余事项保持在清单中。
本文聚焦 `webspeak-webclient`,记录当前代码结构、尚未完成的改动、建议优先级及验收条件。服务端音频、关闭流程及头像已有实现和验证;本批进一步提取 SDK 会话事件与目录编排,修复旧事件回流和踢出通知时序。其余事项保持在清单中。
接下来分离前端剩余媒体职责、服务端 SDK 事件及页面组件。真实 TeamSpeak 连接、Android 真机和发布包验收作为独立事项记录。已经完成的模块提取不重复列为待开发。
接下来分离前端剩余媒体职责及页面组件。真实 TeamSpeak 连接、Android 真机和发布包验收作为独立事项记录。已经完成的模块提取不重复列为待开发。
## 范围与依据
- 记录日期:2026 年 10 月 1 日。
- 提交基线:`dev` 分支,`e9b8c2b9ebfa3ecb07a0891610d3a9c78c138dcd`,应用版本 `0.2.5-preview`。
- 提交基线:`dev` 分支,`cc9714b7368aa9976fca1f4190c7463a28064464`,应用版本 `0.2.5-preview`。
- 分析对象:上述提交加当前工作区已有改动;不是干净检出的提交快照。
- 音频与清理批次 `972ee79` 的 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819043190) 已确认成功;该批本地 219 项测试及前后端构建通过。
- 头像控制器批次 `e9b8c2b` 新增 10 项回归,本地 229 项测试及构建通过,其 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819750447) 已确认成功;三项网关集成问题在修复前实际复现失败。
- 后续 SDK 下载边界新增 6 项测试,当前 `npm run verify` 通过 235 项测试、后端编译、前端类型检查及生产构建。四项下载阶段问题先复现再修复;该批提交 CI 需独立核对。
- SDK 下载边界 `cc9714b` 新增 6 项测试,本地 235 项测试及构建通过,其 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36820095236) 已确认成功。
- 当前事件协调批次新增 19 项测试,其中 13 项先复现问题再修复;`npm run verify` 通过 254 项测试、后端编译、前端类型检查和生产构建。该批 CI 需按对应提交独立核对。
- 文末保留各批历史实施与验证记录。真实 TeamSpeak、媒体设备与 Android 真机没有在本批验收,本机回环与原生 Opus 测试不能替代这些检查。
- 下文“代码可确认”指静态控制流或文件配置可直接支持的判断;“待验收”不等于已经发生故障。P1/P2/P3 表示建议实施顺序,不代表安全漏洞等级。
@@ -29,7 +30,7 @@
| 未跟踪 | `src/server/voice-bridge.integration.test.ts` | 定义 6 项本机 HTTP/WebSocket、原生 Opus 与会话清理集成测试;外部 TeamSpeak SDK 使用替身 |
| 未跟踪 | `src/server/webrtc-audio.test.ts` | 定义 2 项关闭测试,针对资源释放异常及并发关闭;尚未进入根目录测试命令 |
音频批次起始新增文件共定义 19 项测试,补充关闭失败结果共享用例后为 20 项;均已纳入 `972ee79`。后续头像控制器与 SDK 适配层分别增加 10 项及 6 项用例,当前根目录显式列出 33 个测试文件;统一验证结果见上方基线和文末实施记录。
音频批次起始新增文件共定义 19 项测试,补充关闭失败结果共享用例后为 20 项;均已纳入 `972ee79`。后续头像控制器、SDK 下载及事件协调分别增加 10、6、19 项用例,当前根目录显式列出 34 个测试文件;统一验证结果见上方基线和文末实施记录。
## 代码结构与已经建立的边界
@@ -41,6 +42,7 @@
| 服务端音频 | `session-audio.ts`、`webrtc-audio.ts`、`opus-codec.ts` | 会话音频转发、WebRTC 混音及平台编解码适配 |
| SDK 接入 | `ts-client.ts`、`teamspeak-adapter.ts`、`directory-sync.ts` | SDK 连接、目录同步、聊天、音频及实时事件 |
| 成员头像 | `src/server/member-avatars.ts` | 随连接代次失效的下载、缓存、分批调度及清理 |
| 会话事件 | `src/server/session-events.ts` | SDK 监听、目录投影、自身频道状态、聊天映射及头像协调 |
| 共享契约 | `src/shared/` | 命令、服务端消息、WebRTC、屏幕共享、皮肤及管理请求与响应模型 |
| 管理与持久化 | `src/admin/`、`src/persistence/`、`src/security/` | 登录、配置、邀请、审计、访问策略和 SQLite |
| 页面与业务状态 | `web/src/views/`、`web/src/composables/` | 加入、频道、成员、聊天、设备、管理表单及页面编排 |
@@ -64,7 +66,7 @@
| 02-B | 已完成,CI 通过 | 关闭测试曾遗漏于统一命令 | 3 项关闭测试已加入根目录入口 | 对应批次 31 个测试文件、219 项测试及完整构建通过 |
| 05-A | 已提取,CI 通过 | `SessionAudioTransport` 已接入三条音频路径 | 帧格式、路由、背压、统计及清理集中处理 | 11 项转发测试、6 项网关集成测试及全量验证通过;真实媒体另验收 |
| 04-D | P2 | `useVoiceWebSocket.ts` 约 2,129 行,伴奏、WebRTC、连接与命令仍集中 | 依次提取伴奏、WebRTC 传输、连接与命令;复用已有采集和播放模块 | 旧回调不影响新会话,断开释放资源,协商失败正确回退 |
| 05-D | P2,头像部分已完成 | `voice-bridge.ts` 约 960 行,SDK 事件与目录编排仍集中;头像请求已独立 | 接着提取事件订阅与目录更新,复用头像控制器 | 连接前注册监听,清理可解绑;快照与增量事件一致,无跨会话回填 |
| 05-D | 已提取,本地验证通过 | `SessionEventCoordinator` 拥有目录与监听;`voice-bridge.ts` 约 782 行,保留接入与连接恢复编排 | 欢迎及实时事件共用投影,头像复用已有模块;旧 SDK 来源及失效会话均拦截 | 19 项新增回归及全量构建通过;真实 SDK 媒体与平台另验收 |
| 06-C | P2 | `WebClient.vue` 约 1,211 行,`AdminView.vue` 约 400 行,模板仍集中 | 按稳定界面拆组件,继续使用现有业务 composable | 表单、路由、皮肤接口、五语与响应式布局保持一致 |
| 03 | P2 | 共享契约已落地,真实收发兼容仍需验收 | 用实际消息样本核对字段、默认值、非法输入及旧客户端兼容 | 两端解析一致;非法消息受控处理,不误丢有效事件 |
| 02-C | P2 | 本机和模拟边界测试不能证明真实媒体链路 | 建立 TeamSpeak 双向语音、WebRTC 回退及多用户场景验收步骤 | 记录服务端版本、浏览器、网络、设备、步骤和实际结果 |
@@ -105,7 +107,7 @@
## 剩余重构的大致方向
### 服务端音频草稿与 SDK 事件
### 服务端音频与 SDK 事件
[session-audio.ts](../src/server/session-audio.ts) 已拥有会话编码器,集中 PCM 入站、WebRTC 入站、TeamSpeak 下行、耳语路由及计数。`VoiceBridge` 已通过它转发三条音频路径,并在等待 WebRTC 关闭前使音频模块失效。已有草稿还调整了 SDK 构造失败的会话回收,以及 WebSocket 关闭监听保留,不能再将这些写成“尚未开始”。
@@ -115,7 +117,9 @@
SDK 适配层 `getClientAvatar` 也已绑定发起时的客户端与连接代次,在读取元数据、初始化传输及下载完成后重新校验。重连复用同一 SDK 对象仍会使旧请求失效;旧 SDK 的断线事件不能重置新客户端状态。已开始的外部下载没有增加取消 API,结果失效与阻止后续阶段分别由对应校验保证。
接着提取 SDK 事件协调:`directorySnapshot`、`clientEnter`、`clientLeave`、`clientMoved`、`clientUpdated`、聊天及断连事件仍在桥接入口。事件在连接前注册,退出时解除所属监听,异步目录结果绑定发起会话。继续复用 `DirectorySynchronizer`、`SessionManager`、头像、命令和屏幕共享模块,避免建立第二套会话状态。
`SessionEventCoordinator` 已集中目录、成员、聊天、poke、语音和原始通知的 SDK 订阅,自身标识与频道也由该模块维护。目录继续复用 `DirectorySynchronizer`,头像继续复用现有加载器。连接恢复与踢出处理仍由桥接入口编排,不另建会话状态机。
关闭时先解绑所属监听并使已捕获的回调失效,再等待 peer 关闭;重连等待阶段不接收目录快照。适配层的十类旧客户端事件在转发或更新内部状态前校验来源。踢出通知晚于断线时也会终止恢复并保留服务器原因。欢迎合并、自身频道、耳语目标、频道变化、大整数标识、聊天路由和监听归属已有回归覆盖。
### 前端媒体与连接编排
@@ -155,7 +159,8 @@ Android 需记录具体设备与系统,验证双向语音、输入输出切换
| --- | --- | --- |
| 已完成,本地通过 | 05-B、05-C、02-B:WebRTC 清理及测试入口 | 故障注入和并发关闭用例通过,统一入口实际覆盖这些测试 |
| 已完成,本地通过 | 05-A:收尾现有服务端音频草稿 | 相关单元与本机集成用例、完整验证通过 |
| 第三批 | 04-D、05-D:前端剩余媒体及服务端事件 | 一次迁移一个资源边界,沿用原接口和会话规则,补对应行为回归 |
| 已提取,本地通过 | 05-D:服务端事件与目录 | 19 项新增回归与完整验证通过,真实媒体另验收 |
| 接下来 | 04-D:前端剩余媒体 | 一次迁移一个资源边界,沿用原接口和会话规则,补对应行为回归 |
| 第四批 | 06-C、03:页面拆分及契约核对 | 表单、路由、主题、皮肤、五语及协议兼容验证通过 |
| 独立验收 | 02-C、07-A、09-A:真实媒体、Android、发布包 | 每项记录环境、步骤、结果和限制;失败后再形成具体修复任务 |
@@ -324,3 +329,11 @@ Android 需记录具体设备与系统,验证双向语音、输入输出切换
- 新增 6 项实际适配方法测试,其中 4 项先复现失败:旧元数据在替代客户端上发起传输、初始化期间断开后空引用、断开后返回已下载内容、同一 SDK 对象重用时恢复旧请求。另覆盖正常内容与 UID 校验、旧客户端断线不能干扰新请求。
- 当前统一入口包含 33 个测试文件,`npm run verify` 通过 235 项测试和前后端构建。SDK 网络边界使用替身,本批未声称实际 TeamSpeak 文件传输或媒体连接已验收。
- 剩余 SDK 目录事件提取、前端媒体与页面组件、真实服务及平台验收仍未完成,完整目标保持进行中。
### SDK 会话事件与目录实施记录
- 新增 `SessionEventCoordinator`,集中 SDK 订阅、目录与成员投影、自身频道、耳语目标收敛、频道事件、聊天及头像协调;桥接入口继续负责准入、连接恢复与传输组装。
- 先复现并修复关闭等待期间目录回填、重连等待期间旧快照污染下一连接,以及十类旧 SDK 客户端事件进入替代会话。监听按所属模块解绑,已捕获的旧回调也会被拒绝。
- 额外先复现断线通知早于踢出时继续重连的问题;现在两种到达顺序均终止会话,保留踢出错误码和服务器原因。
- 新增 19 项测试,其中 13 项先失败后通过;统一入口共 34 个测试文件,`npm run verify` 通过 254 项测试、后端编译、前端类型检查和生产构建。
- `cc9714b` 的 CI 与 Docker 检查已确认成功。本批真实服务、网络媒体、Android 真机及发布包未验收,剩余前端媒体与页面组件继续推进。
+1 -1
View File
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.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/ts-client.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/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/screen-share.test.ts web/test/android-gateway.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 web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.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/ts-client.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/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/screen-share.test.ts web/test/android-gateway.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",
+146
View File
@@ -0,0 +1,146 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { EventEmitter } from "node:events";
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
import type { ServerMessage } from "../shared/server-messages.js";
import { SessionEventCoordinator, type SessionDirectoryState } from "./session-events.js";
import type { TSDirectorySnapshot } from "./ts-client.js";
const member = (id: number, channelID = 1n): ClientInfo => ({ id, channelID, nickname: `Member ${id}`, uid: `uid-${id}`, type: 1, serverGroups: [] });
const channel = (id: bigint, name: string) => ({ id, parentID: 0n, order: 0n, name, description: "" });
const snapshot = (...clients: ClientInfo[]): TSDirectorySnapshot => ({ channels: [channel(1n, "Lobby"), channel(2n, "Room")], clients });
function fixture(t: TestContext) {
const phase = { current: true, accepting: true, published: false, connected: false, selfId: 1, channelId: 1n };
const state: SessionDirectoryState = { channelTree: [], members: new Map(), avatarCache: new Map(), whisperTargetIds: new Set(), whisperActive: false };
const messages: ServerMessage[] = [];
const events: Array<{ kind: string; message: string }> = [];
const callbacks: Array<{ kind: string; value?: unknown }> = [];
const client = Object.assign(new EventEmitter(), {
getClientId: () => phase.selfId, getChannelId: () => phase.channelId,
getClientAvatar: async () => null,
});
const coordinator = new SessionEventCoordinator({
state, client, nickname: "Self", requestedChannel: "Lobby",
isCurrent: () => phase.current, acceptsDirectory: () => phase.accepting,
isPublished: () => phase.published, isConnected: () => phase.connected,
sendJson: message => messages.push(message), addEvent: (kind, message) => events.push({ kind, message }),
onDirectoryReady: () => callbacks.push({ kind: "ready" }),
onClientLeave: id => callbacks.push({ kind: "leave", value: id }),
onClientMove: (id, channelId) => callbacks.push({ kind: "move", value: [id, channelId] }),
onNotification: value => callbacks.push({ kind: "notification", value }),
onVoice: value => callbacks.push({ kind: "voice", value }),
onKick: value => callbacks.push({ kind: "kick", value }),
onDisconnect: value => callbacks.push({ kind: "disconnect", value }),
onAvatarError: (_id, _uid, value) => callbacks.push({ kind: "avatar-error", value }),
});
t.after(() => coordinator.close());
return { phase, state, messages, events, callbacks, client, coordinator };
}
test("welcome events reconcile before publication and self follows the connected SDK channel", t => {
const f = fixture(t);
f.phase.channelId = 2n;
f.client.emit("clientLeave", { id: 2 });
f.client.emit("clientEnter", member(3));
f.client.emit("clientUpdated", { ...member(3), inputMuted: true });
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
f.coordinator.syncSelf();
assert.equal(f.coordinator.ready, true);
assert.equal(f.coordinator.selfId, 1);
assert.deepEqual([...f.state.members.keys()], [1, 3]);
assert.equal(f.state.members.get(3)?.inputMuted, true);
assert.equal(f.state.channelTree.find(item => item.id === "2")?.members?.some(item => item.id === 1), true);
assert.equal(f.messages.length, 0);
assert.equal(f.events.length, 0);
assert.equal(f.callbacks.filter(item => item.kind === "ready").length, 1);
f.phase.published = true;
f.client.emit("clientUpdated", { ...member(3), nickname: "Renamed" });
assert.equal(f.state.members.get(3)?.nickname, "Renamed");
assert.equal(f.messages.at(-1)?.type, "channelList");
});
test("live movement and departure update directory, sharing callbacks and whisper targets", t => {
const f = fixture(t);
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
f.coordinator.syncSelf(); f.phase.published = true;
for (const id of [1, 2, 99]) f.state.whisperTargetIds.add(id);
f.state.whisperActive = true;
f.client.emit("clientUpdated", { ...member(2), away: true });
assert.deepEqual([...f.state.whisperTargetIds], [2]);
assert.deepEqual(f.messages.find(message => message.type === "whisperTargets"), { type: "whisperTargets", targetIds: [2], active: true });
f.client.emit("clientMoved", { id: 2, targetChannelID: 0n });
assert.equal(f.callbacks.some(item => item.kind === "move"), false);
f.client.emit("clientMoved", { id: 2, targetChannelID: 2n });
assert.deepEqual(f.callbacks.find(item => item.kind === "move")?.value, [2, 2n]);
assert.equal(f.state.channelTree.find(item => item.id === "2")?.members?.some(item => item.id === 2), true);
f.client.emit("clientLeave", { id: 2 });
f.client.emit("clientLeave", { id: 2 });
assert.equal(f.state.members.has(2), false);
assert.equal(f.state.whisperActive, false);
assert.equal(f.state.whisperTargetIds.size, 0);
assert.equal(f.messages.filter(message => message.type === "memberLeave").length, 1);
assert.deepEqual(f.events.map(item => item.kind), ["moved", "left"]);
});
test("channel changes preserve large identifiers and publish only actual create, rename and delete events", t => {
const f = fixture(t);
f.client.emit("directorySnapshot", snapshot(member(1)));
f.coordinator.syncSelf(); f.phase.published = true;
const large = 9_007_199_254_740_993n;
f.client.emit("directorySnapshot", { channels: [channel(1n, "Renamed"), channel(large, "Large")], clients: [member(3, large)] });
assert.deepEqual(f.events.map(item => item.kind), ["moved", "joined", "left"]);
assert.equal(f.state.channelTree[1]?.id, String(large));
assert.equal(f.state.channelTree[1]?.members?.[0]?.id, 3);
assert.doesNotThrow(() => JSON.stringify(f.messages));
f.events.length = 0;
f.client.emit("directorySnapshot", { channels: [channel(1n, "Renamed"), channel(large, "Large")], clients: [] });
assert.equal(f.events.length, 0);
});
test("reset rejects backoff events and close detaches only owned listeners including captured callbacks", t => {
const f = fixture(t);
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
const captured = f.client.listeners("clientEnter")[0]!;
let externalEvents = 0;
f.client.on("clientEnter", () => externalEvents++);
f.state.avatarCache.set("uid-2", "cached");
f.coordinator.reset(); f.phase.accepting = false;
f.client.emit("directorySnapshot", snapshot(member(9)));
assert.equal(f.coordinator.ready, false);
assert.equal(f.state.members.size, 0);
assert.equal(f.state.avatarCache.size, 0);
f.phase.accepting = true;
f.client.emit("directorySnapshot", snapshot(member(1)));
assert.equal(f.state.members.has(9), false);
f.coordinator.close(); f.coordinator.close();
f.client.emit("clientEnter", member(10));
captured(member(11));
assert.equal(f.state.members.size, 0);
assert.equal(f.client.listenerCount("clientEnter"), 1);
assert.equal(externalEvents, 1);
assert.equal(f.client.listenerCount("directorySnapshot"), 0);
});
test("chat routing, poke and forwarded SDK events retain their payloads and stop with the session", t => {
const f = fixture(t);
const chat = { invokerName: "Speaker", invokerId: 2, invokerUid: "uid-2", message: "Hello" };
f.client.emit("textMessage", { ...chat, targetMode: 2, targetId: 0n });
f.phase.channelId = 2n;
f.client.emit("textMessage", { ...chat, targetMode: 1, targetId: 9_007_199_254_740_993n });
f.client.emit("textMessage", { ...chat, targetMode: 3, targetId: 0n });
const routed = f.messages.filter(message => message.type === "chatMessage");
assert.deepEqual(routed.map(message => [message.scope, message.targetId]), [["channel", "1"], ["private", "9007199254740993"], ["server", undefined]]);
f.client.emit("poked", { invokerID: 2, invokerUID: "uid-2", invokerName: "Speaker", message: "Wake up" });
const voice = { clientId: 2, codec: 4, data: Buffer.from([1]) };
const notification = { name: "stream", params: { id: "a" } };
f.client.emit("voiceData", voice); f.client.emit("rawNotification", notification); f.client.emit("disconnected");
assert.equal(f.events.at(-1)?.kind, "poke");
assert.equal(f.callbacks.find(item => item.kind === "voice")?.value, voice);
assert.equal(f.callbacks.find(item => item.kind === "notification")?.value, notification);
f.phase.current = false;
f.client.emit("textMessage", { ...chat, targetMode: 2 });
f.client.emit("poked", {}); f.client.emit("voiceData", voice); f.client.emit("rawNotification", notification); f.client.emit("disconnected");
assert.equal(f.messages.length, 4);
assert.equal(f.callbacks.length, 3);
});
+237
View File
@@ -0,0 +1,237 @@
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
import type { EventEmitter } from "node:events";
import type { WebSpeakError } from "../errors.js";
import type { ChannelInfo, ChannelMember } from "../shared/voice-models.js";
import type { ServerMessage } from "../shared/server-messages.js";
import { DirectorySynchronizer } from "./directory-sync.js";
import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js";
import { MemberAvatarLoader } from "./member-avatars.js";
import type { TSClient, TSChatMessage, TSDirectoryClient, TSDirectorySnapshot, TSRawNotification, TSVoiceData } from "./ts-client.js";
export interface SessionDirectoryState {
channelTree: ChannelInfo[];
members: Map<number, ChannelMember & { uid: string }>;
avatarCache: Map<string, string | null>;
whisperTargetIds: Set<number>;
whisperActive: boolean;
}
interface SdkEvents {
directorySnapshot: TSDirectorySnapshot;
clientEnter: ClientInfo;
clientLeave: { id: number };
clientMoved: { id: number; targetChannelID?: bigint };
clientUpdated: TSDirectoryClient;
rawNotification: TSRawNotification;
voiceData: TSVoiceData;
textMessage: TSChatMessage;
poked: { invokerID: number; invokerUID: string; invokerName: string; message: string };
kicked: WebSpeakError;
disconnected: Error | undefined;
}
export interface SessionEventOptions {
state: SessionDirectoryState;
client: Pick<TSClient, "getClientId" | "getChannelId" | "getClientAvatar"> & Pick<EventEmitter, "on" | "off">;
nickname: string;
requestedChannel?: string;
isCurrent(): boolean;
acceptsDirectory(): boolean;
isPublished(): boolean;
isConnected(): boolean;
sendJson(message: ServerMessage): void;
addEvent(kind: "joined" | "left" | "moved" | "poke", message: string): void;
onDirectoryReady(): void;
onClientLeave(id: number): void;
onClientMove(id: number, channelId: bigint): void;
onNotification(notification: TSRawNotification): void;
onVoice(data: TSVoiceData): void;
onKick(error: WebSpeakError): void;
onDisconnect(error?: Error): void;
onAvatarError(id: number, uid: string, error: unknown): void;
}
/** SDK listeners, directory projection and optional work owned by one session. */
export class SessionEventCoordinator {
private readonly directory = new DirectorySynchronizer();
private readonly avatars: MemberAvatarLoader;
private readonly subscriptions: Array<() => void> = [];
private closed = false;
private clientId = 0;
private channelId = 0n;
constructor(private readonly options: SessionEventOptions) {
const { state, client } = options;
this.avatars = new MemberAvatarLoader({
members: state.members, cache: state.avatarCache,
isCurrent: () => this.isCurrent() && options.isConnected(),
load: (id, uid) => client.getClientAvatar(id, uid),
publish: (id, uid, avatar) => options.sendJson({ type: "memberAvatar", id, uid, avatar }),
onError: options.onAvatarError,
});
// Subscribe before connect(): welcome events may precede the first snapshot.
this.listenDirectory("directorySnapshot", snapshot => {
const previousChannels = state.channelTree;
this.directory.applySnapshot(snapshot);
this.refresh();
this.trackChannelEvents(previousChannels);
options.onDirectoryReady();
this.publishDirectory();
this.avatars.schedule();
});
this.listenDirectory("clientEnter", info => {
const candidateSelfId = client.getClientId();
if (candidateSelfId > 0 && info.id === candidateSelfId) {
this.clientId = candidateSelfId;
if (info.channelID !== undefined && info.channelID !== 0n) this.channelId = info.channelID;
}
const wasKnown = state.members.has(info.id);
this.directory.applyClientEnter(info);
this.refresh();
if (options.isPublished()) {
this.publishDirectory();
if (!wasKnown) options.sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === this.clientId });
if (!wasKnown && info.id !== this.clientId) options.addEvent("joined", `${info.nickname || "未知用户"} 加入了服务器`);
this.avatars.schedule();
}
});
this.listenDirectory("clientLeave", info => {
options.onClientLeave(info.id);
const member = state.members.get(info.id);
this.directory.applyClientLeave(info.id);
this.refresh();
if (options.isPublished() && member) {
options.sendJson({ type: "memberLeave", id: info.id });
this.publishDirectory();
if (info.id !== this.clientId) options.addEvent("left", `${member.nickname || "用户"} 离开了服务器`);
}
});
this.listenDirectory("clientMoved", info => {
if (info.targetChannelID === undefined || info.targetChannelID === 0n) return;
options.onClientMove(info.id, info.targetChannelID);
const member = state.members.get(info.id);
if (info.id === this.clientId) this.channelId = info.targetChannelID;
this.directory.applyClientMoved(info.id, info.targetChannelID);
this.refresh();
if (options.isPublished()) {
this.publishDirectory();
if (info.id !== this.clientId) options.addEvent("moved", `${member?.nickname || "用户"} 移动到了其他频道`);
}
});
this.listenDirectory("clientUpdated", info => {
this.directory.applyClientUpdated(info);
this.refresh();
this.publishDirectory();
});
this.listen("rawNotification", options.onNotification);
this.listen("voiceData", options.onVoice);
this.listen("textMessage", message => {
const scope = message.targetMode === 1 ? "private" : message.targetMode === 2 ? "channel" : "server";
const targetId = message.targetId ?? 0n;
// Channel notifications can omit target; bind them to the current channel.
const effectiveTargetId = scope === "channel" && targetId === 0n ? client.getChannelId() : targetId;
options.sendJson({ type: "chatMessage", scope,
...(effectiveTargetId !== 0n ? { targetId: String(effectiveTargetId) } : {}),
senderUid: message.invokerUid, timestamp: Date.now(), invokerName: message.invokerName,
invokerId: message.invokerId, message: message.message,
});
});
this.listen("poked", event => {
options.sendJson({ type: "pokeReceived", invokerId: event.invokerID, invokerUid: event.invokerUID, invokerName: event.invokerName, message: event.message, timestamp: Date.now() });
options.addEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
});
this.listen("kicked", options.onKick);
this.listen("disconnected", options.onDisconnect);
}
get ready(): boolean { return this.directory.ready; }
get selfId(): number { return this.clientId; }
private isCurrent(): boolean { return !this.closed && this.options.isCurrent(); }
private listen<K extends keyof SdkEvents>(name: K, handler: (data: SdkEvents[K]) => void): void {
const listener = (data: SdkEvents[K]) => { if (this.isCurrent()) handler(data); };
this.options.client.on(name, listener);
this.subscriptions.push(() => this.options.client.off(name, listener));
}
private listenDirectory<K extends keyof SdkEvents>(name: K, handler: (data: SdkEvents[K]) => void): void {
this.listen(name, data => { if (this.options.acceptsDirectory()) handler(data); });
}
syncSelf(): void {
if (!this.isCurrent()) return;
this.clientId = this.options.client.getClientId();
const channelId = this.options.client.getChannelId();
if (channelId !== 0n) this.channelId = channelId;
this.refresh();
if (this.clientId > 0 && !this.options.state.members.has(this.clientId)) {
this.directory.applyClientEnter({ id: this.clientId, nickname: this.options.nickname, channelID: this.channelId, uid: "", type: 1, serverGroups: [] });
this.refresh();
}
}
scheduleAvatars(): void { this.avatars.schedule(); }
private refresh(): void {
const snapshot = this.directory.getSnapshot();
if (!snapshot) return;
const { state, client } = this.options;
const previousTargets = [...state.whisperTargetIds].sort((a, b) => a - b);
const selfId = this.clientId || client.getClientId();
const sdkChannelId = client.getChannelId();
if (this.channelId === 0n && sdkChannelId !== 0n) this.channelId = sdkChannelId;
const normalized = normalizeDirectorySnapshot(snapshot, selfId, this.channelId, this.options.nickname, this.options.requestedChannel);
state.channelTree = mapChannelTree(normalized, state.avatarCache);
state.members.clear();
for (const member of normalized.clients) {
const avatar = member.uid ? state.avatarCache.get(member.uid) : undefined;
state.members.set(member.id, { id: member.id, nickname: member.nickname, uid: member.uid,
...(avatar ? { avatar } : {}), away: member.away, awayMessage: member.awayMessage,
inputMuted: member.inputMuted, outputMuted: member.outputMuted, channelCommander: member.channelCommander,
});
}
for (const id of state.whisperTargetIds) {
if (!state.members.has(id) || id === selfId) state.whisperTargetIds.delete(id);
}
if (!state.whisperTargetIds.size) state.whisperActive = false;
const nextTargets = [...state.whisperTargetIds].sort((a, b) => a - b);
if (this.options.isPublished() && (previousTargets.length !== nextTargets.length || previousTargets.some((id, index) => id !== nextTargets[index]))) {
this.options.sendJson({ type: "whisperTargets", targetIds: nextTargets, active: state.whisperActive });
}
}
private publishDirectory(): void {
if (this.options.isPublished()) this.options.sendJson({ type: "channelList", channels: this.options.state.channelTree });
}
private trackChannelEvents(previous: ChannelInfo[]): void {
if (!this.options.isPublished()) return;
const before = new Map(previous.map(channel => [channel.id, channel]));
const after = new Map(this.options.state.channelTree.map(channel => [channel.id, channel]));
for (const channel of after.values()) {
if (!before.has(channel.id)) this.options.addEvent("joined", `频道「${channel.name}」已创建`);
else if (before.get(channel.id)?.name !== channel.name) this.options.addEvent("moved", `频道已重命名为「${channel.name}」`);
}
for (const channel of before.values()) if (!after.has(channel.id)) this.options.addEvent("left", `频道「${channel.name}」已删除`);
}
reset(): void {
this.avatars.reset();
this.clientId = 0;
this.channelId = 0n;
this.directory.clear();
this.options.state.channelTree = [];
this.options.state.members.clear();
this.options.state.whisperTargetIds.clear();
this.options.state.whisperActive = false;
}
close(): void {
if (this.closed) return;
this.closed = true;
for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
this.avatars.close();
this.reset();
}
}
+28
View File
@@ -108,3 +108,31 @@ test("a retired SDK client's disconnect cannot invalidate a current avatar reque
assert.deepEqual(await result, { cacheKey: "marker", data: Buffer.from("GIF89a") });
assert.equal(replacement.downloaded, 1);
});
const retiredEvents: Array<[string, unknown]> = [
["voiceData", { clientId: 2, codec: 4, data: Buffer.from([1]) }],
["directorySnapshot", { channels: [], clients: [] }],
["rawNotification", { name: "notification", params: {} }],
["textMessage", { invokerName: "Member", invokerID: 2, invokerUID: "uid", targetMode: 2, targetID: 1n, message: "Message" }],
["poked", { invokerName: "Member", invokerID: 2, invokerUID: "uid", message: "Poke" }],
["clientEnter", { id: 2, nickname: "Member", uid: "uid", channelID: 1n, type: 1, serverGroups: [] }],
["clientLeave", { id: 2, reasonID: 4 }],
["clientMoved", { id: 2, targetChannelID: 2n }],
["clientUpdated", { info: { id: 2, inputMuted: true } }],
["kicked", "Removed"],
];
for (const [name, payload] of retiredEvents) {
test(`a retired SDK client's ${name} event cannot reach its replacement session`, () => {
const f = fixture();
const replacement = new SdkStub();
f.state.client = replacement;
f.state.attachClientListeners(replacement);
const observed: unknown[] = [];
f.client.on(name, data => observed.push(data));
f.sdk.emit(name, payload);
assert.equal(observed.length, 0);
replacement.emit(name, payload);
assert.equal(observed.length, 1);
});
}
+10
View File
@@ -236,6 +236,7 @@ export class TSClient extends EventEmitter {
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
if (this.client !== client) return;
this.emit("voiceData", {
clientId: data.clientId,
codec: data.codec,
@@ -247,6 +248,7 @@ export class TSClient extends EventEmitter {
// client welcome sequence. The connect path also reconciles this event
// stream with a complete client-protocol snapshot.
client.on("directorySnapshot", (snapshot) => {
if (this.client !== client) return;
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
clients: snapshot.clients.slice(),
@@ -254,6 +256,7 @@ export class TSClient extends EventEmitter {
});
client.on("rawNotification", (notification: RawNotification) => {
if (this.client !== client) return;
this.emit("rawNotification", {
name: notification.name,
params: { ...notification.params },
@@ -261,10 +264,12 @@ export class TSClient extends EventEmitter {
});
client.on("textMessage", (msg) => {
if (this.client !== client) return;
this.emit("textMessage", toTSChatMessage(msg));
});
client.on("poked", (event) => {
if (this.client !== client) return;
this.emit("poked", event);
});
@@ -286,10 +291,12 @@ export class TSClient extends EventEmitter {
});
client.on("clientEnter", (info) => {
if (this.client !== client) return;
this.emit("clientEnter", info);
});
client.on("clientLeave", (info) => {
if (this.client !== client) return;
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
this.emit("clientLeave", info);
@@ -302,17 +309,20 @@ export class TSClient extends EventEmitter {
// this listener the reason was dropped, so the browser degraded to a generic
// "connection failed" right after the transport went away.
client.on("kicked", (reasonMsg) => {
if (this.client !== client) return;
const reasonId = this.selfLeaveReasonId;
this.selfLeaveReasonId = null;
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
});
client.on("clientMoved", (info) => {
if (this.client !== client) return;
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
this.emit("clientMoved", info);
});
client.on("clientUpdated", (event) => {
if (this.client !== client) return;
this.emit("clientUpdated", event.info);
});
}
@@ -8,6 +8,7 @@ import pino from "pino";
import { VoiceBridge } from "./voice-bridge.js";
import { JoinTicketStore } from "./join-ticket.js";
import { OpusEncoder } from "./opus-codec.js";
import { normalizeTeamSpeakKickedReason } from "../errors.js";
import type { TSClient, TSClientAvatar, TSDirectorySnapshot } from "./ts-client.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { WebRtcAudioSession } from "./webrtc-audio.js";
@@ -67,6 +68,7 @@ async function fixture(t: TestContext, overrides: {
const entries = (bridge as unknown as { entries: Map<string, {
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
isAlive: boolean; avatarCache: Map<string, string | null>;
members: Map<number, { id: number; uid: string }>; eventLog: unknown[];
}> }).entries;
return { bridge, sdk, socket, messages, entries, wss };
}
@@ -191,3 +193,49 @@ test("an interrupted SDK connection invalidates its pending avatar results", { t
assert.equal(f.entry.avatarCache.size, 0);
assert.deepEqual(f.calls, [2]);
});
test("late directory callbacks cannot refill a session while its peer is closing", { timeout: 5_000 }, async t => {
const f = await fixture(t);
const entry = [...f.entries.values()][0]!;
const onEnter = f.sdk.listeners("clientEnter")[0]!;
let release!: () => void;
const pending = new Promise<void>(resolve => { release = resolve; });
entry.webrtc = { close: () => pending, getStats: () => ({}) } as unknown as WebRtcAudioSession;
const closing = f.bridge.terminateSession(entry.id);
try {
onEnter({ id: 9, uid: "", nickname: "Late", channelID: 1n, type: 1, serverGroups: [] });
assert.equal(entry.members.has(9), false);
} finally {
release();
await closing;
}
});
test("directory snapshots during reconnect backoff cannot leak members into the next connection", { timeout: 5_000 }, async t => {
const f = await fixture(t);
const entry = [...f.entries.values()][0]!;
const reconnected = new Promise<void>(resolve => {
f.socket.on("message", (data, binary) => { if (!binary && JSON.parse(data.toString()).type === "reconnected") resolve(); });
});
f.sdk.emit("disconnected");
f.sdk.emit("directorySnapshot", { channels: [], clients: [{ id: 9, uid: "", nickname: "Stale", channelID: 1n, type: 1, serverGroups: [] }] });
await reconnected;
assert.equal(entry.members.has(9), false);
});
for (const order of ["kick-first", "disconnect-first"] as const) {
test(`a kick remains terminal when notifications arrive ${order}`, { timeout: 5_000 }, async t => {
const f = await fixture(t);
const kick = normalizeTeamSpeakKickedReason("Removed by operator", 4);
if (order === "disconnect-first") f.sdk.emit("disconnected");
f.sdk.emit("kicked", kick);
if (order === "kick-first") f.sdk.emit("disconnected");
await nextTurn();
assert.equal(f.bridge.getActiveCount(), 0);
if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close");
const failures = f.messages.filter(message => !message.binary).map(message => JSON.parse(message.data.toString())).filter(message => message.type === "connectionFailed");
assert.equal(failures.length, 1);
assert.equal(failures[0].code, "KICKED");
assert.match(failures[0].detail, /Removed by operator/);
});
}
+53 -231
View File
@@ -1,23 +1,20 @@
import { SessionAudioTransport } from "./session-audio.js";
import { MemberAvatarLoader } from "./member-avatars.js";
import { SessionEventCoordinator, type SessionDirectoryState } from "./session-events.js";
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 } from "./directory-view.js";
import type { ServerMessage } from "../shared/server-messages.js";
import { parseWebRtcClientMessage } from "../shared/webrtc.js";
import type { ChannelInfo } from "../shared/voice-models.js";
import type { ChannelMember as SharedChannelMember, ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { randomUUID } from "node:crypto";
import { isIP } from "node:net";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { DirectorySynchronizer } from "./directory-sync.js";
import { TSClient, type TSClientOptions, type TSDirectorySnapshot, type TSVoiceData, type TSRawNotification } from "./ts-client.js";
import { TSClient, type TSClientOptions } from "./ts-client.js";
import type { Logger as LoggerType } from "../logger.js";
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, type WebSpeakError } from "../errors.js";
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError } 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";
@@ -64,10 +61,9 @@ export interface AdminSessionSummary {
audio: AudioFlowStats;
}
type ChannelMember = SharedChannelMember & { uid: string };
type ServerEvent = SharedServerEvent & { kind: "joined" | "left" | "moved" | "poke" | "connection" };
interface WebClientEntry {
interface WebClientEntry extends SessionDirectoryState {
id: string;
session: ManagedSession;
tsClient: TSClient;
@@ -80,14 +76,9 @@ interface WebClientEntry {
acceleration?: AccelerationRelayOptions;
identityLeaseKey?: string;
webrtcPublicHost?: string;
channelTree: ChannelInfo[];
members: Map<number, ChannelMember>;
avatarCache: Map<string, string | null>;
avatarLoader: MemberAvatarLoader | null;
events: SessionEventCoordinator | null;
eventLog: ServerEvent[];
audioTransport: SessionAudioTransport | null;
whisperTargetIds: Set<number>;
whisperActive: boolean;
isAlive: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | null;
audio: AudioFlowStats;
@@ -214,7 +205,7 @@ export class VoiceBridge {
channelTree: [],
members: new Map(),
avatarCache: new Map(),
avatarLoader: null,
events: null,
eventLog: [],
audioTransport: null,
whisperTargetIds: new Set(),
@@ -230,7 +221,6 @@ export class VoiceBridge {
};
this.entries.set(entryId, entry!);
let tsReady = false;
let selfId = 0;
const sendJson = (message: ServerMessage) => {
if (this.entries.get(entryId) === entry && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
};
@@ -239,7 +229,7 @@ export class VoiceBridge {
audio: entry.audio, socket: ws, client: tsClient,
isCurrent: () => this.entries.get(entryId) === entry,
isReady: () => tsReady && session.state === "connected",
selfId: () => selfId,
selfId: () => entry!.events?.selfId ?? 0,
peer: () => entry!.webrtc,
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
sendJson: message => sendJson(message),
@@ -250,30 +240,10 @@ export class VoiceBridge {
return;
}
let selfChannelId = 0n;
let initialStateSent = false;
let audioReady = true;
let realtimeReady = false;
let hasConnectedOnce = false;
// Set when the server kicks or bans this client. The kick and the transport
// drop can arrive in either order, so the reason is parked here and consumed
// by whichever handler runs second.
let pendingKickReason: WebSpeakError | null = null;
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const directory = new DirectorySynchronizer();
const avatarLoader = new MemberAvatarLoader({
members: entry.members,
cache: entry.avatarCache,
isCurrent: () => this.entries.get(entryId) === entry && tsReady && session.state === "connected",
load: (id, uid) => tsClient.getClientAvatar(id, uid),
publish: (id, uid, avatar) => sendJson({ type: "memberAvatar", id, uid, avatar }),
onError: (clientId, uid, error) => this.logger.debug({
entryId, clientId, uid, err: error instanceof Error ? error.message : String(error),
}, "TeamSpeak client avatar unavailable"),
});
entry.avatarLoader = avatarLoader;
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
const event: ServerEvent = {
id: `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
@@ -285,56 +255,11 @@ export class VoiceBridge {
if (entry!.eventLog.length > 200) entry!.eventLog.splice(0, entry!.eventLog.length - 200);
if (initialStateSent) sendJson({ type: "serverEvent", event });
};
const refreshDirectory = () => {
const snapshot = directory.getSnapshot();
if (!snapshot) return;
const previousWhisperTargets = [...entry!.whisperTargetIds].sort((a, b) => a - b);
const effectiveSelfId = selfId || tsClient.getClientId();
const sdkChannelId = tsClient.getChannelId();
if (selfChannelId === 0n && sdkChannelId !== 0n) selfChannelId = sdkChannelId;
const normalizedSnapshot = normalizeDirectorySnapshot(snapshot, effectiveSelfId, selfChannelId, nickname, channelName);
entry!.channelTree = mapChannelTree(normalizedSnapshot, entry!.avatarCache);
entry!.members.clear();
for (const client of normalizedSnapshot.clients) {
const avatar = client.uid ? entry!.avatarCache.get(client.uid) : undefined;
entry!.members.set(client.id, {
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,
});
}
for (const clientId of entry!.whisperTargetIds) {
if (!entry!.members.has(clientId) || clientId === effectiveSelfId) entry!.whisperTargetIds.delete(clientId);
}
if (!entry!.whisperTargetIds.size) entry!.whisperActive = false;
const nextWhisperTargets = [...entry!.whisperTargetIds].sort((a, b) => a - b);
if (initialStateSent && (previousWhisperTargets.length !== nextWhisperTargets.length || previousWhisperTargets.some((clientId, index) => clientId !== nextWhisperTargets[index]))) {
sendJson({ type: "whisperTargets", targetIds: nextWhisperTargets, active: entry!.whisperActive });
}
};
const trackChannelEvents = (previous: unknown[], next: unknown[]) => {
if (!initialStateSent) return;
const before = new Map(previous.filter(isChannelRecord).map((channel) => [channel.id, channel]));
const after = new Map(next.filter(isChannelRecord).map((channel) => [channel.id, channel]));
for (const channel of after.values()) {
if (!before.has(channel.id)) addServerEvent("joined", `频道「${channel.name}」已创建`);
else if (before.get(channel.id)?.name !== channel.name) addServerEvent("moved", `频道已重命名为「${channel.name}」`);
}
for (const channel of before.values()) if (!after.has(channel.id)) addServerEvent("left", `频道「${channel.name}」已删除`);
};
const sendInitialState = () => {
if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return;
if (initialStateSent || !tsReady || !events.ready || session.state !== "syncing") return;
initialStateSent = true;
const wasReconnecting = hasConnectedOnce;
hasConnectedOnce = true;
// A previous kick reason never applies to a fresh, successful session.
pendingKickReason = null;
reconnectAttempt = 0;
reconnectStartedAt = 0;
if (!wasReconnecting) {
@@ -350,7 +275,7 @@ export class VoiceBridge {
session.transition("connected");
sendJson({
type: "connected",
tsClientId: selfId,
tsClientId: events.selfId,
members: Array.from(entry!.members.values()),
serverEventLog: entry!.eventLog,
whisperTargetIds: [...entry!.whisperTargetIds],
@@ -362,21 +287,14 @@ export class VoiceBridge {
});
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
avatarLoader.schedule();
events.scheduleAvatars();
};
const resetDirectoryForReconnect = () => {
tsReady = false;
avatarLoader.reset();
events.reset();
void this.stopWebRtc(entry!);
initialStateSent = false;
selfId = 0;
selfChannelId = 0n;
directory.clear();
entry!.channelTree = [];
entry!.members.clear();
entry!.whisperTargetIds.clear();
entry!.whisperActive = false;
};
const failReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
@@ -433,14 +351,7 @@ export class VoiceBridge {
if (session.state !== "authenticating") return;
session.transition("syncing");
tsReady = true;
selfId = tsClient.getClientId();
const sdkChannelId = tsClient.getChannelId();
if (sdkChannelId !== 0n) selfChannelId = sdkChannelId;
refreshDirectory();
if (selfId > 0 && !entry!.members.has(selfId)) {
directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] });
refreshDirectory();
}
events.syncSelf();
sendInitialState();
void this.screenShares.discoverExistingStreams(entry!);
} catch (error: unknown) {
@@ -480,129 +391,45 @@ export class VoiceBridge {
}
};
// Register every directory listener before connect(). Events emitted by
// the welcome flow are queued by DirectorySynchronizer until its
// snapshot establishes the baseline.
realtimeReady = true;
tsClient.on("directorySnapshot", (snapshot: TSDirectorySnapshot) => {
const previousChannels = entry!.channelTree;
directory.applySnapshot(snapshot);
refreshDirectory();
trackChannelEvents(previousChannels, entry!.channelTree);
sendInitialState();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
avatarLoader.schedule();
});
tsClient.on("clientEnter", (info) => {
const candidateSelfId = tsClient.getClientId();
if (candidateSelfId > 0 && info.id === candidateSelfId) {
selfId = candidateSelfId;
if (info.channelID !== undefined && info.channelID !== 0n) selfChannelId = info.channelID;
}
const wasKnown = entry!.members.has(info.id);
directory.applyClientEnter(info);
refreshDirectory();
if (tsReady && initialStateSent) {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (!wasKnown) sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === selfId });
if (!wasKnown && info.id !== selfId) addServerEvent("joined", `${info.nickname || "未知用户"} 加入了服务器`);
avatarLoader.schedule();
}
});
tsClient.on("clientLeave", (info) => {
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);
directory.applyClientLeave(info.id);
refreshDirectory();
if (tsReady && initialStateSent && wasKnown) {
sendJson({ type: "memberLeave", id: info.id });
sendJson({ type: "channelList", channels: entry!.channelTree });
if (info.id !== selfId) addServerEvent("left", `${leavingMember?.nickname || "用户"} 离开了服务器`);
}
});
tsClient.on("clientMoved", (info) => {
if (info.targetChannelID === undefined || info.targetChannelID === 0n) return;
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);
refreshDirectory();
if (tsReady && initialStateSent) {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (info.id !== selfId) addServerEvent("moved", `${movedMember?.nickname || "用户"} 移动到了其他频道`);
}
});
tsClient.on("clientUpdated", (info) => {
directory.applyClientUpdated(info);
refreshDirectory();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
});
tsClient.on("rawNotification", (notification: TSRawNotification) => {
this.screenShares.handleNotification(entry!, notification);
});
tsClient.on("voiceData", (data: TSVoiceData) => entry!.audioTransport?.receiveTeamSpeak(data));
tsClient.on("textMessage", (message) => {
const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server";
const targetId = message.targetId ?? 0n;
// TeamSpeak channel notifications omit `target`; the SDK represents
// that as 0. Bind the broadcast to this session's current channel so
// it remains visible now but cannot leak into another channel after a
// later channel switch.
const effectiveTargetId = scope === "channel" && targetId === 0n ? tsClient.getChannelId() : targetId;
sendJson({
type: "chatMessage",
scope,
...(effectiveTargetId !== 0n ? { targetId: String(effectiveTargetId) } : {}),
senderUid: message.invokerUid,
timestamp: Date.now(),
invokerName: message.invokerName,
invokerId: message.invokerId,
message: message.message,
});
});
tsClient.on("poked", (event) => {
sendJson({ type: "pokeReceived", invokerId: event.invokerID, invokerUid: event.invokerUID, invokerName: event.invokerName, message: event.message, timestamp: Date.now() });
addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
});
// 被踢/封禁对本会话是终态:把服务器给出的原因回放给浏览器并拆除会话,
// 而不是像以前那样因原因被丢弃而反复重连、再次撞上同一踢出。
// A kick or ban is terminal for this session: replay the reason the server
// sent instead of reconnecting, which is what used to happen once the reason
// message was dropped (the browser kept retrying straight into the kick).
tsClient.on("kicked", (kick: WebSpeakError) => {
if (!hasConnectedOnce || session.state !== "connected") return;
pendingKickReason = kick;
resetDirectoryForReconnect();
const failureCode = clientConnectionFailureCode(kick, serverPassword);
const failureDetail = publicFailureDetail(kick);
entry!.connectionFailureCode = failureCode;
this.logger.warn({ entryId, code: failureCode, normalizedCode: kick.code, failureDetail: describeTeamSpeakError(kick) }, "TeamSpeak session ended by kick/ban");
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
void this.teardown(entryId, "teamSpeak-kicked");
});
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.
const normalized = pendingKickReason ?? (error ? normalizeTeamSpeakError(error) : null);
pendingKickReason = null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
const events = new SessionEventCoordinator({
state: entry, client: tsClient, nickname, requestedChannel: channelName,
isCurrent: () => this.entries.get(entryId) === entry && session.state !== "disconnecting" && session.state !== "idle" && session.state !== "failed",
acceptsDirectory: () => session.state === "authenticating" || session.state === "syncing" || session.state === "connected",
isPublished: () => tsReady && initialStateSent,
isConnected: () => tsReady && session.state === "connected",
sendJson, addEvent: addServerEvent, onDirectoryReady: sendInitialState,
onClientLeave: id => {
this.screenShares.onClientLeave(entry!, id);
entry!.webrtc?.setMemberVolume(id, 1);
},
onClientMove: (id, channelId) => this.screenShares.onClientMove(entry!, id, channelId),
onNotification: notification => this.screenShares.handleNotification(entry!, notification),
onVoice: data => entry!.audioTransport?.receiveTeamSpeak(data),
onAvatarError: (clientId, uid, error) => this.logger.debug({
entryId, clientId, uid, err: error instanceof Error ? error.message : String(error),
}, "TeamSpeak client avatar unavailable"),
onKick: kick => {
// A transport drop may arrive first and already start recovery. A
// subsequent kick is still terminal and must cancel that recovery.
if (!hasConnectedOnce) return;
resetDirectoryForReconnect();
const failureCode = clientConnectionFailureCode(kick, serverPassword);
const failureDetail = publicFailureDetail(kick);
entry!.connectionFailureCode = failureCode;
this.logger.warn({ entryId, code: failureCode, normalizedCode: kick.code, failureDetail: describeTeamSpeakError(kick) }, "TeamSpeak session ended by kick/ban");
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
void this.teardown(entryId, "teamSpeak-kicked");
},
onDisconnect: error => {
if (!hasConnectedOnce || session.state !== "connected") return;
this.screenShares.removePeer(entryId);
resetDirectoryForReconnect();
const normalized = error ? normalizeTeamSpeakError(error) : null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
},
});
entry.events = events;
ws.on("pong", () => { if (entry) entry.isAlive = true; });
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
@@ -750,8 +577,8 @@ export class VoiceBridge {
private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise<void> {
this.screenShares.removePeer(entry.id);
if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id);
entry.avatarLoader?.close();
entry.avatarLoader = null;
entry.events?.close();
entry.events = null;
if (entry.reconnectTimer) {
clearTimeout(entry.reconnectTimer);
entry.reconnectTimer = null;
@@ -763,7 +590,6 @@ export class VoiceBridge {
entry.whisperActive = false;
entry.channelTree = [];
entry.members.clear();
entry.tsClient.removeAllListeners();
try { await entry.tsClient.disconnect(); } catch { /* disconnect is intentionally idempotent */ }
// Preserve WebSocketServer's close listener, which removes this socket
// from its clients set and allows server shutdown to finish.
@@ -954,7 +780,3 @@ function normalizeWebRtcHost(value: string | undefined): string | undefined {
function sendProtocolError(sendJson: (message: ServerMessage) => void, code: string, message: string): void {
sendJson({ type: "error", error: { code, message, recoverable: false } });
}
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";
}