M006: add scoped chat and client interactions

This commit is contained in:
illusia committed 2026-09-01 17:32:00 +08:00
1 parent 2f8301d188
commit 509dc038c1
9 files changed
+531 -46

No files matched your search

+4
View File
@@ -15,6 +15,8 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关
- 完整频道/成员树、频道切换、频道文字聊天和成员实时移动。
- PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。
- 发言成员头像显示绿色动态边框。
- 频道、服务器和私聊独立标签;成员菜单支持私聊、Poke、复制昵称,频道密码按次输入且不持久化。
- Away、成员状态图标、Session 内服务器事件日志和人类可读的 TeamSpeak 权限错误。
- 中英文访客页面和中英文管理控制台。
- Web 管理闭环:默认账号首次登录强制改密、单管理员登录、概览、服务器设置和真实连接测试。
- `fixed` 与 `open` 两种访问模式。
@@ -227,6 +229,8 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser
- Temporary TeamSpeak failures recover with bounded jittered backoff for up to five minutes; authentication failures are not retried forever, and the previous channel is restored when possible.
- Channel/member directory, channel switching, channel text chat, and live member movement.
- PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls.
- Independent channel, server, and private chat tabs; member actions for private message, poke, and nickname copy; channel passwords are entered per session only.
- Away, member status icons, a session-local server event log, and readable TeamSpeak permission errors.
- Bilingual guest UI and bilingual admin console.
- Browser-based admin login, mandatory first-login password change, Overview, server settings, and a real short-lived connection test.
- Fixed and open guest access modes.
+5 -5
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
const marker = "webspeak-directory-snapshot";
const marker = "webspeak-directory-snapshot-v2";
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
if (packageJson.version !== "0.2.2") {
@@ -26,12 +26,12 @@ await Promise.all([
]);
function patchCjs(source) {
if (source.includes(marker)) return source;
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var K=class", `${helper}var K=class`);
@@ -86,12 +86,12 @@ function webSpeakDirectoryChannelNotification(name,params,decode,channels){const
}
function patchMjs(source) {
if (source.includes(marker)) return source;
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var k = class", `${helper}var k = class`);
+42 -10
View File
@@ -2,6 +2,8 @@ import { EventEmitter } from "node:events";
import {
Client as TS3FullClient,
clientMove as tsClientMove,
poke as tsPoke,
sendTextMessage as tsSendTextMessage,
generateIdentity,
type Identity,
type VoiceData,
@@ -29,9 +31,19 @@ export interface TSVoiceData {
export interface TSDirectorySnapshot {
channels: ChannelInfo[];
clients: ClientInfo[];
clients: TSDirectoryClient[];
}
export interface TSDirectoryClient extends ClientInfo {
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
export type TSChatScope = "channel" | "server" | "private";
export class TSClient extends EventEmitter {
private client: TS3FullClient | null = null;
private adapter: TeamSpeakAdapter | null = null;
@@ -134,6 +146,10 @@ export class TSClient extends EventEmitter {
});
});
client.on("poked", (event) => {
this.emit("poked", event);
});
client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Disconnected from TS");
this.connected = false;
@@ -160,15 +176,21 @@ export class TSClient extends EventEmitter {
this.client.sendVoice(data, codec);
}
sendTextMessage(message: string): void {
// We use execCommand for simplicity — the client API has higher-level wrappers
if (!this.client || !this.connected) return;
const escaped = message
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/");
this.client.execCommand(`sendtextmessage targetmode=2 target=0 msg=${escaped}`)
.catch((err: Error) => this.logger.error({ err }, "sendTextMessage failed"));
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const targetMode = scope === "private" ? 1 : scope === "server" ? 3 : 2;
await tsSendTextMessage(this.client, targetMode, targetId, message);
}
async poke(clientId: number, message: string): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
await tsPoke(this.client, clientId, message);
}
async setAway(away: boolean, message = ""): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const escaped = escapeTeamSpeakValue(message);
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
@@ -210,3 +232,13 @@ export class TSClient extends EventEmitter {
this.clientId = 0;
}
}
function escapeTeamSpeakValue(value: string): string {
return value
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r");
}
+132 -9
View File
@@ -28,6 +28,18 @@ interface ChannelMember {
id: number;
nickname: string;
uid: string;
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
interface ServerEvent {
id: string;
kind: "joined" | "left" | "moved" | "poke" | "connection";
message: string;
timestamp: number;
}
interface WebClientEntry {
@@ -40,6 +52,7 @@ interface WebClientEntry {
target: TeamSpeakTarget;
channelTree: unknown[];
members: Map<number, ChannelMember>;
eventLog: ServerEvent[];
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
isAlive: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | null;
@@ -111,6 +124,7 @@ export class VoiceBridge {
target,
channelTree: [],
members: new Map(),
eventLog: [],
opusEncoder: null,
isAlive: true,
reconnectTimer: null,
@@ -138,6 +152,17 @@ export class VoiceBridge {
const sendJson = (message: Record<string, unknown>) => {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
};
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
const event: ServerEvent = {
id: `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
kind,
message,
timestamp: Date.now(),
};
entry!.eventLog.push(event);
if (entry!.eventLog.length > 200) entry!.eventLog.splice(0, entry!.eventLog.length - 200);
if (initialStateSent) sendJson({ type: "serverEvent", event });
};
const refreshDirectory = () => {
const snapshot = directory.getSnapshot();
if (!snapshot) return;
@@ -148,9 +173,28 @@ export class VoiceBridge {
entry!.channelTree = mapChannelTree(normalizedSnapshot);
entry!.members.clear();
for (const client of normalizedSnapshot.clients) {
entry!.members.set(client.id, { id: client.id, nickname: client.nickname, uid: client.uid });
entry!.members.set(client.id, {
id: client.id,
nickname: client.nickname,
uid: client.uid,
away: client.away,
awayMessage: client.awayMessage,
inputMuted: client.inputMuted,
outputMuted: client.outputMuted,
channelCommander: client.channelCommander,
});
}
};
const trackChannelEvents = (previous: unknown[], next: unknown[]) => {
if (!initialStateSent) return;
const before = new Map(previous.filter(isChannelRecord).map((channel) => [channel.id, channel]));
const after = new Map(next.filter(isChannelRecord).map((channel) => [channel.id, channel]));
for (const channel of after.values()) {
if (!before.has(channel.id)) addServerEvent("joined", `频道「${channel.name}」已创建`);
else if (before.get(channel.id)?.name !== channel.name) addServerEvent("moved", `频道已重命名为「${channel.name}」`);
}
for (const channel of before.values()) if (!after.has(channel.id)) addServerEvent("left", `频道「${channel.name}」已删除`);
};
const sendInitialState = () => {
if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return;
initialStateSent = true;
@@ -158,11 +202,15 @@ export class VoiceBridge {
hasConnectedOnce = true;
reconnectAttempt = 0;
reconnectStartedAt = 0;
if (!wasReconnecting) {
entry!.eventLog.push({ id: `event-${Date.now().toString(36)}-connected`, kind: "connection", message: "已连接到服务器", timestamp: Date.now() });
}
session.transition("connected");
sendJson({
type: "connected",
tsClientId: selfId,
members: Array.from(entry!.members.values()),
serverEventLog: entry!.eventLog,
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
});
sendJson({ type: "channelList", channels: entry!.channelTree });
@@ -266,8 +314,10 @@ export class VoiceBridge {
// snapshot establishes the baseline.
realtimeReady = true;
tsClient.on("directorySnapshot", (snapshot: TSDirectorySnapshot) => {
const previousChannels = entry!.channelTree;
directory.applySnapshot(snapshot);
refreshDirectory();
trackChannelEvents(previousChannels, entry!.channelTree);
sendInitialState();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
});
@@ -284,25 +334,32 @@ export class VoiceBridge {
if (tsReady && initialStateSent) {
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 || "未知用户"} 加入了服务器`);
}
});
tsClient.on("clientLeave", (info) => {
const wasKnown = entry!.members.has(info.id);
const leavingMember = entry!.members.get(info.id);
directory.applyClientLeave(info.id);
refreshDirectory();
if (tsReady && initialStateSent && wasKnown) {
sendJson({ type: "memberLeave", id: info.id });
sendJson({ type: "channelList", channels: entry!.channelTree });
if (info.id !== selfId) addServerEvent("left", `${leavingMember?.nickname || "用户"} 离开了服务器`);
}
});
tsClient.on("clientMoved", (info) => {
if (info.targetChannelID === undefined || info.targetChannelID === 0n) return;
const movedMember = entry!.members.get(info.id);
if (info.id === selfId) selfChannelId = info.targetChannelID;
directory.applyClientMoved(info.id, info.targetChannelID);
refreshDirectory();
if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree });
if (tsReady && initialStateSent) {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (info.id !== selfId) addServerEvent("moved", `${movedMember?.nickname || "用户"} 移动到了其他频道`);
}
});
tsClient.on("voiceData", (data: TSVoiceData) => {
@@ -315,14 +372,24 @@ export class VoiceBridge {
});
tsClient.on("textMessage", (message) => {
const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server";
sendJson({
type: "chatMessage",
scope,
targetId: message.targetID.toString(),
senderUid: message.invokerUID,
timestamp: Date.now(),
invokerName: message.invokerName,
invokerId: message.invokerId,
message: message.message,
});
});
tsClient.on("poked", (event) => {
sendJson({ type: "pokeReceived", invokerId: event.invokerID, invokerUid: event.invokerUID, invokerName: event.invokerName, message: event.message, timestamp: Date.now() });
addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
});
tsClient.on("disconnected", (error?: Error) => {
if (!hasConnectedOnce || session.state !== "connected") return;
resetDirectoryForReconnect();
@@ -466,28 +533,75 @@ async function handleCommand(
): Promise<void> {
if (command.type === "switchChannel") {
const rawId = command.payload.channelId as string;
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
try {
await entry.tsClient.switchChannel(BigInt(rawId));
await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
if (!message.includes("already member")) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_SWITCH_FAILED", message: "频道切换失败", recoverable: false } });
const rawMessage = error instanceof Error ? error.message : String(error);
if (/already member/i.test(rawMessage)) {
sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId });
return;
}
const operation = classifyOperationError(error, "CHANNEL_SWITCH_FAILED", "频道切换失败");
sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } });
return;
}
sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId });
sendJson({ type: "channelList", channels: entry.channelTree });
return;
}
const message = (command.payload.message as string).trim();
if (message) entry.tsClient.sendTextMessage(message);
try {
if (command.type === "sendTextMessage") {
const message = (command.payload.message as string).trim();
if (message) await entry.tsClient.sendTextMessage("channel", message, entry.tsClient.getChannelId());
} else if (command.type === "sendServerMessage") {
const message = (command.payload.message as string).trim();
if (message) await entry.tsClient.sendTextMessage("server", message);
} else if (command.type === "sendPrivateMessage") {
const clientId = command.payload.clientId as number;
if (!entry.members.has(clientId)) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } });
return;
}
const message = (command.payload.message as string).trim();
if (message) await entry.tsClient.sendTextMessage("private", message, BigInt(clientId));
} else if (command.type === "poke") {
const clientId = command.payload.clientId as number;
if (!entry.members.has(clientId)) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } });
return;
}
await entry.tsClient.poke(clientId, (command.payload.message as string).trim());
} else if (command.type === "setAway") {
await entry.tsClient.setAway(command.payload.away as boolean, typeof command.payload.message === "string" ? command.payload.message.trim() : "");
}
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
} catch (error: unknown) {
const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败");
sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } });
}
}
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
const text = error instanceof Error ? error.message : String(error);
const normalized = text.toLocaleLowerCase();
if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|1794/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" };
if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" };
if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" };
return { code: fallbackCode, message: fallbackMessage };
}
function sendProtocolError(sendJson: (message: Record<string, unknown>) => void, code: string, message: string): void {
sendJson({ type: "error", error: { code, message, recoverable: false } });
}
function isChannelRecord(value: unknown): value is { id: string; name: string } {
return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string";
}
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
@@ -496,7 +610,16 @@ 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 })),
.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,
})),
}));
}
+19 -3
View File
@@ -1,5 +1,5 @@
export interface ClientCommand {
type: "switchChannel" | "sendTextMessage";
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway";
requestId?: string;
payload: Record<string, unknown>;
}
@@ -19,7 +19,8 @@ export function parseClientCommand(raw: string): ClientCommandResult {
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
if (value.type !== "switchChannel" && value.type !== "sendTextMessage") {
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
if (!isRecord(value.payload)) {
@@ -28,11 +29,26 @@ export function parseClientCommand(raw: string): ClientCommandResult {
if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
}
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendServerMessage" || value.type === "sendPrivateMessage") && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendPrivateMessage" || value.type === "poke") && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
}
if (value.type === "poke" && (typeof value.payload.message !== "string" || value.payload.message.length > 200)) {
return { error: { code: "INVALID_POKE_MESSAGE", message: "戳一戳消息无效" } };
}
if (value.type === "setAway" && (typeof value.payload.away !== "boolean" || (value.payload.message !== undefined && (typeof value.payload.message !== "string" || value.payload.message.length > 200)))) {
return { error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" } };
}
return {
type: value.type,
type: value.type as ClientCommand["type"],
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
payload: value.payload,
};
+28
View File
@@ -27,3 +27,31 @@ test("voice protocol rejects malformed and unsupported commands", () => {
error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" },
});
});
test("voice protocol keeps chat scopes and status actions explicit", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), {
type: "sendPrivateMessage",
requestId: "pm-1",
payload: { clientId: 7, message: "hello" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), {
type: "setAway",
payload: { away: true, message: "back soon" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), {
type: "switchChannel",
payload: { channelId: "42", password: "secret" },
});
});
test("voice protocol rejects unsafe client and away payloads", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), {
error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), {
error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), {
error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" },
});
});
+1
View File
@@ -39,6 +39,7 @@
<path d="m16 16 4.5 4.5" />
</template>
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
<path v-else-if="name === 'clock'" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-14v5l3 2" />
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
<template v-else-if="name === 'plus'">
<path d="M12 5v14M5 12h14" />
+95 -7
View File
@@ -9,6 +9,7 @@ export interface VoiceState {
reconnectFailed: boolean;
tsClientId: number;
error: string;
errorCode: string;
}
export interface ChannelMember {
@@ -16,6 +17,11 @@ export interface ChannelMember {
nickname: string;
uid?: string;
isSelf?: boolean;
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
export interface AudioInputDevice {
@@ -29,23 +35,37 @@ export interface ChannelInfo {
parentID: string;
name: string;
description?: string;
members?: { id: number; nickname: string; uid?: string }[];
members?: { id: number; nickname: string; uid?: string; away?: boolean; awayMessage?: string; inputMuted?: boolean; outputMuted?: boolean; channelCommander?: boolean }[];
}
export interface ChatMessage {
id: string;
scope: "channel" | "server" | "private" | "system";
targetId?: string;
conversationId?: string;
senderId?: number;
senderUid?: string;
invokerName: string;
message: string;
timestamp: number;
isSelf?: boolean;
}
export interface ServerEvent {
id: string;
kind: string;
message: string;
timestamp: number;
}
export function useVoiceWebSocket() {
const ws = ref<WebSocket | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "" });
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "" });
const members = reactive<ChannelMember[]>([]);
const channels = reactive<ChannelInfo[]>([]);
const chatMessages = reactive<ChatMessage[]>([]);
const serverEvents = reactive<ServerEvent[]>([]);
const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]);
let connectionSequence = 0;
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null;
const identityMaterial = ref("");
@@ -368,6 +388,7 @@ export function useVoiceWebSocket() {
identityMaterial.value = identity;
const sequence = ++connectionSequence;
state.error = "";
state.errorCode = "";
state.connecting = true;
state.reconnecting = false;
state.reconnectAttempt = 0;
@@ -461,6 +482,7 @@ export function useVoiceWebSocket() {
state.reconnectAttempt = 0;
state.reconnectFailed = false;
state.tsClientId = 0;
state.errorCode = "";
identityMaterial.value = "";
members.length = 0;
channels.length = 0;
@@ -485,6 +507,7 @@ export function useVoiceWebSocket() {
state.reconnectAttempt = 0;
state.reconnectFailed = false;
state.error = "";
state.errorCode = "";
state.tsClientId = Number(msg.tsClientId) || 0;
if (Array.isArray(msg.members)) {
members.length = 0;
@@ -493,6 +516,8 @@ export function useVoiceWebSocket() {
}
syncKnownMemberVolumes();
}
serverEvents.length = 0;
if (Array.isArray(msg.serverEventLog)) serverEvents.push(...msg.serverEventLog);
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
identityMaterial.value = msg.identity;
if (lastConnection) lastConnection.identity = msg.identity;
@@ -524,11 +549,30 @@ export function useVoiceWebSocket() {
break;
case "chatMessage":
if (Number(msg.invokerId) === state.tsClientId) break;
const incomingScope = msg.scope === "private" || msg.scope === "server" || msg.scope === "channel" ? msg.scope : "system";
chatMessages.push({
id: `remote-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
scope: incomingScope,
targetId: typeof msg.targetId === "string" ? msg.targetId : undefined,
...(incomingScope === "private" ? { conversationId: String(Number(msg.invokerId) || 0) } : {}),
senderId: Number(msg.invokerId) || undefined,
senderUid: typeof msg.senderUid === "string" ? msg.senderUid : undefined,
invokerName: String(msg.invokerName || "Unknown"),
message: String(msg.message || ""),
timestamp: Date.now(),
timestamp: typeof msg.timestamp === "number" ? msg.timestamp : Date.now(),
});
break;
case "serverEvent":
if (msg.event && typeof msg.event.id === "string") serverEvents.push(msg.event as ServerEvent);
break;
case "pokeReceived":
pokeNotifications.push({
id: `poke-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
invokerId: Number(msg.invokerId) || 0,
invokerUid: typeof msg.invokerUid === "string" ? msg.invokerUid : "",
invokerName: String(msg.invokerName || "Unknown"),
message: String(msg.message || ""),
timestamp: typeof msg.timestamp === "number" ? msg.timestamp : Date.now(),
});
break;
case "channelSwitched":
@@ -561,7 +605,8 @@ export function useVoiceWebSocket() {
state.error = "连接已中断,无法自动恢复";
break;
case "error":
state.error = protocolErrorMessage(String(msg.error?.code || ""), String(msg.error?.message || msg.message || "操作失败"));
state.errorCode = String(msg.error?.code || "");
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
break;
}
}
@@ -578,16 +623,21 @@ export function useVoiceWebSocket() {
if (ws.value?.readyState === WebSocket.OPEN) ws.value.send(JSON.stringify({ type, payload }));
}
function switchChannel(channelId: string): void {
sendCmd("switchChannel", { channelId });
function switchChannel(channelId: string, password = ""): void {
state.error = "";
state.errorCode = "";
sendCmd("switchChannel", { channelId, ...(password ? { password } : {}) });
}
function sendTextMessage(message: string): void {
function sendTextMessage(message: string, targetId = ""): void {
const trimmed = message.trim();
if (!trimmed || trimmed.length > 500) return;
sendCmd("sendTextMessage", { message: trimmed });
chatMessages.push({
id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
scope: "channel",
...(targetId ? { targetId } : {}),
senderId: state.tsClientId,
invokerName: "你",
message: trimmed,
timestamp: Date.now(),
@@ -595,6 +645,28 @@ export function useVoiceWebSocket() {
});
}
function sendServerMessage(message: string): void {
const trimmed = message.trim();
if (!trimmed || trimmed.length > 500) return;
sendCmd("sendServerMessage", { message: trimmed });
chatMessages.push({ id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, scope: "server", senderId: state.tsClientId, invokerName: "你", message: trimmed, timestamp: Date.now(), isSelf: true });
}
function sendPrivateMessage(clientId: number, message: string, targetId = ""): void {
const trimmed = message.trim();
if (!trimmed || trimmed.length > 500) return;
sendCmd("sendPrivateMessage", { clientId, message: trimmed });
chatMessages.push({ id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, scope: "private", targetId, conversationId: String(clientId), senderId: state.tsClientId, invokerName: "你", message: trimmed, timestamp: Date.now(), isSelf: true });
}
function sendPoke(clientId: number, message = ""): void {
sendCmd("poke", { clientId, message: message.trim().slice(0, 200) });
}
function setAway(away: boolean, message = ""): void {
sendCmd("setAway", { away, message: message.trim().slice(0, 200) });
}
function reconnectNow(): void {
if (!lastConnection || state.connecting) return;
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity);
@@ -612,6 +684,7 @@ export function useVoiceWebSocket() {
function clearError(): void {
state.error = "";
state.errorCode = "";
}
function protocolErrorMessage(code: string, fallback: string): string {
@@ -622,10 +695,19 @@ export function useVoiceWebSocket() {
UNKNOWN_MESSAGE_TYPE: "不支持的操作",
INVALID_PAYLOAD: "操作参数无效",
INVALID_CHANNEL_ID: "频道标识无效",
INVALID_CHANNEL_PASSWORD: "频道密码无效",
INVALID_CLIENT_ID: "成员标识无效",
INVALID_TEXT_MESSAGE: "文字消息无效",
INVALID_POKE_MESSAGE: "戳一戳消息无效",
INVALID_AWAY_STATUS: "离开状态无效",
INVALID_AUDIO_FRAME: "音频帧格式无效",
SESSION_NOT_READY: "TeamSpeak 会话尚未就绪",
CHANNEL_SWITCH_FAILED: "频道切换失败",
CHANNEL_PASSWORD_REQUIRED: "该频道需要密码",
CHANNEL_FULL: "该频道已满",
PERMISSION_DENIED: "你没有执行此操作的权限",
CLIENT_NOT_FOUND: "成员已离线",
OPERATION_FAILED: "操作失败",
};
return messages[code] || fallback;
}
@@ -660,6 +742,8 @@ export function useVoiceWebSocket() {
members,
channels,
chatMessages,
serverEvents,
pokeNotifications,
micMode,
inputVolume,
outputVolume,
@@ -682,6 +766,10 @@ export function useVoiceWebSocket() {
disconnect,
switchChannel,
sendTextMessage,
sendServerMessage,
sendPrivateMessage,
sendPoke,
setAway,
setMicMode,
setPTT,
checkSupport,
+205 -12
View File
@@ -87,7 +87,7 @@
</section>
<!-- Connected application shell -->
<div v-else class="app-shell">
<div v-else class="app-shell" @click="memberMenu = null">
<main class="workspace">
<header class="workspace-header">
<div class="breadcrumbs"><span class="mobile-brand">TeamSpeak <em>Web</em></span><span class="crumb-muted">{{ t('serverBreadcrumb') }}</span><Icon name="chevron-right" :size="14" /><strong>{{ currentChannelName }}</strong></div>
@@ -109,6 +109,7 @@
<div class="reconnect-copy"><strong>{{ voiceState.reconnectFailed ? t('reconnectFailed') : t('connectionInterrupted') }}</strong><span v-if="voiceState.reconnecting">{{ t('reconnectingAttempt', { attempt: voiceState.reconnectAttempt }) }}</span><span v-else>{{ localizedMessage(voiceState.error) }}</span></div>
<div class="reconnect-actions"><button v-if="voiceState.reconnectFailed" type="button" class="secondary-button" @click="reconnectNow">{{ t('reconnectNow') }}</button><button type="button" class="text-button" @click="doDisconnect">{{ t('back') }}</button></div>
</div>
<div v-for="poke in visiblePokes" :key="poke.id" class="poke-banner" role="status"><Icon name="bell" :size="17" /><span><strong>{{ poke.invokerName }}</strong> {{ t('pokedYou') }}<small v-if="poke.message">:{{ poke.message }}</small></span><button type="button" @click="dismissPoke(poke.id)"><Icon name="close" :size="15" /></button></div>
<div class="workspace-scroll">
<div class="workspace-content">
@@ -136,16 +137,28 @@
</section>
<section class="chat-panel">
<div class="section-heading chat-heading"><div><span class="section-kicker">{{ t('textChannel') }}</span><h2><Icon name="hash" :size="20" /> {{ t('channelChat', { channel: currentChannelName }) }}</h2></div><span class="section-counter">{{ t('messageCount', { count: chatMessages.length }) }}</span></div>
<div class="chat-tabs" role="tablist" :aria-label="t('chatTabs')">
<button type="button" :class="{ active: chatTab === 'channel' }" @click="chatTab = 'channel'"><Icon name="hash" :size="15" /> {{ currentChannelName }}</button>
<button type="button" :class="{ active: chatTab === 'server' }" @click="chatTab = 'server'"><Icon name="server" :size="15" /> {{ t('serverChat') }}</button>
<button v-for="conversation in privateConversations" :key="conversation.id" type="button" :class="{ active: chatTab === 'private' && privateClientId === conversation.id }" @click="openPrivateChat(conversation.id)"><Icon name="message" :size="15" /> {{ conversation.name }}</button>
<button type="button" :class="{ active: chatTab === 'events' }" @click="chatTab = 'events'"><Icon name="bell" :size="15" /> {{ t('eventLog') }}</button>
</div>
<div class="section-heading chat-heading"><div><span class="section-kicker">{{ chatTabLabel }}</span><h2><Icon :name="chatTab === 'server' ? 'server' : chatTab === 'events' ? 'bell' : chatTab === 'private' ? 'message' : 'hash'" :size="20" /> {{ chatTitle }}</h2></div><span class="section-counter">{{ chatTab === 'events' ? t('eventCount', { count: serverEvents.length }) : t('messageCount', { count: visibleChatMessages.length }) }}</span></div>
<div ref="chatListEl" class="message-list">
<div v-if="!chatMessages.length" class="chat-empty"><div class="chat-empty-icon"><Icon name="message" :size="24" /></div><strong>{{ t('chatStart') }}</strong><span>{{ t('chatStartLead') }}</span></div>
<article v-for="message in chatMessages" :key="message.id" :class="['message-row', { mine: message.isSelf }]">
<div v-if="chatTab === 'events'">
<article v-for="event in serverEvents" :key="event.id" class="event-row"><time>{{ formatTime(event.timestamp) }}</time><span>{{ event.message }}</span></article>
<div v-if="!serverEvents.length" class="chat-empty"><div class="chat-empty-icon"><Icon name="bell" :size="24" /></div><strong>{{ t('noEvents') }}</strong><span>{{ t('noEventsLead') }}</span></div>
</div>
<div v-else-if="!visibleChatMessages.length" class="chat-empty"><div class="chat-empty-icon"><Icon name="message" :size="24" /></div><strong>{{ chatTab === 'private' ? t('privateChatStart') : t('chatStart') }}</strong><span>{{ chatTab === 'private' ? t('privateChatStartLead') : t('chatStartLead') }}</span></div>
<template v-for="message in visibleChatMessages" :key="message.id">
<article v-if="chatTab !== 'events'" :class="['message-row', { mine: message.isSelf }]">
<div class="message-avatar" :style="avatarStyle(message.invokerName, message.isSelf)">{{ avatarInitial(message.invokerName) }}</div>
<div class="message-body"><div class="message-meta"><strong>{{ message.isSelf ? (language === 'zh' ? '你' : 'You') : message.invokerName }}</strong><time>{{ formatTime(message.timestamp) }}</time></div><div class="message-bubble">{{ message.message }}</div></div>
</article>
</article>
</template>
</div>
<form class="message-composer" @submit.prevent="submitMessage">
<input v-model="messageDraft" maxlength="500" :placeholder="t('sendMessagePlaceholder')" :aria-label="t('send')" />
<form v-if="chatTab !== 'events'" class="message-composer" @submit.prevent="submitMessage">
<input v-model="messageDraft" maxlength="500" :placeholder="chatPlaceholder" :aria-label="t('send')" />
<button class="send-button" type="submit" :disabled="!messageDraft.trim()" :title="t('send')"><Icon name="send" :size="18" /></button>
</form>
</section>
@@ -155,7 +168,7 @@
</main>
<aside class="member-panel">
<div class="member-panel-heading"><div><span class="section-kicker">{{ t('people') }}</span><h2>{{ t('people') }}</h2></div></div>
<div class="member-panel-heading"><div><span class="section-kicker">{{ t('people') }}</span><h2>{{ t('people') }}</h2></div><button type="button" class="status-button" :class="{ active: away }" @click="toggleAway"><span class="status-dot"></span>{{ away ? t('away') : t('available') }}</button></div>
<div class="member-search"><Icon name="search" :size="15" /><input v-model="memberQuery" :placeholder="t('searchMembers')" :aria-label="t('searchMembers')" /></div>
<div class="member-tree">
<section v-for="channelItem in filteredMemberChannels" :key="channelItem.id" :class="['member-channel-group', { current: currentChannel?.id === channelItem.id }]" :style="{ marginLeft: `${channelItem.depth * 10}px` }">
@@ -165,10 +178,12 @@
<small>{{ channelItem.members.length }}</small>
</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">
<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-copy"><strong>{{ member.isSelf ? `${member.nickname}${language === 'zh' ? '(你)' : ' (You)'}` : member.nickname }}</strong><span>{{ isSpeaking(member) ? t('speaking') : member.isSelf ? t('yourDevice') : t('memberOnline') }}</span></div>
<div class="member-copy"><strong>{{ member.isSelf ? `${member.nickname}${language === 'zh' ? '(你)' : ' (You)'}` : member.nickname }}</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>
<button v-if="!member.isSelf" type="button" class="member-more" :aria-label="t('moreMemberOptions')" :title="t('moreMemberOptions')" @click.stop="openMemberMenu(member, $event)"><Icon name="more" :size="17" /></button>
</div>
</div>
<div v-else class="channel-no-members">{{ t('noMembersInChannel') }}</div>
@@ -179,6 +194,13 @@
</aside>
</div>
<div v-if="memberMenu" class="member-context-menu" :style="memberMenuStyle" @click.stop>
<strong>{{ memberMenu.member.nickname }}</strong>
<button type="button" @click="openPrivateChat(memberMenu.member.id); memberMenu = null"><Icon name="message" :size="15" /> {{ t('privateMessage') }}</button>
<button type="button" @click="pokeMember(memberMenu.member); memberMenu = null"><Icon name="bell" :size="15" /> {{ t('poke') }}</button>
<button type="button" @click="copyMemberName(memberMenu.member); memberMenu = null"><Icon name="copy" :size="15" /> {{ t('copyNickname') }}</button>
</div>
<!-- Audio settings modal -->
<div v-if="settingsOpen" class="modal-backdrop" @click.self="settingsOpen = false">
<section class="settings-modal" role="dialog" aria-modal="true" :aria-labelledby="'settings-title'">
@@ -209,6 +231,8 @@ const {
members,
channels,
chatMessages,
serverEvents,
pokeNotifications,
micMode,
inputVolume,
outputVolume,
@@ -231,6 +255,10 @@ const {
disconnect,
switchChannel,
sendTextMessage,
sendServerMessage,
sendPrivateMessage,
sendPoke,
setAway,
setMicMode,
setPTT,
checkSupport,
@@ -262,6 +290,11 @@ const toast = ref("");
const chatListEl = ref<HTMLElement | null>(null);
const identityFileInput = ref<HTMLInputElement | null>(null);
const localPersistenceAvailable = isLocalPersistenceAvailable();
const chatTab = ref<"channel" | "server" | "private" | "events">("channel");
const privateClientId = ref(0);
const away = ref(false);
const awayMessage = ref("");
const memberMenu = ref<{ member: ChannelMember; x: number; y: number } | null>(null);
let toastTimer: ReturnType<typeof setTimeout> | undefined;
type Language = "zh" | "en";
@@ -366,6 +399,27 @@ const translations: Record<Language, Record<string, string>> = {
messageCount: "{{count}} 条消息",
chatStart: "这是聊天的开始",
chatStartLead: "发送一条消息,和频道里的朋友打个招呼吧。",
chatTabs: "聊天标签",
serverChat: "服务器",
privateMessage: "私聊",
privateMessagePlaceholder: "发送私聊消息…",
serverMessagePlaceholder: "发送服务器消息…",
channelPasswordPrompt: "请输入频道密码",
privateChatStart: "这是私聊的开始",
privateChatStartLead: "发送一条私聊消息。",
eventLog: "事件日志",
eventCount: "{{count}} 条事件",
noEvents: "暂无服务器事件",
noEventsLead: "频道和成员变化会显示在这里。",
available: "在线",
away: "离开",
awayPrompt: "离开状态说明(可选)",
poke: "戳一戳",
pokedYou: "戳了你一下",
pokeMessagePrompt: "戳一戳消息(可选)",
pokeSent: "已发送戳一戳",
copyNickname: "复制昵称",
copiedNickname: "昵称已复制",
attachmentUnavailable: "附件暂不可用",
emojiUnavailable: "表情暂不可用",
sendMessagePlaceholder: "发送消息给频道成员…",
@@ -381,6 +435,10 @@ const translations: Record<Language, Record<string, string>> = {
onlineGroup: "在线 — {{count}}",
yourDevice: "你的设备",
memberOnline: "在线",
memberStates: "成员状态",
inputMuted: "已禁用麦克风",
outputMuted: "已禁用扬声器",
channelCommander: "频道指挥官",
noMatchingMembers: "没有找到匹配的成员",
noMembersInChannel: "此频道暂无成员",
volumeTip: "拖动成员右侧滑杆,单独调整听到的音量。",
@@ -525,6 +583,27 @@ const translations: Record<Language, Record<string, string>> = {
messageCount: "{{count}} messages",
chatStart: "This is the beginning of the chat",
chatStartLead: "Send a message and say hello to your channel friends.",
chatTabs: "Chat tabs",
serverChat: "Server",
privateMessage: "Private message",
privateMessagePlaceholder: "Message privately…",
serverMessagePlaceholder: "Message the server…",
channelPasswordPrompt: "Enter the channel password",
privateChatStart: "This is the beginning of the private chat",
privateChatStartLead: "Send a private message.",
eventLog: "Event log",
eventCount: "{{count}} events",
noEvents: "No server events yet",
noEventsLead: "Channel and member changes will appear here.",
available: "Available",
away: "Away",
awayPrompt: "Away message (optional)",
poke: "Poke",
pokedYou: "poked you",
pokeMessagePrompt: "Poke message (optional)",
pokeSent: "Poke sent",
copyNickname: "Copy nickname",
copiedNickname: "Nickname copied",
attachmentUnavailable: "Attachments unavailable",
emojiUnavailable: "Emoji unavailable",
sendMessagePlaceholder: "Message the channel…",
@@ -540,6 +619,10 @@ const translations: Record<Language, Record<string, string>> = {
onlineGroup: "ONLINE — {{count}}",
yourDevice: "Your device",
memberOnline: "Online",
memberStates: "Member states",
inputMuted: "Microphone muted",
outputMuted: "Output muted",
channelCommander: "Channel commander",
noMatchingMembers: "No matching members",
noMembersInChannel: "No members in this channel",
volumeTip: "Drag a member slider to adjust their volume just for you.",
@@ -632,10 +715,19 @@ function localizedMessage(message: string) {
"不支持的操作": "This operation is not supported",
"操作参数无效": "The operation payload is invalid",
"频道标识无效": "The channel id is invalid",
"成员标识无效": "The member id is invalid",
"频道密码无效": "The channel password is invalid",
"文字消息无效": "The text message is invalid",
"戳一戳消息无效": "The poke message is invalid",
"离开状态无效": "The away status is invalid",
"音频帧格式无效": "The audio frame is invalid",
"TeamSpeak 会话尚未就绪": "The TeamSpeak session is not ready",
"频道切换失败": "Channel switch failed",
"该频道需要密码": "This channel requires a password",
"该频道已满": "This channel is full",
"你没有执行此操作的权限": "You do not have permission to perform this action",
"成员已离线": "This member is offline",
"操作失败": "The operation failed",
};
if (exact[message]) return exact[message];
if (message.startsWith("麦克风访问失败:")) return `Microphone access failed: ${message.slice(8)}`;
@@ -698,6 +790,33 @@ const filteredMemberChannels = computed(() => {
return memberChannels.value.filter((item) => item.name.toLowerCase().includes(search) || item.members.some((member) => member.nickname.toLowerCase().includes(search)));
});
const privateConversations = computed(() => {
const conversations = new Map<string, { id: number; name: string; lastMessage: number }>();
for (const message of chatMessages) {
if (message.scope !== "private" || !message.conversationId) continue;
const id = Number(message.conversationId);
if (!id) continue;
const member = members.find((candidate) => candidate.id === id);
const existing = conversations.get(message.conversationId);
conversations.set(message.conversationId, { id, name: member?.nickname ?? existing?.name ?? message.invokerName, lastMessage: Math.max(existing?.lastMessage ?? 0, message.timestamp) });
}
return [...conversations.values()].sort((a, b) => b.lastMessage - a.lastMessage);
});
const visibleChatMessages = computed(() => {
if (chatTab.value === "server") return chatMessages.filter((message) => message.scope === "server");
if (chatTab.value === "private") return chatMessages.filter((message) => message.scope === "private" && message.conversationId === String(privateClientId.value));
if (chatTab.value !== "channel") return [];
const channelId = currentChannel.value?.id;
return chatMessages.filter((message) => message.scope === "channel" && (!message.targetId || !channelId || message.targetId === channelId));
});
const chatTabLabel = computed(() => chatTab.value === "channel" ? t("textChannel") : chatTab.value === "server" ? t("serverChat") : chatTab.value === "private" ? t("privateMessage") : t("eventLog"));
const chatTitle = computed(() => chatTab.value === "channel" ? t("channelChat", { channel: currentChannelName.value }) : chatTab.value === "server" ? t("serverChat") : chatTab.value === "events" ? t("eventLog") : privateConversations.value.find((conversation) => conversation.id === privateClientId.value)?.name ?? t("privateMessage"));
const chatPlaceholder = computed(() => chatTab.value === "private" ? t("privateMessagePlaceholder") : chatTab.value === "server" ? t("serverMessagePlaceholder") : t("sendMessagePlaceholder"));
const visiblePokes = computed(() => pokeNotifications.slice(-3));
const memberMenuStyle = computed(() => memberMenu.value ? { left: `${memberMenu.value.x}px`, top: `${memberMenu.value.y}px` } : {});
watch(channelTree, (list) => {
if (!selectedChannelId.value && list[0]) {
selectedChannelId.value = list.find((item) => item.name === channel.value)?.id
@@ -705,7 +824,18 @@ watch(channelTree, (list) => {
?? "";
}
}, { deep: true });
watch(() => chatMessages.length, () => nextTick(scrollChatToEnd));
watch([() => chatMessages.length, chatTab, privateClientId], () => nextTick(scrollChatToEnd));
watch(() => voiceState.errorCode, (code) => {
if (code !== "CHANNEL_PASSWORD_REQUIRED" || !selectedChannelId.value) return;
const password = window.prompt(t("channelPasswordPrompt"), "");
if (password !== null) switchChannel(selectedChannelId.value, password);
});
watch(() => pokeNotifications.length, (length, previousLength) => {
const latest = pokeNotifications[length - 1];
if (!latest || length <= previousLength) return;
showToast(`${latest.invokerName} ${t("pokedYou")}${latest.message ? `:${latest.message}` : ""}`);
if (typeof Notification !== "undefined" && Notification.permission === "granted") new Notification(t("poke"), { body: `${latest.invokerName}: ${latest.message || t("pokedYou")}` });
});
watch(settingsOpen, (open) => {
if (open) {
audioSettingsError.value = "";
@@ -786,6 +916,7 @@ function doDisconnect() {
function selectChannel(item: TreeChannel) {
selectedChannelId.value = item.id;
channel.value = item.name;
chatTab.value = "channel";
switchChannel(item.id);
}
@@ -908,10 +1039,46 @@ async function loadPublicConfig() {
function submitMessage() {
if (!messageDraft.value.trim()) return;
sendTextMessage(messageDraft.value);
if (chatTab.value === "channel") sendTextMessage(messageDraft.value, currentChannel.value?.id ?? selectedChannelId.value);
else if (chatTab.value === "server") sendServerMessage(messageDraft.value);
else if (chatTab.value === "private" && privateClientId.value) sendPrivateMessage(privateClientId.value, messageDraft.value, String(privateClientId.value));
messageDraft.value = "";
}
function openPrivateChat(clientId: number): void {
if (!clientId || clientId === voiceState.tsClientId) return;
privateClientId.value = clientId;
chatTab.value = "private";
memberMenu.value = null;
nextTick(scrollChatToEnd);
}
function openMemberMenu(member: ChannelMember, event: Event): void {
if (member.isSelf) return;
const point = event instanceof MouseEvent ? event : undefined;
memberMenu.value = { member, x: Math.min((point?.clientX ?? 20), Math.max(12, window.innerWidth - 210)), y: Math.min((point?.clientY ?? 20), Math.max(12, window.innerHeight - 170)) };
}
function pokeMember(member: ChannelMember): void {
sendPoke(member.id, window.prompt(t("pokeMessagePrompt"), "") ?? "");
showToast(t("pokeSent"));
}
function copyMemberName(member: ChannelMember): void {
navigator.clipboard?.writeText(member.nickname).then(() => showToast(t("copiedNickname")), () => showToast(t("copyFailedToast")));
}
function toggleAway(): void {
away.value = !away.value;
awayMessage.value = away.value ? (window.prompt(t("awayPrompt"), awayMessage.value) ?? "") : "";
setAway(away.value, awayMessage.value);
}
function dismissPoke(id: string): void {
const index = pokeNotifications.findIndex((poke) => poke.id === id);
if (index >= 0) pokeNotifications.splice(index, 1);
}
function scrollChatToEnd() {
const list = chatListEl.value;
if (list) list.scrollTo({ top: list.scrollHeight, behavior: "smooth" });
@@ -1288,4 +1455,30 @@ function stopPointerTalk() {
.header-note, .guide-button span { display: none; }
.guide-button { width: 32px; justify-content: center; padding: 0; }
}
.chat-tabs { display: flex; align-items: center; gap: 6px; max-width: 100%; margin-top: 18px; overflow-x: auto; padding-bottom: 3px; }
.chat-tabs button { display: inline-flex; align-items: center; gap: 5px; flex: 0 0 auto; padding: 7px 10px; color: #74837e; background: #f3f7f5; border: 1px solid transparent; border-radius: 7px; font-size: 11px; cursor: pointer; }
.chat-tabs button:hover { color: #006a64; background: #e8f4f1; }
.chat-tabs button.active { color: #006a64; background: #dff1ed; border-color: #c9e5df; font-weight: 700; }
.event-row { display: flex; align-items: baseline; gap: 12px; padding: 9px 10px; color: #65746e; border-bottom: 1px solid #edf2f0; font-size: 12px; line-height: 1.45; }
.event-row time { flex: 0 0 auto; color: #99a6a1; font-size: 10px; }
.member-panel-heading { align-items: flex-end; }
.status-button { display: inline-flex; align-items: center; gap: 6px; padding: 6px 8px; color: #5f746c; background: #f2f7f5; border: 1px solid #e0ebe7; border-radius: 7px; font-size: 11px; cursor: pointer; }
.status-button:hover, .status-button.active { color: #8c653a; background: #fcf3e7; border-color: #f0dcc0; }
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: #66d27a; }
.status-button.active .status-dot { background: #e0a34d; }
.member-row { position: relative; }
.member-more { display: grid; place-items: center; width: 24px; height: 24px; flex: 0 0 auto; color: #91a09b; background: transparent; border-radius: 6px; cursor: pointer; opacity: 0; }
.member-row:hover .member-more, .member-more:focus-visible { opacity: 1; }
.member-more:hover { color: #006a64; background: #e6f2ef; }
.member-context-menu { position: fixed; z-index: 40; display: grid; min-width: 188px; gap: 3px; padding: 8px; background: #fff; border: 1px solid #e0eae6; border-radius: 10px; box-shadow: 0 14px 35px rgba(20, 50, 44, .16); }
.member-context-menu strong { padding: 4px 8px 7px; color: #2a3934; font-size: 12px; }
.member-context-menu button { display: flex; align-items: center; gap: 8px; padding: 8px; color: #52625c; background: transparent; border-radius: 6px; font-size: 11px; text-align: left; cursor: pointer; }
.member-context-menu button:hover { color: #006a64; background: #edf6f3; }
.poke-banner { position: fixed; z-index: 35; top: 82px; right: 24px; display: flex; align-items: center; gap: 9px; max-width: min(380px, calc(100% - 48px)); padding: 10px 11px; color: #52645c; background: #fffdf6; border: 1px solid #f0dfbd; border-radius: 9px; box-shadow: 0 8px 22px rgba(88, 65, 28, .12); font-size: 12px; }
.poke-banner > .ui-icon { color: #d2973d; }
.poke-banner span { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.poke-banner strong { color: #8f6532; }
.poke-banner small { font-size: inherit; }
.poke-banner button { display: grid; place-items: center; padding: 3px; color: #9b8a6e; background: transparent; border-radius: 5px; cursor: pointer; }
.poke-banner button:hover { color: #735020; background: #f9eed9; }
</style>