mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix: expose server identity and refine KAAK client
This commit is contained in:
1 parent
e8164abafe
commit
17fb27b89a
28 files changed
+1504
-334
No files matched your search
@@ -17,6 +17,8 @@ const transfer = { size: 6n };
|
||||
|
||||
class SdkStub extends EventEmitter {
|
||||
inputCommands: string[] = [];
|
||||
fileTransfers: Array<{ channelId: bigint; path: string; password: string }> = [];
|
||||
serverInfo: { name: string; iconId: number | null } | null = { name: "兄弟们的teamspeak", iconId: 123456 };
|
||||
inputUpdate = async (_command: string): Promise<void> => {};
|
||||
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
|
||||
initialized = 0;
|
||||
@@ -24,8 +26,12 @@ class SdkStub extends EventEmitter {
|
||||
metadata = async () => rows;
|
||||
transfer = async () => transfer;
|
||||
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
|
||||
execCommandWithResponse() { return this.metadata(); }
|
||||
async fileTransferInitDownload() { this.initialized++; return this.transfer(); }
|
||||
execCommandWithResponse(command = "") { this.inputCommands.push(command); return this.metadata(); }
|
||||
async fileTransferInitDownload(channelId: bigint, path: string, password: string) {
|
||||
this.initialized++;
|
||||
this.fileTransfers.push({ channelId, path, password });
|
||||
return this.transfer();
|
||||
}
|
||||
async downloadFileData(_host: string, _transfer: unknown, destination: Writable) { this.downloaded++; await this.download(destination); }
|
||||
}
|
||||
|
||||
@@ -53,6 +59,25 @@ test("stream commands wait for server acknowledgement and propagate refusals", a
|
||||
await assert.rejects(f.client.sendProtocolCommand("removeclientfromstream id=test"), /missing required parameter/);
|
||||
});
|
||||
|
||||
test("server info uses the name and icon id captured by the SDK handshake", async () => {
|
||||
const f = fixture();
|
||||
assert.deepEqual(await f.client.getServerInfo(), { name: "兄弟们的teamspeak", iconId: 123456 });
|
||||
assert.deepEqual(f.sdk.inputCommands, [], "server identity does not issue a ServerQuery-only command over the client session");
|
||||
f.sdk.serverInfo = { name: "No icon", iconId: null };
|
||||
assert.deepEqual(await f.client.getServerInfo(), { name: "No icon", iconId: null });
|
||||
});
|
||||
|
||||
test("server icons use the TeamSpeak file transfer path and enforce the download limit", async () => {
|
||||
const f = fixture();
|
||||
assert.equal((await f.client.getServerIcon(123456))?.toString(), "GIF89a");
|
||||
assert.deepEqual(f.sdk.fileTransfers, [{ channelId: 0n, path: "/icon_123456", password: "" }]);
|
||||
assert.equal(f.sdk.downloaded, 1);
|
||||
|
||||
f.sdk.transfer = async () => ({ size: 128n * 1024n + 1n });
|
||||
assert.equal(await f.client.getServerIcon(123456), null);
|
||||
assert.equal(f.sdk.downloaded, 1);
|
||||
});
|
||||
|
||||
test("stream cleanup flood retries back off and stop after two retries", async t => {
|
||||
const f = fixture();
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
|
||||
@@ -44,10 +44,16 @@ export interface TSClientAvatar {
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSClientServerInfo {
|
||||
name: string;
|
||||
iconId: number | null;
|
||||
}
|
||||
|
||||
// Keep enough room for avatars produced by the native client. The previous
|
||||
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
|
||||
// so every avatar silently fell back to its initial letter.
|
||||
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
|
||||
const MAX_SERVER_ICON_BYTES = 128 * 1024;
|
||||
|
||||
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity>;
|
||||
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
|
||||
@@ -274,6 +280,43 @@ export class TSClient extends EventEmitter {
|
||||
return { cacheKey, data };
|
||||
}
|
||||
|
||||
/** Read the public virtual-server name and icon marker from the active session. */
|
||||
async getServerInfo(): Promise<TSClientServerInfo> {
|
||||
const client = this.client;
|
||||
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
const generation = this.connectionGeneration;
|
||||
if (this.client !== client || !this.connected || this.connectionGeneration !== generation) {
|
||||
throw new Error("TeamSpeak session changed while reading server information");
|
||||
}
|
||||
return client.serverInfo ?? { name: "", iconId: null };
|
||||
}
|
||||
|
||||
/** Download the public virtual-server icon using TeamSpeak's normal file-transfer port. */
|
||||
async getServerIcon(iconId: number): Promise<Buffer | null> {
|
||||
const client = this.client;
|
||||
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isSafeInteger(iconId) || iconId === 0) return null;
|
||||
const generation = this.connectionGeneration;
|
||||
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
|
||||
const transfer = await client.fileTransferInitDownload(0n, `/icon_${iconId}`, "");
|
||||
if (!isCurrent()) return null;
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_SERVER_ICON_BYTES) return null;
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer | string, _encoding, callback) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
});
|
||||
await client.downloadFileData(this.options.target.host, transfer, destination);
|
||||
if (!isCurrent()) return null;
|
||||
const data = Buffer.concat(chunks);
|
||||
if (data.length === 0 || data.length > MAX_SERVER_ICON_BYTES) return null;
|
||||
return data;
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
if (this.client !== client) return;
|
||||
|
||||
@@ -20,11 +20,16 @@ class TeamSpeakStub extends EventEmitter {
|
||||
sent: Buffer[] = [];
|
||||
directory: TSDirectorySnapshot = { channels: [], clients: [] };
|
||||
avatarRequest: (id: number, uid: string) => Promise<TSClientAvatar | null> = async () => null;
|
||||
async connect() { this.disconnected = false; this.emit("directorySnapshot", this.directory); }
|
||||
emitDirectorySnapshotOnConnect = true;
|
||||
connectCalls = 0;
|
||||
serverInfoCalls = 0;
|
||||
async connect() { this.connectCalls++; this.disconnected = false; if (this.emitDirectorySnapshotOnConnect) this.emit("directorySnapshot", this.directory); }
|
||||
async disconnect() { this.disconnected = true; }
|
||||
getClientId() { return 1; }
|
||||
getChannelId() { return 1n; }
|
||||
isConnected() { return !this.disconnected; }
|
||||
async getServerInfo() { this.serverInfoCalls++; return { name: "兄弟们的teamspeak", iconId: null }; }
|
||||
async getServerIcon() { return null; }
|
||||
async sendProtocolCommand() {}
|
||||
async setAccompanimentActive() {}
|
||||
sendVoice(data: Buffer) { this.sent.push(data); this.emit("sent", data); }
|
||||
@@ -36,6 +41,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
createTeamSpeakClient?: () => TSClient;
|
||||
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
|
||||
configureSdk?: (sdk: TeamSpeakStub) => void;
|
||||
waitForFirstMessage?: boolean;
|
||||
} = {}) {
|
||||
const sdk = new TeamSpeakStub();
|
||||
overrides.configureSdk?.(sdk);
|
||||
@@ -65,7 +71,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
await bridge.shutdown();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
await first;
|
||||
if (overrides.waitForFirstMessage !== false) await first;
|
||||
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>;
|
||||
@@ -82,6 +88,28 @@ test("a TeamSpeak constructor failure releases the admitted gateway slot", { tim
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("server identity lookup waits until the directory sync publishes the connected state", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, { waitForFirstMessage: false, configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; } });
|
||||
while (!f.sdk.connectCalls) await nextTurn();
|
||||
await nextTurn();
|
||||
assert.equal(f.sdk.serverInfoCalls, 0);
|
||||
|
||||
const serverInfo = new Promise<Record<string, unknown>>(resolve => {
|
||||
f.socket.on("message", (data, binary) => {
|
||||
if (binary) return;
|
||||
const message = JSON.parse(data.toString()) as Record<string, unknown>;
|
||||
if (message.type === "serverInfo") resolve(message);
|
||||
});
|
||||
});
|
||||
f.sdk.emit("directorySnapshot", f.sdk.directory);
|
||||
assert.deepEqual(await serverInfo, { type: "serverInfo", name: "兄弟们的teamspeak", icon: null });
|
||||
const publishedTypes = f.messages.filter(message => !message.binary).map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
|
||||
assert.ok(publishedTypes.indexOf("connected") >= 0);
|
||||
assert.ok(publishedTypes.indexOf("serverInfo") > publishedTypes.indexOf("connected"));
|
||||
assert.equal(f.sdk.serverInfoCalls, 1);
|
||||
assert.ok(f.bridge.getActiveCount() > 0);
|
||||
});
|
||||
|
||||
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
|
||||
const encoder = new OpusEncoder(48000, 1);
|
||||
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
|
||||
|
||||
@@ -26,6 +26,7 @@ import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioSessionOpt
|
||||
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
|
||||
@@ -242,6 +243,7 @@ export class VoiceBridge {
|
||||
}
|
||||
|
||||
let initialStateSent = false;
|
||||
let serverInfoGeneration = 0;
|
||||
let hasConnectedOnce = false;
|
||||
let reconnectStartedAt = 0;
|
||||
let reconnectAttempt = 0;
|
||||
@@ -290,6 +292,7 @@ export class VoiceBridge {
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
if (wasReconnecting) sendJson({ type: "reconnected" });
|
||||
events.scheduleAvatars();
|
||||
void publishServerInfo();
|
||||
};
|
||||
|
||||
const resetDirectoryForReconnect = () => {
|
||||
@@ -299,6 +302,25 @@ export class VoiceBridge {
|
||||
initialStateSent = false;
|
||||
};
|
||||
|
||||
const publishServerInfo = async (): Promise<void> => {
|
||||
const generation = ++serverInfoGeneration;
|
||||
const isCurrent = () => generation === serverInfoGeneration
|
||||
&& this.entries.get(entryId) === entry && session.state === "connected";
|
||||
try {
|
||||
const info = await tsClient.getServerInfo();
|
||||
if (!isCurrent()) return;
|
||||
const name = info.name.trim().slice(0, 256);
|
||||
sendJson({ type: "serverInfo", name, icon: null });
|
||||
if (!info.iconId) return;
|
||||
const icon = await tsClient.getServerIcon(info.iconId);
|
||||
if (!icon || !isCurrent()) return;
|
||||
const dataUrl = avatarDataUrl(icon);
|
||||
if (dataUrl) sendJson({ type: "serverInfo", name, icon: dataUrl });
|
||||
} catch (error: unknown) {
|
||||
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server icon unavailable");
|
||||
}
|
||||
};
|
||||
|
||||
const failReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
|
||||
if (entry!.reconnectTimer) {
|
||||
clearTimeout(entry!.reconnectTimer);
|
||||
|
||||
Reference in new issue
Block a user