refactor(webui): extract ApiClient + lift OneBotInstance config editor
App.tsx was the single source of truth for token, fetch policy, 401 handling, and per-UIN config edit state — fetchApi was drilled into every page and LogsPage read localStorage directly to build its SSE URL, giving two parallel truths for the bearer token. Promote the closure to a deep ApiClient module (domain methods + request() escape hatch) injected via ApiProvider/useApi, and lift selectedUin/config/saveStatus into useOneBotInstanceConfig so ConfigPage is self-contained. normalizeOneBotConfig becomes a pure function. ConfigPage now guards UIN switches when the editor is dirty and refetches the server-normalised config after save. ConfigPage prop count drops from 7 to 1; App.tsx from 421 to 270 LOC.
This commit is contained in:
11 files changed
+818
-398
No files matched your search
+194
-321
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
|
||||
import { LoginPage } from '@/components/pages/login-page';
|
||||
@@ -7,31 +7,115 @@ import { OverviewPage } from '@/components/pages/overview-page';
|
||||
import { ConfigPage } from '@/components/pages/config-page';
|
||||
import { LogsPage } from '@/components/pages/logs-page';
|
||||
import { SettingsPage } from '@/components/pages/settings-page';
|
||||
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import type { Page } from '@/components/layout/sidebar';
|
||||
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
|
||||
|
||||
const TOKEN_KEY = 'snowluma_token';
|
||||
|
||||
function readToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || '';
|
||||
}
|
||||
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppInner />
|
||||
<AuthBoundary />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppInner() {
|
||||
const { pollInterval } = useTheme();
|
||||
function AuthBoundary() {
|
||||
const [authChecked, setAuthChecked] = useState(false);
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [mustChange, setMustChange] = useState(false);
|
||||
const [status, setStatus] = useState('未连接');
|
||||
|
||||
const client = useMemo<ApiClient>(
|
||||
() =>
|
||||
createApiClient({
|
||||
onUnauthorized: () => {
|
||||
setAuthed(false);
|
||||
setStatus('未授权');
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const ok = await client.status();
|
||||
if (ok) {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(await client.mustChangePassword());
|
||||
}
|
||||
setAuthChecked(true);
|
||||
})();
|
||||
}, [client]);
|
||||
|
||||
return (
|
||||
<ApiProvider client={client}>
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{!authChecked ? (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
|
||||
初始化中…
|
||||
</div>
|
||||
) : !authed ? (
|
||||
<LoginGate
|
||||
onAuthed={(needsChange) => {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(needsChange);
|
||||
}}
|
||||
/>
|
||||
) : mustChange ? (
|
||||
<ForcedChangePasswordGate onSuccess={() => setMustChange(false)} />
|
||||
) : (
|
||||
<AppInner
|
||||
status={status}
|
||||
onLogoutComplete={() => {
|
||||
setAuthed(false);
|
||||
setStatus('未连接');
|
||||
setMustChange(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
</ApiProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
|
||||
const api = useApi();
|
||||
const handleLogin = useCallback(
|
||||
async (password: string) => {
|
||||
const result = await api.login(password);
|
||||
if (!result.ok) return { success: false, error: result.message };
|
||||
onAuthed(result.mustChangePassword);
|
||||
return { success: true };
|
||||
},
|
||||
[api, onAuthed],
|
||||
);
|
||||
return <LoginPage onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) {
|
||||
const api = useApi();
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface AppInnerProps {
|
||||
status: string;
|
||||
onLogoutComplete: () => void;
|
||||
}
|
||||
|
||||
function AppInner({ status, onLogoutComplete }: AppInnerProps) {
|
||||
const api = useApi();
|
||||
const { pollInterval } = useTheme();
|
||||
const [active, setActive] = useState<Page>('overview');
|
||||
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
@@ -47,100 +131,31 @@ function AppInner() {
|
||||
// collapse spam-clicks instead of firing a second concurrent request.
|
||||
const inflightProcessOps = useRef(new Set<number>());
|
||||
|
||||
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||
const [config, setConfig] = useState<OneBotConfig | null>(null);
|
||||
const [saveStatus, setSaveStatus] = useState('');
|
||||
|
||||
const tokenRef = useRef(readToken());
|
||||
|
||||
// ---------- API helpers ----------
|
||||
const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => {
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string> | undefined),
|
||||
};
|
||||
if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`;
|
||||
if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
const res = await fetch(url, { ...options, headers });
|
||||
if (res.status === 401) {
|
||||
tokenRef.current = '';
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setAuthed(false);
|
||||
setStatus('未授权');
|
||||
}
|
||||
return res;
|
||||
}, []);
|
||||
|
||||
// ---------- Polling ----------
|
||||
const refreshQqList = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/qq-list');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setQqList(data.list || []);
|
||||
setQqList(await api.qqList());
|
||||
} catch (e) {
|
||||
console.error('qq-list', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
}, [api]);
|
||||
|
||||
const refreshProcesses = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/processes');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setProcessList(data.list || []);
|
||||
setProcessList(await api.processes.list());
|
||||
} catch (e) {
|
||||
console.error('processes', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
}, [api]);
|
||||
|
||||
const refreshSystem = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/system');
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as SystemInfo;
|
||||
setSystemInfo(data);
|
||||
setSystemInfo(await api.system());
|
||||
} catch (e) {
|
||||
console.error('system', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
|
||||
const checkStatus = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/status');
|
||||
if (res.ok) {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
return true;
|
||||
}
|
||||
setStatus('未连接');
|
||||
return false;
|
||||
} catch {
|
||||
setStatus('未连接');
|
||||
return false;
|
||||
}
|
||||
}, [fetchApi]);
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (tokenRef.current) {
|
||||
const ok = await checkStatus();
|
||||
if (ok) {
|
||||
// Existing session may still need to change password.
|
||||
try {
|
||||
const r = await fetchApi('/api/auth/state');
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
setMustChange(!!d.mustChangePassword);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
setAuthChecked(true);
|
||||
})();
|
||||
}, [checkStatus, fetchApi]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authed || mustChange) return;
|
||||
if (pollInterval <= 0) return;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
@@ -153,250 +168,108 @@ function AppInner() {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
|
||||
|
||||
// Auto-select first uin when navigating to config
|
||||
useEffect(() => {
|
||||
if (active !== 'config') return;
|
||||
if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin);
|
||||
}, [active, qqList, selectedUin]);
|
||||
|
||||
// Load config when selectedUin changes
|
||||
useEffect(() => {
|
||||
if (!selectedUin) {
|
||||
setConfig(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const loaded = data?.config ?? data;
|
||||
if (cancelled) return;
|
||||
const nets = loaded?.networks ?? {};
|
||||
const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!loaded?.reportSelfMessage;
|
||||
const normalizeNetwork = <T extends Record<string, unknown>>(item: T) => ({
|
||||
...item,
|
||||
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||
reportSelfMessage:
|
||||
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||
});
|
||||
setConfig({
|
||||
networks: {
|
||||
httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [],
|
||||
httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [],
|
||||
wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [],
|
||||
wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [],
|
||||
},
|
||||
musicSignUrl: loaded?.musicSignUrl,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('load-config', e);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedUin, fetchApi]);
|
||||
|
||||
// ---------- Actions ----------
|
||||
const handleLogin = useCallback(async (password: string) => {
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { success: false, error: data.message || data.error || '令牌错误' };
|
||||
}
|
||||
const data = await res.json();
|
||||
const token = data.token as string;
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
tokenRef.current = token;
|
||||
setMustChange(!!data.mustChangePassword);
|
||||
const ok = await checkStatus();
|
||||
return ok ? { success: true } : { success: false, error: '校验失败' };
|
||||
} catch (e) {
|
||||
return { success: false, error: (e as Error).message || '网络错误' };
|
||||
}
|
||||
}, [checkStatus]);
|
||||
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ }
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
tokenRef.current = '';
|
||||
setAuthed(false);
|
||||
setMustChange(false);
|
||||
setStatus('未连接');
|
||||
await api.logout();
|
||||
setQqList([]);
|
||||
setProcessList([]);
|
||||
setSystemInfo(null);
|
||||
setSelectedUin(null);
|
||||
setConfig(null);
|
||||
}, [fetchApi]);
|
||||
onLogoutComplete();
|
||||
}, [api, onLogoutComplete]);
|
||||
|
||||
const handleLoadProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessLoadingPid(pid);
|
||||
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
|
||||
try {
|
||||
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.message || data.error || '加载失败');
|
||||
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`加载失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessLoadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
|
||||
const handleUnloadProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessUnloadingPid(pid);
|
||||
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
|
||||
try {
|
||||
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
|
||||
|
||||
// Check if unload actually failed (pipe still exists)
|
||||
if (data.process?.status === 'connecting' && data.process?.error) {
|
||||
setUnloadFailedAlert({ pid, error: data.process.error });
|
||||
setProcessActionStatus(`进程 ${pid} 卸载失败`);
|
||||
} else {
|
||||
setProcessActionStatus(`已从进程 ${pid} 卸载`);
|
||||
const handleLoadProcess = useCallback(
|
||||
async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessLoadingPid(pid);
|
||||
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
|
||||
try {
|
||||
await api.processes.load(pid);
|
||||
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`加载失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessLoadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessUnloadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
},
|
||||
[api, refreshProcesses],
|
||||
);
|
||||
|
||||
const handleRefreshProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessRefreshingPid(pid);
|
||||
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
|
||||
try {
|
||||
const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
|
||||
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessRefreshingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
const handleUnloadProcess = useCallback(
|
||||
async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessUnloadingPid(pid);
|
||||
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
|
||||
try {
|
||||
const result = await api.processes.unload(pid);
|
||||
if (result.process?.status === 'connecting' && result.process.error) {
|
||||
setUnloadFailedAlert({ pid, error: result.process.error });
|
||||
setProcessActionStatus(`进程 ${pid} 卸载失败`);
|
||||
} else {
|
||||
setProcessActionStatus(`已从进程 ${pid} 卸载`);
|
||||
}
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`卸载失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessUnloadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
},
|
||||
[api, refreshProcesses],
|
||||
);
|
||||
|
||||
const handleSaveConfig = useCallback(async () => {
|
||||
if (!selectedUin || !config) return;
|
||||
setSaveStatus('保存中...');
|
||||
try {
|
||||
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || '保存失败');
|
||||
setSaveStatus('保存成功');
|
||||
} catch (e) {
|
||||
setSaveStatus(`保存失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
setTimeout(() => setSaveStatus(''), 3000);
|
||||
}
|
||||
}, [selectedUin, config, fetchApi]);
|
||||
|
||||
// ---------- Render ----------
|
||||
if (!authChecked) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
|
||||
初始化中…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const checkStrength = async (password: string) => {
|
||||
const res = await fetchApi('/api/auth/check-strength', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
|
||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
||||
};
|
||||
const submitPwd = async (oldPassword: string, newPassword: string) => {
|
||||
const res = await fetchApi('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ oldPassword, newPassword }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
|
||||
return { success: !!data.success, message: data.message };
|
||||
};
|
||||
const handleRefreshProcess = useCallback(
|
||||
async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessRefreshingPid(pid);
|
||||
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
|
||||
try {
|
||||
await api.processes.refresh(pid);
|
||||
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`刷新失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessRefreshingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
},
|
||||
[api, refreshProcesses],
|
||||
);
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{!authed ? (
|
||||
<LoginPage onLogin={handleLogin} />
|
||||
) : mustChange ? (
|
||||
<ChangePasswordPage
|
||||
forced
|
||||
checkStrength={checkStrength}
|
||||
submit={submitPwd}
|
||||
onSuccess={() => setMustChange(false)}
|
||||
/>
|
||||
) : (
|
||||
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
|
||||
{active === 'overview' && (
|
||||
<OverviewPage
|
||||
qqList={qqList}
|
||||
status={status}
|
||||
processList={processList}
|
||||
processLoadingPid={processLoadingPid}
|
||||
processUnloadingPid={processUnloadingPid}
|
||||
processRefreshingPid={processRefreshingPid}
|
||||
processActionStatus={processActionStatus}
|
||||
systemInfo={systemInfo}
|
||||
onRefreshProcesses={refreshProcesses}
|
||||
onRefreshSystem={refreshSystem}
|
||||
onLoadProcess={handleLoadProcess}
|
||||
onUnloadProcess={handleUnloadProcess}
|
||||
onRefreshProcess={handleRefreshProcess}
|
||||
/>
|
||||
)}
|
||||
{active === 'config' && (
|
||||
<ConfigPage
|
||||
qqList={qqList}
|
||||
selectedUin={selectedUin}
|
||||
config={config}
|
||||
saveStatus={saveStatus}
|
||||
onSelectAccount={setSelectedUin}
|
||||
onSave={handleSaveConfig}
|
||||
onConfigChange={setConfig}
|
||||
/>
|
||||
)}
|
||||
{active === 'logs' && <LogsPage fetchApi={fetchApi} />}
|
||||
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
|
||||
</MainLayout>
|
||||
)}
|
||||
<>
|
||||
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
|
||||
{active === 'overview' && (
|
||||
<OverviewPage
|
||||
qqList={qqList}
|
||||
status={status}
|
||||
processList={processList}
|
||||
processLoadingPid={processLoadingPid}
|
||||
processUnloadingPid={processUnloadingPid}
|
||||
processRefreshingPid={processRefreshingPid}
|
||||
processActionStatus={processActionStatus}
|
||||
systemInfo={systemInfo}
|
||||
onRefreshProcesses={refreshProcesses}
|
||||
onRefreshSystem={refreshSystem}
|
||||
onLoadProcess={handleLoadProcess}
|
||||
onUnloadProcess={handleUnloadProcess}
|
||||
onRefreshProcess={handleRefreshProcess}
|
||||
/>
|
||||
)}
|
||||
{active === 'config' && <ConfigPage qqList={qqList} />}
|
||||
{active === 'logs' && <LogsPage />}
|
||||
{active === 'settings' && <SettingsPage onLogout={handleLogout} />}
|
||||
</MainLayout>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!unloadFailedAlert}
|
||||
@@ -416,6 +289,6 @@ function AppInner() {
|
||||
confirmText="知道了"
|
||||
onConfirm={() => setUnloadFailedAlert(null)}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -19,15 +19,10 @@ import type {
|
||||
QQInfo,
|
||||
WsRole,
|
||||
} from '@/types';
|
||||
import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config';
|
||||
|
||||
interface ConfigPageProps {
|
||||
qqList: QQInfo[];
|
||||
selectedUin: string | null;
|
||||
config: OneBotConfig | null;
|
||||
saveStatus: string;
|
||||
onSelectAccount: (uin: string) => void;
|
||||
onSave: () => Promise<void> | void;
|
||||
onConfigChange: (config: OneBotConfig) => void;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
@@ -98,18 +93,25 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfigPage({
|
||||
qqList,
|
||||
selectedUin,
|
||||
config,
|
||||
saveStatus,
|
||||
onSelectAccount,
|
||||
onSave,
|
||||
onConfigChange,
|
||||
}: ConfigPageProps) {
|
||||
export function ConfigPage({ qqList }: ConfigPageProps) {
|
||||
const {
|
||||
selectedUin,
|
||||
config,
|
||||
setConfig,
|
||||
dirty,
|
||||
requestSwitchUin,
|
||||
pendingSwitchUin,
|
||||
confirmSwitch,
|
||||
cancelSwitch,
|
||||
save,
|
||||
saveStatus,
|
||||
} = useOneBotInstanceConfig(qqList);
|
||||
const [confirmSave, setConfirmSave] = useState(false);
|
||||
|
||||
const update = (next: OneBotConfig) => onConfigChange(next);
|
||||
const update = (next: OneBotConfig) => setConfig(next);
|
||||
const pendingSwitchAccount = pendingSwitchUin
|
||||
? qqList.find((q) => q.uin === pendingSwitchUin) ?? null
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
|
||||
@@ -132,7 +134,7 @@ export function ConfigPage({
|
||||
type="button"
|
||||
whileHover={{ scale: 1.01 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={() => onSelectAccount(q.uin)}
|
||||
onClick={() => requestSwitchUin(q.uin)}
|
||||
className={cn(
|
||||
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
|
||||
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
|
||||
@@ -193,7 +195,12 @@ export function ConfigPage({
|
||||
{saveStatus}
|
||||
</span>
|
||||
)}
|
||||
<Button onClick={() => setConfirmSave(true)} size="sm">
|
||||
{dirty && !saveStatus && (
|
||||
<span className="rounded-full border border-warning/30 bg-warning/10 px-2.5 py-1 text-[11px] font-medium text-warning">
|
||||
未保存
|
||||
</span>
|
||||
)}
|
||||
<Button onClick={() => setConfirmSave(true)} size="sm" disabled={!dirty}>
|
||||
<Save className="size-3.5" /> 保存设定
|
||||
</Button>
|
||||
</div>
|
||||
@@ -421,7 +428,27 @@ export function ConfigPage({
|
||||
title="保存配置变更?"
|
||||
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
|
||||
confirmText="保存"
|
||||
onConfirm={onSave}
|
||||
onConfirm={save}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingSwitchUin != null}
|
||||
onOpenChange={(open) => !open && cancelSwitch()}
|
||||
title="放弃未保存的修改?"
|
||||
description={
|
||||
<>
|
||||
<p>
|
||||
当前会话 <code className="font-mono">{selectedUin}</code> 还有未保存的修改。
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
切换到 <code className="font-mono">{pendingSwitchAccount?.uin ?? pendingSwitchUin}</code>
|
||||
{pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。
|
||||
</p>
|
||||
</>
|
||||
}
|
||||
confirmText="放弃并切换"
|
||||
destructive
|
||||
onConfirm={confirmSwitch}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { LogEntry } from '@/types';
|
||||
|
||||
interface LogsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
const levelClass: Record<LogEntry['level'], string> = {
|
||||
debug: 'text-muted-foreground',
|
||||
@@ -24,7 +21,8 @@ const levelClass: Record<LogEntry['level'], string> = {
|
||||
|
||||
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
export function LogsPage() {
|
||||
const api = useApi();
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||
const [paused, setPaused] = useState(false);
|
||||
@@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
const endRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
|
||||
|
||||
async function loadLogs() {
|
||||
const res = await fetchApi('/api/logs?limit=500');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setLogs(data.list || []);
|
||||
}
|
||||
const loadLogs = useCallback(async () => {
|
||||
try {
|
||||
setLogs(await api.logs.list(500));
|
||||
} catch (e) {
|
||||
console.error('logs', e);
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs().catch(console.error);
|
||||
}, []);
|
||||
void loadLogs();
|
||||
}, [loadLogs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => setStreamStatus('实时');
|
||||
source.onerror = () => setStreamStatus('重连中');
|
||||
source.onmessage = (event) => {
|
||||
try {
|
||||
const entry = JSON.parse(event.data) as LogEntry | { type: string };
|
||||
if ('type' in entry) return;
|
||||
return api.logs.stream({
|
||||
onLine: (entry) => {
|
||||
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
return () => source.close();
|
||||
}, [token]);
|
||||
},
|
||||
onStatus: (s) => {
|
||||
if (s === 'open') setStreamStatus('实时');
|
||||
else if (s === 'reconnecting') setStreamStatus('重连中');
|
||||
else setStreamStatus('已断开');
|
||||
},
|
||||
});
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (paused) return;
|
||||
@@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
|
||||
{paused ? '继续' : '暂停'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => loadLogs().catch(console.error)}>
|
||||
<Button variant="outline" size="sm" onClick={() => void loadLogs()}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
<Button
|
||||
|
||||
@@ -14,14 +14,11 @@ import {
|
||||
type Density,
|
||||
type ThemeMode,
|
||||
} from '@/contexts/ThemeContext';
|
||||
import {
|
||||
ChangePasswordPage,
|
||||
type PasswordRule,
|
||||
} from '@/components/pages/change-password-page';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
/** Called after successful logout (e.g. all-sessions invalidated). */
|
||||
onLogout: () => void;
|
||||
}
|
||||
@@ -37,7 +34,8 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
|
||||
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
|
||||
];
|
||||
|
||||
export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
|
||||
export function SettingsPage({ onLogout }: SettingsPageProps) {
|
||||
const api = useApi();
|
||||
const {
|
||||
mode, setMode,
|
||||
accent, setAccent,
|
||||
@@ -49,30 +47,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
const checkStrength = async (password: string) => {
|
||||
const res = await fetchApi('/api/auth/check-strength', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
|
||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
||||
};
|
||||
|
||||
const submitPwd = async (oldPassword: string, newPassword: string) => {
|
||||
const res = await fetchApi('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ oldPassword, newPassword }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
|
||||
return { success: !!data.success, message: data.message };
|
||||
};
|
||||
|
||||
if (showChangePwd) {
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced={false}
|
||||
checkStrength={checkStrength}
|
||||
submit={submitPwd}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
setShowChangePwd(false);
|
||||
setPwdSavedAt(Date.now());
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { OneBotConfig, QQInfo } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Per-UIN OneBotInstance configuration editor. Owns the full lifecycle:
|
||||
* selection, load, in-memory edit (with dirty tracking), save (with refetch),
|
||||
* and a "switch UIN while dirty" guard that surfaces a pending switch the
|
||||
* view can confirm or cancel.
|
||||
*/
|
||||
export interface UseOneBotInstanceConfig {
|
||||
selectedUin: string | null;
|
||||
/** Loaded config for the current UIN. Null while loading or before a selection. */
|
||||
config: OneBotConfig | null;
|
||||
setConfig: (next: OneBotConfig) => void;
|
||||
/** True if the in-memory config diverges from the last server-confirmed snapshot. */
|
||||
dirty: boolean;
|
||||
/**
|
||||
* Request a UIN switch. If currently dirty, the switch is parked as
|
||||
* `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it
|
||||
* applies immediately.
|
||||
*/
|
||||
requestSwitchUin: (uin: string) => void;
|
||||
/** Non-null while a switch is parked waiting for confirmation. */
|
||||
pendingSwitchUin: string | null;
|
||||
confirmSwitch: () => void;
|
||||
cancelSwitch: () => void;
|
||||
save: () => Promise<void>;
|
||||
saveStatus: string;
|
||||
}
|
||||
|
||||
const CLEAR_SAVE_STATUS_MS = 3000;
|
||||
|
||||
export function useOneBotInstanceConfig(accounts: QQInfo[]): UseOneBotInstanceConfig {
|
||||
const api = useApi();
|
||||
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||
const [config, setConfigState] = useState<OneBotConfig | null>(null);
|
||||
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
|
||||
const [saveStatus, setSaveStatus] = useState('');
|
||||
const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null);
|
||||
const clearTimerRef = useRef<number | null>(null);
|
||||
|
||||
// Auto-select first account when none is selected yet.
|
||||
useEffect(() => {
|
||||
if (!selectedUin && accounts.length > 0) setSelectedUin(accounts[0].uin);
|
||||
}, [accounts, selectedUin]);
|
||||
|
||||
// Load on UIN change. The api client already runs normalizeOneBotConfig.
|
||||
useEffect(() => {
|
||||
if (!selectedUin) {
|
||||
setConfigState(null);
|
||||
setSavedSnapshot(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const loaded = await api.config.get(selectedUin);
|
||||
if (cancelled) return;
|
||||
setConfigState(loaded);
|
||||
setSavedSnapshot(JSON.stringify(loaded));
|
||||
} catch (e) {
|
||||
console.error('load-config', e);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedUin, api]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const dirty = useMemo(() => {
|
||||
if (config == null || savedSnapshot == null) return false;
|
||||
return JSON.stringify(config) !== savedSnapshot;
|
||||
}, [config, savedSnapshot]);
|
||||
|
||||
const setConfig = useCallback((next: OneBotConfig) => setConfigState(next), []);
|
||||
|
||||
const requestSwitchUin = useCallback(
|
||||
(uin: string) => {
|
||||
if (uin === selectedUin) return;
|
||||
if (dirty) setPendingSwitchUin(uin);
|
||||
else setSelectedUin(uin);
|
||||
},
|
||||
[dirty, selectedUin],
|
||||
);
|
||||
|
||||
const confirmSwitch = useCallback(() => {
|
||||
if (pendingSwitchUin == null) return;
|
||||
setSelectedUin(pendingSwitchUin);
|
||||
setPendingSwitchUin(null);
|
||||
}, [pendingSwitchUin]);
|
||||
|
||||
const cancelSwitch = useCallback(() => setPendingSwitchUin(null), []);
|
||||
|
||||
const scheduleStatusClear = useCallback(() => {
|
||||
if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
|
||||
clearTimerRef.current = window.setTimeout(() => {
|
||||
setSaveStatus('');
|
||||
clearTimerRef.current = null;
|
||||
}, CLEAR_SAVE_STATUS_MS);
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!selectedUin || !config) return;
|
||||
setSaveStatus('保存中...');
|
||||
try {
|
||||
const serverView = await api.config.save(selectedUin, config);
|
||||
setConfigState(serverView);
|
||||
setSavedSnapshot(JSON.stringify(serverView));
|
||||
setSaveStatus('保存成功');
|
||||
} catch (e) {
|
||||
setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
} finally {
|
||||
scheduleStatusClear();
|
||||
}
|
||||
}, [api, selectedUin, config, scheduleStatusClear]);
|
||||
|
||||
return {
|
||||
selectedUin,
|
||||
config,
|
||||
setConfig,
|
||||
dirty,
|
||||
requestSwitchUin,
|
||||
pendingSwitchUin,
|
||||
confirmSwitch,
|
||||
cancelSwitch,
|
||||
save,
|
||||
saveStatus,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
ApiError,
|
||||
type ApiClient,
|
||||
type ChangePasswordResult,
|
||||
type CreateApiClientOptions,
|
||||
type LoginResult,
|
||||
type LogsStreamOptions,
|
||||
type ProcessActionResult,
|
||||
type TokenStore,
|
||||
} from './types';
|
||||
import { localStorageTokenStore } from './token-store';
|
||||
|
||||
const DEFAULT_TOKEN_KEY = 'snowluma_token';
|
||||
|
||||
interface ErrorPayload {
|
||||
message?: string;
|
||||
error?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response): Promise<T> {
|
||||
try {
|
||||
return (await res.json()) as T;
|
||||
} catch {
|
||||
return {} as T;
|
||||
}
|
||||
}
|
||||
|
||||
function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
|
||||
return payload.message || payload.error || fallback;
|
||||
}
|
||||
|
||||
class HttpApiClient implements ApiClient {
|
||||
private tokenStore: TokenStore;
|
||||
private currentToken: string | null;
|
||||
private onUnauthorized?: () => void;
|
||||
|
||||
// namespaced surfaces are bound up-front so callers can destructure
|
||||
readonly processes: ApiClient['processes'];
|
||||
readonly config: ApiClient['config'];
|
||||
readonly logs: ApiClient['logs'];
|
||||
|
||||
constructor(opts: CreateApiClientOptions = {}) {
|
||||
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
|
||||
this.currentToken = this.tokenStore.load();
|
||||
this.onUnauthorized = opts.onUnauthorized;
|
||||
|
||||
this.processes = {
|
||||
list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []),
|
||||
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
|
||||
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
|
||||
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`),
|
||||
};
|
||||
|
||||
this.config = {
|
||||
get: async (uin) => {
|
||||
const url = `/api/config/${encodeURIComponent(uin)}`;
|
||||
const data = await this.getJson<{ config?: unknown } | unknown>(url);
|
||||
const raw =
|
||||
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
|
||||
? (data as { config: unknown }).config
|
||||
: data;
|
||||
return normalizeOneBotConfig(raw);
|
||||
},
|
||||
save: async (uin, config) => {
|
||||
const url = `/api/config/${encodeURIComponent(uin)}`;
|
||||
const data = await this.fetchJson<{ config?: unknown } | unknown>(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
const raw =
|
||||
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
|
||||
? (data as { config: unknown }).config
|
||||
: data;
|
||||
return normalizeOneBotConfig(raw);
|
||||
},
|
||||
};
|
||||
|
||||
this.logs = {
|
||||
list: async (limit = 500) => {
|
||||
const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`);
|
||||
return data.list ?? [];
|
||||
},
|
||||
stream: (options) => this.openLogStream(options),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- HTTP helpers ----------
|
||||
|
||||
async request(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const headers: Record<string, string> = {
|
||||
...((init.headers as Record<string, string> | undefined) ?? {}),
|
||||
};
|
||||
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
|
||||
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
if (res.status === 401) {
|
||||
this.setToken(null);
|
||||
this.onUnauthorized?.();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Like request(), but throws ApiError on non-2xx and parses JSON. */
|
||||
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const res = await this.request(url, init);
|
||||
if (!res.ok) {
|
||||
const payload = await readJson<ErrorPayload>(res);
|
||||
throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code);
|
||||
}
|
||||
return readJson<T>(res);
|
||||
}
|
||||
|
||||
private getJson<T>(url: string): Promise<T> {
|
||||
return this.fetchJson<T>(url);
|
||||
}
|
||||
|
||||
private postJson<T>(url: string, body?: unknown): Promise<T> {
|
||||
return this.fetchJson<T>(url, {
|
||||
method: 'POST',
|
||||
body: body == null ? undefined : JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- token management ----------
|
||||
|
||||
private setToken(token: string | null): void {
|
||||
this.currentToken = token;
|
||||
this.tokenStore.save(token);
|
||||
}
|
||||
|
||||
// ---------- auth ----------
|
||||
|
||||
async login(password: string): Promise<LoginResult> {
|
||||
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
|
||||
// doesn't trigger a global sign-out side effect.
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const payload = await readJson<ErrorPayload>(res);
|
||||
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
|
||||
}
|
||||
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
|
||||
this.setToken(payload.token);
|
||||
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
|
||||
} catch (e) {
|
||||
return { ok: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await this.request('/api/logout', { method: 'POST' });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
this.setToken(null);
|
||||
}
|
||||
|
||||
async status(): Promise<boolean> {
|
||||
if (!this.currentToken) return false;
|
||||
try {
|
||||
const res = await this.request('/api/status');
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async mustChangePassword(): Promise<boolean> {
|
||||
try {
|
||||
const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state');
|
||||
return !!data.mustChangePassword;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
|
||||
try {
|
||||
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
|
||||
'/api/auth/check-strength',
|
||||
{ password },
|
||||
);
|
||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
||||
} catch {
|
||||
return { rules: [], valid: false };
|
||||
}
|
||||
}
|
||||
|
||||
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
|
||||
try {
|
||||
const data = await this.postJson<{ success?: boolean; message?: string }>(
|
||||
'/api/auth/change-password',
|
||||
{ oldPassword, newPassword },
|
||||
);
|
||||
return { success: !!data.success, message: data.message };
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError) return { success: false, message: e.message };
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- top-level resources ----------
|
||||
|
||||
async qqList(): Promise<QQInfo[]> {
|
||||
const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list');
|
||||
return data.list ?? [];
|
||||
}
|
||||
|
||||
system(): Promise<SystemInfo> {
|
||||
return this.getJson<SystemInfo>('/api/system');
|
||||
}
|
||||
|
||||
// ---------- SSE ----------
|
||||
|
||||
private openLogStream(options: LogsStreamOptions): () => void {
|
||||
if (!this.currentToken) {
|
||||
options.onStatus?.('closed');
|
||||
return () => {};
|
||||
}
|
||||
const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => options.onStatus?.('open');
|
||||
source.onerror = () => options.onStatus?.('reconnecting');
|
||||
source.onmessage = (event) => {
|
||||
try {
|
||||
const parsed = JSON.parse(event.data) as LogEntry | { type: string };
|
||||
if ('type' in parsed) return; // control frame, not a log line
|
||||
options.onLine(parsed);
|
||||
} catch {
|
||||
/* malformed frame, skip */
|
||||
}
|
||||
};
|
||||
return () => {
|
||||
source.close();
|
||||
options.onStatus?.('closed');
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
|
||||
return new HttpApiClient(options);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import type { ApiClient } from './types';
|
||||
|
||||
const ApiContext = createContext<ApiClient | null>(null);
|
||||
|
||||
export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) {
|
||||
return <ApiContext.Provider value={client}>{children}</ApiContext.Provider>;
|
||||
}
|
||||
|
||||
export function useApi(): ApiClient {
|
||||
const client = useContext(ApiContext);
|
||||
if (!client) throw new Error('useApi must be used inside <ApiProvider>');
|
||||
return client;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export { createApiClient } from './client';
|
||||
export { ApiProvider, useApi } from './context';
|
||||
export { ApiError } from './types';
|
||||
export type {
|
||||
ApiClient,
|
||||
ChangePasswordResult,
|
||||
CreateApiClientOptions,
|
||||
LoginResult,
|
||||
LogsStreamOptions,
|
||||
ProcessActionResult,
|
||||
StreamStatus,
|
||||
TokenStore,
|
||||
} from './types';
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { TokenStore } from './types';
|
||||
|
||||
export function localStorageTokenStore(key: string): TokenStore {
|
||||
return {
|
||||
load: () => localStorage.getItem(key),
|
||||
save: (token) => {
|
||||
if (token == null) localStorage.removeItem(key);
|
||||
else localStorage.setItem(key, token);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
} from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string | undefined;
|
||||
constructor(status: number, message: string, code?: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export type LoginResult =
|
||||
| { ok: true; mustChangePassword: boolean }
|
||||
| { ok: false; message: string };
|
||||
|
||||
export type ChangePasswordResult = { success: boolean; message?: string };
|
||||
|
||||
export type ProcessActionResult = {
|
||||
process?: HookProcessInfo & { error?: string };
|
||||
};
|
||||
|
||||
export type StreamStatus = 'open' | 'reconnecting' | 'closed';
|
||||
|
||||
export interface LogsStreamOptions {
|
||||
onLine: (line: LogEntry) => void;
|
||||
onStatus?: (status: StreamStatus) => void;
|
||||
}
|
||||
|
||||
export interface ApiClient {
|
||||
// ---- auth ----
|
||||
login(password: string): Promise<LoginResult>;
|
||||
logout(): Promise<void>;
|
||||
/** True if the current token is still valid. */
|
||||
status(): Promise<boolean>;
|
||||
/** Whether the current session must rotate its password before doing anything else. */
|
||||
mustChangePassword(): Promise<boolean>;
|
||||
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
|
||||
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
|
||||
// ---- hook processes ----
|
||||
processes: {
|
||||
list(): Promise<HookProcessInfo[]>;
|
||||
load(pid: number): Promise<ProcessActionResult>;
|
||||
unload(pid: number): Promise<ProcessActionResult>;
|
||||
refresh(pid: number): Promise<ProcessActionResult>;
|
||||
};
|
||||
|
||||
// ---- OneBotInstance per-UIN config ----
|
||||
config: {
|
||||
get(uin: string): Promise<OneBotConfig>;
|
||||
save(uin: string, config: OneBotConfig): Promise<OneBotConfig>;
|
||||
};
|
||||
|
||||
// ---- logs ----
|
||||
logs: {
|
||||
list(limit?: number): Promise<LogEntry[]>;
|
||||
/** Subscribe to the SSE log stream. Returns a disposer. */
|
||||
stream(options: LogsStreamOptions): () => void;
|
||||
};
|
||||
|
||||
/** Escape hatch for endpoints not yet wrapped above. */
|
||||
request(url: string, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
export interface TokenStore {
|
||||
load(): string | null;
|
||||
save(token: string | null): void;
|
||||
}
|
||||
|
||||
export interface CreateApiClientOptions {
|
||||
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
|
||||
tokenStore?: TokenStore;
|
||||
/** Fires whenever a request returns 401, after the token has been cleared. */
|
||||
onUnauthorized?: () => void;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { MessageFormat, OneBotConfig } from '@/types';
|
||||
|
||||
/**
|
||||
* Anti-corruption layer for the per-UIN config payload. Older backends emit
|
||||
* `messageFormat` / `reportSelfMessage` at the top level instead of per
|
||||
* adapter, and may omit them on adapters entirely. This collapses both shapes
|
||||
* into the canonical {@link OneBotConfig} the editor expects.
|
||||
*/
|
||||
export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
|
||||
const cfg = (raw ?? {}) as Record<string, unknown>;
|
||||
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
|
||||
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!cfg.reportSelfMessage;
|
||||
|
||||
const normalize = (item: Record<string, unknown>): Record<string, unknown> => ({
|
||||
...item,
|
||||
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||
reportSelfMessage:
|
||||
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||
});
|
||||
|
||||
const list = (x: unknown): Record<string, unknown>[] =>
|
||||
Array.isArray(x) ? x.map((it) => normalize(it as Record<string, unknown>)) : [];
|
||||
|
||||
return {
|
||||
networks: {
|
||||
httpServers: list(nets.httpServers) as unknown as OneBotConfig['networks']['httpServers'],
|
||||
httpClients: list(nets.httpClients) as unknown as OneBotConfig['networks']['httpClients'],
|
||||
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
|
||||
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
|
||||
},
|
||||
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user