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 { downloaders } from "~/api/instances.ts"; 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select.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 (
{result ? ( result.ok ? ( {result.userData ? ( {[result.userData.username, result.userData.userLevel].filter(Boolean).join(" · ")} · 上传{" "} {bytes(result.userData.upload)} · 分享率 {ratioText(result.userData)} ) : ( {result.message ?? "没有取到用户数据"} )} ) : ( ) ) : null} {health ? ( {healthLine(health, health.checkedAt).text} {!health.ok && health.message ? {health.message} : null} ) : null}
); } function FailureRow({ result, onUseCookie }: { result: SiteLoginResult; onUseCookie?: () => void }) { const f = loginFailureText(result.reason, result.message); return ( {f.text} {f.suggestCookie || result.decisionId ? ( {f.suggestCookie && onUseCookie ? ( ) : null} {result.decisionId ? ( ) : null} ) : null} ); } function ResultRow({ ok, warn, title, children, }: { ok: boolean; warn?: boolean; title: string; children: React.ReactNode; }) { const Icon = ok ? CircleCheck : warn ? TriangleAlert : CircleX; return (

{title}

{children}
); } /** 更新凭证:保存后立即刷新登录,结果留在对话框里 */ 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>({}); const [result, setResult] = useState(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 ( !o && !busy && onClose()}> 更新凭证 · {site.name} {current ? `当前:${AUTH_KIND_LABEL[current.authKind]}。凭证加密保存,不回显;保存后立即刷新登录` : "凭证加密保存,不回显;保存后立即刷新登录"}
{result && !result.ok ? ( { setDraft(emptyCredential("cookie")); setResult(null); } : undefined } /> ) : null}
); } /** 编辑抽屉:名称、域名、限流(空 = 站点默认)、定时快照、代理 */ const DEFAULT_DOWNLOADER = "__default__"; export function SiteEditSheet({ site, onClose }: { site: SiteListItem; onClose: () => void }) { const update = useUpdateSite(); const dl = downloaders.useList(); 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, downloader: site.downloaderInstanceId ?? DEFAULT_DOWNLOADER, }); const [errors, setErrors] = useState>({}); const set = (k: K, val: (typeof v)[K]) => setV((s) => ({ ...s, [k]: val })); const busy = update.isPending; const save = async () => { const fe: Record = {}; 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, downloaderInstanceId: v.downloader === DEFAULT_DOWNLOADER ? null : v.downloader, }, }); toast.success(`${v.name.trim()} 已保存`); onClose(); } catch (err) { toast.error(errorMessage(err, "保存失败")); } }; return ( !o && !busy && onClose()} title={`编辑 · ${site.name}`} description="限流和抓取周期留空时用「设置 → 站点默认」" footer={ <> } >
set("name", e.target.value)} disabled={busy} /> set("baseUrl", e.target.value)} disabled={busy} />
set("rpm", e.target.value)} disabled={busy} /> set("concurrency", e.target.value)} disabled={busy} />
set("snapshotEnabled", x)} disabled={busy} />
{v.snapshotEnabled ? ( set("intervalMin", e.target.value)} disabled={busy} /> ) : null}
set("proxy", x)} disabled={busy} />
set("searchDefault", x)} disabled={busy} />

User-Agent 随凭证保存,在「更新凭证」里填写。

); } /** 删除站点确认:写明影响 */ export function DeleteSiteDialog({ site, onClose, onDeleted, }: { site: SiteListItem; onClose: () => void; onDeleted?: () => void; }) { const del = useDeleteSite(); return ( !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; } }} >
  • 站点、{site.accounts?.length ?? 0} 个账号和全部凭证都会删除
  • 已抓到的资源保留,标为「站点已关闭」,不再进入收录评估
  • 这个站点的 RSS 停用;已有下载任务继续
  • 同一站点以后可以重新添加
); } /** 页面级对话框出口 */ export function SiteDialogHost({ dialog, onClose, onDeleted, }: { dialog: SiteDialog | null; onClose: () => void; onDeleted?: () => void; }) { if (!dialog) return null; if (dialog.kind === "credentials") return ( ); if (dialog.kind === "edit") return ; return ( { onClose(); onDeleted?.(); }} /> ); }