mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
refactor: scope SDK events and directory state to their session
This commit is contained in:
1 parent
2047e30984
commit
878e94a93a
9 files changed
+548
-241
No files matched your search
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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
@@ -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";
|
||||
}
|
||||
Reference in new issue
Block a user