Files
UHD_Media_Tool/apps/web/app/components/sites/site-dialogs.tsx
T
rootandClaude Opus 5.5 fa344a7184 feat(web): token 数以 K 输入显示,已存凭证显示掩码占位(FIX-8)
- 新增 UnitInput 与 kind=tokens:上下文预算、单次 token 上限、自定义模型上下文窗口以 K 输入(允许小数),存储仍为原始 token 数;校验与提示用 K 表述;列表/详情 token 数统一 K/M 简写(formatTokens)
- 新增 SecretInput 与 kind=secret:已保存时显示「已设置 ••••••••」(有服务端掩码时带末 4 位),聚焦直接输入替换,留空保持,「清除」确认后保存生效;替换模型服务、TMDB、网页搜索、下载器、媒体服务器、浏览器服务、站点账号、Passkey、本机 Token 各处
- 统一只写凭证服务端语义:省略或空串 = 不变,null = 清除(contracts secretInput);下载器/媒体服务器新增清除;站点凭证同类更新可留空保持密码/Cookie/API Key/TOTP,TOTP 可 null 清除,不再误删 TOTP 与 UA
- contextBudget 最小值 4096→4000、contextWindow 1024→1000,便于按 K 填写
- 测试:换算与校验、SecretInput 渲染与状态、各接口留空不变/显式清除

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 00:10:46 +08:00

562 lines
19 KiB
TypeScript

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,
draftFromAccount,
emptyCredential,
type SavedCredential,
} 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(() => draftFromAccount(initialKind, current));
const saved: SavedCredential | null =
current && current.authKind !== "passkey" && current.secretRef
? { kind: current.authKind as LoginKind, hasTotp: current.hasTotp }
: null;
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, saved);
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"
saved={saved}
/>
</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,
searchDefault: site.searchDefault !== false,
});
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,
searchDefault: v.searchDefault,
},
});
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>
<div className="mb-2 flex items-start gap-3">
<Switch
id="se-search"
checked={v.searchDefault}
onCheckedChange={(x) => set("searchDefault", x)}
disabled={busy}
/>
<label htmlFor="se-search" 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>该站 RSS 停用;已有下载任务按原策略继续</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?.();
}}
/>
);
}