mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
refactor: isolate gateway commands and screen-sharing coordination
This commit is contained in:
1 parent
f4cbd61cff
commit
8960189bc7
12 files changed
+1533
-1067
No files matched your search
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createAudioFlowStats, snapshotAudioStats, snapshotAudioStatus } from "./audio-stats.js";
|
||||
import type { WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
test("diagnostic snapshots remain stable while new traffic changes live counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.egressFramesByClient[2] = 3;
|
||||
const snapshot = snapshotAudioStats({ audio, webrtc: null });
|
||||
audio.egressFramesByClient[2]++;
|
||||
assert.equal(snapshot.egressFramesByClient[2], 3);
|
||||
snapshot.egressFramesByClient[2] = 10;
|
||||
assert.equal(audio.egressFramesByClient[2], 4);
|
||||
});
|
||||
|
||||
test("public audio status includes live WebRTC counters without losing gateway counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.ingressFrames = 12;
|
||||
const rtc: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 7, webrtcIngressRtpFirstAt: 100, webrtcIngressRtpLastAt: 220, webrtcIngressRtpMaxGapMs: 20,
|
||||
webrtcEgressRtpFrames: 3, webrtcEgressRtpFirstAt: 100, webrtcEgressRtpLastAt: 140, webrtcEgressRtpMaxGapMs: 20,
|
||||
webrtcQueuePeakFrames: 2, webrtcQueueDroppedFrames: 1, webrtcQueueUnderrunTicks: 0, webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 1, webrtcIngressQuietFrames: 0, webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 3, webrtcDownlinkDecodeErrors: 0, webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
const source = { audio, webrtc: { getStats: () => rtc } };
|
||||
const status = snapshotAudioStatus(source);
|
||||
assert.equal(status.transport, "webrtc");
|
||||
assert.equal(status.ingressFrames, 12);
|
||||
assert.equal(status.webrtcIngressRtpFrames, 7);
|
||||
assert.equal(snapshotAudioStatus({ audio, webrtc: null }).transport, "websocket");
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { VoiceAudioBridgeStats } from "../shared/voice-models.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
ingressFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressFirstAt: number | null;
|
||||
ingressLastAt: number | null;
|
||||
ingressMaxGapMs: number;
|
||||
tsSendFrames: number;
|
||||
tsSendErrors: number;
|
||||
tsSendFirstAt: number | null;
|
||||
tsSendLastAt: number | null;
|
||||
tsSendMaxGapMs: number;
|
||||
tsEncodeMaxMs: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveFirstAt: number | null;
|
||||
tsReceiveLastAt: number | null;
|
||||
tsReceiveMaxGapMs: number;
|
||||
egressFrames: number;
|
||||
egressDroppedFrames: number;
|
||||
egressFirstAt: number | null;
|
||||
egressLastAt: number | null;
|
||||
egressMaxGapMs: number;
|
||||
egressSentFirstAt: number | null;
|
||||
egressSentLastAt: number | null;
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
|
||||
}
|
||||
|
||||
export interface AudioStatsSource {
|
||||
audio: AudioFlowStats;
|
||||
webrtc: Pick<WebRtcAudioSession, "getStats"> | null;
|
||||
}
|
||||
|
||||
export function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
ingressMaxGapMs: 0,
|
||||
tsSendFrames: 0,
|
||||
tsSendErrors: 0,
|
||||
tsSendFirstAt: null,
|
||||
tsSendLastAt: null,
|
||||
tsSendMaxGapMs: 0,
|
||||
tsEncodeMaxMs: 0,
|
||||
tsReceiveFrames: 0,
|
||||
tsReceiveFirstAt: null,
|
||||
tsReceiveLastAt: null,
|
||||
tsReceiveMaxGapMs: 0,
|
||||
egressFrames: 0,
|
||||
egressDroppedFrames: 0,
|
||||
egressFirstAt: null,
|
||||
egressLastAt: null,
|
||||
egressMaxGapMs: 0,
|
||||
egressSentFirstAt: null,
|
||||
egressSentLastAt: null,
|
||||
egressSentMaxGapMs: 0,
|
||||
egressPeakBufferedBytes: 0,
|
||||
egressFramesByClient: {},
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function snapshotAudioStats(entry: AudioStatsSource): AudioFlowStats {
|
||||
const stats = { ...entry.audio, egressFramesByClient: { ...entry.audio.egressFramesByClient } };
|
||||
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
|
||||
if (webRtcStats) Object.assign(stats, webRtcStats);
|
||||
return stats;
|
||||
}
|
||||
|
||||
export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeStats {
|
||||
const stats = snapshotAudioStats(entry);
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
egressDroppedFrames: stats.egressDroppedFrames,
|
||||
egressMaxGapMs: stats.egressMaxGapMs,
|
||||
webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames,
|
||||
webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs,
|
||||
webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames,
|
||||
webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs,
|
||||
webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames,
|
||||
webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks,
|
||||
webrtcPacerLateTicks: stats.webrtcPacerLateTicks,
|
||||
webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors,
|
||||
webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js";
|
||||
import { parseServerMessage } from "../shared/server-messages.js";
|
||||
|
||||
const directory = (): TSDirectorySnapshot => ({
|
||||
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }],
|
||||
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
|
||||
});
|
||||
|
||||
test("self restoration uses the connected channel before a snapshot or requested channel", () => {
|
||||
const source = directory();
|
||||
const result = normalizeDirectorySnapshot(source, 2, 18446744073709551615n, "Self", "Lobby");
|
||||
assert.equal(result.clients[0]?.channelID, 18446744073709551615n);
|
||||
assert.equal(result.clients[0]?.uid, "uid-2");
|
||||
assert.equal(source.clients[0]?.channelID, 1n);
|
||||
assert.equal(normalizeDirectorySnapshot(source, 0, 1n, "Unknown"), source);
|
||||
});
|
||||
|
||||
test("partial welcome data can restore self by channel name without duplicating existing members", () => {
|
||||
const source = directory();
|
||||
const result = normalizeDirectorySnapshot(source, 3, 0n, "Self", " room ");
|
||||
assert.equal(result.clients.length, 2);
|
||||
assert.equal(result.clients[1]?.channelID, 18446744073709551615n);
|
||||
assert.equal(normalizeDirectorySnapshot(result, 3, 0n, "Self").clients.length, 2);
|
||||
assert.equal(source.clients.length, 1);
|
||||
});
|
||||
|
||||
test("directory presentation survives JSON transport with large IDs, member flags and cached avatars", () => {
|
||||
const source = directory();
|
||||
const channels = mapChannelTree(source, new Map([["uid-2", "data:image/png;base64,test"]]));
|
||||
const decoded = parseServerMessage(JSON.parse(JSON.stringify({ type: "channelList", channels })));
|
||||
assert.ok(decoded?.type === "channelList");
|
||||
assert.equal(decoded.channels[1]?.id, "18446744073709551615");
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true);
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.away, true);
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test");
|
||||
assert.deepEqual(decoded.channels[1]?.members, []);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): ChannelInfo[] {
|
||||
return snapshot.channels.map((channel) => ({
|
||||
id: String(channel.id),
|
||||
parentID: String(channel.parentID),
|
||||
order: String(channel.order),
|
||||
name: channel.name || "未命名频道",
|
||||
description: channel.description || "",
|
||||
members: snapshot.clients
|
||||
.filter((client) => client.channelID === channel.id)
|
||||
.map((client) => {
|
||||
const avatar = client.uid ? avatarCache.get(client.uid) : undefined;
|
||||
return {
|
||||
id: client.id,
|
||||
nickname: client.nickname || "未知用户",
|
||||
uid: client.uid,
|
||||
...(avatar ? { avatar } : {}),
|
||||
away: client.away,
|
||||
awayMessage: client.awayMessage,
|
||||
inputMuted: client.inputMuted,
|
||||
outputMuted: client.outputMuted,
|
||||
channelCommander: client.channelCommander,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function avatarDataUrl(data: Buffer): string | null {
|
||||
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return `data:image/png;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 3 && data.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return `data:image/jpeg;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 6 && (data.subarray(0, 6).toString("ascii") === "GIF87a" || data.subarray(0, 6).toString("ascii") === "GIF89a")) return `data:image/gif;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return `data:image/webp;base64,${data.toString("base64")}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function normalizeDirectorySnapshot(
|
||||
snapshot: TSDirectorySnapshot,
|
||||
selfId: number,
|
||||
selfChannelId: bigint,
|
||||
nickname: string,
|
||||
requestedChannelName?: string,
|
||||
): TSDirectorySnapshot {
|
||||
if (selfId <= 0) return snapshot;
|
||||
|
||||
const clients = snapshot.clients.slice();
|
||||
const selfIndex = clients.findIndex((client) => client.id === selfId);
|
||||
const snapshotChannelId = selfIndex >= 0 ? clients[selfIndex]!.channelID : 0n;
|
||||
const requestedName = requestedChannelName?.trim().toLocaleLowerCase();
|
||||
const requestedChannel = requestedName
|
||||
? snapshot.channels.find((channel) => channel.name.trim().toLocaleLowerCase() === requestedName)
|
||||
: undefined;
|
||||
const resolvedChannelId = selfChannelId !== 0n
|
||||
? selfChannelId
|
||||
: snapshotChannelId !== 0n
|
||||
? snapshotChannelId
|
||||
: requestedChannel?.id ?? snapshot.channels[0]?.id ?? 0n;
|
||||
if (selfIndex >= 0) {
|
||||
const current = clients[selfIndex]!;
|
||||
if (resolvedChannelId !== 0n) clients[selfIndex] = { ...current, channelID: resolvedChannelId };
|
||||
} else if (resolvedChannelId !== 0n) {
|
||||
clients.push({ id: selfId, nickname, uid: "", channelID: resolvedChannelId, type: 1, serverGroups: [] });
|
||||
}
|
||||
|
||||
return { ...snapshot, clients };
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { ScreenShareCoordinator, type ScreenShareParticipant } from "./screen-share-coordinator.js";
|
||||
import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ScreenShareClientMessage } from "../shared/screen-share.js";
|
||||
|
||||
function fixture() {
|
||||
const entries = new Map<string, ScreenShareParticipant>();
|
||||
const messages: Array<{ to: string; message: ServerMessage }> = [];
|
||||
const commands: Array<{ from: string; command: string }> = [];
|
||||
const send = (to: string, message: ServerMessage) => {
|
||||
assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid message: ${message.type}`);
|
||||
messages.push({ to, message });
|
||||
};
|
||||
const coordinator = new ScreenShareCoordinator(entries, send, { debug() {}, warn() {} });
|
||||
function participant(id: string, clientId: number, channel = 1n, host = "first.example") {
|
||||
const entry: ScreenShareParticipant = {
|
||||
id, nickname: id, screenPeerId: `peer-${id}`, target: { host, port: 9987 }, members: new Map([[clientId, {}]]),
|
||||
channelTree: [{ id: String(channel), parentID: "0", name: "Room", members: [{ id: clientId, nickname: id }] }],
|
||||
tsClient: {
|
||||
getClientId: () => clientId, getChannelId: () => channel, isConnected: () => true,
|
||||
sendProtocolCommand: async command => { commands.push({ from: id, command }); },
|
||||
},
|
||||
};
|
||||
entries.set(id, entry);
|
||||
return entry;
|
||||
}
|
||||
function handle(entry: ScreenShareParticipant, command: ScreenShareClientMessage) {
|
||||
coordinator.handleMessage(entry, command, message => send(entry.id, message));
|
||||
}
|
||||
function list(entry: ScreenShareParticipant) {
|
||||
handle(entry, { type: "screenShareList" });
|
||||
const message = messages.at(-1)?.message;
|
||||
assert.ok(message?.type === "screenShareList");
|
||||
return message.streams;
|
||||
}
|
||||
function start(entry: ScreenShareParticipant) {
|
||||
handle(entry, { type: "screenShareStart", requestId: "start", name: "Screen", audio: false });
|
||||
const share = list(entry)[0];
|
||||
assert.ok(share);
|
||||
return share.streamId;
|
||||
}
|
||||
return { entries, messages, commands, coordinator, participant, handle, list, start };
|
||||
}
|
||||
|
||||
test("sharing is isolated by server and channel, and only its owner can stop it", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const otherChannel = f.participant("other-channel", 3, 2n);
|
||||
const otherServer = f.participant("other-server", 1, 1n, "second.example");
|
||||
const streamId = f.start(owner);
|
||||
assert.equal(f.messages.some(({ to }) => to === otherChannel.id || to === otherServer.id), false);
|
||||
for (const [entry, code] of [[otherServer, "SCREEN_SHARE_NOT_FOUND"], [otherChannel, "SCREEN_SHARE_TARGET_MISMATCH"]] as const) {
|
||||
f.handle(entry, { type: "screenShareJoin", streamId });
|
||||
const reply = f.messages.at(-1)?.message;
|
||||
assert.ok(reply?.type === "screenShareError");
|
||||
assert.equal(reply.code, code);
|
||||
}
|
||||
f.handle(viewer, { type: "screenShareStop", streamId });
|
||||
assert.equal(f.list(owner).length, 1);
|
||||
f.handle(owner, { type: "screenShareStop", streamId });
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
});
|
||||
|
||||
test("signaling permits owner-viewer pairs but rejects viewer-to-viewer injection", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const left = f.participant("left", 2);
|
||||
const right = f.participant("right", 3);
|
||||
const streamId = f.start(owner);
|
||||
for (const viewer of [left, right]) f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.messages.length = 0;
|
||||
f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: right.screenPeerId, signal: { kind: "offer", sdp: "invalid-peer" } });
|
||||
assert.equal(f.messages.some(({ to }) => to === right.id), false);
|
||||
assert.equal(f.messages[0]?.message.type, "screenShareError");
|
||||
f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: owner.screenPeerId, signal: { kind: "offer", sdp: "offer" } });
|
||||
assert.equal(f.messages.at(-1)?.to, owner.id);
|
||||
assert.equal(f.messages.at(-1)?.message.type, "screenShareSignal");
|
||||
});
|
||||
|
||||
test("another member moving channels cannot stop the owner's share or evict its viewer", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const streamId = f.start(owner);
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.coordinator.onClientMove(owner, 99, 2n);
|
||||
f.coordinator.onClientMove(viewer, 99, 2n);
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 1);
|
||||
f.coordinator.onClientMove(viewer, 2, 2n);
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 0);
|
||||
f.coordinator.onClientMove(owner, 1, 2n);
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
});
|
||||
|
||||
test("native source lookup cannot use another server's colliding client ID", () => {
|
||||
const f = fixture();
|
||||
f.participant("collision", 17, 99n, "second.example");
|
||||
const observer = f.participant("observer", 1);
|
||||
const viewer = f.participant("viewer", 2, 3n);
|
||||
observer.channelTree.push({ id: "3", parentID: "0", name: "Source", members: [{ id: 17, nickname: "Native" }] });
|
||||
f.coordinator.handleNotification(observer, { name: "notifystreamstarted", params: { id: "native", clid: "17", name: "Native" } });
|
||||
assert.equal(f.list(observer).length, 0);
|
||||
assert.equal(f.list(viewer)[0]?.streamId, "native");
|
||||
});
|
||||
|
||||
test("a gateway publisher's repeated native notification cannot create a duplicate stream", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native-copy", clid: "1" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreaminfo", params: { id: "native-copy", clid: "1" } });
|
||||
assert.deepEqual(f.list(owner).map(stream => stream.streamId), [streamId]);
|
||||
f.handle(owner, { type: "screenShareStop", streamId });
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "late-copy", clid: "1" } });
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
assert.ok(f.commands.some(({ command }) => command.startsWith("stopstream id=late-copy ")));
|
||||
});
|
||||
|
||||
test("native discovery runs again when the last session on a target has left", async () => {
|
||||
const f = fixture();
|
||||
const first = f.participant("first", 1);
|
||||
await f.coordinator.discoverExistingStreams(first);
|
||||
f.coordinator.removePeer(first.id);
|
||||
f.entries.delete(first.id);
|
||||
const second = f.participant("second", 2);
|
||||
await f.coordinator.discoverExistingStreams(second);
|
||||
assert.ok(f.commands.some(({ from, command }) => from === second.id && command === "requeststreaminfo clid=2"));
|
||||
});
|
||||
|
||||
test("owner removal is idempotent and clears the stream from remaining viewers", async () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const streamId = f.start(owner);
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.messages.length = 0;
|
||||
f.coordinator.removePeer(owner.id);
|
||||
f.coordinator.removePeer(owner.id);
|
||||
await nextTurn();
|
||||
assert.equal(f.messages.filter(({ to, message }) => to === viewer.id && message.type === "screenShareStopped").length, 1);
|
||||
assert.equal(f.list(viewer).length, 0);
|
||||
});
|
||||
|
||||
test("a failed old native join cannot remove a newer membership", async () => {
|
||||
const f = fixture();
|
||||
const viewer = f.participant("viewer", 2);
|
||||
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
f.coordinator.handleNotification(viewer, { name: "notifystreamstarted", params: { id: "native", clid: "17" } });
|
||||
let rejectOld!: (error: Error) => void;
|
||||
const old = new Promise<void>((_, reject) => { rejectOld = reject; });
|
||||
let joins = 0;
|
||||
viewer.tsClient.sendProtocolCommand = command => command.startsWith("joinstreamrequest") && ++joins === 1 ? old : Promise.resolve();
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "old" });
|
||||
f.handle(viewer, { type: "screenShareLeave", streamId: "native" });
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "new" });
|
||||
rejectOld(new Error("old request failed"));
|
||||
await nextTurn();
|
||||
assert.equal(f.list(viewer)[0]?.viewerCount, 1);
|
||||
assert.equal(f.messages.some(({ message }) => message.type === "screenShareError" && message.requestId === "old"), false);
|
||||
});
|
||||
@@ -0,0 +1,746 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { TSClient, TSRawNotification } from "./ts-client.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { ScreenShareClientMessage, ScreenSharePeerSignal, ScreenShareStreamDescription, ScreenShareViewerDescription } from "../shared/screen-share.js";
|
||||
|
||||
export interface ScreenShareParticipant {
|
||||
id: string;
|
||||
screenPeerId: string;
|
||||
nickname: string;
|
||||
target: TeamSpeakTarget;
|
||||
members: ReadonlyMap<number, { avatar?: string }>;
|
||||
channelTree: ChannelInfo[];
|
||||
tsClient: Pick<TSClient, "getClientId" | "getChannelId" | "isConnected" | "sendProtocolCommand">;
|
||||
}
|
||||
|
||||
interface ScreenStreamRecord extends ScreenShareStreamDescription {
|
||||
targetKey: string;
|
||||
channelId: bigint;
|
||||
ownerEntryId: string;
|
||||
viewerEntryIds: Map<string, symbol>;
|
||||
sourceClientId?: number;
|
||||
/** The gateway TS client that publishes a browser-owned stream to TS6. */
|
||||
teamSpeakPublisherEntryId?: string;
|
||||
/** The TS6 stream id paired with a browser-owned WebSpeak stream. */
|
||||
teamSpeakStreamId?: string;
|
||||
/** Native TS6 viewer client ids paired with a browser-owned stream. */
|
||||
nativeViewerClids: Set<number>;
|
||||
}
|
||||
|
||||
// Stream ids are scoped to a TeamSpeak server. Keep the target in the key so
|
||||
// two unrelated servers cannot overwrite each other's native stream record.
|
||||
function screenStreamKey(targetKey: string, streamId: string): string {
|
||||
return `${targetKey}\u0000${streamId}`;
|
||||
}
|
||||
|
||||
/** Coordinates channel-scoped browser/native sharing; media stays peer-to-peer. */
|
||||
export class ScreenShareCoordinator {
|
||||
private readonly screenStreams = new Map<string, ScreenStreamRecord>();
|
||||
private readonly discoveredClients = new Map<string, Set<number>>();
|
||||
|
||||
constructor(
|
||||
private readonly entries: ReadonlyMap<string, ScreenShareParticipant>,
|
||||
private readonly sendToEntry: (entryId: string, message: ServerMessage) => void,
|
||||
private readonly logger: Pick<Logger, "debug" | "warn">,
|
||||
) {}
|
||||
|
||||
handleMessage(
|
||||
entry: ScreenShareParticipant,
|
||||
message: ScreenShareClientMessage,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): void {
|
||||
if (message.type === "screenShareList") {
|
||||
sendJson({ type: "screenShareList", streams: this.listScreenStreamsFor(entry) });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareStart") {
|
||||
if ([...this.screenStreams.values()].some((stream) => stream.source === "browser" && stream.ownerEntryId === entry.id)) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_ALREADY_ACTIVE", message: "你已经在共享屏幕" });
|
||||
return;
|
||||
}
|
||||
const stream: ScreenStreamRecord = {
|
||||
streamId: `screen-${randomUUID()}`,
|
||||
source: "browser",
|
||||
ownerPeerId: entry.screenPeerId,
|
||||
ownerClientId: entry.tsClient.getClientId() || undefined,
|
||||
ownerNickname: entry.nickname,
|
||||
name: message.name?.trim() || `${entry.nickname} 的屏幕`,
|
||||
audio: message.audio === true,
|
||||
createdAt: Date.now(),
|
||||
viewerCount: 0,
|
||||
viewers: [],
|
||||
targetKey: teamSpeakTargetKey(entry.target),
|
||||
channelId: entry.tsClient.getChannelId(),
|
||||
ownerEntryId: entry.id,
|
||||
viewerEntryIds: new Map(),
|
||||
teamSpeakPublisherEntryId: entry.id,
|
||||
nativeViewerClids: new Set(),
|
||||
};
|
||||
this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream);
|
||||
sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true });
|
||||
this.broadcastScreenMessage(stream, {
|
||||
type: "screenShareStarted",
|
||||
stream: this.describeScreenStream(stream),
|
||||
owner: false,
|
||||
}, entry.id);
|
||||
void this.publishBrowserScreenStream(entry, stream);
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId));
|
||||
if (!stream) {
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" });
|
||||
return;
|
||||
}
|
||||
if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) {
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareStop") {
|
||||
if (stream.ownerEntryId !== entry.id) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_NOT_OWNER", message: "只有共享者可以结束共享" });
|
||||
return;
|
||||
}
|
||||
this.stopScreenStream(stream, "owner-stopped");
|
||||
if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareJoin") {
|
||||
if (stream.ownerEntryId === entry.id) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_OWNER_CANNOT_JOIN", message: "共享者不能作为观看者加入自己的共享" });
|
||||
return;
|
||||
}
|
||||
const alreadyJoined = stream.viewerEntryIds.has(entry.id);
|
||||
if (!alreadyJoined) stream.viewerEntryIds.set(entry.id, Symbol("screen-membership"));
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
sendJson({
|
||||
type: "screenShareJoined",
|
||||
requestId: message.requestId,
|
||||
stream: this.describeScreenStream(stream),
|
||||
ownerPeerId: stream.ownerPeerId,
|
||||
mode: stream.source,
|
||||
});
|
||||
if (stream.source === "browser" && !alreadyJoined) {
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareViewerJoined",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: entry.screenPeerId,
|
||||
viewerNickname: entry.nickname,
|
||||
});
|
||||
} else if (stream.source === "teamspeak" && !alreadyJoined) {
|
||||
void this.joinNativeScreenStream(entry, stream, sendJson, message.requestId);
|
||||
}
|
||||
if (!alreadyJoined) {
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareLeave") {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareSignal") {
|
||||
this.relayScreenShareSignal(entry, stream, message.targetPeerId, message.signal, sendJson);
|
||||
}
|
||||
}
|
||||
|
||||
private listScreenStreamsFor(entry: ScreenShareParticipant): ScreenShareStreamDescription[] {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
return [...this.screenStreams.values()]
|
||||
.filter((stream) => stream.targetKey === targetKey && stream.channelId === entry.tsClient.getChannelId())
|
||||
.map((stream) => this.describeScreenStream(stream));
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway session can connect after a native TeamSpeak stream has already
|
||||
* started. TS6 does not replay that stream in the normal welcome snapshot;
|
||||
* requeststreaminfo is the official client-protocol query for this case.
|
||||
* Query each visible client once per TeamSpeak target, then let the normal
|
||||
* raw notification path announce the discovered stream to web viewers.
|
||||
*/
|
||||
async discoverExistingStreams(entry: ScreenShareParticipant): Promise<void> {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
let discovered = this.discoveredClients.get(targetKey);
|
||||
if (!discovered) this.discoveredClients.set(targetKey, discovered = new Set());
|
||||
const clientIds = [...entry.members.keys()].filter((clientId) => Number.isInteger(clientId) && clientId > 0);
|
||||
for (const clientId of clientIds) {
|
||||
if (this.entries.get(entry.id) !== entry || !entry.tsClient.isConnected()) return;
|
||||
if (discovered.has(clientId)) continue;
|
||||
discovered.add(clientId);
|
||||
try {
|
||||
await entry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`);
|
||||
} catch (error: unknown) {
|
||||
discovered.delete(clientId);
|
||||
this.logger.debug({
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
clientId,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not query existing TeamSpeak screen stream");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private describeScreenStream(stream: ScreenStreamRecord): ScreenShareStreamDescription {
|
||||
return {
|
||||
streamId: stream.streamId,
|
||||
source: stream.source,
|
||||
ownerPeerId: stream.ownerPeerId,
|
||||
...(typeof stream.ownerClientId === "number" ? { ownerClientId: stream.ownerClientId } : {}),
|
||||
ownerNickname: stream.ownerNickname,
|
||||
name: stream.name,
|
||||
audio: stream.audio,
|
||||
createdAt: stream.createdAt,
|
||||
viewerCount: stream.viewerCount,
|
||||
viewers: this.describeScreenViewers(stream),
|
||||
};
|
||||
}
|
||||
|
||||
private describeScreenViewers(stream: ScreenStreamRecord): ScreenShareViewerDescription[] {
|
||||
return [...stream.viewerEntryIds.keys()]
|
||||
.map((entryId) => this.entries.get(entryId))
|
||||
.filter((entry): entry is ScreenShareParticipant => Boolean(entry))
|
||||
.slice(0, 64)
|
||||
.map((entry) => {
|
||||
const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar;
|
||||
return {
|
||||
peerId: entry.screenPeerId,
|
||||
nickname: entry.nickname,
|
||||
...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private screenShareViewerCountMessage(stream: ScreenStreamRecord): ServerMessage {
|
||||
return {
|
||||
type: "screenShareViewerCount",
|
||||
streamId: stream.streamId,
|
||||
viewerCount: stream.viewerCount,
|
||||
viewers: this.describeScreenViewers(stream),
|
||||
};
|
||||
}
|
||||
|
||||
private screenShareViewerCount(stream: ScreenStreamRecord): number {
|
||||
return stream.viewerEntryIds.size + stream.nativeViewerClids.size;
|
||||
}
|
||||
|
||||
private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void {
|
||||
for (const candidate of this.entries.values()) {
|
||||
if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue;
|
||||
// A stream is scoped to the source channel. Do not leak its card or
|
||||
// viewer roster to users who are connected to another channel on the
|
||||
// same TeamSpeak target.
|
||||
if (candidate.id !== stream.ownerEntryId) {
|
||||
try {
|
||||
if (candidate.tsClient.getChannelId() !== stream.channelId) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
this.sendToEntry(candidate.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
private stopScreenStream(stream: ScreenStreamRecord, reason: string): void {
|
||||
if (!this.screenStreams.delete(screenStreamKey(stream.targetKey, stream.streamId))) return;
|
||||
if (stream.source === "browser" && stream.teamSpeakStreamId && stream.teamSpeakPublisherEntryId) {
|
||||
const publisher = this.entries.get(stream.teamSpeakPublisherEntryId);
|
||||
if (publisher) {
|
||||
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
reason: "1",
|
||||
})).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason };
|
||||
this.broadcastScreenMessage(stream, message);
|
||||
stream.viewerEntryIds.clear();
|
||||
stream.nativeViewerClids.clear();
|
||||
stream.viewerCount = 0;
|
||||
}
|
||||
|
||||
private leaveScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): void {
|
||||
if (!stream.viewerEntryIds.delete(entry.id)) return;
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
if (stream.source === "browser") this.sendToEntry(stream.ownerEntryId, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: entry.screenPeerId });
|
||||
else {
|
||||
void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
|
||||
id: stream.streamId,
|
||||
clid: String(entry.tsClient.getClientId()),
|
||||
})).catch(() => undefined);
|
||||
}
|
||||
this.sendToEntry(entry.id, { type: "screenShareLeft", streamId: stream.streamId });
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
}
|
||||
|
||||
private relayScreenShareSignal(
|
||||
entry: ScreenShareParticipant,
|
||||
stream: ScreenStreamRecord,
|
||||
targetPeerId: string,
|
||||
signal: ScreenSharePeerSignal,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): void {
|
||||
if (stream.source === "teamspeak") {
|
||||
if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
|
||||
return;
|
||||
}
|
||||
const sourceClientId = stream.sourceClientId;
|
||||
if (!sourceClientId) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" });
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "close") {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "offer") {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "观看端不能向 TeamSpeak 来源发送 offer" });
|
||||
return;
|
||||
}
|
||||
const payload = signal.kind === "iceCandidate"
|
||||
? { cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }
|
||||
: { cmd: "answer", args: { answer: signal.sdp } };
|
||||
void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("streamsignaling", {
|
||||
id: stream.streamId,
|
||||
clid: String(sourceClientId),
|
||||
json: JSON.stringify(payload),
|
||||
})).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (stream.source === "browser" && entry.id === stream.ownerEntryId && targetPeerId.startsWith("ts-viewer-")) {
|
||||
const viewerClid = parseNativeViewerPeerId(targetPeerId);
|
||||
const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined;
|
||||
if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" });
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "close") {
|
||||
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
})).catch(() => undefined);
|
||||
stream.nativeViewerClids.delete(viewerClid);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId });
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "answer") {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "TeamSpeak 观看端不能先发送 answer" });
|
||||
return;
|
||||
}
|
||||
let command: string;
|
||||
if (signal.kind === "offer") {
|
||||
command = buildTeamSpeakCommand("respondjoinstreamrequest", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
msg: "",
|
||||
offer: signal.sdp,
|
||||
decision: "1",
|
||||
});
|
||||
} else if (signal.kind === "iceCandidate") {
|
||||
command = buildTeamSpeakCommand("streamsignaling", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }),
|
||||
});
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = this.entries.get(stream.ownerEntryId);
|
||||
const isOwner = entry.id === stream.ownerEntryId;
|
||||
const isViewer = stream.viewerEntryIds.has(entry.id);
|
||||
if (!owner || (!isOwner && !isViewer)) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
|
||||
return;
|
||||
}
|
||||
// Keep the browser P2P graph bipartite: the owner may signal only an
|
||||
// active viewer, and a viewer may signal only the owner. Without this
|
||||
// check one viewer could inject SDP/ICE into another viewer's peer.
|
||||
const targetEntry = isOwner
|
||||
? [...stream.viewerEntryIds.keys()]
|
||||
.map((id) => this.entries.get(id))
|
||||
.find((candidate) => candidate?.screenPeerId === targetPeerId)
|
||||
: targetPeerId === owner.screenPeerId ? owner : undefined;
|
||||
if (!targetEntry || targetEntry.id === entry.id) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "观看者已离开" });
|
||||
return;
|
||||
}
|
||||
this.sendToEntry(targetEntry.id, { type: "screenShareSignal", streamId: stream.streamId, fromPeerId: entry.screenPeerId, signal });
|
||||
}
|
||||
|
||||
private async publishBrowserScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): Promise<void> {
|
||||
try {
|
||||
await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("setupstream", {
|
||||
name: stream.name,
|
||||
type: "3",
|
||||
bitrate: "4608",
|
||||
accessibility: "1",
|
||||
mode: "1",
|
||||
viewer_limit: "0",
|
||||
audio: stream.audio ? "1" : "0",
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not publish browser screen share to TeamSpeak");
|
||||
}
|
||||
}
|
||||
|
||||
private async joinNativeScreenStream(
|
||||
entry: ScreenShareParticipant,
|
||||
stream: ScreenStreamRecord,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
requestId?: string,
|
||||
): Promise<void> {
|
||||
const membership = stream.viewerEntryIds.get(entry.id);
|
||||
const sourceClientId = stream.sourceClientId;
|
||||
if (!entry.tsClient.getClientId() || !sourceClientId) {
|
||||
sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("joinstreamrequest", {
|
||||
id: stream.streamId,
|
||||
// TS6 uses the source client id on joinstreamrequest. The requesting
|
||||
// gateway session is identified later by the response/signaling
|
||||
// notification delivered to this TS connection.
|
||||
clid: String(sourceClientId),
|
||||
msg: "",
|
||||
is_remove: "0",
|
||||
muted: "0",
|
||||
volume: "0",
|
||||
hidden: "0",
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
if (this.entries.get(entry.id) !== entry
|
||||
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream
|
||||
|| stream.viewerEntryIds.get(entry.id) !== membership) return;
|
||||
this.leaveScreenStream(entry, stream);
|
||||
sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_JOIN_FAILED", message: error instanceof Error ? error.message : "无法加入屏幕共享" });
|
||||
}
|
||||
}
|
||||
|
||||
removePeer(entryId: string): void {
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.ownerEntryId === entryId) {
|
||||
this.stopScreenStream(stream, "owner-disconnected");
|
||||
continue;
|
||||
}
|
||||
const entry = this.entries.get(entryId);
|
||||
if (entry && stream.viewerEntryIds.has(entryId)) this.leaveScreenStream(entry, stream);
|
||||
}
|
||||
const departing = this.entries.get(entryId);
|
||||
if (!departing) return;
|
||||
const targetKey = teamSpeakTargetKey(departing.target);
|
||||
if (![...this.entries.values()].some(entry => entry.id !== entryId && teamSpeakTargetKey(entry.target) === targetKey)) {
|
||||
this.discoveredClients.delete(targetKey);
|
||||
// Native notifications are not observed while no session is attached.
|
||||
// Rediscover on the next connection instead of retaining stale cards.
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey === targetKey) this.stopScreenStream(stream, "target-disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onClientMove(entry: ScreenShareParticipant, movedClientId: number, targetChannelId: bigint): void {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const selfMoved = movedClientId === entry.tsClient.getClientId();
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey !== targetKey) continue;
|
||||
// A browser share belongs to the gateway user's current channel. Stop
|
||||
// it when that user moves so existing viewers cannot keep a cross-
|
||||
// channel peer alive.
|
||||
if (selfMoved && stream.source === "browser" && stream.ownerEntryId === entry.id && stream.channelId !== targetChannelId) {
|
||||
this.stopScreenStream(stream, "owner-moved-channel");
|
||||
continue;
|
||||
}
|
||||
// Native TS6 shares are channel-scoped as well. The notification is
|
||||
// observed by every gateway session, so stop the shared record once the
|
||||
// native source changes channels.
|
||||
if (stream.source === "teamspeak" && stream.sourceClientId === movedClientId && stream.channelId !== targetChannelId) {
|
||||
this.stopScreenStream(stream, "source-moved-channel");
|
||||
continue;
|
||||
}
|
||||
if (selfMoved && stream.viewerEntryIds.has(entry.id) && stream.channelId !== targetChannelId) {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onClientLeave(entry: ScreenShareParticipant, clientId: number): void {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
this.discoveredClients.get(targetKey)?.delete(clientId);
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey === targetKey && stream.source === "teamspeak" && stream.sourceClientId === clientId) {
|
||||
this.stopScreenStream(stream, "source-left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleNotification(entry: ScreenShareParticipant, notification: TSRawNotification): void {
|
||||
if (this.entries.get(entry.id) !== entry) return;
|
||||
const params = notification.params;
|
||||
if (notification.name === "notifyjoinstreamrequest") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!streamId || !viewerClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id
|
||||
&& candidate.teamSpeakStreamId === streamId);
|
||||
if (!stream) return;
|
||||
stream.nativeViewerClids.add(viewerClientId);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareNativeViewerJoined",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: nativeViewerPeerId(viewerClientId),
|
||||
viewerClientId,
|
||||
});
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const sourceClientId = parseNumber(params.clid);
|
||||
if (!streamId || !sourceClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target
|
||||
&& teamSpeakTargetKey(candidate.target) === targetKey
|
||||
&& candidate.tsClient.getClientId() === sourceClientId);
|
||||
const browserStream = publisherEntry
|
||||
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === publisherEntry.id
|
||||
&& (!candidate.teamSpeakStreamId || candidate.teamSpeakStreamId === streamId))
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
browserStream.teamSpeakStreamId = streamId;
|
||||
return;
|
||||
}
|
||||
if (publisherEntry) {
|
||||
// A delayed setup acknowledgement can arrive after the browser stopped.
|
||||
// A gateway-owned publication is never a second native source.
|
||||
void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
const sourceChannel = entry.channelTree.find(channel => channel.members?.some(member => member.id === sourceClientId));
|
||||
// Do not guess a channel from the observer, or from a colliding client id
|
||||
// on another server. Discovery will retry after the directory is ready.
|
||||
if (!sourceChannel) return;
|
||||
const key = screenStreamKey(targetKey, streamId);
|
||||
const current = this.screenStreams.get(key);
|
||||
const stream: ScreenStreamRecord = current ?? {
|
||||
streamId,
|
||||
source: "teamspeak",
|
||||
ownerPeerId: `ts-${sourceClientId}`,
|
||||
ownerClientId: sourceClientId,
|
||||
ownerNickname: params.name || `TeamSpeak 用户 ${sourceClientId}`,
|
||||
name: params.name || "TeamSpeak 屏幕共享",
|
||||
audio: params.audio === "1",
|
||||
createdAt: Date.now(),
|
||||
viewerCount: 0,
|
||||
viewers: [],
|
||||
targetKey,
|
||||
channelId: BigInt(sourceChannel.id),
|
||||
ownerEntryId: "",
|
||||
viewerEntryIds: new Map(),
|
||||
nativeViewerClids: new Set(),
|
||||
sourceClientId,
|
||||
};
|
||||
stream.sourceClientId = sourceClientId;
|
||||
stream.ownerNickname = params.name || stream.ownerNickname;
|
||||
stream.name = params.name || stream.name;
|
||||
stream.audio = params.audio === "1";
|
||||
this.screenStreams.set(key, stream);
|
||||
// Every gateway session attached to the same TS target sees the same
|
||||
// raw notification. Only the first one should announce a new stream to
|
||||
// browsers; otherwise each connected user receives duplicate cards.
|
||||
if (!current) {
|
||||
this.broadcastScreenMessage(stream, { type: "screenShareStarted", stream: this.describeScreenStream(stream), owner: false });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamstopped") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
if (!streamId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
|
||||
if (stream) {
|
||||
this.stopScreenStream(stream, "source-stopped");
|
||||
return;
|
||||
}
|
||||
const browserStream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakStreamId === streamId);
|
||||
if (browserStream) {
|
||||
browserStream.teamSpeakStreamId = undefined;
|
||||
browserStream.nativeViewerClids.clear();
|
||||
browserStream.viewerCount = this.screenShareViewerCount(browserStream);
|
||||
this.sendToEntry(browserStream.ownerEntryId, {
|
||||
type: "screenShareError",
|
||||
code: "SCREEN_SHARE_NATIVE_PUBLISHER_STOPPED",
|
||||
message: "TeamSpeak 客户端屏幕共享通道已停止,网页共享仍可继续",
|
||||
});
|
||||
this.broadcastScreenMessage(browserStream, this.screenShareViewerCountMessage(browserStream));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamclientleft") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!streamId || !viewerClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakStreamId === streamId
|
||||
&& candidate.nativeViewerClids.has(viewerClientId));
|
||||
if (!stream) return;
|
||||
stream.nativeViewerClids.delete(viewerClientId);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareViewerLeft",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: nativeViewerPeerId(viewerClientId),
|
||||
});
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
if (!streamId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const browserStream = notification.name === "notifystreamsignaling"
|
||||
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id
|
||||
&& candidate.teamSpeakStreamId === streamId)
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return;
|
||||
const payload = parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
this.sendToEntry(browserStream.ownerEntryId, {
|
||||
type: "screenShareSignal",
|
||||
streamId: browserStream.streamId,
|
||||
fromPeerId: nativeViewerPeerId(viewerClientId),
|
||||
signal,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
|
||||
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return;
|
||||
const payload = notification.name === "notifyrespondjoinstreamrequest"
|
||||
? { cmd: "offer", args: { offer: params.offer || "" } }
|
||||
: parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal });
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function parseNumber(value: string | undefined): number | undefined {
|
||||
if (!value || !/^\d+$/.test(value)) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
||||
}
|
||||
|
||||
function nativeViewerPeerId(clientId: number): string {
|
||||
return `ts-viewer-${clientId}`;
|
||||
}
|
||||
|
||||
function parseNativeViewerPeerId(peerId: string): number | undefined {
|
||||
const match = /^ts-viewer-(\d+)$/.exec(peerId);
|
||||
if (!match) return undefined;
|
||||
return parseNumber(match[1]);
|
||||
}
|
||||
|
||||
function buildTeamSpeakCommand(command: string, params: Record<string, string>): string {
|
||||
return [command, ...Object.entries(params).map(([key, value]) => `${key}=${escapeTeamSpeakValue(value)}`)].join(" ");
|
||||
}
|
||||
|
||||
function parseStreamSignalPayload(raw: string): { cmd: string; args: Record<string, unknown> } | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (!isRecord(value) || typeof value.cmd !== "string" || !isRecord(value.args)) return null;
|
||||
return { cmd: value.cmd, args: value.args };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function toBrowserScreenSignal(payload: { cmd: string; args: Record<string, unknown> }): ScreenSharePeerSignal | null {
|
||||
const args = payload.args;
|
||||
// TeamSpeak's native screen-share source wraps the initial SDP in a
|
||||
// `joinResponse` message after it accepts a viewer's join request. The
|
||||
// browser-side protocol uses the regular offer shape, so normalize it here
|
||||
// before forwarding it. Without this mapping the native source can accept a
|
||||
// viewer while the browser waits forever for its first SDP.
|
||||
if (payload.cmd === "joinResponse") {
|
||||
const decision = args.decision;
|
||||
if (decision === false || decision === 0 || decision === "0") return { kind: "close" };
|
||||
const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "offer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "offer" || payload.cmd === "reconnectOffer") {
|
||||
const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "offer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "answer") {
|
||||
const sdp = typeof args.answer === "string" ? args.answer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "answer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "iceCandidate") {
|
||||
const candidate = typeof args.sdp === "string" ? args.sdp : typeof args.candidate === "string" ? args.candidate : "";
|
||||
if (!candidate) return null;
|
||||
return {
|
||||
kind: "iceCandidate",
|
||||
candidate,
|
||||
...(typeof args.mid === "string" ? { sdpMid: args.mid } : {}),
|
||||
...(typeof args.mLine === "number" ? { sdpMLineIndex: args.mLine } : {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function escapeTeamSpeakValue(value: string): string {
|
||||
return value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/ /g, "\\s")
|
||||
.replace(/\//g, "\\/")
|
||||
.replace(/\|/g, "\\p")
|
||||
.replace(/\n/g, "\\n")
|
||||
.replace(/\r/g, "\\r");
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
+22
-1061
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,124 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { parseClientCommand, type ClientCommand } from "../shared/client-commands.js";
|
||||
import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { handleCommand, type VoiceCommandContext } from "./voice-commands.js";
|
||||
|
||||
function fixture() {
|
||||
const calls: Array<[string, ...unknown[]]> = [];
|
||||
const messages: ServerMessage[] = [];
|
||||
const context: VoiceCommandContext = {
|
||||
tsClient: {
|
||||
execCommandWithResponse: async request => { calls.push(["exec", request]); return []; },
|
||||
switchChannel: async (...args) => { calls.push(["switch", ...args]); },
|
||||
getClientId: () => 1, getChannelId: () => 5n,
|
||||
moveClient: async (...args) => { calls.push(["move", ...args]); },
|
||||
sendTextMessage: async (...args) => { calls.push(["text", ...args]); },
|
||||
poke: async (...args) => { calls.push(["poke", ...args]); },
|
||||
setAway: async (...args) => { calls.push(["away", ...args]); },
|
||||
setInputMuted: async (...args) => { calls.push(["mute", ...args]); },
|
||||
},
|
||||
channelTree: [{ id: "18446744073709551615", parentID: "0", name: "Large ID" }],
|
||||
members: new Map([[1, {}], [2, {}]]),
|
||||
whisperTargetIds: new Set(), whisperActive: false,
|
||||
lastAudioStatsProbeAt: 0, lastLatencyProbeAt: 0,
|
||||
audio: createAudioFlowStats(), webrtc: null,
|
||||
};
|
||||
async function run(command: ClientCommand, now = 10_000) {
|
||||
// The same parsers used at both ends must accept the command and reply.
|
||||
const parsed = parseClientCommand(JSON.stringify(command));
|
||||
assert.ok(!("error" in parsed));
|
||||
await handleCommand(context, parsed, message => {
|
||||
assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid response: ${message.type}`);
|
||||
messages.push(message);
|
||||
}, () => now);
|
||||
}
|
||||
return { context, calls, messages, run };
|
||||
}
|
||||
|
||||
test("moving a visible member preserves bigint channel IDs and request correlation", async () => {
|
||||
const f = fixture();
|
||||
await f.run({ type: "moveClient", payload: { clientId: 2, channelId: "18446744073709551615", password: "ignored-for-admin-move" }, requestId: "move-1" });
|
||||
assert.deepEqual(f.calls, [["move", 2, 18446744073709551615n]]);
|
||||
assert.deepEqual(f.messages, [{ type: "commandCompleted", requestId: "move-1" }]);
|
||||
});
|
||||
|
||||
test("invalid move targets are rejected before invoking the SDK", async () => {
|
||||
const f = fixture();
|
||||
for (const [clientId, channelId, code] of [[1, "18446744073709551615", "CANNOT_MOVE_SELF"], [3, "18446744073709551615", "CLIENT_NOT_FOUND"], [2, "9", "CHANNEL_NOT_FOUND"]] as const) {
|
||||
await f.run({ type: "moveClient", payload: { clientId, channelId }, requestId: code });
|
||||
const reply = f.messages.at(-1);
|
||||
assert.ok(reply?.type === "error");
|
||||
assert.equal(reply.error?.code, code);
|
||||
assert.equal(reply.requestId, code);
|
||||
}
|
||||
assert.deepEqual(f.calls, []);
|
||||
});
|
||||
|
||||
test("channel switching preserves already-member success and authoritative password errors", async () => {
|
||||
const f = fixture();
|
||||
f.context.tsClient.switchChannel = async () => { throw new Error("already member"); };
|
||||
await f.run({ type: "switchChannel", payload: { channelId: "2" }, requestId: "same" });
|
||||
assert.deepEqual(f.messages, [{ type: "channelSwitched", requestId: "same", channelId: "2" }]);
|
||||
f.context.tsClient.switchChannel = async () => { throw Object.assign(new Error("generic failure"), { id: 781 }); };
|
||||
await f.run({ type: "switchChannel", payload: { channelId: "3" }, requestId: "password" });
|
||||
const failure = f.messages.at(-1);
|
||||
assert.ok(failure?.type === "error");
|
||||
assert.equal(failure.error?.code, "CHANNEL_PASSWORD_REQUIRED");
|
||||
assert.equal(failure.requestId, "password");
|
||||
});
|
||||
|
||||
test("whisper transitions reject unavailable targets and deactivate when targets are cleared", async () => {
|
||||
const f = fixture();
|
||||
await f.run({ type: "setWhisperActive", payload: { active: true } });
|
||||
assert.equal(f.context.whisperActive, false);
|
||||
await f.run({ type: "setWhisperTargets", payload: { targetIds: [1] } });
|
||||
assert.equal(f.context.whisperTargetIds.size, 0);
|
||||
await f.run({ type: "setWhisperTargets", payload: { targetIds: [2] } });
|
||||
await f.run({ type: "setWhisperActive", payload: { active: true } });
|
||||
assert.equal(f.context.whisperActive, true);
|
||||
await f.run({ type: "setWhisperTargets", payload: { targetIds: [] } });
|
||||
assert.equal(f.context.whisperActive, false);
|
||||
assert.deepEqual(f.messages.at(-1), { type: "whisperTargets", targetIds: [], active: false });
|
||||
});
|
||||
|
||||
test("mute state reaches the mixer only after TeamSpeak accepts the change", async () => {
|
||||
const f = fixture();
|
||||
f.context.webrtc = {
|
||||
getStats: createAudioFlowStats,
|
||||
setMicrophoneMuted: value => { f.calls.push(["mixer-mute", value]); },
|
||||
setAccompanimentActive() {}, setMemberVolume() {},
|
||||
};
|
||||
await f.run({ type: "setMicrophoneMuted", payload: { muted: true }, requestId: "mute" });
|
||||
assert.deepEqual(f.calls, [["mute", true], ["mixer-mute", true]]);
|
||||
f.context.tsClient.setInputMuted = async () => { throw Object.assign(new Error("denied"), { id: 2568 }); };
|
||||
await f.run({ type: "setMicrophoneMuted", payload: { muted: false }, requestId: "unmute" });
|
||||
assert.equal(f.calls.length, 2);
|
||||
const reply = f.messages.at(-1);
|
||||
assert.ok(reply?.type === "error");
|
||||
assert.equal(reply.error?.code, "PERMISSION_DENIED");
|
||||
});
|
||||
|
||||
test("chat routing uses the current channel, server scope, and private target independently", async () => {
|
||||
const f = fixture();
|
||||
await f.run({ type: "sendTextMessage", payload: { message: " channel " } });
|
||||
await f.run({ type: "sendServerMessage", payload: { message: " server " } });
|
||||
await f.run({ type: "sendPrivateMessage", payload: { clientId: 2, message: " private " } });
|
||||
await f.run({ type: "sendTextMessage", payload: { message: " " }, requestId: "empty" });
|
||||
assert.deepEqual(f.calls, [["text", "channel", "channel", 5n], ["text", "server", "server"], ["text", "private", "private", 2n]]);
|
||||
assert.deepEqual(f.messages.at(-1), { type: "commandCompleted", requestId: "empty" });
|
||||
});
|
||||
|
||||
test("audio probing is bounded per session and accepts the next request at the interval boundary", async () => {
|
||||
const f = fixture();
|
||||
f.context.audio.ingressFrames = 8;
|
||||
const request = (sequence: string): ClientCommand => ({ type: "audioStatsProbe", payload: { sequence } });
|
||||
await f.run(request("first"), 1000);
|
||||
await f.run(request("early"), 1749);
|
||||
await f.run(request("next"), 1750);
|
||||
assert.equal(f.messages.length, 2);
|
||||
assert.ok(f.messages[1]?.type === "audioStats");
|
||||
assert.equal(f.messages[1].sequence, "next");
|
||||
assert.equal(f.messages[1].stats.ingressFrames, 8);
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { ClientCommand } from "../shared/client-commands.js";
|
||||
import type { TSClient } from "./ts-client.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
import { snapshotAudioStatus, type AudioStatsSource } from "./audio-stats.js";
|
||||
import { pingTeamSpeakSession } from "./network-probe.js";
|
||||
import { teamSpeakServerErrorCode } from "../errors.js";
|
||||
|
||||
/** Only the session capabilities used by control commands cross this boundary. */
|
||||
export interface VoiceCommandContext extends AudioStatsSource {
|
||||
tsClient: Pick<TSClient, "execCommandWithResponse" | "switchChannel" | "getClientId" | "getChannelId" | "moveClient" | "sendTextMessage" | "poke" | "setAway" | "setInputMuted">;
|
||||
channelTree: ChannelInfo[];
|
||||
members: ReadonlyMap<number, unknown>;
|
||||
whisperTargetIds: Set<number>;
|
||||
whisperActive: boolean;
|
||||
lastLatencyProbeAt: number;
|
||||
lastAudioStatsProbeAt: number;
|
||||
webrtc: Pick<WebRtcAudioSession, "getStats" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume"> | null;
|
||||
}
|
||||
|
||||
export async function handleCommand(
|
||||
entry: VoiceCommandContext,
|
||||
command: ClientCommand,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
clock: () => number = Date.now,
|
||||
): Promise<void> {
|
||||
if (command.type === "latencyProbe") {
|
||||
// Keep the control-path probe for already-open older browser clients. The
|
||||
// current voice status panel exclusively requests actual audio counters.
|
||||
const sequence = command.payload.sequence;
|
||||
const now = clock();
|
||||
if (now - entry.lastLatencyProbeAt < 150) return;
|
||||
entry.lastLatencyProbeAt = now;
|
||||
const result = await pingTeamSpeakSession(
|
||||
(request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs),
|
||||
);
|
||||
sendJson({
|
||||
type: "latencyPong",
|
||||
sequence,
|
||||
teamSpeakLatencyMs: result.latencyMs,
|
||||
teamSpeakReachable: result.ok,
|
||||
teamSpeakErrorCode: result.errorCode ?? null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.type === "audioStatsProbe") {
|
||||
const sequence = command.payload.sequence;
|
||||
const now = clock();
|
||||
if (now - entry.lastAudioStatsProbeAt < 750) return;
|
||||
entry.lastAudioStatsProbeAt = now;
|
||||
sendJson({
|
||||
type: "audioStats",
|
||||
sequence,
|
||||
stats: snapshotAudioStatus(entry),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.type === "switchChannel") {
|
||||
const rawId = command.payload.channelId;
|
||||
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
|
||||
try {
|
||||
await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined);
|
||||
} catch (error: unknown) {
|
||||
const rawMessage = error instanceof Error ? error.message : String(error);
|
||||
if (/already member/i.test(rawMessage)) {
|
||||
sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId });
|
||||
return;
|
||||
}
|
||||
const operation = classifyOperationError(error, "CHANNEL_SWITCH_FAILED", "频道切换失败");
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } });
|
||||
return;
|
||||
}
|
||||
sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId });
|
||||
sendJson({ type: "channelList", channels: entry.channelTree });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (command.type === "moveClient") {
|
||||
const clientId = command.payload.clientId;
|
||||
const channelId = command.payload.channelId;
|
||||
if (clientId === entry.tsClient.getClientId()) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CANNOT_MOVE_SELF", message: "不能移动自己的客户端", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
if (!entry.members.has(clientId)) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线或当前不可见", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
const targetExists = entry.channelTree.some((channel) => channel.id === channelId);
|
||||
if (!targetExists) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_NOT_FOUND", message: "目标频道不可用", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
// TeamSpeak evaluates i_client_move_power against the target's
|
||||
// i_client_needed_move_power inside clientmove. Do not duplicate that
|
||||
// policy in the gateway; forwarding the authoritative command keeps TS3
|
||||
// and TS6 permission behavior aligned.
|
||||
// Moving another visible client is an administrator operation. It must
|
||||
// not prompt for or depend on the target channel's join password.
|
||||
await entry.tsClient.moveClient(clientId, BigInt(channelId));
|
||||
} else if (command.type === "sendTextMessage") {
|
||||
const message = command.payload.message.trim();
|
||||
if (message) await entry.tsClient.sendTextMessage("channel", message, entry.tsClient.getChannelId());
|
||||
} else if (command.type === "sendServerMessage") {
|
||||
const message = command.payload.message.trim();
|
||||
if (message) await entry.tsClient.sendTextMessage("server", message);
|
||||
} else if (command.type === "sendPrivateMessage") {
|
||||
const clientId = command.payload.clientId;
|
||||
if (!entry.members.has(clientId)) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
const message = command.payload.message.trim();
|
||||
if (message) await entry.tsClient.sendTextMessage("private", message, BigInt(clientId));
|
||||
} else if (command.type === "poke") {
|
||||
const clientId = command.payload.clientId;
|
||||
if (!entry.members.has(clientId)) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
await entry.tsClient.poke(clientId, command.payload.message.trim());
|
||||
} else if (command.type === "setAway") {
|
||||
await entry.tsClient.setAway(command.payload.away, typeof command.payload.message === "string" ? command.payload.message.trim() : "");
|
||||
} else if (command.type === "setWhisperTargets") {
|
||||
const targetIds = command.payload.targetIds;
|
||||
const selfId = entry.tsClient.getClientId();
|
||||
if (targetIds.some((clientId) => clientId === selfId || !entry.members.has(clientId))) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "私语目标已离线", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
entry.whisperTargetIds = new Set(targetIds);
|
||||
if (!entry.whisperTargetIds.size) entry.whisperActive = false;
|
||||
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
||||
} else if (command.type === "setWhisperActive") {
|
||||
const active = command.payload.active;
|
||||
if (active && !entry.whisperTargetIds.size) {
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: "NO_WHISPER_TARGETS", message: "请先选择私语目标", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
entry.whisperActive = active;
|
||||
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
||||
} else if (command.type === "setMicrophoneMuted") {
|
||||
const muted = command.payload.muted;
|
||||
await entry.tsClient.setInputMuted(muted);
|
||||
entry.webrtc?.setMicrophoneMuted(muted);
|
||||
} else if (command.type === "setAccompanimentActive") {
|
||||
entry.webrtc?.setAccompanimentActive(command.payload.active);
|
||||
} else if (command.type === "setMemberVolume") {
|
||||
const clientId = command.payload.clientId;
|
||||
entry.webrtc?.setMemberVolume(clientId, command.payload.volume);
|
||||
}
|
||||
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
|
||||
} catch (error: unknown) {
|
||||
const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败");
|
||||
sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } });
|
||||
}
|
||||
}
|
||||
|
||||
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const normalized = text.toLocaleLowerCase();
|
||||
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
|
||||
// is consulted before the keyword rules: 781 (channel password), 2568
|
||||
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
|
||||
// meaning instead of being guessed from prose.
|
||||
const rawId = isRecord(error) ? (error.id ?? error.code) : undefined;
|
||||
const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1];
|
||||
// Operation permissions are distinct from connection/identity failures.
|
||||
// Preserve the existing 2568 mapping even when the SDK only exposes an id.
|
||||
if (["2568", "0x0a08", "0a08"].includes(String(rawId ?? inlineId).trim().toLowerCase())) {
|
||||
return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
|
||||
}
|
||||
const serverCode = teamSpeakServerErrorCode(rawId) ?? teamSpeakServerErrorCode(inlineId);
|
||||
if (serverCode) {
|
||||
if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
|
||||
if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
|
||||
if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" };
|
||||
if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" };
|
||||
if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" };
|
||||
if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" };
|
||||
if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" };
|
||||
}
|
||||
if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
|
||||
if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|781/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
|
||||
if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" };
|
||||
if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" };
|
||||
if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" };
|
||||
return { code: fallbackCode, message: fallbackMessage };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
Reference in new issue
Block a user