feat(web): site center page, add-site wizard, credentials, health and user-data chart (FE-2)
- 资源 → 站点:卡片 / 列表切换(URL ?view= + localStorage 记住),筛选全部 / 已启用 / 需处理, 按分享率 / 上传 / 上次登录排序;卡片显示账号状态、凭证类型、上次登录、上传 / 下载 / 分享率、 等级 / VIP、做种、健康检测结果与时间、快照、限流 - 操作:检测健康、刷新登录(wait:true 同步结果)、更新凭证、编辑(限流 / 快照 / 代理)、启停、 删除(确认框列出影响) - 添加站点向导:按适配器分组选 23 个定义(未实测标注)→ 名称 / 域名覆盖 / 凭证三选一 (馒头默认 API Key)→ 保存并测试(刷新登录 + 健康检测);验证码 / 二次验证提示改用 Cookie 并链接待处理 - 站点详情:概览(用户数据磁贴 + 30 天上传 / 下载与分享率折线,recharts,无彩)/ 资源 / 快照与 Feed / 账号(凭证管理、Passkey、登录历史) - 设置"站点与账号"改为"站点默认"(限流、快照周期、UA、代理、做种页数) - 侧栏改名"站点";smoke 补站点路由;依赖新增 recharts Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
81bf010e3e
commit
f8362a3f4c
21 files changed
+3083
-1126
No files matched your search
@@ -0,0 +1,534 @@
|
||||
import type { SiteAccount, SiteHealthResult, SiteListItem, SiteLoginResult } from "@umt/contracts";
|
||||
import { CircleCheck, CircleX, KeyRound, LoaderCircle, TriangleAlert } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useDeleteSite,
|
||||
useHealthCheck,
|
||||
usePutCredentials,
|
||||
useRefreshLogin,
|
||||
useSiteDefinitions,
|
||||
useUpdateSite,
|
||||
} from "~/api/sites.ts";
|
||||
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
|
||||
import { DetailSheet } from "~/components/console/detail-sheet.tsx";
|
||||
import { FormField } from "~/components/console/form-field.tsx";
|
||||
import { consolePath } from "~/components/console/nav.ts";
|
||||
import { Button } from "~/components/ui/button.tsx";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog.tsx";
|
||||
import { Input } from "~/components/ui/input.tsx";
|
||||
import { Switch } from "~/components/ui/switch.tsx";
|
||||
import { errorMessage } from "~/lib/api.ts";
|
||||
import { cn } from "~/lib/utils.ts";
|
||||
import { CredentialFields, credentialBody, emptyCredential } from "./credential-fields.tsx";
|
||||
import {
|
||||
AUTH_KIND_LABEL,
|
||||
bytes,
|
||||
healthLine,
|
||||
type LoginKind,
|
||||
loginFailureText,
|
||||
primaryAccount,
|
||||
ratioText,
|
||||
supportedKinds,
|
||||
} from "./site-fields.ts";
|
||||
|
||||
// 站点页的对话框与动作:检测健康、刷新登录、更新凭证、编辑、删除(卡片、列表、详情页共用)
|
||||
|
||||
export type SiteDialog =
|
||||
| { kind: "credentials"; site: SiteListItem; account?: SiteAccount | null; loginKind?: LoginKind }
|
||||
| { kind: "edit"; site: SiteListItem }
|
||||
| { kind: "delete"; site: SiteListItem };
|
||||
|
||||
/** 检测健康 + 刷新登录,结果用 toast 说 */
|
||||
export function useSiteChecks(onDialog?: (d: SiteDialog) => void) {
|
||||
const health = useHealthCheck();
|
||||
const login = useRefreshLogin();
|
||||
const [busy, setBusy] = useState<{ id: string; what: "health" | "login" } | null>(null);
|
||||
|
||||
const checkHealth = async (site: SiteListItem) => {
|
||||
setBusy({ id: site.id, what: "health" });
|
||||
try {
|
||||
const r = await health.mutateAsync(site.id);
|
||||
const line = healthLine(r, r.checkedAt);
|
||||
if (r.ok) toast.success(`${site.name}:${line.text}`);
|
||||
else toast.warning(`${site.name}:${line.text}`, { description: r.message ?? undefined });
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e, "检测失败"));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshLogin = async (site: SiteListItem, account?: SiteAccount | null) => {
|
||||
setBusy({ id: site.id, what: "login" });
|
||||
try {
|
||||
const r = await login.mutateAsync({ id: site.id, accountId: account?.id });
|
||||
const res = r.result;
|
||||
if (!res) toast.success("刷新登录已排队");
|
||||
else notifyLogin(site, res, account ?? primaryAccount(site.accounts), onDialog);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e, "刷新登录失败"));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
checkHealth,
|
||||
refreshLogin,
|
||||
isBusy: (id: string, what: "health" | "login") => busy?.id === id && busy.what === what,
|
||||
};
|
||||
}
|
||||
|
||||
function notifyLogin(
|
||||
site: SiteListItem,
|
||||
res: SiteLoginResult,
|
||||
account: SiteAccount | null,
|
||||
onDialog?: (d: SiteDialog) => void,
|
||||
) {
|
||||
if (res.ok) {
|
||||
const u = res.userData;
|
||||
toast.success(`${site.name} 已登录`, {
|
||||
description: u ? [u.username, u.userLevel, `分享率 ${ratioText(u)}`].filter(Boolean).join(" · ") : undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const f = loginFailureText(res.reason, res.message, account?.authKind);
|
||||
toast.error(`${site.name}:${f.text}`, {
|
||||
duration: 10_000,
|
||||
action:
|
||||
f.suggestCookie && onDialog
|
||||
? { label: "改用 Cookie", onClick: () => onDialog({ kind: "credentials", site, account, loginKind: "cookie" }) }
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/** 登录结果块(向导第 ③ 步、凭证对话框保存后) */
|
||||
export function LoginResultView({
|
||||
result,
|
||||
health,
|
||||
onUseCookie,
|
||||
}: {
|
||||
result: SiteLoginResult | null;
|
||||
health?: SiteHealthResult | null;
|
||||
onUseCookie?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{result ? (
|
||||
result.ok ? (
|
||||
<ResultRow ok title="登录成功">
|
||||
{result.userData ? (
|
||||
<span>
|
||||
{[result.userData.username, result.userData.userLevel].filter(Boolean).join(" · ")}
|
||||
{result.userData.vip ? " · VIP" : ""} · 上传 {bytes(result.userData.upload)} · 分享率{" "}
|
||||
{ratioText(result.userData)}
|
||||
</span>
|
||||
) : (
|
||||
<span>{result.message ?? "没有取到用户数据"}</span>
|
||||
)}
|
||||
</ResultRow>
|
||||
) : (
|
||||
<FailureRow result={result} onUseCookie={onUseCookie} />
|
||||
)
|
||||
) : null}
|
||||
{health ? (
|
||||
<ResultRow ok={health.ok} warn={!health.ok} title="健康检测">
|
||||
<span className="block">{healthLine(health, health.checkedAt).text}</span>
|
||||
{!health.ok && health.message ? <span className="block">{health.message}</span> : null}
|
||||
</ResultRow>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FailureRow({ result, onUseCookie }: { result: SiteLoginResult; onUseCookie?: () => void }) {
|
||||
const f = loginFailureText(result.reason, result.message);
|
||||
return (
|
||||
<ResultRow ok={false} title="登录失败">
|
||||
<span className="block">{f.text}</span>
|
||||
{f.suggestCookie || result.decisionId ? (
|
||||
<span className="mt-1.5 flex flex-wrap gap-2">
|
||||
{f.suggestCookie && onUseCookie ? (
|
||||
<Button type="button" size="xs" variant="outline" onClick={onUseCookie}>
|
||||
<KeyRound />
|
||||
改用 Cookie
|
||||
</Button>
|
||||
) : null}
|
||||
{result.decisionId ? (
|
||||
<Button asChild size="xs" variant="ghost">
|
||||
<Link to={consolePath("inbox")}>查看待处理</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
</ResultRow>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultRow({
|
||||
ok,
|
||||
warn,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
ok: boolean;
|
||||
warn?: boolean;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const Icon = ok ? CircleCheck : warn ? TriangleAlert : CircleX;
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-start gap-2 rounded-lg border px-3 py-2 text-caption",
|
||||
ok
|
||||
? "border-success/30 bg-success/10"
|
||||
: warn
|
||||
? "border-warning/40 bg-warning/10"
|
||||
: "border-destructive/30 bg-destructive/10",
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
className={cn("mt-0.5 h-4 w-4 shrink-0", ok ? "text-success" : warn ? "text-warning" : "text-destructive")}
|
||||
/>
|
||||
<div className="min-w-0 break-words">
|
||||
<p className="font-medium text-foreground">{title}</p>
|
||||
<div className="text-muted-foreground">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 更新凭证:保存后立即刷新登录,结果留在对话框里 */
|
||||
export function CredentialDialog({
|
||||
site,
|
||||
account,
|
||||
loginKind,
|
||||
onClose,
|
||||
}: {
|
||||
site: SiteListItem;
|
||||
account?: SiteAccount | null;
|
||||
loginKind?: LoginKind;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const defs = useSiteDefinitions();
|
||||
const def = defs.data?.items.find((d) => d.siteId === site.id || d.key === site.key);
|
||||
const kinds = supportedKinds(def ?? { adapter: site.adapter, authSupported: [] });
|
||||
const current = account ?? primaryAccount(site.accounts);
|
||||
const initialKind: LoginKind =
|
||||
loginKind ??
|
||||
(current && current.authKind !== "passkey" && kinds.includes(current.authKind as LoginKind)
|
||||
? (current.authKind as LoginKind)
|
||||
: (kinds[0] ?? "cookie"));
|
||||
const [draft, setDraft] = useState(() => emptyCredential(initialKind));
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [result, setResult] = useState<SiteLoginResult | null>(null);
|
||||
const put = usePutCredentials();
|
||||
const login = useRefreshLogin();
|
||||
const busy = put.isPending || login.isPending;
|
||||
const shownKinds = kinds.includes(draft.kind) ? kinds : [...kinds, draft.kind];
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const b = credentialBody(draft, current?.label ?? site.key);
|
||||
if (!b.body) {
|
||||
setErrors(b.errors);
|
||||
return;
|
||||
}
|
||||
setErrors({});
|
||||
setResult(null);
|
||||
try {
|
||||
const saved = await put.mutateAsync({ siteId: site.id, body: b.body });
|
||||
const r = await login.mutateAsync({ id: site.id, accountId: saved.siteAccountId });
|
||||
if (r.result) {
|
||||
setResult(r.result);
|
||||
if (r.result.ok) {
|
||||
toast.success(`${site.name} 凭证已更新并登录`);
|
||||
onClose();
|
||||
}
|
||||
} else {
|
||||
toast.success("凭证已保存,刷新登录已排队");
|
||||
onClose();
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "保存失败"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(o) => !o && !busy && onClose()}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>更新凭证 · {site.name}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{current
|
||||
? `当前:${AUTH_KIND_LABEL[current.authKind]}。凭证加密保存,不回显;保存后立即刷新登录`
|
||||
: "凭证加密保存,不回显;保存后立即刷新登录"}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form id="site-cred" onSubmit={submit} noValidate>
|
||||
<CredentialFields
|
||||
value={draft}
|
||||
onChange={setDraft}
|
||||
kinds={shownKinds}
|
||||
errors={errors}
|
||||
disabled={busy}
|
||||
idPrefix="upd"
|
||||
/>
|
||||
</form>
|
||||
{result && !result.ok ? (
|
||||
<LoginResultView
|
||||
result={result}
|
||||
onUseCookie={
|
||||
draft.kind !== "cookie"
|
||||
? () => {
|
||||
setDraft(emptyCredential("cookie"));
|
||||
setResult(null);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={busy}>
|
||||
{result ? "关闭" : "取消"}
|
||||
</Button>
|
||||
<Button type="submit" form="site-cred" disabled={busy}>
|
||||
{busy ? <LoaderCircle className="animate-spin" /> : null}
|
||||
{busy ? (login.isPending ? "登录中…" : "保存中…") : "保存并登录"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** 编辑抽屉:名称、域名、限流(空 = 站点默认)、定时快照、代理 */
|
||||
export function SiteEditSheet({ site, onClose }: { site: SiteListItem; onClose: () => void }) {
|
||||
const update = useUpdateSite();
|
||||
const [v, setV] = useState({
|
||||
name: site.name,
|
||||
baseUrl: site.baseUrl,
|
||||
rpm: site.rateLimit.requestsPerMinute ? String(site.rateLimit.requestsPerMinute) : "",
|
||||
concurrency: site.rateLimit.concurrency ? String(site.rateLimit.concurrency) : "",
|
||||
snapshotEnabled: site.snapshotEnabled,
|
||||
intervalMin: site.snapshotIntervalSec ? String(Math.round(site.snapshotIntervalSec / 60)) : "",
|
||||
proxy: site.proxy,
|
||||
});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const set = <K extends keyof typeof v>(k: K, val: (typeof v)[K]) => setV((s) => ({ ...s, [k]: val }));
|
||||
const busy = update.isPending;
|
||||
|
||||
const save = async () => {
|
||||
const fe: Record<string, string> = {};
|
||||
if (!v.name.trim()) fe.name = "填写名称";
|
||||
try {
|
||||
new URL(v.baseUrl.trim());
|
||||
} catch {
|
||||
fe.baseUrl = "填完整地址,如 https://example.org";
|
||||
}
|
||||
const posInt = (s: string, k: string, min = 1) => {
|
||||
if (!s.trim()) return undefined;
|
||||
const n = Number(s);
|
||||
if (!Number.isInteger(n) || n < min) fe[k] = `填不小于 ${min} 的整数,留空用站点默认`;
|
||||
return n;
|
||||
};
|
||||
const rpm = posInt(v.rpm, "rpm");
|
||||
const concurrency = posInt(v.concurrency, "concurrency");
|
||||
const interval = posInt(v.intervalMin, "intervalMin", 5);
|
||||
if (Object.keys(fe).length) {
|
||||
setErrors(fe);
|
||||
return;
|
||||
}
|
||||
setErrors({});
|
||||
const rateLimit = {
|
||||
...(rpm ? { requestsPerMinute: rpm } : {}),
|
||||
...(concurrency ? { concurrency } : {}),
|
||||
};
|
||||
try {
|
||||
await update.mutateAsync({
|
||||
id: site.id,
|
||||
body: {
|
||||
name: v.name.trim(),
|
||||
baseUrl: v.baseUrl.trim(),
|
||||
rateLimit,
|
||||
snapshotEnabled: v.snapshotEnabled,
|
||||
snapshotIntervalSec: interval ? interval * 60 : null,
|
||||
proxy: v.proxy,
|
||||
},
|
||||
});
|
||||
toast.success(`${v.name.trim()} 已保存`);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "保存失败"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DetailSheet
|
||||
open
|
||||
onOpenChange={(o) => !o && !busy && onClose()}
|
||||
title={`编辑 · ${site.name}`}
|
||||
description="限流和快照周期留空时用「设置 → 站点默认」"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={onClose} disabled={busy}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={() => void save()} disabled={busy}>
|
||||
{busy ? <LoaderCircle className="animate-spin" /> : null}
|
||||
保存
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-x-4 gap-y-1">
|
||||
<FormField label="名称" htmlFor="se-name" required error={errors.name}>
|
||||
<Input id="se-name" value={v.name} onChange={(e) => set("name", e.target.value)} disabled={busy} />
|
||||
</FormField>
|
||||
<FormField label="地址" htmlFor="se-url" required error={errors.baseUrl} hint="站点换域名时改这里">
|
||||
<Input
|
||||
id="se-url"
|
||||
inputMode="url"
|
||||
value={v.baseUrl}
|
||||
onChange={(e) => set("baseUrl", e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="grid gap-x-4 sm:grid-cols-2">
|
||||
<FormField label="每分钟请求数" htmlFor="se-rpm" error={errors.rpm} hint="留空用站点默认">
|
||||
<Input
|
||||
id="se-rpm"
|
||||
inputMode="numeric"
|
||||
value={v.rpm}
|
||||
onChange={(e) => set("rpm", e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="并发" htmlFor="se-conc" error={errors.concurrency} hint="留空用站点默认">
|
||||
<Input
|
||||
id="se-conc"
|
||||
inputMode="numeric"
|
||||
value={v.concurrency}
|
||||
onChange={(e) => set("concurrency", e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<Switch
|
||||
id="se-snap"
|
||||
checked={v.snapshotEnabled}
|
||||
onCheckedChange={(x) => set("snapshotEnabled", x)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label htmlFor="se-snap" className="text-caption text-foreground">
|
||||
定时抓取快照
|
||||
</label>
|
||||
</div>
|
||||
{v.snapshotEnabled ? (
|
||||
<FormField label="快照周期(分钟)" htmlFor="se-int" error={errors.intervalMin} hint="留空用站点默认">
|
||||
<Input
|
||||
id="se-int"
|
||||
inputMode="numeric"
|
||||
value={v.intervalMin}
|
||||
onChange={(e) => set("intervalMin", e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
<div className="mb-2 flex items-start gap-3">
|
||||
<Switch id="se-proxy" checked={v.proxy} onCheckedChange={(x) => set("proxy", x)} disabled={busy} />
|
||||
<label htmlFor="se-proxy" className="text-caption">
|
||||
<span className="block font-medium text-foreground">使用代理</span>
|
||||
<span className="block text-muted-foreground">走「站点默认」里的代理地址;没填代理地址时不生效</span>
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-meta text-muted-foreground">User-Agent 随凭证保存,在"更新凭证"里填写。</p>
|
||||
</div>
|
||||
</DetailSheet>
|
||||
);
|
||||
}
|
||||
|
||||
/** 删除站点确认:写明影响 */
|
||||
export function DeleteSiteDialog({
|
||||
site,
|
||||
onClose,
|
||||
onDeleted,
|
||||
}: {
|
||||
site: SiteListItem;
|
||||
onClose: () => void;
|
||||
onDeleted?: () => void;
|
||||
}) {
|
||||
const del = useDeleteSite();
|
||||
return (
|
||||
<ConfirmDialog
|
||||
open
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`删除站点「${site.name}」?`}
|
||||
description="不可恢复。"
|
||||
confirmLabel="删除站点"
|
||||
destructive
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await del.mutateAsync(site.id);
|
||||
toast.success(`已删除 ${site.name}`);
|
||||
onDeleted?.();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "删除失败"));
|
||||
throw err;
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ul className="list-disc space-y-1 pl-5 text-caption text-muted-foreground">
|
||||
<li>站点、{site.accounts?.length ?? 0} 个账号和全部凭证删除</li>
|
||||
<li>已抓到的资源保留,标为"站点已关闭",不再产生新候选</li>
|
||||
<li>该站 Feed 停用;已有下载任务按原策略继续</li>
|
||||
<li>同一站点以后可以重新添加</li>
|
||||
</ul>
|
||||
</ConfirmDialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** 页面级对话框出口 */
|
||||
export function SiteDialogHost({
|
||||
dialog,
|
||||
onClose,
|
||||
onDeleted,
|
||||
}: {
|
||||
dialog: SiteDialog | null;
|
||||
onClose: () => void;
|
||||
onDeleted?: () => void;
|
||||
}) {
|
||||
if (!dialog) return null;
|
||||
if (dialog.kind === "credentials")
|
||||
return (
|
||||
<CredentialDialog
|
||||
key={`${dialog.site.id}-${dialog.loginKind ?? ""}`}
|
||||
site={dialog.site}
|
||||
account={dialog.account}
|
||||
loginKind={dialog.loginKind}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
if (dialog.kind === "edit") return <SiteEditSheet key={dialog.site.id} site={dialog.site} onClose={onClose} />;
|
||||
return (
|
||||
<DeleteSiteDialog
|
||||
site={dialog.site}
|
||||
onClose={onClose}
|
||||
onDeleted={() => {
|
||||
onClose();
|
||||
onDeleted?.();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user