merge: integrate issue 5 avatar support

This commit is contained in:
illusia committed 2026-09-18 18:02:27 +08:00
commit b71632cc29
4 files changed
+165 -21

No files matched your search

+49
View File
@@ -1,4 +1,5 @@
import { EventEmitter } from "node:events";
import { Writable } from "node:stream";
import {
Client as TS3FullClient,
clientMove as tsClientMove,
@@ -35,6 +36,14 @@ export interface TSVoiceData {
data: Buffer;
}
export interface TSClientAvatar {
/** TeamSpeak's avatar content marker, used to invalidate a cached avatar. */
cacheKey: string;
data: Buffer;
}
const MAX_CLIENT_AVATAR_BYTES = 120 * 1024;
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryClient = DirectoryClientInfo;
@@ -172,6 +181,46 @@ export class TSClient extends EventEmitter {
this.emit("connected", this.clientId);
}
/**
* Load a visible client's TeamSpeak avatar through the client protocol.
*
* TeamSpeak does not include the avatar bytes in directory notifications.
* `clientinfo` exposes the avatar marker and the per-identity filename; the
* file itself is then read through the normal TeamSpeak file-transfer port.
* A missing permission, missing avatar, blocked file-transfer port, or an
* oversized image is intentionally reported as `null` so the web client can
* keep its generated initial avatar.
*/
async getClientAvatar(clientId: number, expectedUid = ""): Promise<TSClientAvatar | null> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
const rows = await this.client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
const info = rows.find((row) => {
if (expectedUid && row.client_unique_identifier !== expectedUid) return false;
return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string";
});
if (!info) return null;
const cacheKey = info.client_flag_avatar?.trim() ?? "";
const avatarFileKey = info.client_base64HashClientUID?.trim() ?? "";
if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null;
const transfer = await this.client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
const size = Number(transfer.size);
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer | string, _encoding, callback) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
callback();
},
});
await this.client.downloadFileData(this.options.target.host, transfer, destination);
const data = Buffer.concat(chunks);
if (data.length === 0 || data.length > MAX_CLIENT_AVATAR_BYTES) return null;
return { cacheKey, data };
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
+83 -12
View File
@@ -111,6 +111,7 @@ interface ChannelMember {
id: number;
nickname: string;
uid: string;
avatar?: string;
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
@@ -140,6 +141,7 @@ interface WebClientEntry {
webrtcPublicHost?: string;
channelTree: unknown[];
members: Map<number, ChannelMember>;
avatarCache: Map<string, string | null>;
eventLog: ServerEvent[];
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
@@ -258,6 +260,7 @@ export class VoiceBridge {
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
channelTree: [],
members: new Map(),
avatarCache: new Map(),
eventLog: [],
opusEncoder: null,
opusEncoderWarnedAt: 0,
@@ -294,6 +297,9 @@ export class VoiceBridge {
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const directory = new DirectorySynchronizer();
const avatarRequests = new Set<string>();
let avatarRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let avatarRefreshRunning = false;
const sendJson = (message: Record<string, unknown>) => {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
@@ -317,13 +323,15 @@ export class VoiceBridge {
const sdkChannelId = tsClient.getChannelId();
if (selfChannelId === 0n && sdkChannelId !== 0n) selfChannelId = sdkChannelId;
const normalizedSnapshot = normalizeDirectorySnapshot(snapshot, effectiveSelfId, selfChannelId, nickname, channelName);
entry!.channelTree = mapChannelTree(normalizedSnapshot);
entry!.channelTree = mapChannelTree(normalizedSnapshot, entry!.avatarCache);
entry!.members.clear();
for (const client of normalizedSnapshot.clients) {
const avatar = client.uid ? entry!.avatarCache.get(client.uid) : undefined;
entry!.members.set(client.id, {
id: client.id,
nickname: client.nickname,
uid: client.uid,
...(avatar ? { avatar } : {}),
away: client.away,
awayMessage: client.awayMessage,
inputMuted: client.inputMuted,
@@ -340,6 +348,54 @@ export class VoiceBridge {
sendJson({ type: "whisperTargets", targetIds: nextWhisperTargets, active: entry!.whisperActive });
}
};
const scheduleMemberAvatarRefresh = (delayMs = 0): void => {
if (!entry || !entry.isAlive || avatarRefreshTimer) return;
avatarRefreshTimer = setTimeout(() => {
avatarRefreshTimer = null;
void refreshMemberAvatars();
}, delayMs);
avatarRefreshTimer.unref?.();
};
const refreshMemberAvatars = async (): Promise<void> => {
if (!entry || !entry.isAlive || !tsReady || session.state !== "connected" || avatarRefreshRunning) return;
avatarRefreshRunning = true;
try {
const candidates = [...entry.members.values()]
.filter((member) => member.uid && !entry!.avatarCache.has(member.uid) && !avatarRequests.has(member.uid))
.slice(0, 50);
for (const member of candidates) {
if (!entry || !entry.isAlive || !member.uid) return;
avatarRequests.add(member.uid);
try {
const loaded = await tsClient.getClientAvatar(member.id, member.uid);
const avatar = loaded ? avatarDataUrl(loaded.data) : null;
entry.avatarCache.set(member.uid, avatar);
const current = entry.members.get(member.id);
if (current && current.uid === member.uid && avatar) {
current.avatar = avatar;
sendJson({ type: "memberAvatar", id: member.id, uid: member.uid, avatar });
}
} catch (error: unknown) {
// Avatar access is optional. A permission or file-transfer failure
// must never affect joining, directory updates, or voice traffic.
entry.avatarCache.set(member.uid, null);
this.logger.debug({
entryId,
clientId: member.id,
uid: member.uid,
err: error instanceof Error ? error.message : String(error),
}, "TeamSpeak client avatar unavailable");
} finally {
avatarRequests.delete(member.uid);
}
}
} finally {
avatarRefreshRunning = false;
if (entry?.isAlive && tsReady && session.state === "connected" && [...entry.members.values()].some((member) => member.uid && !entry!.avatarCache.has(member.uid))) {
scheduleMemberAvatarRefresh(250);
}
}
};
const trackChannelEvents = (previous: unknown[], next: unknown[]) => {
if (!initialStateSent) return;
const before = new Map(previous.filter(isChannelRecord).map((channel) => [channel.id, channel]));
@@ -384,6 +440,7 @@ export class VoiceBridge {
});
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
scheduleMemberAvatarRefresh();
};
let movePermissionProbeInFlight = false;
@@ -547,6 +604,7 @@ export class VoiceBridge {
trackChannelEvents(previousChannels, entry!.channelTree);
sendInitialState();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
scheduleMemberAvatarRefresh();
});
tsClient.on("clientEnter", (info) => {
@@ -562,6 +620,7 @@ export class VoiceBridge {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (!wasKnown) sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === selfId });
if (!wasKnown && info.id !== selfId) addServerEvent("joined", `${info.nickname || "未知用户"} 加入了服务器`);
scheduleMemberAvatarRefresh();
void refreshMoveCapability();
}
});
@@ -1290,7 +1349,7 @@ function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
return stats;
}
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): unknown[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
parentID: String(channel.parentID),
@@ -1299,16 +1358,20 @@ function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
description: channel.description || "",
members: snapshot.clients
.filter((client) => client.channelID === channel.id)
.map((client) => ({
id: client.id,
nickname: client.nickname || "未知用户",
uid: client.uid,
away: client.away,
awayMessage: client.awayMessage,
inputMuted: client.inputMuted,
outputMuted: client.outputMuted,
channelCommander: client.channelCommander,
})),
.map((client) => {
const avatar = client.uid ? avatarCache.get(client.uid) : undefined;
return {
id: client.id,
nickname: client.nickname || "未知用户",
uid: client.uid,
...(avatar ? { avatar } : {}),
away: client.away,
awayMessage: client.awayMessage,
inputMuted: client.inputMuted,
outputMuted: client.outputMuted,
channelCommander: client.channelCommander,
};
}),
}));
}
@@ -1323,6 +1386,14 @@ function findMovePermissionProbeTarget(entry: Pick<WebClientEntry, "channelTree"
return null;
}
function avatarDataUrl(data: Buffer): string | null {
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return `data:image/png;base64,${data.toString("base64")}`;
if (data.length >= 3 && data.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return `data:image/jpeg;base64,${data.toString("base64")}`;
if (data.length >= 6 && (data.subarray(0, 6).toString("ascii") === "GIF87a" || data.subarray(0, 6).toString("ascii") === "GIF89a")) return `data:image/gif;base64,${data.toString("base64")}`;
if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return `data:image/webp;base64,${data.toString("base64")}`;
return null;
}
function normalizeDirectorySnapshot(
snapshot: TSDirectorySnapshot,
selfId: number,