mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat: split TeamSpeak address and port inputs
This commit is contained in:
1 parent
bf1158aff2
commit
3ec9ab497a
7 files changed
+144
-42
No files matched your search
@@ -0,0 +1,56 @@
|
||||
export const DEFAULT_TEAM_SPEAK_PORT = "9987";
|
||||
|
||||
export interface TeamSpeakTargetFields {
|
||||
address: string;
|
||||
port: string;
|
||||
}
|
||||
|
||||
/** Split both the current canonical target and the legacy address#port form. */
|
||||
export function splitTeamSpeakTarget(value: unknown, fallbackPort = DEFAULT_TEAM_SPEAK_PORT): TeamSpeakTargetFields {
|
||||
const input = typeof value === "string" ? value.trim() : "";
|
||||
if (!input) return { address: "", port: fallbackPort };
|
||||
|
||||
const hash = input.lastIndexOf("#");
|
||||
if (hash > 0 && isPort(input.slice(hash + 1))) {
|
||||
return { address: stripBrackets(input.slice(0, hash)), port: input.slice(hash + 1) };
|
||||
}
|
||||
|
||||
if (input.startsWith("[")) {
|
||||
const closingBracket = input.indexOf("]");
|
||||
if (closingBracket > 0) {
|
||||
const address = input.slice(1, closingBracket);
|
||||
const suffix = input.slice(closingBracket + 1);
|
||||
const port = suffix.startsWith(":") && isPort(suffix.slice(1)) ? suffix.slice(1) : fallbackPort;
|
||||
return { address, port };
|
||||
}
|
||||
}
|
||||
|
||||
const colon = input.lastIndexOf(":");
|
||||
if (colon > 0 && input.indexOf(":") === colon && isPort(input.slice(colon + 1))) {
|
||||
return { address: input.slice(0, colon), port: input.slice(colon + 1) };
|
||||
}
|
||||
|
||||
return { address: stripBrackets(input), port: fallbackPort };
|
||||
}
|
||||
|
||||
/** Build the canonical API value from the two user-facing fields. */
|
||||
export function combineTeamSpeakTarget(address: string, port: string): string {
|
||||
const normalizedAddress = stripBrackets(address.trim());
|
||||
const normalizedPort = port.trim() || DEFAULT_TEAM_SPEAK_PORT;
|
||||
if (!normalizedAddress) return "";
|
||||
return normalizedAddress.includes(":") ? `[${normalizedAddress}]:${normalizedPort}` : `${normalizedAddress}:${normalizedPort}`;
|
||||
}
|
||||
|
||||
export function isValidTeamSpeakPort(value: string): boolean {
|
||||
return isPort(value.trim());
|
||||
}
|
||||
|
||||
function isPort(value: string): boolean {
|
||||
if (!/^\d+$/.test(value)) return false;
|
||||
const port = Number(value);
|
||||
return Number.isInteger(port) && port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
function stripBrackets(value: string): string {
|
||||
return value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
|
||||
}
|
||||
+20
-13
@@ -34,7 +34,7 @@
|
||||
<section v-if="route.path === '/admin/server'" class="page-content">
|
||||
<div class="page-heading"><div><h2>{{ tr('serverSettings') }}</h2><p>{{ tr('serverSettingsLead') }}</p></div><button class="primary-button" :disabled="submitting" @click="saveServerSettings">{{ submitting ? tr('saving') : tr('saveChanges') }}</button></div>
|
||||
<div class="settings-grid">
|
||||
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.target" :placeholder="tr('serverPlaceholder')" /></label><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}</strong><small>{{ testResultText }}</small></div></div></article>
|
||||
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}</strong><small>{{ testResultText }}</small></div></div></article>
|
||||
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><label><span>{{ tr('welcomeText') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="4"></textarea></label></article>
|
||||
</div>
|
||||
<article class="readonly-card"><h3>{{ tr('runtimeFacts') }}</h3><dl><div><dt>{{ tr('detectedProtocol') }}</dt><dd>{{ serverForm.detectedProtocol?.toUpperCase() || tr('unknown') }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></article>
|
||||
@@ -65,6 +65,7 @@
|
||||
import { computed, onMounted, reactive, ref, watch } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
type Language = "zh" | "en";
|
||||
@@ -90,7 +91,7 @@ const newPassword = ref("");
|
||||
const confirmNewPassword = ref("");
|
||||
const testResult = ref<ProbeState | null>(null);
|
||||
|
||||
const serverForm = reactive({ target: "", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", detectedProtocol: null as string | null, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", detectedProtocol: null as string | null, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", protocol: null as string | null, lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false });
|
||||
interface AdminSession { id: string; nickname: string; target: string; state: string; createdAt: string; ageSeconds: number; tsClientId: number | null; channelId: string | null; memberCount: number }
|
||||
interface ManagedInvite { id: string; target: string; channel: string; expiresAt: string; maxUses: number; useCount: number; createdAt: string; revokedAt: string | null; status: "active" | "expired" | "exhausted" | "revoked" }
|
||||
@@ -133,9 +134,11 @@ const copy = {
|
||||
saving: "正在保存…",
|
||||
saveChanges: "保存更改",
|
||||
teamSpeakTarget: "默认 TeamSpeak 目标",
|
||||
serverAddress: "目标地址(服务器:端口)",
|
||||
serverPlaceholder: "例如 ts.example.com:9987",
|
||||
serverHint: "支持主机名、IPv4 与 [IPv6]:端口;不需要选择 TS3 或 TS6。",
|
||||
serverAddress: "TeamSpeak 服务器地址",
|
||||
serverPlaceholder: "例如:ts.example.com 或 127.0.0.1",
|
||||
serverPort: "语音端口",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverHint: "请分别填写服务器地址和语音端口;IPv6 地址可直接填写,不需要方括号。",
|
||||
serverPassword: "服务器密码",
|
||||
optional: "可选",
|
||||
optionalPassword: "无密码则留空",
|
||||
@@ -273,9 +276,11 @@ const copy = {
|
||||
saving: "Saving…",
|
||||
saveChanges: "Save changes",
|
||||
teamSpeakTarget: "Default TeamSpeak target",
|
||||
serverAddress: "Target address (server:port)",
|
||||
serverPlaceholder: "e.g. ts.example.com:9987",
|
||||
serverHint: "Hostnames, IPv4 and [IPv6]:port are supported. TS3/TS6 is detected automatically.",
|
||||
serverAddress: "TeamSpeak server address",
|
||||
serverPlaceholder: "e.g. ts.example.com or 127.0.0.1",
|
||||
serverPort: "Voice port",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverHint: "Enter the server address and voice port separately. IPv6 addresses do not need brackets.",
|
||||
serverPassword: "Server password",
|
||||
optional: "Optional",
|
||||
optionalPassword: "Leave blank when unused",
|
||||
@@ -391,7 +396,7 @@ const testResultText = computed(() => { if (!testResult.value) return ""; if (!t
|
||||
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
|
||||
onMounted(loadAdminView);
|
||||
watch(() => [serverForm.target, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
|
||||
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
|
||||
watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); });
|
||||
|
||||
async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } }
|
||||
@@ -399,7 +404,7 @@ async function login() { submitting.value = true; errorMessage.value = ""; try {
|
||||
async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } }
|
||||
async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); }
|
||||
async function loadServerSettings() { const value = await getJson("/api/admin/server"); Object.assign(serverForm, value, { serverPassword: "", passwordAction: "keep" }); }
|
||||
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep" }); }
|
||||
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
|
||||
async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } }
|
||||
async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
@@ -407,9 +412,9 @@ async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('con
|
||||
async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } }
|
||||
function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); }
|
||||
async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
|
||||
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); Object.assign(serverForm, result.settings, { serverPassword: "", passwordAction: "keep" }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function testServerConnection() { await runTest("/api/admin/server/test", { target: serverForm.target, serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.detectedProtocol = testResult.value.protocol ?? null; serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } }
|
||||
function serverPayload() { return { target: serverForm.target, serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText }; }
|
||||
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep" }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.detectedProtocol = testResult.value.protocol ?? null; serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } }
|
||||
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText }; }
|
||||
async function runTest(url: string, body: Record<string, unknown>) { testing.value = true; errorMessage.value = ""; testResult.value = null; try { testResult.value = await sendJson(url, "POST", body, url.includes("/server/test")); } catch (error) { testResult.value = { ok: false, code: (error as ApiError).code }; } finally { testing.value = false; } }
|
||||
async function dismissLegacyNotice() { await sendJson("/api/admin/legacy-import/dismiss", "POST", {}); overview.legacyConfigImported = false; }
|
||||
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
|
||||
@@ -446,4 +451,6 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
:global(:root[data-theme="dark"]) .operation-card,:global(:root[data-theme="dark"]) .invite-row,:global(:root[data-theme="dark"]) .diagnostic-list div,:global(:root[data-theme="dark"]) .log-row{color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap{border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td,:global(:root[data-theme="dark"]) .invite-list{border-color:#30413d}:global(:root[data-theme="dark"]) .operation-card header p,:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td small,:global(:root[data-theme="dark"]) .invite-row small{color:#9bb0aa}
|
||||
@media(max-width:850px){.operations-grid{grid-template-columns:1fr}.operation-wide{overflow:hidden}}
|
||||
@media(max-width:520px){.operation-card{padding:18px}.table-wrap{margin-left:-18px;margin-right:-18px;margin-bottom:-18px}.invite-form-grid,.diagnostic-list{grid-template-columns:1fr}.generated-link{display:grid}.invite-row{align-items:flex-start;flex-direction:column}.invite-row-meta{width:100%;justify-content:flex-end}.lower-operations{margin-top:14px}}
|
||||
.target-fields{display:grid;grid-template-columns:minmax(0,1fr) 132px;gap:12px}
|
||||
@media(max-width:520px){.target-fields{grid-template-columns:1fr}}
|
||||
</style>
|
||||
+39
-23
@@ -36,16 +36,16 @@
|
||||
<div v-if="!localPersistenceAvailable" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ t('localPersistenceUnavailable') }}</span></div>
|
||||
|
||||
<form v-if="initialized" class="join-form" @submit.prevent="doConnect">
|
||||
<div v-if="accessMode === 'open'">
|
||||
<label class="field-label" for="server-address">{{ t('serverAddress') }}</label>
|
||||
<div class="field-wrap"><Icon name="server" :size="17" /><input id="server-address" v-model="serverAddress" autocomplete="url" :placeholder="t('serverAddressPlaceholder')" /></div>
|
||||
<div v-if="accessMode === 'open'" class="field-grid target-fields">
|
||||
<label class="field-label" for="server-address"><span>{{ t('serverAddress') }}</span><div class="field-wrap"><Icon name="server" :size="17" /><input id="server-address" v-model="serverHost" autocomplete="url" :placeholder="t('serverAddressPlaceholder')" /></div></label>
|
||||
<label class="field-label" for="server-port"><span>{{ t('serverPort') }}</span><div class="field-wrap"><Icon name="hash" :size="17" /><input id="server-port" v-model="serverPort" inputmode="numeric" type="text" maxlength="5" :placeholder="t('serverPortPlaceholder')" /></div></label>
|
||||
</div>
|
||||
<p v-if="accessMode === 'open'" class="field-hint">{{ t('serverAddressHint') }}</p>
|
||||
<div v-if="accessMode === 'open' && (favoriteServers.length || recentServers.length)" class="local-servers">
|
||||
<div v-if="favoriteServers.length" class="local-server-group"><span>{{ t('favoriteServers') }}</span><button v-for="favorite in favoriteServers" :key="favorite.id" type="button" @click="selectLocalServer(favorite.address, favorite.nickname)">{{ favorite.label }}</button></div>
|
||||
<div v-if="recentServers.length" class="local-server-group"><span>{{ t('recentServers') }}</span><button v-for="recent in recentServers" :key="recent.id" type="button" @click="selectLocalServer(recent.address, recent.nickname)">{{ recent.address }}</button></div>
|
||||
</div>
|
||||
<button v-if="accessMode === 'open' && serverAddress.trim()" type="button" class="favorite-toggle" @click="toggleFavorite">{{ isFavorite ? t('removeFavorite') : t('saveFavorite') }}</button>
|
||||
<button v-if="accessMode === 'open' && serverHost.trim()" type="button" class="favorite-toggle" @click="toggleFavorite">{{ isFavorite ? t('removeFavorite') : t('saveFavorite') }}</button>
|
||||
|
||||
<template v-if="accessMode === 'open'">
|
||||
<label class="field-label" for="server-password">{{ t('serverPassword') }} <span>{{ t('optional') }}</span></label>
|
||||
@@ -242,6 +242,7 @@ import Icon from "../components/Icon.vue";
|
||||
import { useVoiceWebSocket, type ChannelInfo, type ChannelMember } from "../composables/useVoiceWebSocket.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listFavorites, listRecentServers, loadLocalPreferences, loadStoredIdentity, recordRecentServer, removeFavorite, saveFavorite, saveLocalPreferences, saveStoredIdentity, type FavoriteServer, type RecentServer } from "../services/local-persistence.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
|
||||
interface TreeChannel extends ChannelInfo {
|
||||
depth: number;
|
||||
@@ -307,9 +308,11 @@ const {
|
||||
const query = new URLSearchParams(location.search);
|
||||
const initialChannel = query.get("channel") ?? "";
|
||||
const inviteToken = query.get("invite") ?? "";
|
||||
const initialTarget = initialServerTarget();
|
||||
const nickname = ref(localStorage.getItem("webspeak:nickname") ?? "");
|
||||
const channel = ref(initialChannel);
|
||||
const serverAddress = ref(initialServerAddress());
|
||||
const serverHost = ref(initialTarget.address);
|
||||
const serverPort = ref(initialTarget.port);
|
||||
const serverPassword = ref("");
|
||||
const accessMode = ref<"fixed" | "open">("fixed");
|
||||
const rememberIdentity = ref(localStorage.getItem("webspeak:remember-identity") === "1");
|
||||
@@ -372,7 +375,9 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
joinLead: "输入一个昵称,选择进入的频道。",
|
||||
serverAddress: "TeamSpeak 服务器地址",
|
||||
serverAddressPlaceholder: "例如:ts.example.com 或 127.0.0.1",
|
||||
serverAddressHint: "这是网关服务器连接的 TeamSpeak 地址,不是浏览器直接连接地址。",
|
||||
serverPort: "语音端口",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "这是网关服务器连接的 TeamSpeak 地址和端口,不是浏览器直接连接地址。",
|
||||
nickname: "你的昵称",
|
||||
nicknamePlaceholder: "例如:Alex Rivera",
|
||||
targetChannel: "目标频道",
|
||||
@@ -591,7 +596,9 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
joinLead: "Choose a nickname and the channel to enter.",
|
||||
serverAddress: "TeamSpeak server address",
|
||||
serverAddressPlaceholder: "e.g. ts.example.com or 127.0.0.1",
|
||||
serverAddressHint: "This is the TeamSpeak address reached by the gateway, not a direct browser connection.",
|
||||
serverPort: "Voice port",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "This is the TeamSpeak address and port reached by the gateway, not a direct browser connection.",
|
||||
nickname: "Your nickname",
|
||||
nicknamePlaceholder: "e.g. Alex Rivera",
|
||||
targetChannel: "Target channel",
|
||||
@@ -785,15 +792,12 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
},
|
||||
};
|
||||
|
||||
function initialServerAddress(): string {
|
||||
function initialServerTarget() {
|
||||
const explicit = query.get("server") ?? query.get("target");
|
||||
if (explicit?.trim()) return explicit.trim();
|
||||
if (explicit?.trim()) return splitTeamSpeakTarget(explicit);
|
||||
const host = (query.get("tsHost") ?? location.hostname).trim();
|
||||
const port = (query.get("tsPort") ?? "9987").trim();
|
||||
if (!host) return `127.0.0.1:${port}`;
|
||||
if (/^[^:]+:\d+$/.test(host) || /^\[[^\]]+\]:\d+$/.test(host)) return host;
|
||||
if (host.startsWith("[") || !host.includes(":")) return `${host}:${port}`;
|
||||
return `[${host}]:${port}`;
|
||||
const port = (query.get("tsPort") ?? DEFAULT_TEAM_SPEAK_PORT).trim();
|
||||
return splitTeamSpeakTarget(host, port || DEFAULT_TEAM_SPEAK_PORT);
|
||||
}
|
||||
|
||||
function getInitialLanguage(): Language {
|
||||
@@ -992,7 +996,7 @@ watch(() => voiceState.connected, (connected) => {
|
||||
return;
|
||||
}
|
||||
playNotification("connected");
|
||||
const address = serverAddress.value.trim();
|
||||
const address = currentServerTarget();
|
||||
if (!address) return;
|
||||
const recent: RecentServer = {
|
||||
id: serverKey(address),
|
||||
@@ -1059,10 +1063,11 @@ function doConnect() {
|
||||
localStorage.setItem("webspeak:nickname", nickname.value);
|
||||
void saveLocalPreferences({ schemaVersion: 1, lastNickname: nickname.value });
|
||||
if (accessMode.value === "open") {
|
||||
serverAddress.value = serverAddress.value.trim();
|
||||
serverHost.value = serverHost.value.trim();
|
||||
serverPort.value = serverPort.value.trim();
|
||||
}
|
||||
selectedChannelId.value = "";
|
||||
connect(serverAddress.value, channel.value.trim(), nickname.value, accessMode.value === "open" ? serverPassword.value : "", rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value, inviteToken);
|
||||
connect(currentServerTarget(), channel.value.trim(), nickname.value, accessMode.value === "open" ? serverPassword.value : "", rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value, inviteToken);
|
||||
}
|
||||
|
||||
function doDisconnect() {
|
||||
@@ -1095,7 +1100,7 @@ function doShare() {
|
||||
invite.searchParams.delete("tsHost");
|
||||
invite.searchParams.delete("tsPort");
|
||||
invite.searchParams.delete("server");
|
||||
if (accessMode.value === "open" && serverAddress.value.trim()) invite.searchParams.set("server", serverAddress.value.trim());
|
||||
if (accessMode.value === "open" && serverHost.value.trim()) invite.searchParams.set("server", currentServerTarget());
|
||||
if (channel.value) invite.searchParams.set("channel", channel.value);
|
||||
navigator.clipboard?.writeText(invite.toString()).then(() => showToast(t("copiedToast")), () => showToast(t("copyFailedToast")));
|
||||
}
|
||||
@@ -1103,21 +1108,27 @@ function doShare() {
|
||||
const canJoin = computed(() => Boolean(
|
||||
initialized.value
|
||||
&& nickname.value.trim()
|
||||
&& (accessMode.value === "fixed" || serverAddress.value.trim()),
|
||||
&& (accessMode.value === "fixed" || (serverHost.value.trim() && isValidTeamSpeakPort(serverPort.value))),
|
||||
));
|
||||
const isFavorite = computed(() => favoriteServers.value.some((favorite) => favorite.id === serverKey(serverAddress.value)));
|
||||
const isFavorite = computed(() => favoriteServers.value.some((favorite) => favorite.id === serverKey(currentServerTarget())));
|
||||
|
||||
function currentServerTarget(): string {
|
||||
return combineTeamSpeakTarget(serverHost.value, serverPort.value);
|
||||
}
|
||||
|
||||
function serverKey(address: string): string {
|
||||
return address.trim().toLocaleLowerCase();
|
||||
}
|
||||
|
||||
function selectLocalServer(address: string, savedNickname?: string): void {
|
||||
serverAddress.value = address;
|
||||
const target = splitTeamSpeakTarget(address);
|
||||
serverHost.value = target.address;
|
||||
serverPort.value = target.port;
|
||||
if (savedNickname && !nickname.value.trim()) nickname.value = savedNickname;
|
||||
}
|
||||
|
||||
async function toggleFavorite(): Promise<void> {
|
||||
const address = serverAddress.value.trim();
|
||||
const address = currentServerTarget();
|
||||
if (!address) return;
|
||||
const id = serverKey(address);
|
||||
const existing = favoriteServers.value.find((favorite) => favorite.id === id);
|
||||
@@ -1190,7 +1201,11 @@ async function loadPublicConfig() {
|
||||
if (typeof config.welcomeText === "string") welcomeText.value = config.welcomeText;
|
||||
accessMode.value = config.accessMode === "open" ? "open" : "fixed";
|
||||
const hasInviteTarget = query.has("server") || query.has("target") || query.has("tsHost") || query.has("tsPort");
|
||||
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) serverAddress.value = config.target.trim();
|
||||
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
|
||||
const target = splitTeamSpeakTarget(config.target);
|
||||
serverHost.value = target.address;
|
||||
serverPort.value = target.port;
|
||||
}
|
||||
} catch {
|
||||
// Keep joining disabled until the gateway can confirm its initialized policy.
|
||||
} finally {
|
||||
@@ -1474,6 +1489,7 @@ function stopWhisperTalk(): void {
|
||||
.join-form { display: grid; gap: 8px; }
|
||||
.field-grid { display: grid; grid-template-columns: minmax(0, 1fr) 132px; gap: 12px; }
|
||||
.field-grid .field-label { display: block; }
|
||||
.field-grid .field-label:not(:first-child) { margin-top: 0; }
|
||||
.field-hint { margin: 1px 0 5px; color: #879590; font-size: 10px; line-height: 1.5; }
|
||||
.field-label, .settings-label { color: #43514d; font-size: 11px; font-weight: 600; }
|
||||
.field-label:not(:first-child) { margin-top: 10px; }
|
||||
|
||||
Reference in new issue
Block a user