mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-11-30 18:02:50 +08:00
feat(open-protocol): add OpenProtocol v1 discovery and slash-command support
This commit is contained in:
1 parent
17008ae52e
commit
263c1ba6da
16 files changed
+1359
-183
No files matched your search
Generated
+24
-13
@@ -10,7 +10,7 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.1",
|
||||
"@honeybbq/teamspeak": "^1.0.0-beta.31",
|
||||
"@koa/router": "^15.4.0",
|
||||
"@sansenjian/qq-music-api": "~2.4.0",
|
||||
"axios": "^1.14.0",
|
||||
@@ -42,6 +42,9 @@
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2",
|
||||
"vitest": "^4.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.12.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@derhuerst/http-basic": {
|
||||
@@ -575,16 +578,24 @@
|
||||
"integrity": "sha512-Waj1cwPXJDucOib4a3bAISsKJVb15MKi9IvmTI/7ssVEm6sywXGjVJDhl6/umt1pK1ZS7PacXU3A1PmFKHEZ2w==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak-client": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz",
|
||||
"integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==",
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.31",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.31.tgz",
|
||||
"integrity": "sha512-rOTnUVJdSmBruIA0UGLaUbat6iRCB64Ztuj7mCtyPif7vWnXzUA1FypjNWGorFLOrACgzEYCw+nfy2VQW8GudA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
"node": ">=22.12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ssh2": "^1.17.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ssh2": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
@@ -637,12 +648,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.0.1.tgz",
|
||||
"integrity": "sha512-vs1Az2OOTBiP4q0pwjW5aF0xp9n4MxVrmkFBxc6EKZc6ddYx5gaZiAsZoq0uRRXWbi3AT/sBqn05eRPtn1JCPw==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
|
||||
"integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.0.1"
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
@@ -652,9 +663,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz",
|
||||
"integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
|
||||
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.1",
|
||||
"@honeybbq/teamspeak": "^1.0.0-beta.31",
|
||||
"@koa/router": "^15.4.0",
|
||||
"@sansenjian/qq-music-api": "~2.4.0",
|
||||
"axios": "^1.14.0",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseCommand, canRunCommand, isAdminCommand } from "./commands.js";
|
||||
import {
|
||||
parseCommand,
|
||||
parseCommandWithFallback,
|
||||
canRunCommand,
|
||||
isAdminCommand,
|
||||
} from "./commands.js";
|
||||
|
||||
describe("Command Parser", () => {
|
||||
it("parses simple command", () => {
|
||||
@@ -93,3 +98,31 @@ describe("canRunCommand", () => {
|
||||
expect(canRunCommand("clear", [], [6])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCommandWithFallback", () => {
|
||||
it("accepts both the configured primary prefix and slash fallback", () => {
|
||||
expect(parseCommandWithFallback("!play 晴天", "!")).toEqual({
|
||||
name: "play",
|
||||
args: "晴天",
|
||||
rawArgs: ["晴天"],
|
||||
flags: new Set(),
|
||||
});
|
||||
expect(parseCommandWithFallback("/play 晴天", "!")).toEqual({
|
||||
name: "play",
|
||||
args: "晴天",
|
||||
rawArgs: ["晴天"],
|
||||
flags: new Set(),
|
||||
});
|
||||
});
|
||||
|
||||
it("applies aliases on slash fallback and ignores bare slash", () => {
|
||||
expect(parseCommandWithFallback("/p 稻香", "!", { p: "play" })).toEqual({
|
||||
name: "play",
|
||||
args: "稻香",
|
||||
rawArgs: ["稻香"],
|
||||
flags: new Set(),
|
||||
});
|
||||
expect(parseCommandWithFallback("/", "!")).toBeNull();
|
||||
expect(parseCommandWithFallback("plain chat", "!")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,23 @@ export function parseCommand(
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCommandWithFallback(
|
||||
message: string,
|
||||
primaryPrefix: string,
|
||||
aliases: Record<string, string> = {},
|
||||
fallbackPrefixes: readonly string[] = ["/"],
|
||||
): ParsedCommand | null {
|
||||
const direct = parseCommand(message, primaryPrefix, aliases);
|
||||
if (direct) return direct;
|
||||
|
||||
for (const fallback of fallbackPrefixes) {
|
||||
if (!fallback || fallback === primaryPrefix) continue;
|
||||
const parsed = parseCommand(message, fallback, aliases);
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isAdminCommand(commandName: string): boolean {
|
||||
return ADMIN_COMMANDS.has(commandName);
|
||||
}
|
||||
|
||||
@@ -1948,3 +1948,115 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance — OpenProtocol & slash command routing", () => {
|
||||
it("accepts / commands when commandPrefix is '!' and routes private replies to invokerId", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [] });
|
||||
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
|
||||
`ok:${parsed.name}:${parsed.args}`,
|
||||
);
|
||||
|
||||
const dm: TS3TextMessage = {
|
||||
invokerName: "FlSpeakUser",
|
||||
invokerId: "12",
|
||||
invokerUid: "uid-fl",
|
||||
message: "/play 晴天",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dm);
|
||||
|
||||
expect(ctx.executeCommand).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
await handleTextMessage.call(ctx, makeMsg("/now"));
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
|
||||
});
|
||||
|
||||
it("routes permission denied and execution errors privately when triggered via DM", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] });
|
||||
const dmStop: TS3TextMessage = {
|
||||
invokerName: "Guest",
|
||||
invokerId: "22",
|
||||
invokerUid: "uid-guest",
|
||||
message: "/stop",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dmStop);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
const okCtx = makeGateCtx({ adminGroups: [] });
|
||||
okCtx.executeCommand = vi.fn(async () => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
await handleTextMessage.call(okCtx, { ...dmStop, message: "/play x" });
|
||||
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
|
||||
});
|
||||
|
||||
it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => {
|
||||
const tsClient = new EventEmitter() as EventEmitter & {
|
||||
getClientId(): number;
|
||||
};
|
||||
tsClient.getClientId = () => 99;
|
||||
const openProtocol = {
|
||||
scheduleAnnounce: vi.fn(),
|
||||
handlePluginCommand: vi.fn(async () => {}),
|
||||
reset: vi.fn(),
|
||||
};
|
||||
const ctx = {
|
||||
tsClient,
|
||||
openProtocol,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
autoPaused: false,
|
||||
idleTimer: null,
|
||||
idlePollTimer: null,
|
||||
jellyfinPollTimer: null,
|
||||
snapshotTimer: null,
|
||||
currentSourceIsSpotify: false,
|
||||
disconnectEmitted: false,
|
||||
_cancelIdleTimer: vi.fn(),
|
||||
_startIdlePoller: vi.fn(),
|
||||
_startJellyfinReportPoller: vi.fn(),
|
||||
unregisterManagedVoiceClient: vi.fn(),
|
||||
voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() },
|
||||
spotifyController: { stop: vi.fn() },
|
||||
player: { stop: vi.fn() },
|
||||
jellyfinReporter: undefined,
|
||||
queue: { clear: vi.fn() },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
refreshOccupancy: vi.fn(async () => {}),
|
||||
profileManager: { onChannelMoved: vi.fn(async () => {}) },
|
||||
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
} as Record<string, any>;
|
||||
|
||||
(BotInstance.prototype as any).setupTsEvents.call(ctx);
|
||||
|
||||
tsClient.emit("connected");
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 5, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 99, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(2);
|
||||
|
||||
const pluginCmd = {
|
||||
name: "tsclient:commands",
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 5,
|
||||
invokerName: "User",
|
||||
invokerUid: "uid-user",
|
||||
};
|
||||
tsClient.emit("pluginCommand", pluginCmd);
|
||||
expect(openProtocol.handlePluginCommand).toHaveBeenCalledWith(pluginCmd);
|
||||
|
||||
tsClient.emit("disconnected");
|
||||
expect(openProtocol.reset).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+42
-8
@@ -2,15 +2,17 @@ import { EventEmitter } from "node:events";
|
||||
import {
|
||||
TS3Client,
|
||||
type TS3ClientOptions,
|
||||
type TS3PluginCommand,
|
||||
type TS3TextMessage,
|
||||
type TS3VoiceActivity,
|
||||
type TS3VoiceSendFailure,
|
||||
} from "../ts-protocol/client.js";
|
||||
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, Song } from "../music/provider.js";
|
||||
import {
|
||||
parseCommand,
|
||||
parseCommandWithFallback,
|
||||
canRunCommand,
|
||||
type ParsedCommand,
|
||||
} from "./commands.js";
|
||||
@@ -154,11 +156,27 @@ export interface BotStatus {
|
||||
effectiveDuration?: number;
|
||||
}
|
||||
|
||||
async function sendTextReply(
|
||||
tsClient: Pick<TS3Client, "sendTextMessage">,
|
||||
msg: TS3TextMessage,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
if (msg.targetMode === 1) {
|
||||
const targetClientId = Number(msg.invokerId);
|
||||
if (Number.isInteger(targetClientId) && targetClientId > 0) {
|
||||
await tsClient.sendTextMessage(text, 1, targetClientId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await tsClient.sendTextMessage(text);
|
||||
}
|
||||
|
||||
export class BotInstance extends EventEmitter {
|
||||
readonly id: string;
|
||||
name: string;
|
||||
|
||||
private tsClient: TS3Client;
|
||||
private openProtocol: OpenProtocolManager;
|
||||
private player: AudioPlayer;
|
||||
private voiceDucking: VoiceDuckingController;
|
||||
private managedVoiceClients: ManagedVoiceClientRegistry;
|
||||
@@ -230,6 +248,14 @@ export class BotInstance extends EventEmitter {
|
||||
this.avatarStore = options.avatarStore;
|
||||
|
||||
this.tsClient = new TS3Client(options.tsOptions, this.logger);
|
||||
this.openProtocol = new OpenProtocolManager({
|
||||
transport: this.tsClient,
|
||||
getConfig: () => ({
|
||||
locale: this.config.locale,
|
||||
commandPrefix: this.config.commandPrefix,
|
||||
}),
|
||||
logger: this.logger,
|
||||
});
|
||||
this.player = new AudioPlayer(this.logger);
|
||||
this.voiceDucking = new VoiceDuckingController(
|
||||
this.player,
|
||||
@@ -446,6 +472,12 @@ export class BotInstance extends EventEmitter {
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("pluginCommand", (cmd: TS3PluginCommand) => {
|
||||
this.openProtocol?.handlePluginCommand(cmd).catch((err) => {
|
||||
this.logger.debug({ err }, "OpenProtocol plugin command handler failed");
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("disconnected", () => {
|
||||
// Always reset local state — covers the case where connect() never
|
||||
// completed (hanging handshake → 60s library idle timeout) and
|
||||
@@ -453,6 +485,7 @@ export class BotInstance extends EventEmitter {
|
||||
// short-circuited on !this.connected, leaving player stuck as "playing".
|
||||
this.lifecycleGeneration++;
|
||||
this.connected = false;
|
||||
this.openProtocol?.reset();
|
||||
this._cancelIdleTimer();
|
||||
this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS);
|
||||
this.voiceDucking.reset(true);
|
||||
@@ -487,6 +520,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.autoPaused = false;
|
||||
this._startIdlePoller();
|
||||
this._startJellyfinReportPoller();
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
});
|
||||
|
||||
this.tsClient.on("voiceActivity", (activity: TS3VoiceActivity) => {
|
||||
@@ -525,6 +559,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.profileManager.onChannelMoved(event.targetChannelID).catch((err) => {
|
||||
this.logger.warn({ err }, "Channel description move update failed");
|
||||
});
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
} else {
|
||||
this.voiceDucking.removeSpeaker(event.id);
|
||||
}
|
||||
@@ -667,6 +702,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.disconnectEmitted = true;
|
||||
this.emit("disconnected");
|
||||
}
|
||||
this.openProtocol?.reset();
|
||||
this.tsClient.disconnect();
|
||||
// Stop outbound PCM and initiate the TeamSpeak disconnect before removing
|
||||
// our id from the shared registry, minimizing the window in which another
|
||||
@@ -787,10 +823,10 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private async handleTextMessage(msg: TS3TextMessage): Promise<void> {
|
||||
const parsed = parseCommand(
|
||||
const parsed = parseCommandWithFallback(
|
||||
msg.message,
|
||||
this.config.commandPrefix,
|
||||
this.config.commandAliases
|
||||
this.config.commandAliases,
|
||||
);
|
||||
if (!parsed) return;
|
||||
|
||||
@@ -800,7 +836,7 @@ export class BotInstance extends EventEmitter {
|
||||
"Command denied: invoker not in adminGroups"
|
||||
);
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(COMMAND_DENIED_MESSAGE);
|
||||
await sendTextReply(this.tsClient, msg, COMMAND_DENIED_MESSAGE);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send permission-denied message to chat");
|
||||
}
|
||||
@@ -818,15 +854,13 @@ export class BotInstance extends EventEmitter {
|
||||
// A single long reply (e.g. full lyrics) would exceed TeamSpeak's
|
||||
// per-message byte cap, so split it and send the chunks in order.
|
||||
for (const chunk of splitTextIntoChunks(response)) {
|
||||
await this.tsClient.sendTextMessage(chunk);
|
||||
await sendTextReply(this.tsClient, msg, chunk);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error({ err, command: parsed.name }, "Command execution error");
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(
|
||||
`Error: ${(err as Error).message}`
|
||||
);
|
||||
await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send error message to chat");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { Client, generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { BotProfileManager } from "./profile.js";
|
||||
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
|
||||
import type { TS3Client } from "../ts-protocol/client.js";
|
||||
@@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => {
|
||||
|
||||
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
|
||||
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
|
||||
const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot");
|
||||
const commands: string[] = [];
|
||||
client.handler.sendPacket = vi.fn((_type, data: Buffer) => {
|
||||
const command = data.toString();
|
||||
ts.execCommand.mockImplementation(async (command: string) => {
|
||||
commands.push(command);
|
||||
const returnCode = command.match(/return_code=(\d+)/)?.[1];
|
||||
client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) });
|
||||
throw new Error("insufficient client permissions (error id=2568)");
|
||||
});
|
||||
ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command));
|
||||
ts.execCommand.mockImplementation((command: string) => client.execCommand(command));
|
||||
await pm.onSongChange(null);
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/);
|
||||
expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false);
|
||||
pm.onConnect();
|
||||
|
||||
@@ -29,7 +29,11 @@ function withFakeClient(
|
||||
): string[] {
|
||||
const calls: string[] = [];
|
||||
const fake = {
|
||||
execCommandWithResponse: vi.fn(async (cmd: string) => {
|
||||
send: vi.fn(async (req: { command: string; params?: readonly (readonly [string, unknown])[] }) => {
|
||||
const paramPairs = (req.params ?? [])
|
||||
.filter(([, v]) => v !== undefined)
|
||||
.map(([k, v]) => `${k}=${String(v)}`);
|
||||
const cmd = paramPairs.length > 0 ? `${req.command} ${paramPairs.join(" ")}` : req.command;
|
||||
calls.push(cmd);
|
||||
return respond(cmd);
|
||||
}),
|
||||
|
||||
@@ -1,34 +1,77 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Client as SDKClient, type ResolvedAddr } from "@honeybbq/teamspeak-client";
|
||||
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
|
||||
import { Resolver, type Client as SDKClient, type ClientOptions as SDKClientOptions, type ResolvedAddr } from "@honeybbq/teamspeak/client";
|
||||
import { TS3Client, type TS3VoiceSendFailure } from "./client.js";
|
||||
import type { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
class FakeSdkClient extends EventEmitter {
|
||||
clientID = 0;
|
||||
channelID = 1n;
|
||||
uid = "fake-uid";
|
||||
readonly addr: string;
|
||||
readonly options: SDKClientOptions;
|
||||
|
||||
constructor(addr: string, options: SDKClientOptions) {
|
||||
super();
|
||||
this.addr = addr;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.clientID = 42;
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.emit("disconnected", { error: undefined, willReconnect: false });
|
||||
}
|
||||
|
||||
async send(_request: { command: string; params?: Record<string, unknown> }): Promise<Record<string, string>[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
sendVoice(_data: Uint8Array, _codec: number): void {}
|
||||
|
||||
emitDisconnected(error?: Error): void {
|
||||
this.emit("disconnected", { error, willReconnect: false });
|
||||
}
|
||||
}
|
||||
|
||||
type Failure = TS3VoiceSendFailure;
|
||||
type Harness = { client: SDKClient | null; voiceFramesSent: number };
|
||||
type Harness = { client: FakeSdkClient | null; voiceFramesSent: number };
|
||||
|
||||
describe("TS3Client voice send failure lifecycle", () => {
|
||||
let client: TS3Client;
|
||||
let sdk: SDKClient;
|
||||
let sdk: FakeSdkClient;
|
||||
let logger: Logger;
|
||||
let records: Array<{ level: string; args: unknown[] }>;
|
||||
let onCreateSdk: ((sdk: FakeSdkClient) => void) | undefined;
|
||||
|
||||
const createClient = (extra: Partial<ConstructorParameters<typeof TS3Client>[0]> = {}) =>
|
||||
new TS3Client(
|
||||
{
|
||||
host: "localhost",
|
||||
port: 9987,
|
||||
queryPort: 10011,
|
||||
nickname: "VoiceTest",
|
||||
serverProtocol: "ts3",
|
||||
sdkClientFactory: (_identity, addr, _nickname, sdkOptions) => {
|
||||
const fake = new FakeSdkClient(addr, sdkOptions);
|
||||
onCreateSdk?.(fake);
|
||||
return fake as unknown as SDKClient;
|
||||
},
|
||||
...extra,
|
||||
},
|
||||
logger,
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers();
|
||||
// Keep the real SDK object, logger bridge and event dispatch. Replace only
|
||||
// its network handshake and explicit shutdown so no UDP socket is opened.
|
||||
vi.spyOn(SDKClient.prototype, "connect").mockImplementation(async function (this: SDKClient) {
|
||||
this.clid = 42;
|
||||
this._markConnected();
|
||||
});
|
||||
vi.spyOn(SDKClient.prototype, "disconnect").mockImplementation(async function (this: SDKClient) {
|
||||
this.handler.onClosed?.(null);
|
||||
});
|
||||
records = [];
|
||||
onCreateSdk = undefined;
|
||||
const capture = (level: string) => (...args: unknown[]) => records.push({ level, args });
|
||||
logger = { info: capture("info"), warn: capture("warn"), error: capture("error"), debug() {} } as unknown as Logger;
|
||||
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3" }, logger);
|
||||
client = createClient();
|
||||
await client.connect();
|
||||
sdk = (client as unknown as Harness).client!;
|
||||
});
|
||||
@@ -141,7 +184,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
send.mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
sdk.handler.onClosed?.(new Error("synthetic connection loss"));
|
||||
sdk.emitDisconnected(new Error("synthetic connection loss"));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(terminal).toEqual([]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
|
||||
@@ -152,22 +195,21 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
|
||||
it("does not revive a connection whose handshake was cancelled", async () => {
|
||||
let finishHandshake!: () => void;
|
||||
vi.spyOn(SDKClient.prototype, "connect").mockImplementationOnce(function (this: SDKClient) {
|
||||
return new Promise<void>(resolve => {
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementationOnce(() => new Promise<void>(resolve => {
|
||||
finishHandshake = () => {
|
||||
this.clid = 99;
|
||||
this._markConnected();
|
||||
fake.clientID = 99;
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
});
|
||||
}));
|
||||
};
|
||||
const connected = vi.fn();
|
||||
client.on("connected", connected);
|
||||
const pending = client.connect();
|
||||
await Promise.resolve();
|
||||
expect(finishHandshake).toBeTypeOf("function");
|
||||
const connectingSdk = (client as unknown as Harness).client!;
|
||||
const close = vi.spyOn(connectingSdk.handler, "close");
|
||||
const close = vi.spyOn(connectingSdk, "disconnect");
|
||||
const send = vi.spyOn(connectingSdk, "sendVoice");
|
||||
client.disconnect();
|
||||
finishHandshake();
|
||||
@@ -188,7 +230,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
await client.connect();
|
||||
// Old disconnect dispatch is queued; old socket callbacks may follow it.
|
||||
const before = records.length;
|
||||
sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(client.getClientId()).toBe(42);
|
||||
expect(records.slice(before).filter(record => record.level === "warn")).toEqual([]);
|
||||
@@ -198,28 +240,44 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
it("does not let an older named-channel lookup move the replacement connection", async () => {
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3", defaultChannel: "Music" }, logger);
|
||||
client = createClient({ defaultChannel: "Music" });
|
||||
let nextClientId = 101;
|
||||
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
|
||||
this.clid = nextClientId++;
|
||||
this._markConnected();
|
||||
});
|
||||
let finishOlderLookup!: (rows: Record<string, string>[]) => void;
|
||||
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockImplementation(function (this: SDKClient) {
|
||||
if (this.clid === 101) return new Promise(resolve => { finishOlderLookup = resolve; });
|
||||
return Promise.resolve([{ cid: "20", channel_name: "Music" }]);
|
||||
});
|
||||
const moves: Array<{ clientId: number; command: string }> = [];
|
||||
vi.spyOn(SDKClient.prototype, "execCommand").mockImplementation(async function (this: SDKClient, command: string) {
|
||||
moves.push({ clientId: this.clid, command });
|
||||
});
|
||||
const moves: Array<{ clientId: number; command: string; params: Record<string, unknown> | undefined }> = [];
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementation(async () => {
|
||||
fake.clientID = nextClientId++;
|
||||
});
|
||||
vi.spyOn(fake, "send").mockImplementation(async (req) => {
|
||||
if (req.command === "channellist") {
|
||||
if (fake.clientID === 101) {
|
||||
return new Promise(resolve => { finishOlderLookup = resolve; });
|
||||
}
|
||||
return [{ cid: "20", channel_name: "Music", pid: "0", channel_order: "0" }];
|
||||
}
|
||||
if (req.command === "clientmove") {
|
||||
moves.push({ clientId: fake.clientID, command: req.command, params: req.params });
|
||||
}
|
||||
return [];
|
||||
});
|
||||
};
|
||||
const first = client.connect();
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(finishOlderLookup).toBeTypeOf("function");
|
||||
await client.connect();
|
||||
finishOlderLookup([{ cid: "10", channel_name: "Music" }]);
|
||||
finishOlderLookup([{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }]);
|
||||
await first;
|
||||
expect(moves).toEqual([{ clientId: 102, command: "clientmove clid=102 cid=20" }]);
|
||||
expect(moves).toEqual([
|
||||
{
|
||||
clientId: 102,
|
||||
command: "clientmove",
|
||||
params: [
|
||||
["clid", 102],
|
||||
["cid", 20n],
|
||||
["cpw", undefined],
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(records.filter(record => record.args[1] === "Joined channel").map(record => record.args[0])).toEqual([{ channelName: "Music", cid: "20" }]);
|
||||
expect(client.getClientId()).toBe(102);
|
||||
});
|
||||
@@ -230,13 +288,14 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
vi.spyOn(Resolver.prototype, "resolve").mockImplementationOnce(() => new Promise(resolve => { finishOlderResolution = resolve; }))
|
||||
.mockResolvedValue([row("192.0.2.2:9987")]);
|
||||
let sequence = 0;
|
||||
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
|
||||
const clientId = 101 + sequence++;
|
||||
const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver;
|
||||
await resolver.resolve("voice.test:9987");
|
||||
this.clid = clientId;
|
||||
this._markConnected();
|
||||
});
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementation(async () => {
|
||||
const clientId = 101 + sequence++;
|
||||
const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver;
|
||||
await resolver.resolve("voice.test:9987");
|
||||
fake.clientID = clientId;
|
||||
});
|
||||
};
|
||||
const first = client.connect();
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(finishOlderResolution).toBeTypeOf("function");
|
||||
@@ -249,12 +308,20 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
});
|
||||
|
||||
it.each(["10", "Music"])("does not report an old %s channel move after connection replacement", async channel => {
|
||||
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockResolvedValue([{ cid: "10", channel_name: "Music" }]);
|
||||
let finishMove!: () => void;
|
||||
const move = vi.spyOn(sdk, "execCommand").mockImplementation(() => new Promise<void>(resolve => { finishMove = resolve; }));
|
||||
const moveSpy = vi.fn(() => new Promise<void>(resolve => { finishMove = resolve; }));
|
||||
vi.spyOn(sdk, "send").mockImplementation(async (req) => {
|
||||
if (req.command === "channellist") {
|
||||
return [{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }];
|
||||
}
|
||||
if (req.command === "clientmove") {
|
||||
await moveSpy();
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const joining = client.joinChannel(channel);
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(move).toHaveBeenCalledWith("clientmove clid=42 cid=10", 10000);
|
||||
expect(moveSpy).toHaveBeenCalledTimes(1);
|
||||
await client.connect();
|
||||
finishMove();
|
||||
await joining;
|
||||
@@ -263,7 +330,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
|
||||
it("does not report a stale channel lookup failure against the new connection", async () => {
|
||||
let failLookup!: (error: Error) => void;
|
||||
vi.spyOn(sdk, "execCommandWithResponse").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; }));
|
||||
vi.spyOn(sdk, "send").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; }));
|
||||
const joining = client.joinChannel("Music");
|
||||
await client.connect();
|
||||
failLookup(new Error("old credential-secret failure"));
|
||||
@@ -275,7 +342,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
it("keeps safe async UDP error detail while throttling without terminalizing it", async () => {
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
for (let i = 0; i < 100; i++) sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
for (let i = 0; i < 100; i++) sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
const warnings = records.filter(record => record.level === "warn");
|
||||
expect(warnings).toHaveLength(2);
|
||||
@@ -286,7 +353,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
});
|
||||
|
||||
it("discards unsafe async UDP codes and cancels their summary on disconnect", async () => {
|
||||
sdk.logger.warn("udp send error", { code: "credential-secret", message: "credential-secret" });
|
||||
sdk.options.logger?.warn?.("udp send error", { code: "credential-secret", message: "credential-secret" });
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(records.filter(record => record.level === "warn").filter(record => String(record.args[1]).includes("udp send error"))).toHaveLength(1);
|
||||
|
||||
+150
-75
@@ -1,24 +1,39 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentity as genTS3Identity,
|
||||
getUidFromPublicKey,
|
||||
identityFromString,
|
||||
sendTextMessage,
|
||||
asChannelID,
|
||||
asClientID,
|
||||
Codec,
|
||||
deleteFile,
|
||||
getClientProperties,
|
||||
initFileUpload,
|
||||
listChannels,
|
||||
listClients,
|
||||
clientMove,
|
||||
getClientInfo,
|
||||
fileTransferDeleteFile,
|
||||
type Identity,
|
||||
type TextMessage,
|
||||
type ClientInfo,
|
||||
type ClientLeftViewEvent,
|
||||
moveClient,
|
||||
sendChannelMessage,
|
||||
sendPluginCommand as sdkSendPluginCommand,
|
||||
sendPrivateMessage,
|
||||
sendServerMessage,
|
||||
type ChannelID,
|
||||
type ClientEnterEvent,
|
||||
type ClientEntry,
|
||||
type ClientLeaveEvent,
|
||||
type ClientMovedEvent,
|
||||
type VoiceData,
|
||||
type DisconnectedEvent,
|
||||
type FileUploadInfo,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
type PluginCommandEvent,
|
||||
type PluginCommandTarget,
|
||||
type TextMessageEvent,
|
||||
type VoiceDataEvent,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentitySync as genTS3Identity,
|
||||
parseIdentity,
|
||||
UIDAlgorithm,
|
||||
type ClientOptions as SDKClientOptions,
|
||||
type Identity,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import {
|
||||
detectServerProtocol,
|
||||
@@ -32,7 +47,7 @@ import {
|
||||
|
||||
export { CODEC_OPUS_MUSIC } from "./voice.js";
|
||||
export type { ServerProtocol } from "./protocol-detect.js";
|
||||
export type { FileUploadInfo } from "@honeybbq/teamspeak-client";
|
||||
export type { FileUploadInfo, PluginCommandTarget } from "@honeybbq/teamspeak";
|
||||
|
||||
/** Escape a string for use in TS3 ServerQuery-style commands. */
|
||||
export function escapeTS3(str: string): string {
|
||||
@@ -60,6 +75,13 @@ export interface TS3ClientOptions {
|
||||
serverProtocol?: ServerProtocol;
|
||||
/** API key for TS6 HTTP Query authentication. */
|
||||
ts6ApiKey?: string;
|
||||
/** @internal Test seam to substitute the underlying SDK Client instance. */
|
||||
sdkClientFactory?: (
|
||||
identity: Identity,
|
||||
addr: string,
|
||||
nickname: string,
|
||||
options: SDKClientOptions,
|
||||
) => TS3FullClient;
|
||||
}
|
||||
|
||||
export interface TS3TextMessage {
|
||||
@@ -71,6 +93,14 @@ export interface TS3TextMessage {
|
||||
invokerGroups: string[]; // sender's TS server-group ids; [] when not in view cache
|
||||
}
|
||||
|
||||
export interface TS3PluginCommand {
|
||||
name: string;
|
||||
data: string;
|
||||
invokerId: number;
|
||||
invokerName: string;
|
||||
invokerUid: string;
|
||||
}
|
||||
|
||||
/** Lightweight voice-packet signal used for activity detection. The encoded
|
||||
* payload is intentionally not forwarded beyond this protocol wrapper. */
|
||||
export interface TS3VoiceActivity {
|
||||
@@ -115,26 +145,36 @@ function safeSocketErrorCode(error: unknown): string | undefined {
|
||||
const VISIBLE_CLIENT_UID_RELEASE_GRACE_MS = 1_000;
|
||||
|
||||
/**
|
||||
* Map the library's TextMessage to our wrapper. Preserves invokerGroups (the
|
||||
* Map the library's TextMessageEvent to our wrapper. Preserves invokerGroups (the
|
||||
* sender's TS server groups), which the library populates only when the sender
|
||||
* is in the bot's client-view cache; otherwise it is []. Used by the chat
|
||||
* command permission gate.
|
||||
*/
|
||||
export function toTS3TextMessage(msg: TextMessage): TS3TextMessage {
|
||||
export function toTS3TextMessage(msg: TextMessageEvent): TS3TextMessage {
|
||||
return {
|
||||
invokerName: msg.invokerName,
|
||||
invokerId: String(msg.invokerID),
|
||||
invokerUid: msg.invokerUID,
|
||||
message: msg.message,
|
||||
targetMode: msg.targetMode,
|
||||
invokerGroups: msg.invokerGroups ?? [],
|
||||
invokerGroups: (msg.invokerGroups ?? []).map((groupId) => String(groupId)),
|
||||
};
|
||||
}
|
||||
|
||||
export function toTS3PluginCommand(ev: PluginCommandEvent): TS3PluginCommand {
|
||||
return {
|
||||
name: ev.name,
|
||||
data: ev.data,
|
||||
invokerId: Number(ev.invokerID),
|
||||
invokerName: ev.invokerName,
|
||||
invokerUid: ev.invokerUID,
|
||||
};
|
||||
}
|
||||
|
||||
export class TS3Client extends EventEmitter {
|
||||
private client: TS3FullClient | null = null;
|
||||
private identity: Identity;
|
||||
private readonly clientUid: string;
|
||||
private clientUid: string;
|
||||
private clientId = 0;
|
||||
private readonly visibleClientUids = new Map<number, string>();
|
||||
private readonly visibleClientUidReleaseTimers = new Map<
|
||||
@@ -156,11 +196,11 @@ export class TS3Client extends EventEmitter {
|
||||
this.logger = logger;
|
||||
|
||||
if (options.identity) {
|
||||
this.identity = identityFromString(options.identity);
|
||||
this.identity = parseIdentity(options.identity);
|
||||
} else {
|
||||
this.identity = genTS3Identity(8);
|
||||
}
|
||||
this.clientUid = getUidFromPublicKey(this.identity.publicKeyBase64());
|
||||
this.clientUid = this.identity.uid(UIDAlgorithm.SHA1);
|
||||
}
|
||||
|
||||
/** The detected (or forced) server protocol after connect(). */
|
||||
@@ -275,43 +315,52 @@ export class TS3Client extends EventEmitter {
|
||||
this.logger.warn(msg);
|
||||
};
|
||||
|
||||
sdkClient = new TS3FullClient(this.identity, addr, this.options.nickname, {
|
||||
const sdkOptions: SDKClientOptions = {
|
||||
// Forward server password to the protocol library so it can be
|
||||
// included in clientinit for password-protected servers
|
||||
serverPassword: this.options.serverPassword,
|
||||
resolver: voiceEndpointResolver,
|
||||
logger: {
|
||||
debug: (msg) => { if (isCurrent()) this.logger.debug(msg); },
|
||||
info: (msg) => { if (isCurrent()) this.logger.info(msg); },
|
||||
debug: (msg: string) => { if (isCurrent()) this.logger.debug(msg); },
|
||||
info: (msg: string) => { if (isCurrent()) this.logger.info(msg); },
|
||||
warn: throttledWarn,
|
||||
error: (msg) => { if (isCurrent()) this.logger.error(msg); },
|
||||
error: (msg: string) => { if (isCurrent()) this.logger.error(msg); },
|
||||
},
|
||||
});
|
||||
};
|
||||
sdkClient = this.options.sdkClientFactory
|
||||
? this.options.sdkClientFactory(this.identity, addr, this.options.nickname, sdkOptions)
|
||||
: new TS3FullClient(this.identity, addr, this.options.nickname, sdkOptions);
|
||||
this.client = sdkClient;
|
||||
|
||||
sdkClient.on("textMessage", (msg: TextMessage) => {
|
||||
sdkClient.on("textMessage", (msg: TextMessageEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
if (msg.invokerID === this.clientId) return;
|
||||
this.emit("textMessage", toTS3TextMessage(msg));
|
||||
});
|
||||
|
||||
sdkClient.on("voiceData", (voice: VoiceData) => {
|
||||
sdkClient.on("pluginCommand", (ev: PluginCommandEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("pluginCommand", toTS3PluginCommand(ev));
|
||||
});
|
||||
|
||||
sdkClient.on("voiceData", (voice: VoiceDataEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
// The library normally suppresses our own packets; retain the explicit
|
||||
// guard so a future protocol change cannot make a bot duck itself.
|
||||
if (voice.clientId === this.clientId) return;
|
||||
const clientUid = this.visibleClientUids.get(voice.clientId);
|
||||
const voiceClientId = Number(voice.clientID);
|
||||
if (voiceClientId === this.clientId) return;
|
||||
const clientUid = this.visibleClientUids.get(voiceClientId);
|
||||
const activity: TS3VoiceActivity = {
|
||||
clientId: voice.clientId,
|
||||
clientId: voiceClientId,
|
||||
codec: voice.codec,
|
||||
...(clientUid ? { clientUid } : {}),
|
||||
};
|
||||
this.emit("voiceActivity", activity);
|
||||
});
|
||||
|
||||
sdkClient.on("disconnected", (err) => {
|
||||
sdkClient.on("disconnected", (ev: DisconnectedEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const code = safeSocketErrorCode(err);
|
||||
const code = safeSocketErrorCode(ev.error);
|
||||
this.logger.warn(code ? { code } : {}, "Connection closed");
|
||||
++this.connectionGeneration;
|
||||
this.resetVoiceSendState();
|
||||
@@ -321,48 +370,44 @@ export class TS3Client extends EventEmitter {
|
||||
this.emit("disconnected");
|
||||
});
|
||||
|
||||
sdkClient.on("clientEnter", (info: ClientInfo) => {
|
||||
sdkClient.on("clientEnter", (info: ClientEnterEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.rememberVisibleClientUid(info.id, info.uid);
|
||||
this.rememberVisibleClientUid(Number(info.id), info.uid ?? "");
|
||||
this.logger.debug(
|
||||
{ nickname: info.nickname, id: info.id },
|
||||
{ nickname: info.nickname, id: Number(info.id) },
|
||||
"Client entered"
|
||||
);
|
||||
this.emit("clientEnter", info);
|
||||
});
|
||||
|
||||
sdkClient.on("clientLeave", (ev: ClientLeftViewEvent) => {
|
||||
sdkClient.on("clientLeave", (ev: ClientLeaveEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.releaseVisibleClientUid(ev.id);
|
||||
this.logger.debug({ id: ev.id }, "Client left");
|
||||
this.emit("clientLeave", ev);
|
||||
const id = Number(ev.clientID);
|
||||
this.releaseVisibleClientUid(id);
|
||||
this.logger.debug({ id }, "Client left");
|
||||
this.emit("clientLeave", { ...ev, id });
|
||||
});
|
||||
|
||||
sdkClient.on("clientMoved", (ev: ClientMovedEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(ev.clientID);
|
||||
this.logger.debug(
|
||||
{ id: ev.id, targetChannelID: ev.targetChannelID.toString() },
|
||||
{ id, targetChannelID: ev.targetChannelID.toString() },
|
||||
"Client moved"
|
||||
);
|
||||
this.emit("clientMoved", ev);
|
||||
this.emit("clientMoved", { ...ev, id });
|
||||
});
|
||||
|
||||
await sdkClient.connect();
|
||||
if (!isCurrent()) {
|
||||
// DNS/socket setup may finish after disconnect() closed the transport.
|
||||
// Close it again without waiting on command replies from a stale session.
|
||||
sdkClient.handler.close();
|
||||
// Handshake may finish after disconnect() or a newer connect() superseded it.
|
||||
await sdkClient.disconnect().catch(() => {});
|
||||
return;
|
||||
}
|
||||
// Note: @honeybbq/teamspeak-client 0.2.x ships a universal clientinit
|
||||
// (client_version "3.?.? [Build: 5680278000]" + matching signature)
|
||||
// that works against both TS3 and TS6 servers. The old 3.6.2 monkey-
|
||||
// patch on handler.sendPacket was removed when we bumped to 0.2.1 — it
|
||||
// would have replaced the library's new correct version with a stale
|
||||
// signature and made TS6 handshakes fail.
|
||||
await sdkClient.waitConnected();
|
||||
if (!isCurrent()) return;
|
||||
this.clientId = sdkClient.clientID();
|
||||
this.clientId = Number(sdkClient.clientID);
|
||||
if (sdkClient.uid) {
|
||||
this.clientUid = sdkClient.uid;
|
||||
}
|
||||
this.voiceFramesSent = 0;
|
||||
this.logger.info(
|
||||
{ clientId: this.clientId, protocol: this.detectedProtocol },
|
||||
@@ -393,7 +438,12 @@ export class TS3Client extends EventEmitter {
|
||||
const isNumeric = /^\d+$/.test(channelName);
|
||||
if (isNumeric) {
|
||||
try {
|
||||
await clientMove(client, clientId, BigInt(channelName), password);
|
||||
await moveClient(
|
||||
client,
|
||||
asClientID(clientId),
|
||||
asChannelID(BigInt(channelName)),
|
||||
password ? { password } : undefined,
|
||||
);
|
||||
if (!isCurrent()) return;
|
||||
this.logger.info({ channelName }, "Joined channel");
|
||||
} catch (err) {
|
||||
@@ -412,7 +462,12 @@ export class TS3Client extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
await clientMove(client, clientId, channel.id, password);
|
||||
await moveClient(
|
||||
client,
|
||||
asClientID(clientId),
|
||||
channel.id,
|
||||
password ? { password } : undefined,
|
||||
);
|
||||
if (!isCurrent()) return;
|
||||
this.logger.info(
|
||||
{ channelName, cid: channel.id.toString() },
|
||||
@@ -425,19 +480,38 @@ export class TS3Client extends EventEmitter {
|
||||
|
||||
async sendTextMessage(
|
||||
message: string,
|
||||
targetMode: number = 2
|
||||
targetMode: number = 2,
|
||||
targetClientId?: number,
|
||||
): Promise<void> {
|
||||
if (!this.client) return;
|
||||
// targetMode 2 = channel, target 0 = current channel
|
||||
const target = targetMode === 2 ? BigInt(0) : BigInt(this.clientId);
|
||||
await sendTextMessage(this.client, targetMode, target, message);
|
||||
if (targetMode === 1) {
|
||||
if (targetClientId === undefined) return;
|
||||
await sendPrivateMessage(this.client, asClientID(targetClientId), message);
|
||||
return;
|
||||
}
|
||||
if (targetMode === 3) {
|
||||
await sendServerMessage(this.client, message);
|
||||
return;
|
||||
}
|
||||
await sendChannelMessage(this.client, message);
|
||||
}
|
||||
|
||||
async getClientsInChannel(): Promise<ClientInfo[]> {
|
||||
async sendPluginCommand(
|
||||
name: string,
|
||||
data: string,
|
||||
target: PluginCommandTarget | number = "channel",
|
||||
): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
const resolvedTarget: PluginCommandTarget =
|
||||
typeof target === "number" ? { clientID: asClientID(target) } : target;
|
||||
await sdkSendPluginCommand(this.client, name, data, resolvedTarget);
|
||||
}
|
||||
|
||||
async getClientsInChannel(): Promise<ClientEntry[]> {
|
||||
if (!this.client) return [];
|
||||
try {
|
||||
const allClients = await listClients(this.client);
|
||||
const myChannelId = this.client.channelID();
|
||||
const myChannelId = this.client.channelID;
|
||||
return allClients.filter((c) => c.channelID === myChannelId);
|
||||
} catch {
|
||||
return [];
|
||||
@@ -454,9 +528,7 @@ export class TS3Client extends EventEmitter {
|
||||
async getClientServerGroups(clid: number): Promise<string[]> {
|
||||
if (!this.client) return [];
|
||||
try {
|
||||
const info = await getClientInfo(this.client, clid);
|
||||
// `client_servergroups`: comma-separated server-group ids (verified in
|
||||
// @honeybbq/teamspeak-client dist/index.mjs; listClients parses the same).
|
||||
const info = await getClientProperties(this.client, asClientID(clid));
|
||||
const raw = info.client_servergroups ?? "";
|
||||
return raw ? raw.split(",") : [];
|
||||
} catch {
|
||||
@@ -468,29 +540,32 @@ export class TS3Client extends EventEmitter {
|
||||
|
||||
async execCommand(cmd: string): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await this.client.execCommand(cmd);
|
||||
await this.client.exec(cmd);
|
||||
}
|
||||
|
||||
/** Fire a command without waiting for the server's response. */
|
||||
async sendCommandNoWait(cmd: string): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await this.client.sendCommandNoWait(cmd);
|
||||
await this.client.execNoWait(cmd);
|
||||
}
|
||||
|
||||
async execCommandWithResponse(cmd: string): Promise<Record<string, string>[]> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
return this.client.execCommandWithResponse(cmd);
|
||||
return this.client.exec(cmd);
|
||||
}
|
||||
|
||||
async fileTransferInitUpload(
|
||||
channelID: bigint,
|
||||
channelID: bigint | ChannelID,
|
||||
path: string,
|
||||
password: string,
|
||||
size: bigint,
|
||||
overwrite = true,
|
||||
): Promise<FileUploadInfo> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
return this.client.fileTransferInitUpload(channelID, path, password, size, overwrite);
|
||||
return initFileUpload(this.client, asChannelID(channelID), path, size, {
|
||||
password,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
async uploadFileData(host: string, info: FileUploadInfo, data: Readable): Promise<void> {
|
||||
@@ -498,9 +573,9 @@ export class TS3Client extends EventEmitter {
|
||||
await this.client.uploadFileData(host, info, data);
|
||||
}
|
||||
|
||||
async fileTransferDeleteFile(channelID: bigint, paths: string[]): Promise<void> {
|
||||
async fileTransferDeleteFile(channelID: bigint | ChannelID, paths: string[]): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await fileTransferDeleteFile(this.client, channelID, paths);
|
||||
await deleteFile(this.client, asChannelID(channelID), paths);
|
||||
}
|
||||
|
||||
/** The server host (needed for file transfer TCP connections). */
|
||||
@@ -511,7 +586,7 @@ export class TS3Client extends EventEmitter {
|
||||
/** The current channel ID of this client. */
|
||||
getChannelId(): bigint {
|
||||
if (!this.client) return 0n;
|
||||
return this.client.channelID();
|
||||
return this.client.channelID;
|
||||
}
|
||||
|
||||
private voiceFramesSent = 0;
|
||||
@@ -520,7 +595,7 @@ export class TS3Client extends EventEmitter {
|
||||
const client = this.client;
|
||||
if (!client || this.disconnecting) return "unavailable";
|
||||
try {
|
||||
client.sendVoice(opusFrame, 5);
|
||||
client.sendVoice(opusFrame, Codec.OpusMusic);
|
||||
} catch (err) {
|
||||
if (this.voiceFailure) {
|
||||
this.voiceFailure.consecutiveFailures++;
|
||||
@@ -581,7 +656,7 @@ export class TS3Client extends EventEmitter {
|
||||
}
|
||||
|
||||
getIdentityExport(): string {
|
||||
return this.identity.toString();
|
||||
return this.identity.export();
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import pino from "pino";
|
||||
import {
|
||||
ACK_GLOBAL_BURST,
|
||||
ANNOUNCE_DEBOUNCE_MS,
|
||||
ANNOUNCE_RETRY_DELAY_MS,
|
||||
APP_NAME,
|
||||
APP_VERSION,
|
||||
BOT_CAPABILITIES,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
COMMANDS_PLUGIN,
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_PLUGIN,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
MAX_CMD_ARGS_CHARS,
|
||||
MAX_CMD_DESC_CHARS,
|
||||
MAX_CMD_NAME_CHARS,
|
||||
MAX_COMMANDS,
|
||||
MAX_PAYLOAD_BYTES,
|
||||
OPEN_PROTOCOL_VERSION,
|
||||
OpenProtocolManager,
|
||||
buildCommandsListAckJson,
|
||||
buildIdentityPayloadJson,
|
||||
buildOpenProtocolCommands,
|
||||
type OpenProtocolRuntimeConfig,
|
||||
type OpenProtocolTransport,
|
||||
} from "./open-protocol.js";
|
||||
import type { TS3PluginCommand } from "./client.js";
|
||||
|
||||
function makeCmd(overrides: Partial<TS3PluginCommand> = {}): TS3PluginCommand {
|
||||
return {
|
||||
name: IDENTITY_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "announce" }),
|
||||
invokerId: 7,
|
||||
invokerName: "Alice",
|
||||
invokerUid: "uid-alice",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("OpenProtocol payload builders", () => {
|
||||
it("builds valid v1 identity payloads with package version and command_prefix under 1024 bytes", () => {
|
||||
const raw = buildIdentityPayloadJson("announce", "!");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
expect(JSON.parse(raw)).toEqual({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "announce",
|
||||
client_type: "bot",
|
||||
app_name: APP_NAME,
|
||||
app_version: APP_VERSION,
|
||||
capabilities: [...BOT_CAPABILITIES],
|
||||
command_prefix: "!",
|
||||
});
|
||||
|
||||
const ack = JSON.parse(buildIdentityPayloadJson("announce_ack", "?"));
|
||||
expect(ack.action).toBe("announce_ack");
|
||||
expect(ack.command_prefix).toBe("?");
|
||||
});
|
||||
|
||||
it("drops command_prefix if an oversized value would exceed 1024 bytes", () => {
|
||||
const raw = buildIdentityPayloadJson("announce", "p".repeat(1200));
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
expect(JSON.parse(raw).app_name).toBe(APP_NAME);
|
||||
});
|
||||
|
||||
it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => {
|
||||
for (const locale of ["zh", "en"] as const) {
|
||||
const cmds = buildOpenProtocolCommands(locale);
|
||||
expect(cmds.length).toBeGreaterThan(0);
|
||||
expect(cmds.length).toBeLessThanOrEqual(MAX_COMMANDS);
|
||||
|
||||
for (const cmd of cmds) {
|
||||
expect(Array.from(cmd.name).length).toBeLessThanOrEqual(MAX_CMD_NAME_CHARS);
|
||||
expect(Array.from(cmd.desc).length).toBeLessThanOrEqual(MAX_CMD_DESC_CHARS);
|
||||
if (cmd.args !== undefined) {
|
||||
expect(Array.from(cmd.args).length).toBeLessThanOrEqual(MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
const raw = buildCommandsListAckJson(locale, "!");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
const parsed = JSON.parse(raw) as {
|
||||
v: number;
|
||||
action: string;
|
||||
prefix: string;
|
||||
commands: unknown[];
|
||||
};
|
||||
expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION);
|
||||
expect(parsed.action).toBe("list_ack");
|
||||
expect(parsed.prefix).toBe("!");
|
||||
expect(parsed.commands.length).toBe(cmds.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenProtocolManager", () => {
|
||||
let nowMs: number;
|
||||
let clientId: number;
|
||||
let config: OpenProtocolRuntimeConfig;
|
||||
let sendPluginCommand: ReturnType<typeof vi.fn>;
|
||||
let manager: OpenProtocolManager;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
nowMs = 100_000;
|
||||
clientId = 42;
|
||||
config = { locale: "zh", commandPrefix: "!" };
|
||||
sendPluginCommand = vi.fn(async () => {});
|
||||
const transport: OpenProtocolTransport = {
|
||||
getClientId: () => clientId,
|
||||
sendPluginCommand: sendPluginCommand as OpenProtocolTransport["sendPluginCommand"],
|
||||
};
|
||||
manager = new OpenProtocolManager({
|
||||
transport,
|
||||
getConfig: () => config,
|
||||
logger: pino({ level: "silent" }),
|
||||
now: () => nowMs,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
manager.reset();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("ignores unrelated plugins, self-sent commands, malformed JSON, and non-v1 versions", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ name: "other:plugin" }));
|
||||
await manager.handlePluginCommand(makeCmd({ invokerId: 42 }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: "{not-json" }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 2, action: "query" }) }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce_ack" }) }));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({ name: COMMANDS_PLUGIN, data: JSON.stringify({ v: 1, action: "list_ack" }) }),
|
||||
);
|
||||
expect(sendPluginCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replies with unicast announce_ack to announce and query, with separate cooldowns", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), 7);
|
||||
expect(JSON.parse(sendPluginCommand.mock.calls[0][1] as string).action).toBe("announce_ack");
|
||||
|
||||
// Repeated announce within 10s cooldown is suppressed
|
||||
nowMs += 3_000;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
// query uses an independent 5s cooldown bucket, so it succeeds immediately
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Repeated query within 5s is suppressed, then allowed after 5s
|
||||
nowMs += IDENTITY_QUERY_COOLDOWN_MS - 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
nowMs += 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
// announce still respects its 10s cooldown until elapsed
|
||||
nowMs += 1_000; // total 9_000ms since first announce
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
nowMs += IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("replies with localized unicast list_ack on commands list_req using dynamic config", async () => {
|
||||
config = { locale: "en", commandPrefix: "?" };
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenCalledWith(COMMANDS_PLUGIN, expect.any(String), 11);
|
||||
const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
|
||||
expect(payload.v).toBe(1);
|
||||
expect(payload.action).toBe("list_ack");
|
||||
expect(payload.prefix).toBe("?");
|
||||
expect(payload.commands[0]).toEqual({ name: "play", args: "<query>", desc: "Play song" });
|
||||
|
||||
// Cooldown falls back to invokerId when invokerUid is empty
|
||||
nowMs += COMMANDS_LIST_REQ_COOLDOWN_MS - 10;
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("enforces global token bucket across peers and rolls back cooldown/token on send failure", async () => {
|
||||
for (let i = 1; i <= ACK_GLOBAL_BURST; i++) {
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: i,
|
||||
invokerUid: `peer-${i}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// 5th distinct peer in same millisecond is throttled by global burst
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// After 500ms, 1 token refills (2/sec)
|
||||
nowMs += 500;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("transient send failure"));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
|
||||
// Because send failed, both peer-99 cooldown and global token were rolled back
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 2);
|
||||
});
|
||||
|
||||
it("debounces self-announce over 2s window and emits at most one trailing announce", async () => {
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), "channel");
|
||||
|
||||
// Two calls inside 2s window coalesce into a single trailing broadcast
|
||||
nowMs += 400;
|
||||
manager.scheduleAnnounce();
|
||||
nowMs += 600;
|
||||
manager.scheduleAnnounce();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS - 1_000;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_DEBOUNCE_MS - 400);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries failed announce once after 500ms and cancels pending timers on reset", async () => {
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("channel broadcast error"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_RETRY_DELAY_MS;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Trigger another failure then reset before retry fires
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("error before disconnect"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
manager.reset();
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { PluginCommandTarget, TS3PluginCommand } from "./client.js";
|
||||
|
||||
export const OPEN_PROTOCOL_VERSION = 1;
|
||||
export const IDENTITY_PLUGIN = "tsclient:identity";
|
||||
export const COMMANDS_PLUGIN = "tsclient:commands";
|
||||
export const MAX_PAYLOAD_BYTES = 1024;
|
||||
|
||||
export const APP_NAME = "TSMusicBot";
|
||||
export const BOT_CAPABILITIES = ["chat:slash_commands"] as const;
|
||||
|
||||
export const ANNOUNCE_DEBOUNCE_MS = 2_000;
|
||||
export const ANNOUNCE_RETRY_DELAY_MS = 500;
|
||||
|
||||
export const IDENTITY_ANNOUNCE_COOLDOWN_MS = 10_000;
|
||||
export const IDENTITY_QUERY_COOLDOWN_MS = 5_000;
|
||||
export const COMMANDS_LIST_REQ_COOLDOWN_MS = 5_000;
|
||||
|
||||
export const ACK_GLOBAL_BURST = 4;
|
||||
export const ACK_GLOBAL_RATE_PER_SEC = 2;
|
||||
|
||||
export const MAX_COMMANDS = 16;
|
||||
export const MAX_CMD_NAME_CHARS = 24;
|
||||
export const MAX_CMD_ARGS_CHARS = 32;
|
||||
export const MAX_CMD_DESC_CHARS = 64;
|
||||
export const MAX_APP_META_CHARS = 32;
|
||||
const MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE = 128;
|
||||
|
||||
export interface OpenProtocolCommandSpec {
|
||||
name: string;
|
||||
args?: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolIdentityPayload {
|
||||
v: 1;
|
||||
action: "announce" | "announce_ack";
|
||||
client_type: "bot";
|
||||
app_name: string;
|
||||
app_version: string;
|
||||
capabilities: string[];
|
||||
command_prefix?: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolCommandsListAckPayload {
|
||||
v: 1;
|
||||
action: "list_ack";
|
||||
prefix?: string;
|
||||
commands: OpenProtocolCommandSpec[];
|
||||
}
|
||||
|
||||
export interface OpenProtocolRuntimeConfig {
|
||||
locale: "zh" | "en";
|
||||
commandPrefix: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolTransport {
|
||||
getClientId(): number;
|
||||
sendPluginCommand(
|
||||
name: string,
|
||||
data: string,
|
||||
target?: PluginCommandTarget | number,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
interface CommandCatalogEntry {
|
||||
name: string;
|
||||
args?: string;
|
||||
descZh: string;
|
||||
descEn: string;
|
||||
}
|
||||
|
||||
const CORE_COMMAND_CATALOG: readonly CommandCatalogEntry[] = [
|
||||
{ name: "play", args: "<歌曲>", descZh: "点歌并立即播放", descEn: "Play song" },
|
||||
{ name: "add", args: "<歌曲>", descZh: "添加到队列", descEn: "Add to queue" },
|
||||
{ name: "search", args: "<关键词>", descZh: "搜索歌曲", descEn: "Search songs" },
|
||||
{ name: "pause", descZh: "暂停播放", descEn: "Pause playback" },
|
||||
{ name: "resume", descZh: "恢复播放", descEn: "Resume playback" },
|
||||
{ name: "next", descZh: "下一首", descEn: "Next track" },
|
||||
{ name: "prev", descZh: "上一首", descEn: "Previous track" },
|
||||
{ name: "stop", descZh: "停止并清空队列", descEn: "Stop & clear" },
|
||||
{ name: "now", descZh: "当前播放", descEn: "Current track" },
|
||||
{ name: "queue", descZh: "查看队列", descEn: "Show queue" },
|
||||
{ name: "vol", args: "<0-100>", descZh: "调节音量", descEn: "Set volume" },
|
||||
{ name: "mode", args: "<order|loop|single|shuffle>", descZh: "切换播放模式", descEn: "Set play mode" },
|
||||
{ name: "clear", descZh: "清空队列", descEn: "Clear queue" },
|
||||
{ name: "remove", args: "<序号>", descZh: "移除指定曲目", descEn: "Remove track" },
|
||||
{ name: "playlist", args: "<歌单>", descZh: "导入歌单", descEn: "Load playlist" },
|
||||
{ name: "help", descZh: "命令帮助", descEn: "Command help" },
|
||||
];
|
||||
|
||||
const CORE_COMMAND_ARGS_EN: Readonly<Record<string, string>> = {
|
||||
play: "<query>",
|
||||
add: "<query>",
|
||||
search: "<keyword>",
|
||||
vol: "<0-100>",
|
||||
mode: "<order|loop|single|shuffle>",
|
||||
remove: "<index>",
|
||||
playlist: "<id|url>",
|
||||
};
|
||||
|
||||
function loadAppVersion(): string {
|
||||
try {
|
||||
const raw = readFileSync(new URL("../../package.json", import.meta.url), "utf8");
|
||||
const parsed = JSON.parse(raw) as { version?: unknown };
|
||||
if (typeof parsed.version === "string" && parsed.version.trim().length > 0) {
|
||||
return truncateChars(parsed.version.trim(), MAX_APP_META_CHARS);
|
||||
}
|
||||
} catch {
|
||||
// Fallback below if package.json is unavailable in a custom bundle
|
||||
}
|
||||
return "0.1.0";
|
||||
}
|
||||
|
||||
export const APP_VERSION = loadAppVersion();
|
||||
|
||||
function truncateChars(value: string, maxChars: number): string {
|
||||
const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, "");
|
||||
const chars = Array.from(sanitized);
|
||||
if (chars.length <= maxChars) return sanitized;
|
||||
return chars.slice(0, maxChars).join("");
|
||||
}
|
||||
|
||||
export function buildIdentityPayloadJson(
|
||||
action: "announce" | "announce_ack",
|
||||
commandPrefix?: string,
|
||||
appVersion: string = APP_VERSION,
|
||||
): string {
|
||||
const normalizedPrefix =
|
||||
typeof commandPrefix === "string" && commandPrefix.trim().length > 0
|
||||
? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS)
|
||||
: undefined;
|
||||
|
||||
const payload: OpenProtocolIdentityPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action,
|
||||
client_type: "bot",
|
||||
app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS),
|
||||
app_version: truncateChars(appVersion, MAX_APP_META_CHARS),
|
||||
capabilities: [...BOT_CAPABILITIES],
|
||||
...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}),
|
||||
};
|
||||
|
||||
const json = JSON.stringify(payload);
|
||||
if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) {
|
||||
return json;
|
||||
}
|
||||
|
||||
delete payload.command_prefix;
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
export function buildOpenProtocolCommands(locale: "zh" | "en"): OpenProtocolCommandSpec[] {
|
||||
return CORE_COMMAND_CATALOG.slice(0, MAX_COMMANDS).map((entry) => {
|
||||
const rawArgs = locale === "zh" ? entry.args : (CORE_COMMAND_ARGS_EN[entry.name] ?? entry.args);
|
||||
const rawDesc = locale === "zh" ? entry.descZh : entry.descEn;
|
||||
const spec: OpenProtocolCommandSpec = {
|
||||
name: truncateChars(entry.name, MAX_CMD_NAME_CHARS),
|
||||
desc: truncateChars(rawDesc, MAX_CMD_DESC_CHARS),
|
||||
};
|
||||
if (rawArgs) {
|
||||
spec.args = truncateChars(rawArgs, MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
return spec;
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCommandsListAckJson(
|
||||
locale: "zh" | "en",
|
||||
commandPrefix?: string,
|
||||
): string {
|
||||
const normalizedPrefix =
|
||||
typeof commandPrefix === "string" && commandPrefix.trim().length > 0
|
||||
? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS)
|
||||
: undefined;
|
||||
|
||||
const commands = buildOpenProtocolCommands(locale);
|
||||
while (commands.length > 0) {
|
||||
const payload: OpenProtocolCommandsListAckPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
...(normalizedPrefix ? { prefix: normalizedPrefix } : {}),
|
||||
commands,
|
||||
};
|
||||
const json = JSON.stringify(payload);
|
||||
if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) {
|
||||
return json;
|
||||
}
|
||||
commands.pop();
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
...(normalizedPrefix ? { prefix: normalizedPrefix } : {}),
|
||||
commands: [],
|
||||
} satisfies OpenProtocolCommandsListAckPayload);
|
||||
}
|
||||
|
||||
interface RateLimitToken {
|
||||
key: string;
|
||||
cooldownMs: number;
|
||||
previousTimestamp: number | undefined;
|
||||
}
|
||||
|
||||
class AckRateLimiter {
|
||||
private readonly lastSent = new Map<string, number>();
|
||||
private tokens = ACK_GLOBAL_BURST;
|
||||
private lastRefillMs: number | null = null;
|
||||
|
||||
private refill(nowMs: number): void {
|
||||
if (this.lastRefillMs === null) {
|
||||
this.lastRefillMs = nowMs;
|
||||
return;
|
||||
}
|
||||
const elapsedMs = Math.max(0, nowMs - this.lastRefillMs);
|
||||
this.tokens = Math.min(
|
||||
ACK_GLOBAL_BURST,
|
||||
this.tokens + (elapsedMs / 1000) * ACK_GLOBAL_RATE_PER_SEC,
|
||||
);
|
||||
this.lastRefillMs = nowMs;
|
||||
}
|
||||
|
||||
private prune(nowMs: number): void {
|
||||
if (this.lastSent.size <= MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE) return;
|
||||
const maxAgeMs = Math.max(
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
);
|
||||
for (const [key, ts] of this.lastSent) {
|
||||
if (nowMs - ts >= maxAgeMs) {
|
||||
this.lastSent.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): RateLimitToken | null {
|
||||
this.prune(nowMs);
|
||||
const key = `${peerKey}:${actionKey}`;
|
||||
const prev = this.lastSent.get(key);
|
||||
if (prev !== undefined && nowMs - prev < cooldownMs) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.refill(nowMs);
|
||||
if (this.tokens < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.tokens -= 1;
|
||||
this.lastSent.set(key, nowMs);
|
||||
return { key, cooldownMs, previousTimestamp: prev };
|
||||
}
|
||||
|
||||
rollback(token: RateLimitToken): void {
|
||||
this.tokens = Math.min(ACK_GLOBAL_BURST, this.tokens + 1);
|
||||
if (token.previousTimestamp === undefined) {
|
||||
this.lastSent.delete(token.key);
|
||||
} else {
|
||||
this.lastSent.set(token.key, token.previousTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.lastSent.clear();
|
||||
this.tokens = ACK_GLOBAL_BURST;
|
||||
this.lastRefillMs = null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenProtocolManagerOptions {
|
||||
transport: OpenProtocolTransport;
|
||||
getConfig: () => OpenProtocolRuntimeConfig;
|
||||
logger: Logger;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class OpenProtocolManager {
|
||||
private readonly transport: OpenProtocolTransport;
|
||||
private readonly getConfig: () => OpenProtocolRuntimeConfig;
|
||||
private readonly logger: Logger;
|
||||
private readonly now: () => number;
|
||||
private readonly rateLimiter = new AckRateLimiter();
|
||||
|
||||
private generation = 0;
|
||||
private announceSeq = 0;
|
||||
private lastSuccessSeq = 0;
|
||||
private lastAnnounceAttemptMs: number | null = null;
|
||||
private trailingAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private retryAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(options: OpenProtocolManagerOptions) {
|
||||
this.transport = options.transport;
|
||||
this.getConfig = options.getConfig;
|
||||
this.logger = options.logger;
|
||||
this.now = options.now ?? (() => Date.now());
|
||||
}
|
||||
|
||||
/** Reset timers and rate-limit state on disconnect or teardown. */
|
||||
reset(): void {
|
||||
this.generation += 1;
|
||||
this.announceSeq = 0;
|
||||
this.lastSuccessSeq = 0;
|
||||
this.lastAnnounceAttemptMs = null;
|
||||
this.clearTimers();
|
||||
this.rateLimiter.clear();
|
||||
}
|
||||
|
||||
/** Schedule or send a debounced channel broadcast announcing this bot's identity. */
|
||||
scheduleAnnounce(): void {
|
||||
const clientId = this.transport.getClientId();
|
||||
if (clientId <= 0) return;
|
||||
|
||||
const nowMs = this.now();
|
||||
if (
|
||||
this.lastAnnounceAttemptMs !== null &&
|
||||
nowMs - this.lastAnnounceAttemptMs < ANNOUNCE_DEBOUNCE_MS
|
||||
) {
|
||||
if (!this.trailingAnnounceTimer) {
|
||||
const delayMs = Math.max(
|
||||
0,
|
||||
ANNOUNCE_DEBOUNCE_MS - (nowMs - this.lastAnnounceAttemptMs),
|
||||
);
|
||||
const gen = this.generation;
|
||||
this.trailingAnnounceTimer = setTimeout(() => {
|
||||
this.trailingAnnounceTimer = null;
|
||||
if (gen !== this.generation) return;
|
||||
this.dispatchAnnounce(gen);
|
||||
}, delayMs);
|
||||
this.trailingAnnounceTimer.unref?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.clearTimers();
|
||||
this.dispatchAnnounce(this.generation);
|
||||
}
|
||||
|
||||
/** Handle an incoming TeamSpeak plugin command. */
|
||||
async handlePluginCommand(cmd: TS3PluginCommand): Promise<void> {
|
||||
if (cmd.name !== IDENTITY_PLUGIN && cmd.name !== COMMANDS_PLUGIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selfClientId = this.transport.getClientId();
|
||||
if (selfClientId <= 0 || cmd.invokerId === selfClientId) {
|
||||
return;
|
||||
}
|
||||
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
const value = JSON.parse(cmd.data) as unknown;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
parsed = value as Record<string, unknown>;
|
||||
} catch {
|
||||
this.logger.debug(
|
||||
{ name: cmd.name, invokerId: cmd.invokerId },
|
||||
"Ignoring malformed OpenProtocol JSON payload",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.v !== OPEN_PROTOCOL_VERSION || typeof parsed.action !== "string") {
|
||||
return;
|
||||
}
|
||||
|
||||
const peerKey = cmd.invokerUid.trim() || String(cmd.invokerId);
|
||||
|
||||
if (cmd.name === IDENTITY_PLUGIN) {
|
||||
await this.handleIdentityAction(parsed.action, peerKey, cmd.invokerId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd.name === COMMANDS_PLUGIN) {
|
||||
await this.handleCommandsAction(parsed.action, peerKey, cmd.invokerId);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleIdentityAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
let cooldownMs: number;
|
||||
if (action === "announce") {
|
||||
cooldownMs = IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
} else if (action === "query") {
|
||||
cooldownMs = IDENTITY_QUERY_COOLDOWN_MS;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
const token = this.rateLimiter.tryAcquire(
|
||||
peerKey,
|
||||
`${IDENTITY_PLUGIN}:${action}`,
|
||||
cooldownMs,
|
||||
this.now(),
|
||||
);
|
||||
if (!token) return;
|
||||
|
||||
const { commandPrefix } = this.getConfig();
|
||||
const payload = buildIdentityPayloadJson("announce_ack", commandPrefix);
|
||||
await this.sendAck(IDENTITY_PLUGIN, payload, invokerId, token);
|
||||
}
|
||||
|
||||
private async handleCommandsAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
if (action !== "list_req") return;
|
||||
|
||||
const token = this.rateLimiter.tryAcquire(
|
||||
peerKey,
|
||||
`${COMMANDS_PLUGIN}:list_req`,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
this.now(),
|
||||
);
|
||||
if (!token) return;
|
||||
|
||||
const { locale, commandPrefix } = this.getConfig();
|
||||
const payload = buildCommandsListAckJson(locale, commandPrefix);
|
||||
await this.sendAck(COMMANDS_PLUGIN, payload, invokerId, token);
|
||||
}
|
||||
|
||||
private async sendAck(
|
||||
pluginName: string,
|
||||
payload: string,
|
||||
invokerId: number,
|
||||
token: RateLimitToken,
|
||||
): Promise<void> {
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.rateLimiter.rollback(token);
|
||||
this.logger.debug({ pluginName }, "OpenProtocol payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
const gen = this.generation;
|
||||
try {
|
||||
await this.transport.sendPluginCommand(pluginName, payload, invokerId);
|
||||
} catch (err) {
|
||||
if (gen === this.generation) {
|
||||
this.rateLimiter.rollback(token);
|
||||
}
|
||||
this.logger.debug(
|
||||
{ err, pluginName, invokerId },
|
||||
"Failed to send OpenProtocol response",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchAnnounce(expectedGen: number): void {
|
||||
if (expectedGen !== this.generation || this.transport.getClientId() <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
const seq = ++this.announceSeq;
|
||||
const { commandPrefix } = this.getConfig();
|
||||
const payload = buildIdentityPayloadJson("announce", commandPrefix);
|
||||
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.logger.debug("OpenProtocol announce payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, seq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce broadcast failed");
|
||||
this.scheduleAnnounceRetry(expectedGen, seq);
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleAnnounceRetry(expectedGen: number, failedSeq: number): void {
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
|
||||
this.retryAnnounceTimer = setTimeout(() => {
|
||||
this.retryAnnounceTimer = null;
|
||||
if (
|
||||
expectedGen !== this.generation ||
|
||||
this.lastSuccessSeq >= failedSeq ||
|
||||
this.transport.getClientId() <= 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const retrySeq = ++this.announceSeq;
|
||||
const { commandPrefix } = this.getConfig();
|
||||
const payload = buildIdentityPayloadJson("announce", commandPrefix);
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, retrySeq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce retry failed");
|
||||
});
|
||||
}, ANNOUNCE_RETRY_DELAY_MS);
|
||||
this.retryAnnounceTimer.unref?.();
|
||||
}
|
||||
|
||||
private clearTimers(): void {
|
||||
if (this.trailingAnnounceTimer) {
|
||||
clearTimeout(this.trailingAnnounceTimer);
|
||||
this.trailingAnnounceTimer = null;
|
||||
}
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { toTS3TextMessage } from "./client.js";
|
||||
import type { TextMessage } from "@honeybbq/teamspeak-client";
|
||||
import {
|
||||
asClientID,
|
||||
asServerGroupID,
|
||||
asUID,
|
||||
type TextMessageEvent,
|
||||
} from "@honeybbq/teamspeak";
|
||||
|
||||
function makeMsg(over: Partial<TextMessage> = {}): TextMessage {
|
||||
function makeMsg(over: Partial<TextMessageEvent> = {}): TextMessageEvent {
|
||||
return {
|
||||
invokerName: "Alice",
|
||||
invokerUID: "uid-abc",
|
||||
invokerUID: asUID("uid-abc"),
|
||||
message: "!stop",
|
||||
invokerGroups: ["6", "8"],
|
||||
invokerGroups: [asServerGroupID(6n), asServerGroupID(8n)],
|
||||
targetMode: 2,
|
||||
targetID: 0n,
|
||||
invokerID: 5,
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(5),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -26,18 +31,20 @@ describe("toTS3TextMessage", () => {
|
||||
});
|
||||
|
||||
it("preserves the sender's server groups", () => {
|
||||
expect(toTS3TextMessage(makeMsg({ invokerGroups: ["6"] })).invokerGroups).toEqual(["6"]);
|
||||
expect(
|
||||
toTS3TextMessage(makeMsg({ invokerGroups: [asServerGroupID(6n)] })).invokerGroups,
|
||||
).toEqual(["6"]);
|
||||
});
|
||||
|
||||
it("defaults missing invokerGroups to an empty array", () => {
|
||||
const partial = {
|
||||
invokerName: "Bob",
|
||||
invokerUID: "u",
|
||||
invokerUID: asUID("u"),
|
||||
message: "!stop",
|
||||
targetMode: 1,
|
||||
targetID: 0n,
|
||||
invokerID: 7,
|
||||
} as unknown as TextMessage;
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(7),
|
||||
} as unknown as TextMessageEvent;
|
||||
expect(toTS3TextMessage(partial).invokerGroups).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak-client";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak/client";
|
||||
import { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
|
||||
|
||||
function result(addr: string): ResolvedAddr {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
|
||||
import { Resolver } from "@honeybbq/teamspeak/client";
|
||||
import type {
|
||||
AddrResolver,
|
||||
ResolvedAddr,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
export interface ResolvedVoiceEndpoint {
|
||||
host: string;
|
||||
@@ -66,9 +66,12 @@ export class TrackingVoiceEndpointResolver implements AddrResolver {
|
||||
private readonly resolveHost: ResolveIpv4 = resolveIpv4,
|
||||
) {}
|
||||
|
||||
async resolve(input: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
async resolve(
|
||||
input: string,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
): Promise<readonly ResolvedAddr[]> {
|
||||
this.endpoint = null;
|
||||
const candidates = await this.delegate.resolve(input, signal);
|
||||
const candidates = await this.delegate.resolve(input, options);
|
||||
const selected = candidates[0];
|
||||
if (!selected) return candidates;
|
||||
|
||||
|
||||
+7
-8
@@ -10,12 +10,12 @@ import { QQMusicProvider } from "./src/music/qq.js";
|
||||
import { BotManager } from "./src/bot/manager.js";
|
||||
import { createWebServer } from "./src/web/server.js";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentity,
|
||||
listClients,
|
||||
sendTextMessage,
|
||||
consoleLogger,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentitySync,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
const logger = createLogger();
|
||||
let passed = 0;
|
||||
@@ -83,7 +83,7 @@ async function main() {
|
||||
// ═══ Test 2: Verify bot is visible using a second client ═══
|
||||
log("\n═══ Test 2: Verify Bot Visibility ═══");
|
||||
|
||||
const verifyIdentity = generateIdentity(8);
|
||||
const verifyIdentity = generateIdentitySync(8);
|
||||
const verifyClient = new TS3FullClient(
|
||||
verifyIdentity,
|
||||
"127.0.0.1:9987",
|
||||
@@ -92,8 +92,7 @@ async function main() {
|
||||
);
|
||||
|
||||
await verifyClient.connect();
|
||||
await verifyClient.waitConnected();
|
||||
log(` Verification client connected (id=${verifyClient.clientID()})`);
|
||||
log(` Verification client connected (id=${verifyClient.clientID})`);
|
||||
|
||||
try {
|
||||
const clients = await listClients(verifyClient);
|
||||
|
||||
Reference in new issue
Block a user