feat(kaak): show channel occupancy limits

This commit is contained in:
Corrupted ILLUSIA committed 2026-10-10 22:25:01 +08:00
1 parent 387462d89a
commit a3bf476db6
23 files changed
+244 -20

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { applyChannelCapacityNotification, parseChannelCapacities } from "./channel-capacity.js";
test("channel capacity rows keep finite limits and distinguish unlimited channels", () => {
const capacities = parseChannelCapacities([
{ cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0" },
{ cid: "2", channel_maxclients: "0", channel_flag_maxclients_unlimited: "1" },
{ cid: "3", channel_maxclients: "65536", channel_flag_maxclients_unlimited: "0" },
{ cid: "4", channel_maxclients: "12" },
{ cid: "18446744073709551616", channel_maxclients: "4", channel_flag_maxclients_unlimited: "0" },
]);
assert.deepEqual(capacities.get(1n), { maxClients: 10, maxClientsLimited: true });
assert.deepEqual(capacities.get(2n), { maxClients: 0, maxClientsLimited: false });
assert.equal(capacities.has(3n), false);
assert.equal(capacities.has(4n), false);
assert.equal(capacities.size, 2);
});
test("channel capacity notifications merge edits and remove deleted channels", () => {
const capacities = new Map([[1n, { maxClients: 10, maxClientsLimited: true }]]);
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_maxclients: "16" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_flag_maxclients_unlimited: "1" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: false });
applyChannelCapacityNotification("notifychannelcreated", {
cid: "2", channel_maxclients: "8", channel_flag_maxclients_unlimited: "0",
}, capacities);
assert.deepEqual(capacities.get(2n), { maxClients: 8, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneldeleted", { cid: "2" }, capacities);
assert.equal(capacities.has(2n), false);
});
+63
View File
@@ -0,0 +1,63 @@
export interface ChannelCapacity {
maxClients: number;
maxClientsLimited: boolean;
}
const UINT64_MAX = 18_446_744_073_709_551_615n;
function parseChannelId(value: string | undefined): bigint | null {
if (!value || !/^\d{1,20}$/.test(value)) return null;
try {
const id = BigInt(value);
return id > 0n && id <= UINT64_MAX ? id : null;
} catch {
return null;
}
}
export function parseChannelCapacity(row: Record<string, string>): ChannelCapacity | null {
const maxClientsRaw = row.channel_maxclients;
const unlimitedRaw = row.channel_flag_maxclients_unlimited;
if (!maxClientsRaw || !/^\d{1,5}$/.test(maxClientsRaw) || (unlimitedRaw !== "0" && unlimitedRaw !== "1")) return null;
const maxClients = Number(maxClientsRaw);
if (!Number.isSafeInteger(maxClients) || maxClients > 65_535) return null;
return { maxClients, maxClientsLimited: unlimitedRaw === "0" };
}
export function parseChannelCapacities(rows: readonly Record<string, string>[]): Map<bigint, ChannelCapacity> {
const capacities = new Map<bigint, ChannelCapacity>();
for (const row of rows) {
const id = parseChannelId(row.cid);
const capacity = parseChannelCapacity(row);
if (id !== null && capacity) capacities.set(id, capacity);
}
return capacities;
}
/** Keep capacity metadata in step with TeamSpeak's incremental channel events. */
export function applyChannelCapacityNotification(
name: string,
params: Record<string, string>,
capacities: Map<bigint, ChannelCapacity>,
): void {
const id = parseChannelId(params.cid);
if (id === null) return;
if (name === "notifychanneldeleted") {
capacities.delete(id);
return;
}
if (name !== "notifychannelcreated" && name !== "notifychanneledited") return;
const current = name === "notifychanneledited" ? capacities.get(id) : undefined;
const maxClientsRaw = params.channel_maxclients;
const unlimitedRaw = params.channel_flag_maxclients_unlimited;
const maxClients = maxClientsRaw !== undefined && /^\d{1,5}$/.test(maxClientsRaw) && Number(maxClientsRaw) <= 65_535
? Number(maxClientsRaw)
: current?.maxClients;
const unlimited = unlimitedRaw === "0" || unlimitedRaw === "1"
? unlimitedRaw === "1"
: current ? !current.maxClientsLimited : undefined;
if (maxClients === undefined || unlimited === undefined) return;
capacities.set(id, { maxClients, maxClientsLimited: !unlimited });
}
+3 -1
View File
@@ -5,7 +5,7 @@ import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js"
import { parseServerMessage } from "../shared/server-messages.js";
const directory = (): TSDirectorySnapshot => ({
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }],
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "", maxClients: 10, maxClientsLimited: true }],
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
});
@@ -36,5 +36,7 @@ test("directory presentation survives JSON transport with large IDs, member flag
assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true);
assert.equal(decoded.channels[0]?.members?.[0]?.away, true);
assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test");
assert.equal(decoded.channels[1]?.maxClients, 10);
assert.equal(decoded.channels[1]?.maxClientsLimited, true);
assert.deepEqual(decoded.channels[1]?.members, []);
});
+3
View File
@@ -8,6 +8,9 @@ export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new
order: String(channel.order),
name: channel.name || "未命名频道",
description: channel.description || "",
...(typeof channel.maxClients === "number" && typeof channel.maxClientsLimited === "boolean"
? { maxClients: channel.maxClients, maxClientsLimited: channel.maxClientsLimited }
: {}),
members: snapshot.clients
.filter((client) => client.channelID === channel.id)
.map((client) => {
+32
View File
@@ -258,6 +258,38 @@ test("a current avatar download preserves its bytes and rejects a mismatched ide
assert.equal(f.sdk.downloaded, 1);
});
test("public channel capacity survives directory snapshots and follows channel edits", () => {
const f = fixture();
const snapshots: Array<{ channels: Array<{ id: bigint; maxClients?: number; maxClientsLimited?: boolean }>; clients: unknown[] }> = [];
f.client.on("directorySnapshot", snapshot => snapshots.push(snapshot));
f.sdk.emit("rawNotification", {
name: "notifychannelcreated",
params: { cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0" },
});
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 10);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
f.sdk.emit("rawNotification", { name: "notifychanneledited", params: { cid: "1", channel_maxclients: "12" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 12);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
f.sdk.emit("rawNotification", { name: "notifychanneldeleted", params: { cid: "1" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, undefined);
});
test("a retired SDK client's disconnect cannot invalidate a current avatar request", async () => {
const f = fixture();
const replacement = new SdkStub();
+22 -3
View File
@@ -20,6 +20,7 @@ import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKick
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
import { applyChannelCapacityNotification, parseChannelCapacities, type ChannelCapacity } from "./channel-capacity.js";
export interface TSClientOptions {
target: TeamSpeakTarget;
@@ -48,7 +49,8 @@ export interface TSClientAvatar {
// so every avatar silently fell back to its initial letter.
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity>;
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
export type TSDirectoryClient = DirectoryClientInfo;
export type TSRawNotification = RawNotification;
@@ -92,6 +94,7 @@ export class TSClient extends EventEmitter {
private inputStateQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
// reason message to its `kicked` handler, not the reason id.
@@ -109,6 +112,7 @@ export class TSClient extends EventEmitter {
this.syncedInputMuted = null;
this.inputStateQueue = Promise.resolve();
this.selfLeaveReasonId = null;
this.channelCapacities.clear();
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
if (this.options.acceleration && !this.accelerationClient) {
@@ -163,7 +167,20 @@ export class TSClient extends EventEmitter {
tsListChannels(client),
tsListClients(client),
]);
this.emit("directorySnapshot", { channels, clients });
try {
// The high-level SDK directory type intentionally omits channel limit
// metadata. Its raw client-protocol rows still include the public
// maximum-client properties, so retain those without another SDK API.
const rows = await client.execCommandWithResponse("channellist", 5_000);
const capacities = parseChannelCapacities(rows);
for (const [id, capacity] of capacities) this.channelCapacities.set(id, capacity);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not read TeamSpeak channel limits");
}
this.emit("directorySnapshot", {
channels: channels.map((channel) => ({ ...channel, ...this.channelCapacities.get(channel.id) })),
clients,
});
} catch (error: unknown) {
this.logger.warn({
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
@@ -273,13 +290,14 @@ export class TSClient extends EventEmitter {
client.on("directorySnapshot", (snapshot) => {
if (this.client !== client) return;
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
channels: snapshot.channels.map((channel) => ({ ...channel, ...this.channelCapacities.get(channel.id) })),
clients: snapshot.clients.slice(),
});
});
client.on("rawNotification", (notification: RawNotification) => {
if (this.client !== client) return;
applyChannelCapacityNotification(notification.name, notification.params, this.channelCapacities);
this.emit("rawNotification", {
name: notification.name,
params: { ...notification.params },
@@ -310,6 +328,7 @@ export class TSClient extends EventEmitter {
}
this.connected = false;
this.clientId = 0;
this.channelCapacities.clear();
this.emit("disconnected", err);
});