feat: display TeamSpeak client avatars

This commit is contained in:
illusia committed 2026-09-18 17:48:33 +08:00
1 parent fae21ec086
commit a2e33ff176
4 files changed
+137 -19

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", {
+65 -12
View File
@@ -110,6 +110,7 @@ interface ChannelMember {
id: number;
nickname: string;
uid: string;
avatar?: string;
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
@@ -139,6 +140,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 编码器不可用告警的时间戳,用于限流避免反复刷屏
@@ -255,6 +257,7 @@ export class VoiceBridge {
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
channelTree: [],
members: new Map(),
avatarCache: new Map(),
eventLog: [],
opusEncoder: null,
opusEncoderWarnedAt: 0,
@@ -289,6 +292,7 @@ export class VoiceBridge {
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const directory = new DirectorySynchronizer();
const avatarRequests = new Set<string>();
const sendJson = (message: Record<string, unknown>) => {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
@@ -312,13 +316,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,
@@ -335,6 +341,38 @@ export class VoiceBridge {
sendJson({ type: "whisperTargets", targetIds: nextWhisperTargets, active: entry!.whisperActive });
}
};
const refreshMemberAvatars = async (): Promise<void> => {
if (!entry || !tsReady || session.state !== "connected") return;
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);
}
}
};
const trackChannelEvents = (previous: unknown[], next: unknown[]) => {
if (!initialStateSent) return;
const before = new Map(previous.filter(isChannelRecord).map((channel) => [channel.id, channel]));
@@ -378,6 +416,7 @@ export class VoiceBridge {
});
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
void refreshMemberAvatars();
};
const resetDirectoryForReconnect = () => {
@@ -503,6 +542,7 @@ export class VoiceBridge {
trackChannelEvents(previousChannels, entry!.channelTree);
sendInitialState();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
void refreshMemberAvatars();
});
tsClient.on("clientEnter", (info) => {
@@ -518,6 +558,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 || "未知用户"} 加入了服务器`);
void refreshMemberAvatars();
}
});
@@ -1219,7 +1260,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),
@@ -1227,19 +1268,31 @@ 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,
};
}),
}));
}
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,
+15 -2
View File
@@ -32,6 +32,7 @@ export interface ChannelMember {
id: number;
nickname: string;
uid?: string;
avatar?: string;
isSelf?: boolean;
away?: boolean;
awayMessage?: string;
@@ -74,7 +75,7 @@ export interface ChannelInfo {
parentID: string;
name: string;
description?: string;
members?: { id: number; nickname: string; uid?: string; away?: boolean; awayMessage?: string; inputMuted?: boolean; outputMuted?: boolean; channelCommander?: boolean }[];
members?: { id: number; nickname: string; uid?: string; avatar?: string; away?: boolean; awayMessage?: string; inputMuted?: boolean; outputMuted?: boolean; channelCommander?: boolean }[];
}
export interface ChatMessage {
@@ -1619,7 +1620,7 @@ export function useVoiceWebSocket() {
break;
case "memberEnter":
if (!members.some((member) => member.id === msg.id)) {
members.push({ id: msg.id, nickname: msg.nickname, uid: typeof msg.uid === "string" ? msg.uid : undefined, isSelf: Boolean(msg.isSelf) });
members.push({ id: msg.id, nickname: msg.nickname, uid: typeof msg.uid === "string" ? msg.uid : undefined, avatar: typeof msg.avatar === "string" ? msg.avatar : undefined, isSelf: Boolean(msg.isSelf) });
syncKnownMemberVolumes();
}
break;
@@ -1638,6 +1639,18 @@ export function useVoiceWebSocket() {
}
syncKnownMemberVolumes();
break;
case "memberAvatar": {
const clientId = Number(msg.id);
const uid = typeof msg.uid === "string" ? msg.uid : "";
const avatar = typeof msg.avatar === "string" ? msg.avatar : "";
const member = members.find((candidate) => candidate.id === clientId && (!uid || candidate.uid === uid));
if (member) member.avatar = avatar || undefined;
for (const channel of channels) {
const channelMember = channel.members?.find((candidate) => candidate.id === clientId && (!uid || candidate.uid === uid));
if (channelMember) channelMember.avatar = avatar || undefined;
}
break;
}
case "chatMessage":
if (Number(msg.invokerId) === state.tsClientId) break;
const incomingScope = msg.scope === "private" || msg.scope === "server" || msg.scope === "channel" ? msg.scope : "system";
+8 -5
View File
@@ -143,7 +143,7 @@
<div v-if="currentMembers.length" class="voice-grid">
<article v-for="member in roomMembers" :key="member.id" :class="['voice-card', { speaking: isSpeaking(member), self: member.isSelf }]">
<button v-if="isMobileViewport && !member.isSelf" type="button" class="voice-member-action" :aria-label="t('moreMemberOptions')" @click.stop="openMemberActions(member)"><Icon name="more" :size="17" /></button>
<div class="voice-avatar-wrap"><div :class="['voice-avatar', { speaking: isSpeaking(member) }]" :style="avatarStyle(member.nickname, member.isSelf)">{{ avatarInitial(member.nickname) }}</div></div>
<div class="voice-avatar-wrap"><div :class="['voice-avatar', { speaking: isSpeaking(member) }]" :style="avatarStyle(member.nickname, member.isSelf, member.avatar)">{{ member.avatar ? '' : avatarInitial(member.nickname) }}</div></div>
<strong>{{ member.isSelf ? t('you') : member.nickname }}</strong><span>{{ isSpeaking(member) ? t('speaking') : member.isSelf ? t('connectedYou') : t('connected') }}</span>
</article>
<article v-if="currentMembers.length > roomMembers.length" class="voice-card more-card"><div class="more-count">+{{ currentMembers.length - roomMembers.length }}</div><strong>{{ t('moreMembers') }}</strong><span>{{ t('viewLeft') }}</span></article>
@@ -203,7 +203,7 @@
</button>
<div v-if="channelItem.members.length" class="member-list">
<div v-for="member in channelItem.members" :key="`${channelItem.id}-${member.id}`" class="member-row" @contextmenu.prevent="openMemberMenu(member, $event)">
<div :class="['member-avatar', { speaking: isSpeaking(member) }]" :style="avatarStyle(member.nickname, member.isSelf)">{{ avatarInitial(member.nickname) }}<span class="member-presence"></span></div>
<div :class="['member-avatar', { speaking: isSpeaking(member) }]" :style="avatarStyle(member.nickname, member.isSelf, member.avatar)">{{ member.avatar ? '' : avatarInitial(member.nickname) }}<span class="member-presence"></span></div>
<div class="member-copy"><strong>{{ memberDisplayName(member) }}</strong><span>{{ member.away ? t('away') : isSpeaking(member) ? t('speaking') : member.isSelf ? t('yourDevice') : t('memberOnline') }}</span></div>
<div class="member-flags" :aria-label="t('memberStates')"><span v-if="member.away" :title="t('away')" :aria-label="t('away')"><Icon name="clock" :size="13" /></span><span v-if="member.inputMuted" :title="t('inputMuted')" :aria-label="t('inputMuted')"><Icon name="mic-off" :size="13" /></span><span v-if="member.outputMuted" :title="t('outputMuted')" :aria-label="t('outputMuted')"><Icon name="volume-off" :size="13" /></span><span v-if="member.channelCommander" :title="t('channelCommander')" :aria-label="t('channelCommander')"><Icon name="shield" :size="13" /></span></div>
<div class="member-volume"><Icon :name="(volumes[member.id] ?? 1) === 0 ? 'volume-off' : 'volume'" :size="14" /><input type="range" min="0" max="400" :value="(volumes[member.id] ?? 1) * 100" :style="rangeStyle((volumes[member.id] ?? 1) / 4, 1)" :aria-label="t('memberVolume')" @input="onVolInput(member.id, $event)" /></div>
@@ -2276,11 +2276,14 @@ function avatarInitial(name: string) {
}
const avatarColors = ["#9edbd4", "#b9d4c5", "#e8c6a8", "#c5c7e8", "#edd2d4", "#c8d9e9", "#e4d3b8"];
function avatarStyle(name: string, isSelf = false) {
if (isSelf) return { background: "linear-gradient(135deg, #006a64, #2e9f96)" };
function avatarStyle(name: string, isSelf = false, avatar = "") {
const fallback = isSelf ? "linear-gradient(135deg, #006a64, #2e9f96)" : "";
let hash = 0;
for (let index = 0; index < name.length; index++) hash = name.charCodeAt(index) + ((hash << 5) - hash);
return { background: avatarColors[Math.abs(hash) % avatarColors.length] };
return {
background: fallback || avatarColors[Math.abs(hash) % avatarColors.length],
...(avatar ? { backgroundImage: `url("${avatar}")`, backgroundPosition: "center", backgroundSize: "cover" } : {}),
};
}
function isSpeaking(member: ChannelMember) {