mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat: 浏览器端报错翻译与提示改造
- errors: 新增 TeamSpeak 服务器错误 ID 映射表与不可重连错误码集合,归一化 normalizeTeamSpeakError 按 错误ID/关键词/异常类/传输层特征 分级收敛错误 - voice-bridge: 身份无效/客户端不可用时先发结构化 connectionFailed 帧再关闭, 新增 pendingKickReason 机制在 kicked 事件后优先回放踢出原因;Opus 编码器 不可用时限流上报 AUDIO_ENCODER_UNAVAILABLE - ts-client: 记录本端退出 reasonID,转发 kicked 事件并归一化踢出/封禁原因 - network-probe/teamspeak-probe: 收窄关键字匹配、拒绝原因收敛到既有探测码 - session-manager: 新增 teamSpeak-kicked 拆除原因 - WebClient: 麦克风失败不再假成功,音频状态避免自相矛盾,新增降级横幅与 中/英/德三语提示词表 - useVoiceWebSocket: 导出 ensureMicrophone 供开麦前预检,新增音频诊断状态、 CONNECTION_FAILURE_MESSAGES 总表与网关关闭码映射 - 关键新增逻辑补充中文注释说明改动意图
This commit is contained in:
1 parent
1ba8cd5ee1
commit
4ead174c04
8 files changed
+677
-74
No files matched your search
@@ -12,6 +12,15 @@ export interface VoiceState {
|
||||
tsClientId: number;
|
||||
error: string;
|
||||
errorCode: string;
|
||||
/**
|
||||
* Non-fatal audio diagnostics. Unlike error/errorCode these never take over
|
||||
* the connect form: they explain a degraded microphone or playback path while
|
||||
* the voice room itself stays joined and usable.
|
||||
*/
|
||||
microphoneError: string;
|
||||
microphoneErrorCode: string;
|
||||
audioNotice: string;
|
||||
audioNoticeCode: string;
|
||||
channelSwitchedChannelId: string;
|
||||
}
|
||||
|
||||
@@ -89,7 +98,6 @@ const CLIENT_ERROR_CODE_ALIASES: Record<string, string> = {
|
||||
PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED",
|
||||
INVALID_PASSWORD: "INVALID_SERVER_PASSWORD",
|
||||
AUTHENTICATION_FAILED: "INVALID_SERVER_PASSWORD",
|
||||
SERVER_FULL: "SERVER_REJECTED",
|
||||
GATEWAY_FULL: "SERVER_REJECTED",
|
||||
TS_CONNECT_FAILED: "CONNECTION_FAILED",
|
||||
TEAM_SPEAK_CONNECT_FAILED: "CONNECTION_FAILED",
|
||||
@@ -118,9 +126,101 @@ function safeClientErrorDetail(value: unknown): string {
|
||||
.slice(0, 160);
|
||||
}
|
||||
|
||||
// TeamSpeak 对非法昵称没有独立错误码:长度违规统一报 invalid parameter size
|
||||
// (服务器错误 id 1541),该特征串是网关能转发的唯一机器可读线索,因此把匹配器
|
||||
// 与解释文案放在一起,保证两者同步演进。
|
||||
/**
|
||||
* TeamSpeak has no dedicated error for a nickname it refuses: a nickname outside
|
||||
* its length rules is answered with "invalid parameter size" and server error id
|
||||
* 1541. That signature is the only machine-readable hint the gateway can forward,
|
||||
* so keep the matcher next to the message builder that explains it to the user.
|
||||
*/
|
||||
const NICKNAME_LENGTH_SIGNATURE = /invalid[\s_-]*parameter[\s_-]*size|\bid[\s=:]*1541\b|nickname.{0,30}(?:length|size)/i;
|
||||
|
||||
/** Shown whenever TeamSpeak refuses the nickname because of its length. */
|
||||
const NICKNAME_LENGTH_MESSAGE = "昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试";
|
||||
|
||||
/**
|
||||
* Browsers only hand out a DOMException name for getUserMedia failures (and an
|
||||
* often-English message that used to reach the UI verbatim). Map every name the
|
||||
* browsers actually raise to a sentence the user can act on, and keep the
|
||||
* DOMException name as the stable failure code.
|
||||
*/
|
||||
const MICROPHONE_FAILURE_REASONS: Record<string, string> = {
|
||||
NOTALLOWEDERROR: "浏览器未授予麦克风权限",
|
||||
PERMISSIONDENIEDERROR: "浏览器未授予麦克风权限",
|
||||
PERMISSION_DISMISSED: "浏览器未授予麦克风权限",
|
||||
SECURITYERROR: "浏览器阻止了麦克风访问",
|
||||
NOTFOUNDERROR: "未找到可用的麦克风",
|
||||
DEVICESNOTFOUNDERROR: "未找到可用的麦克风",
|
||||
OVERCONSTRAINEDERROR: "所选麦克风当前不可用",
|
||||
NOTREADABLEERROR: "麦克风可能正被其他程序占用",
|
||||
TRACKSTARTERROR: "麦克风可能正被其他程序占用",
|
||||
ABORTERROR: "麦克风启动被中断,请重试",
|
||||
INVALIDSTATEERROR: "麦克风启动被中断,请重试",
|
||||
TYPEFERROR: "麦克风访问参数被系统拒绝",
|
||||
};
|
||||
|
||||
const MICROPHONE_FAILURE_FALLBACK = "麦克风不可用,请检查浏览器权限与音频设备";
|
||||
|
||||
const MICROPHONE_FAILURE_CODE_PREFIX = "MIC_";
|
||||
|
||||
/** Turn a getUserMedia / DOMException failure into a stable code plus a readable sentence. */
|
||||
export function normalizeMicrophoneFailure(error: unknown): { code: string; message: string } {
|
||||
const rawName = error instanceof Error ? String(error.name || "") : "";
|
||||
const name = safeClientErrorCode(rawName).slice(0, 40);
|
||||
const reason = MICROPHONE_FAILURE_REASONS[name] ?? MICROPHONE_FAILURE_FALLBACK;
|
||||
return { code: `${MICROPHONE_FAILURE_CODE_PREFIX}${name || "UNAVAILABLE"}`, message: `麦克风访问失败:${reason}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every code this client can render for a failed connection. A code is regarded
|
||||
* as "explainable" only when it appears here, which is also what keeps the
|
||||
* gateway close codes from being replaced by an unknown close reason.
|
||||
*/
|
||||
const CONNECTION_FAILURE_MESSAGES: Record<string, string> = {
|
||||
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
|
||||
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
|
||||
RATE_LIMITED: "请求过于频繁,请稍后重试",
|
||||
INVALID_TARGET: "TeamSpeak 服务器地址无效",
|
||||
INVALID_NICKNAME: NICKNAME_LENGTH_MESSAGE,
|
||||
HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址",
|
||||
UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址",
|
||||
CONNECTION_REFUSED: "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态",
|
||||
CONNECTION_RESET: "TeamSpeak 连接被服务器或网络重置,请稍后重试",
|
||||
TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态",
|
||||
SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试",
|
||||
INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入",
|
||||
PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败",
|
||||
SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接",
|
||||
CHANNEL_PASSWORD_REQUIRED: "该频道需要密码",
|
||||
NICKNAME_IN_USE: "该昵称已被服务器上的其他用户占用,请更换昵称",
|
||||
IDENTITY_SECURITY_LEVEL_TOO_LOW: "你的身份安全等级低于该服务器要求,请提升后重试",
|
||||
IDENTITY_LIMIT_REACHED: "该身份建立的连接数已达上限,请关闭其他连接后重试",
|
||||
CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝连接,请升级后重试",
|
||||
FLOOD_PROTECTION: "操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试",
|
||||
BANNED: "你已被该服务器封禁,无法连接",
|
||||
KICKED: "你已被服务器移出",
|
||||
SERVER_SHUTTING_DOWN: "TeamSpeak 服务器正在关闭,暂时无法连接",
|
||||
CONNECTION_INITIALISATION_FAILED: "TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试",
|
||||
SERVER_FULL: "服务器当前已满,请稍后重试",
|
||||
INVALID_PARAMETER: "TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规",
|
||||
IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试",
|
||||
CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态",
|
||||
// Gateway close codes: these replace the generic "connection failed" when the
|
||||
// gateway drops the socket itself (see GATEWAY_CLOSE_CODE_CODES).
|
||||
JOIN_TICKET_REQUIRED: "语音会话票据缺失或已过期,请返回列表重新进入语音空间",
|
||||
IDENTITY_INVALID: "语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入",
|
||||
IDENTITY_REJECTED: "语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入",
|
||||
ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速后重试或联系管理员",
|
||||
GATEWAY_NETWORK_LOST: "与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入",
|
||||
GATEWAY_SESSION_ENDED: "语音网关会话意外结束,请重新进入语音空间",
|
||||
TEAM_SPEAK_CLIENT_UNAVAILABLE: "语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试",
|
||||
};
|
||||
|
||||
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: "", errorCode: "", channelSwitchedChannelId: "" });
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const members = reactive<ChannelMember[]>([]);
|
||||
const channels = reactive<ChannelInfo[]>([]);
|
||||
const chatMessages = reactive<ChatMessage[]>([]);
|
||||
@@ -306,6 +406,51 @@ export function useVoiceWebSocket() {
|
||||
return Math.max(minimum, Math.min(maximum, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Microphone failures are a degraded state, not a connection failure: the room
|
||||
* stays joined, so they get their own slot instead of taking over `error`.
|
||||
*/
|
||||
function setMicrophoneError(error: unknown): string {
|
||||
const failure = normalizeMicrophoneFailure(error);
|
||||
state.microphoneErrorCode = failure.code;
|
||||
state.microphoneError = failure.message;
|
||||
return failure.message;
|
||||
}
|
||||
|
||||
function clearMicrophoneError(): void {
|
||||
state.microphoneError = "";
|
||||
state.microphoneErrorCode = "";
|
||||
}
|
||||
|
||||
/** Non-fatal audio notice (WebRTC fallback, blocked autoplay, device list failure...). */
|
||||
function setAudioNotice(code: string, message: string): void {
|
||||
state.audioNoticeCode = safeClientErrorCode(code) || "AUDIO_NOTICE";
|
||||
state.audioNotice = message;
|
||||
}
|
||||
|
||||
function clearAudioNotice(code?: string): void {
|
||||
if (code && state.audioNoticeCode !== safeClientErrorCode(code)) return;
|
||||
state.audioNotice = "";
|
||||
state.audioNoticeCode = "";
|
||||
}
|
||||
|
||||
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
|
||||
function syncAudioContextNotice(): void {
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
|
||||
} else {
|
||||
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
|
||||
}
|
||||
}
|
||||
|
||||
function audioNoticeMessage(code: string, detail?: unknown): string {
|
||||
const detailText = safeClientErrorDetail(detail);
|
||||
if (code === "AUDIO_ENCODER_UNAVAILABLE") {
|
||||
return `麦克风声音未能发送:语音网关的音频编码器不可用(错误代码:${code})${detailText ? `:${detailText}` : ""},请联系管理员`;
|
||||
}
|
||||
return `音频链路异常(错误代码:${code})${detailText ? `:${detailText}` : ""},麦克风声音可能没有发送给其他成员`;
|
||||
}
|
||||
|
||||
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
|
||||
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
|
||||
if (!ctx.setSinkId && !mediaSinkSupported) {
|
||||
@@ -339,12 +484,19 @@ export function useVoiceWebSocket() {
|
||||
// route: a running-but-silent graph could leave the UI reporting a live
|
||||
// speaker while the actual remote audio element remained muted.
|
||||
output.muted = false;
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
try { await audioCtx.resume(); } catch { /* a user gesture is still required */ }
|
||||
}
|
||||
try {
|
||||
await output.play();
|
||||
webrtcPlaybackRetryCleanup?.();
|
||||
clearAudioNotice("PLAYBACK_BLOCKED");
|
||||
syncAudioContextNotice();
|
||||
} catch {
|
||||
// Mobile and privacy-focused browsers can require a gesture even for a
|
||||
// MediaStream. Keep retrying after the next real interaction.
|
||||
// MediaStream. Keep retrying after the next real interaction, but tell the
|
||||
// user why the remote audio is missing instead of staying silent.
|
||||
setAudioNotice("PLAYBACK_BLOCKED", "浏览器阻止了音频自动播放,暂时听不到其他成员的声音:请点击页面任意位置,或在地址栏允许本站播放声音");
|
||||
installWebRtcPlaybackRetry();
|
||||
}
|
||||
}
|
||||
@@ -374,9 +526,21 @@ export function useVoiceWebSocket() {
|
||||
if (!navigator.mediaDevices?.enumerateDevices) {
|
||||
inputDevices.length = 0;
|
||||
outputDevices.length = 0;
|
||||
setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息");
|
||||
return;
|
||||
}
|
||||
let devices: MediaDeviceInfo[];
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
clearAudioNotice("DEVICE_LIST_UNAVAILABLE");
|
||||
} catch {
|
||||
// enumerateDevices rejects when the device list is blocked (for example in a
|
||||
// locked-down iframe). Use the browser defaults and explain the limitation.
|
||||
inputDevices.length = 0;
|
||||
outputDevices.length = 0;
|
||||
setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息");
|
||||
return;
|
||||
}
|
||||
const devices = await navigator.mediaDevices.enumerateDevices();
|
||||
const microphones = devices
|
||||
.filter((device) => device.kind === "audioinput")
|
||||
.map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId }));
|
||||
@@ -405,15 +569,21 @@ export function useVoiceWebSocket() {
|
||||
|
||||
async function startMicrophone(): Promise<void> {
|
||||
const ctx = getAudioCtx();
|
||||
if (ctx.state === "suspended") await ctx.resume();
|
||||
if (ctx.state === "suspended") {
|
||||
try { await ctx.resume(); } catch { /* the audio context notice explains the silence */ }
|
||||
}
|
||||
// Acquire the replacement stream before tearing down the current graph so
|
||||
// changing devices does not interrupt an active microphone on failure.
|
||||
let nextStream: MediaStream;
|
||||
try {
|
||||
nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() });
|
||||
audioPermission.value = "granted";
|
||||
clearMicrophoneError();
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied";
|
||||
// Never let the raw DOMException (usually an English message) reach the UI:
|
||||
// record a readable failure first, then let the caller decide how to show it.
|
||||
setMicrophoneError(error);
|
||||
throw error;
|
||||
}
|
||||
stopMicrophone(false);
|
||||
@@ -508,8 +678,10 @@ export function useVoiceWebSocket() {
|
||||
captureNode.connect(silentGain);
|
||||
silentGain.connect(ctx.destination);
|
||||
await refreshAudioDevices();
|
||||
syncAudioContextNotice();
|
||||
}
|
||||
|
||||
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
|
||||
async function ensureMicrophone(): Promise<void> {
|
||||
if (micStream) return;
|
||||
if (!microphoneStartPromise) {
|
||||
@@ -724,7 +896,7 @@ export function useVoiceWebSocket() {
|
||||
};
|
||||
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
|
||||
peer.onconnectionstatechange = () => {
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket, "WEBRTC_CONNECTION_FAILED");
|
||||
};
|
||||
|
||||
const negotiation = (async () => {
|
||||
@@ -741,14 +913,14 @@ export function useVoiceWebSocket() {
|
||||
accompanimentActive: accompanimentActive.value,
|
||||
} }));
|
||||
window.setTimeout(() => {
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_TIMEOUT");
|
||||
}, 8_000);
|
||||
})();
|
||||
webrtcNegotiationPromise = negotiation;
|
||||
try {
|
||||
await negotiation;
|
||||
} catch (error) {
|
||||
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket);
|
||||
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
|
||||
throw error;
|
||||
} finally {
|
||||
if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null;
|
||||
@@ -781,19 +953,22 @@ export function useVoiceWebSocket() {
|
||||
webrtcActive.value = true;
|
||||
syncWebRtcMemberVolumes();
|
||||
} catch {
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value, "WEBRTC_ANSWER_REJECTED");
|
||||
}
|
||||
}
|
||||
|
||||
async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise<void> {
|
||||
async function fallbackFromWebRtc(sequence: number, socket: WebSocket, reasonCode = "WEBRTC_UNAVAILABLE"): Promise<void> {
|
||||
if (sequence !== connectionSequence || webrtcFallbackStarted) return;
|
||||
webrtcFallbackStarted = true;
|
||||
webrtcActive.value = false;
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" }));
|
||||
stopWebRtcTransport();
|
||||
if (socket.readyState === WebSocket.OPEN && state.connected) {
|
||||
// Degrading to the compatibility transport must be visible: the user is
|
||||
// still connected, but with different latency and audio quality.
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reasonCode) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); } catch (error: unknown) {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1129,6 +1304,9 @@ export function useVoiceWebSocket() {
|
||||
const sequence = ++connectionSequence;
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
// Audio diagnostics belong to the previous session, never to the new one.
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
state.connecting = true;
|
||||
state.reconnecting = false;
|
||||
state.reconnectAttempt = 0;
|
||||
@@ -1198,6 +1376,8 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
};
|
||||
@@ -1221,38 +1401,45 @@ export function useVoiceWebSocket() {
|
||||
return messages[normalized] ?? connectionFailureMessage(normalized, detail);
|
||||
}
|
||||
|
||||
// 网关关闭码 → 前端可解释错误码的映射:4000-4003 是网关/会话级,4004/4005 是
|
||||
// TeamSpeak 拒绝与身份冲突,4006 是中继加速,1006/1011 是传输级掉线,绝不能
|
||||
// 被误当成 TeamSpeak 服务器拒绝。
|
||||
/**
|
||||
* Gateway close codes. 4000-4003 are gateway/session level, 4004/4005 are a
|
||||
* TeamSpeak rejection and an identity conflict, 4006 is the acceleration relay,
|
||||
* and 1006 is a transport-level drop that must not be blamed on TeamSpeak.
|
||||
*/
|
||||
const GATEWAY_CLOSE_CODE_CODES: Record<number, string> = {
|
||||
4000: "CONNECTION_FAILED",
|
||||
4001: "JOIN_TICKET_REQUIRED",
|
||||
4002: "INVALID_TARGET",
|
||||
4003: "IDENTITY_REJECTED",
|
||||
4004: "SERVER_REJECTED",
|
||||
4005: "IDENTITY_IN_USE",
|
||||
4006: "ACCELERATION_UNAVAILABLE",
|
||||
1006: "GATEWAY_NETWORK_LOST",
|
||||
1011: "GATEWAY_SESSION_ENDED",
|
||||
};
|
||||
|
||||
function closeErrorCode(code: number, reason = ""): string {
|
||||
const closeCode = normalizedClientErrorCode(reason, "");
|
||||
if (closeCode) return closeCode;
|
||||
if (code === 4002) return "INVALID_TARGET";
|
||||
if (code === 4004) return "SERVER_REJECTED";
|
||||
if (code === 4005) return "IDENTITY_IN_USE";
|
||||
return "CONNECTION_FAILED";
|
||||
// The gateway repeats the failure code in the close reason. Trust it when the
|
||||
// browser can explain that code, otherwise fall back to the numeric close code
|
||||
// so even a silent close maps to an actionable message.
|
||||
if (closeCode && CONNECTION_FAILURE_MESSAGES[closeCode]) return closeCode;
|
||||
return GATEWAY_CLOSE_CODE_CODES[code] ?? "CONNECTION_FAILED";
|
||||
}
|
||||
|
||||
function connectionFailureMessage(code: string, detail?: unknown): string {
|
||||
const messages: Record<string, string> = {
|
||||
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
|
||||
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
|
||||
RATE_LIMITED: "请求过于频繁,请稍后重试",
|
||||
INVALID_TARGET: "TeamSpeak 服务器地址无效",
|
||||
INVALID_NICKNAME: "昵称长度不符合 TeamSpeak 服务器要求,请修改后重试",
|
||||
HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址",
|
||||
UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址",
|
||||
CONNECTION_REFUSED: "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态",
|
||||
CONNECTION_RESET: "TeamSpeak 连接被服务器或网络重置,请稍后重试",
|
||||
TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态",
|
||||
SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试",
|
||||
INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入",
|
||||
PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败",
|
||||
SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接",
|
||||
IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试",
|
||||
CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态",
|
||||
};
|
||||
const messages = CONNECTION_FAILURE_MESSAGES;
|
||||
const normalized = normalizedClientErrorCode(code);
|
||||
if (messages[normalized]) return messages[normalized];
|
||||
const safeCode = safeClientErrorCode(normalized);
|
||||
const safeDetail = safeClientErrorDetail(detail);
|
||||
// The gateway classifies a refused nickname before it reaches the browser,
|
||||
// but translate the raw TeamSpeak signature too: a nickname problem must
|
||||
// never end up as the generic "check your network" fallback.
|
||||
if (safeDetail && NICKNAME_LENGTH_SIGNATURE.test(safeDetail)) return NICKNAME_LENGTH_MESSAGE;
|
||||
return `TeamSpeak 连接失败(错误代码:${safeCode})${safeDetail ? `:${safeDetail}` : ""},请检查输入、网络或服务器状态`;
|
||||
}
|
||||
|
||||
@@ -1268,6 +1455,8 @@ export function useVoiceWebSocket() {
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
stopMicrophone();
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
const socket = ws.value;
|
||||
ws.value = null;
|
||||
stopWebRtcTransport();
|
||||
@@ -1335,17 +1524,13 @@ export function useVoiceWebSocket() {
|
||||
const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined"
|
||||
? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve())
|
||||
: ensureMicrophone();
|
||||
start.catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
// A failed microphone must not look like a failed connection: record it
|
||||
// as an audio diagnostic so the room stays visible with a clear reason.
|
||||
start.catch((error: unknown) => { setMicrophoneError(error); });
|
||||
} else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) {
|
||||
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => { setMicrophoneError(error); });
|
||||
} else {
|
||||
void ensureMicrophone().catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
void ensureMicrophone().catch((error: unknown) => { setMicrophoneError(error); });
|
||||
}
|
||||
break;
|
||||
case "memberEnter":
|
||||
@@ -1475,8 +1660,15 @@ export function useVoiceWebSocket() {
|
||||
void applyWebRtcAnswer(msg.payload?.sdp);
|
||||
break;
|
||||
case "webrtcError":
|
||||
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value, safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
|
||||
break;
|
||||
case "audioError": {
|
||||
// The gateway could not encode our microphone audio (for example its Opus
|
||||
// encoder is unavailable): say it instead of dropping frames silently.
|
||||
const audioCode = safeClientErrorCode(msg.code) || "AUDIO_ERROR";
|
||||
setAudioNotice(audioCode, audioNoticeMessage(audioCode, msg.detail));
|
||||
break;
|
||||
}
|
||||
case "voiceActivity":
|
||||
if (Array.isArray(msg.clientIds)) {
|
||||
for (const clientId of msg.clientIds) {
|
||||
@@ -1634,6 +1826,11 @@ export function useVoiceWebSocket() {
|
||||
CHANNEL_SWITCH_FAILED: "频道切换失败",
|
||||
CHANNEL_PASSWORD_REQUIRED: "该频道需要密码",
|
||||
CHANNEL_FULL: "该频道已满",
|
||||
NICKNAME_IN_USE: "该昵称已被占用,请更换昵称",
|
||||
CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝了该操作",
|
||||
FLOOD_PROTECTION: "操作过于频繁,请稍后重试",
|
||||
BANNED: "你已被该服务器封禁",
|
||||
KICKED: "你已被服务器移出",
|
||||
PERMISSION_DENIED: "你没有执行此操作的权限",
|
||||
CLIENT_NOT_FOUND: "成员已离线",
|
||||
OPERATION_FAILED: "操作失败",
|
||||
@@ -1752,6 +1949,7 @@ export function useVoiceWebSocket() {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
ensureMicrophone,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
|
||||
Reference in new issue
Block a user