fix: bind admin state to request and page lifecycles

This commit is contained in:
illusia committed 2026-10-01 12:11:47 +08:00
1 parent 0785f82386
commit 525f512f4a
11 files changed
+1175 -229

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
import { onScopeDispose, reactive, ref, type Ref } from "vue";
import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord } from "../../../src/shared/admin-responses.js";
import type { copy } from "../i18n/admin.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
interface Options {
api: AdminApi;
errorMessage: Ref<string>;
errorText(code?: string): string;
tr(key: keyof typeof copy.zh, vars?: Record<string, string | number>): string;
refreshOverview(): Promise<void>;
}
export function useAdminOperations(options: Options) {
const requests = createAdminRequests();
const operationsLoading = ref(false), terminatingSession = ref(""), inviteSubmitting = ref(false);
const revokingInvites = reactive(new Set<string>());
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[],
diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 },
logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
let noticeTimer: number | undefined;
function cancelRequests() {
requests.reset();
operationsLoading.value = false; terminatingSession.value = ""; inviteSubmitting.value = false;
revokingInvites.clear();
if (noticeTimer !== undefined) window.clearTimeout(noticeTimer);
noticeTimer = undefined;
}
function reset() {
cancelRequests();
createdInvite.value = null;
operations.sessions = []; operations.invites = []; operations.audit = [];
operations.logs = { available: false, entries: [], sessions: [] };
operations.diagnostics = { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 };
Object.assign(inviteForm, { channel: "", expiresInHours: 24, maxUses: 0 });
}
onScopeDispose(reset);
function report(error: unknown) {
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
}
async function loadOperations() {
const request = requests.begin("load");
operationsLoading.value = true;
try {
const [sessions, invites, diagnostics, logs, audit] = await Promise.all([
options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
]);
if (!request.isCurrent()) return;
operations.sessions = sessions.sessions;
operations.invites = invites.invites;
operations.diagnostics = { ...diagnostics.gateway, schemaVersion: diagnostics.database.schemaVersion, createdSessions: diagnostics.sessions.created };
operations.logs = logs;
operations.audit = audit.events;
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) operationsLoading.value = false; request.finish(); }
}
async function terminateSession(session: AdminSession) {
if (terminatingSession.value || !window.confirm(options.tr("confirmTerminate", { nickname: session.nickname }))) return;
const request = requests.begin("terminate");
terminatingSession.value = session.id; options.errorMessage.value = "";
try {
await options.api.terminateSession(session.id, request.signal);
if (request.isCurrent()) await Promise.all([loadOperations(), options.refreshOverview()]);
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) terminatingSession.value = ""; request.finish(); }
}
async function createInvite() {
if (inviteSubmitting.value) return;
const request = requests.begin("invite"), channel = inviteForm.channel;
inviteSubmitting.value = true; options.errorMessage.value = ""; createdInvite.value = null;
try {
const result = await options.api.createInvite({ ...inviteForm }, request.signal);
if (!request.isCurrent()) return;
createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` };
if (inviteForm.channel === channel) inviteForm.channel = "";
await loadOperations();
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) inviteSubmitting.value = false; request.finish(); }
}
async function revokeInvite(invite: ManagedInvite) {
if (revokingInvites.has(invite.id) || !window.confirm(options.tr("confirmRevoke"))) return;
const request = requests.begin(`revoke:${invite.id}`);
revokingInvites.add(invite.id);
try {
await options.api.revokeInvite(invite.id, request.signal);
if (request.isCurrent()) await loadOperations();
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) revokingInvites.delete(invite.id); request.finish(); }
}
async function copyInviteLink() {
if (!createdInvite.value) return;
const request = requests.begin("copy");
try {
await navigator.clipboard.writeText(createdInvite.value.link);
if (!request.isCurrent()) return;
const message = options.tr("copiedLink");
options.errorMessage.value = message;
if (noticeTimer !== undefined) window.clearTimeout(noticeTimer);
noticeTimer = window.setTimeout(() => { if (options.errorMessage.value === message) options.errorMessage.value = ""; noticeTimer = undefined; }, 2200);
} catch (error) { if (request.isCurrent()) report(error); }
finally { request.finish(); }
}
async function downloadBackup() {
const request = requests.begin("backup");
try {
const blob = await options.api.backup(request.signal);
if (!request.isCurrent()) return;
const url = URL.createObjectURL(blob);
try {
const anchor = document.createElement("a");
anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click();
} finally { URL.revokeObjectURL(url); }
await loadOperations();
} catch (error) { if (request.isCurrent()) report(error); }
finally { request.finish(); }
}
return { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, cancelRequests, reset };
}
@@ -0,0 +1,150 @@
import { onScopeDispose, reactive, ref, watch, type Ref } from "vue";
import { DEFAULT_WELCOME_TEXTS } from "../../../src/site-copy.js";
import type { AdminSettings } from "../../../src/shared/admin-responses.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
type SecretAction = "keep" | "replace" | "remove";
interface RelayNodeForm { id: string; name: string; enabled: boolean; target: string; token: string; tokenAction: SecretAction; hasToken: boolean }
interface ProbeState { ok: boolean; checkType?: "network" | "protocol"; latencyMs?: number; serverName?: string | null; packetLossPercent?: number; code?: string; errorCode?: string }
interface Options { api: AdminApi; errorMessage: Ref<string>; errorText(code?: string): string; refreshOverview(): Promise<void> }
function emptyForm() {
return { address: "", port: "9987", serverPassword: "", passwordAction: "keep" as SecretAction, hasPassword: false,
accessMode: "fixed" as "fixed" | "open", siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", welcomeTextDe: "", welcomeTextRu: "", welcomeTextJa: "",
welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS }, webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099,
relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null };
}
type ServerForm = ReturnType<typeof emptyForm>;
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcUdpStart", "webRtcUdpEnd"] as const;
const snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(form));
export function useAdminServerSettings(options: Options) {
const requests = createAdminRequests();
const serverForm = reactive(emptyForm());
const serverSaving = ref(false);
const testing = ref(false);
const testResult = ref<ProbeState | null>(null);
let probeRevision = 0;
let applyingSettings = false;
function cancelRequests() {
requests.reset();
serverSaving.value = false;
testing.value = false;
}
function reset() { cancelRequests(); Object.assign(serverForm, emptyForm()); testResult.value = null; }
onScopeDispose(cancelRequests);
function invalidateProbe() {
probeRevision++;
requests.cancel("probe");
testing.value = false;
testResult.value = null;
serverForm.lastTestAt = null;
serverForm.lastTestLatencyMs = null;
}
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => {
if (!applyingSettings) invalidateProbe();
}, { flush: "sync" });
function mergeSettings(value: AdminSettings, baseline: ServerForm, observedProbeRevision: number): void {
const target = splitTeamSpeakTarget(value.target);
const next: ServerForm = { ...emptyForm(), ...value, address: target.address, port: target.port,
relayNodes: value.relayNodes.map(node => ({ ...node, token: "", tokenAction: "keep" })),
welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS, ...value.welcomeDefaults } };
const applyProbeMetadata = observedProbeRevision === probeRevision;
const previousAddress = serverForm.address, previousPort = serverForm.port;
// Clearing acknowledged secret inputs does not change the tested credential.
applyingSettings = true;
try {
for (const key of editable) {
if (serverForm[key] === baseline[key]) Object.assign(serverForm, { [key]: next[key] });
}
if (serverForm.address !== previousAddress || serverForm.port !== previousPort) invalidateProbe();
if (serverForm.serverPassword === baseline.serverPassword && serverForm.passwordAction === baseline.passwordAction) {
serverForm.serverPassword = "";
serverForm.passwordAction = "keep";
}
serverForm.hasPassword = next.hasPassword;
serverForm.welcomeDefaults = next.welcomeDefaults;
if (applyProbeMetadata && serverForm.address === next.address && serverForm.port === next.port) {
serverForm.lastTestAt = next.lastTestAt;
serverForm.lastTestLatencyMs = next.lastTestLatencyMs;
}
const oldNodes = new Map(baseline.relayNodes.map(node => [node.id, node]));
const savedNodes = new Map(next.relayNodes.map(node => [node.id, node]));
const currentIds = new Set(serverForm.relayNodes.map(node => node.id));
serverForm.relayNodes = [
...next.relayNodes.filter(node => !oldNodes.has(node.id) && !currentIds.has(node.id)),
...serverForm.relayNodes.map(node => {
const old = oldNodes.get(node.id), saved = savedNodes.get(node.id);
if (!old || !saved) return node;
const merged = { ...node, hasToken: saved.hasToken };
for (const key of ["name", "target", "enabled"] as const) {
if (node[key] === old[key]) Object.assign(merged, { [key]: saved[key] });
}
if (node.token === old.token && node.tokenAction === old.tokenAction) {
merged.token = ""; merged.tokenAction = "keep";
}
return merged;
}),
];
} finally { applyingSettings = false; }
}
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, welcomeTextEn: serverForm.welcomeTextEn, welcomeTextDe: serverForm.welcomeTextDe, welcomeTextRu: serverForm.welcomeTextRu, welcomeTextJa: serverForm.welcomeTextJa,
webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd,
relayNodes: serverForm.relayNodes.map(node => ({ id: node.id, name: node.name, target: node.target, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) };
}
function report(error: unknown) {
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
}
async function loadServerSettings() {
const request = requests.begin("load"), baseline = snapshot(serverForm), observedProbeRevision = probeRevision;
try {
const value = await options.api.settings(request.signal);
if (request.isCurrent()) mergeSettings(value, baseline, observedProbeRevision);
} catch (error) { if (request.isCurrent()) report(error); }
finally { request.finish(); }
}
async function saveServerSettings() {
if (serverSaving.value) return;
requests.cancel("load");
const request = requests.begin("save"), baseline = snapshot(serverForm), observedProbeRevision = probeRevision;
serverSaving.value = true;
options.errorMessage.value = "";
try {
const result = await options.api.saveSettings(serverPayload(), request.signal);
if (!request.isCurrent()) return;
mergeSettings(result.settings, baseline, observedProbeRevision);
await options.refreshOverview();
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) serverSaving.value = false; request.finish(); }
}
async function testServerConnection() {
probeRevision++;
const request = requests.begin("probe");
testing.value = true;
testResult.value = null;
options.errorMessage.value = "";
try {
const result = await options.api.probe(serverPayload(), request.signal);
if (!request.isCurrent()) return;
testResult.value = result;
serverForm.lastTestAt = new Date().toISOString();
serverForm.lastTestLatencyMs = result.ok ? result.latencyMs ?? null : null;
await options.refreshOverview();
} catch (error) {
if (request.isCurrent() && !isAdminRequestCancelled(error)) testResult.value = { ok: false, code: (error as { code?: string }).code };
} finally { if (request.isCurrent()) testing.value = false; request.finish(); }
}
function addRelayNode() {
serverForm.relayNodes.push({ id: `relay-new-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, name: "", enabled: false, target: "", token: "", tokenAction: "replace", hasToken: false });
}
function removeRelayNode(index: number) { serverForm.relayNodes.splice(index, 1); }
return { serverForm, serverSaving, testing, testResult, loadServerSettings, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode, cancelRequests, reset };
}
+103
View File
@@ -0,0 +1,103 @@
import { computed, onScopeDispose, ref } from "vue";
import type { copy } from "../i18n/admin.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
import { BUILTIN_SKIN_CATALOG, type SkinCatalogEntry } from "../services/skin-catalog.js";
interface Options { api: AdminApi; tr(key: keyof typeof copy.zh): string }
export function useAdminSkins(options: Options) {
const requests = createAdminRequests();
const skinFileInput = ref<HTMLInputElement | null>(null);
const skinEntries = ref<SkinCatalogEntry[]>([]);
const skinLoading = ref(false), skinUploading = ref(false), skinDefaultSaving = ref(false);
const removingSkinId = ref(""), updatingSkinId = ref(""), skinDefaultId = ref("builtin.light");
const skinManagerError = ref(""), skinManagerNotice = ref("");
const skinBusy = computed(() => skinUploading.value || skinDefaultSaving.value || Boolean(removingSkinId.value || updatingSkinId.value));
const enabledSkinEntries = computed(() => skinEntries.value.filter(skin => skin.builtIn || skin.enabled !== false));
let savedDefault = "builtin.light";
function cancelRequests() {
requests.reset();
skinLoading.value = false; skinUploading.value = false; skinDefaultSaving.value = false;
removingSkinId.value = ""; updatingSkinId.value = "";
skinManagerError.value = ""; skinManagerNotice.value = "";
}
function reset() { cancelRequests(); skinEntries.value = []; savedDefault = skinDefaultId.value = "builtin.light"; }
onScopeDispose(reset);
function report(error: unknown, upload = false) {
if (!isAdminRequestCancelled(error)) skinManagerError.value = upload && error instanceof Error ? error.message : options.tr("operationFailed");
}
async function loadSkinCatalog() {
const request = requests.begin("load"), selected = skinDefaultId.value;
skinLoading.value = true; skinManagerError.value = "";
try {
const value = await options.api.skins(request.signal);
if (!request.isCurrent()) return;
const protectedIds = new Set(BUILTIN_SKIN_CATALOG.map(skin => skin.id));
skinEntries.value = [...BUILTIN_SKIN_CATALOG, ...value.skins.filter(skin => !protectedIds.has(skin.id))];
savedDefault = value.defaultSkinId;
if (skinDefaultId.value === selected) skinDefaultId.value = savedDefault;
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) skinLoading.value = false; request.finish(); }
}
async function saveSkinDefault() {
if (skinBusy.value) return;
requests.cancel("load"); skinLoading.value = false;
const request = requests.begin("mutation"), selected = skinDefaultId.value;
skinDefaultSaving.value = true; skinManagerError.value = ""; skinManagerNotice.value = "";
try {
const result = await options.api.setDefaultSkin(selected, request.signal);
if (!request.isCurrent()) return;
savedDefault = result.defaultSkinId;
if (skinDefaultId.value === selected) skinDefaultId.value = savedDefault;
skinManagerNotice.value = options.tr("skinDefaultSaved");
} catch (error) {
if (request.isCurrent()) { report(error); if (skinDefaultId.value === selected) skinDefaultId.value = savedDefault; }
} finally { if (request.isCurrent()) skinDefaultSaving.value = false; request.finish(); }
}
async function toggleSkinEnabled(skin: SkinCatalogEntry) {
if (skinBusy.value) return;
requests.cancel("load"); skinLoading.value = false;
const request = requests.begin("mutation"), selected = skinDefaultId.value;
updatingSkinId.value = skin.id; skinManagerError.value = ""; skinManagerNotice.value = "";
try {
const result = await options.api.setSkinEnabled(skin.id, skin.enabled === false, request.signal);
if (!request.isCurrent()) return;
const current = skinEntries.value.find(entry => entry.id === skin.id);
if (current) Object.assign(current, result.skin);
savedDefault = result.defaultSkinId;
if (skinDefaultId.value === selected) skinDefaultId.value = savedDefault;
skinManagerNotice.value = options.tr(result.skin.enabled === false ? "skinDisabledNotice" : "skinEnabledNotice");
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) updatingSkinId.value = ""; request.finish(); }
}
async function onSkinFileChanged(event: Event) {
const input = event.target as HTMLInputElement, file = input.files?.[0];
if (!file || skinBusy.value) return;
requests.cancel("load"); skinLoading.value = false;
const request = requests.begin("mutation");
skinUploading.value = true; skinManagerError.value = ""; skinManagerNotice.value = "";
try {
const result = await options.api.uploadSkin(file, id => !skinEntries.value.some(entry => entry.id === id) || window.confirm(`${options.tr("skinReplaceConfirm")}\n${id}`), request.signal);
if (!request.isCurrent() || !result) return;
skinManagerNotice.value = options.tr("skinImported");
await loadSkinCatalog();
} catch (error) { if (request.isCurrent()) report(error, true); }
finally { input.value = ""; if (request.isCurrent()) skinUploading.value = false; request.finish(); }
}
async function removeSkin(skin: SkinCatalogEntry) {
if (skinBusy.value || !window.confirm(`${options.tr("skinConfirmRemove")}\n${skin.name} (${skin.id})`)) return;
requests.cancel("load"); skinLoading.value = false;
const request = requests.begin("mutation");
removingSkinId.value = skin.id; skinManagerError.value = ""; skinManagerNotice.value = "";
try {
await options.api.deleteSkin(skin.id, request.signal);
if (!request.isCurrent()) return;
skinManagerNotice.value = options.tr("skinRemoved");
await loadSkinCatalog();
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) removingSkinId.value = ""; request.finish(); }
}
return { skinFileInput, skinEntries, skinLoading, skinUploading, skinDefaultSaving, removingSkinId, updatingSkinId, skinDefaultId,
skinManagerError, skinManagerNotice, skinBusy, enabledSkinEntries, loadSkinCatalog, saveSkinDefault, toggleSkinEnabled, onSkinFileChanged, removeSkin, cancelRequests, reset };
}