import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { createColumnHelper } from "@tanstack/react-table"; import { AlertTriangle, Eye, Filter, Info, Pencil, Plus, RefreshCw, Search, Sparkles, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useForm } from "react-hook-form"; import { Link } from "react-router-dom"; import { z } from "zod"; import { Badge } from "../../components/ui/Badge"; import { Button } from "../../components/ui/Button"; import { Card } from "../../components/ui/Card"; import { DataTable } from "../../components/ui/DataTable"; import { Input } from "../../components/ui/Input"; import { OffsetPagination } from "../../components/ui/OffsetPagination"; import { Select } from "../../components/ui/Select"; import { Switch } from "../../components/ui/Switch"; import { Textarea } from "../../components/ui/Textarea"; import { ToastContainer } from "../../components/ui/Toast"; import { useToast } from "../../hooks/useToast"; import { useI18n } from "../../i18n"; import { formatApiErrorMessage } from "../../lib/error-message"; import { formatDateTime, formatGoDuration, formatRelativeTime } from "../../lib/time"; import { cleanupSubscriptionCircuitOpenNodes, createSubscription, deleteSubscription, listSubscriptions, refreshSubscription, updateSubscription, } from "./api"; import type { Subscription } from "./types"; type EnabledFilter = "all" | "enabled" | "disabled"; type SubscriptionSourceType = "remote" | "local"; const SUBSCRIPTION_SOURCE_TABS: Array<{ key: SubscriptionSourceType; label: string; hint: string }> = [ { key: "remote", label: "远程", hint: "从 HTTP/HTTPS 订阅链接拉取内容" }, { key: "local", label: "本地", hint: "直接填写订阅文本,不经过网络拉取" }, ]; const subscriptionCreateSchema = z.object({ name: z.string().trim().min(1, "订阅名称不能为空"), source_type: z.enum(["remote", "local"]), url: z.string(), content: z.string(), update_interval: z.string().trim().min(1, "更新间隔不能为空"), ephemeral_node_evict_delay: z.string().trim().min(1, "临时节点驱逐延迟不能为空"), enabled: z.boolean(), ephemeral: z.boolean(), incremental_alive_nodes: z.boolean(), }).superRefine((value, ctx) => { const url = value.url.trim(); const content = value.content.trim(); if (value.source_type === "remote") { if (!url) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["url"], message: "URL 不能为空" }); return; } if (!(url.startsWith("http://") || url.startsWith("https://"))) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["url"], message: "URL 必须是 http/https 地址" }); } return; } if (!content) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["content"], message: "订阅内容不能为空" }); } }); const subscriptionEditSchema = subscriptionCreateSchema; type SubscriptionCreateForm = z.infer; type SubscriptionEditForm = z.infer; const EMPTY_SUBSCRIPTIONS: Subscription[] = []; const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const; const LOCAL_SOURCE_UPDATE_INTERVAL = "12h"; const SUBSCRIPTION_DISABLE_HINT = "禁用订阅后,相关节点不会参与平台路由、健康统计或自动探测。"; const SUBSCRIPTION_EPHEMERAL_HINT = "临时订阅的非健康节点会在一段时间后被自动删除。订阅本身不会被删除。"; const SUBSCRIPTION_INCREMENTAL_HINT = "开启后刷新时保留当前仍存活的旧节点,仅清理失效旧节点,并合并新订阅内容;关闭后仅保留刷新后的订阅内容。"; function extractHostname(url: string): string { try { return new URL(url).hostname; } catch { return url; } } function subscriptionToEditForm(subscription: Subscription): SubscriptionEditForm { return { name: subscription.name, source_type: subscription.source_type, url: subscription.url, content: subscription.content ?? "", update_interval: subscription.update_interval, ephemeral_node_evict_delay: subscription.ephemeral_node_evict_delay, enabled: subscription.enabled, ephemeral: subscription.ephemeral, incremental_alive_nodes: subscription.incremental_alive_nodes, }; } function sourceTypeLabel(sourceType: SubscriptionSourceType): string { return sourceType === "local" ? "本地" : "远程"; } function parseEnabledFilter(value: EnabledFilter): boolean | undefined { if (value === "enabled") { return true; } if (value === "disabled") { return false; } return undefined; } function normalizeSubmitUpdateInterval(sourceType: SubscriptionSourceType, raw: string): string { if (sourceType === "local") { return LOCAL_SOURCE_UPDATE_INTERVAL; } return raw.trim(); } export function SubscriptionPage() { const { t } = useI18n(); const [enabledFilter, setEnabledFilter] = useState("all"); const [search, setSearch] = useState(""); const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState(20); const [selectedSubscriptionId, setSelectedSubscriptionId] = useState(""); const [drawerOpen, setDrawerOpen] = useState(false); const [createModalOpen, setCreateModalOpen] = useState(false); const [pendingRefreshIds, setPendingRefreshIds] = useState>(() => new Set()); const { toasts, showToast, dismissToast } = useToast(); const pendingRefreshIdsRef = useRef>(new Set()); const queryClient = useQueryClient(); const enabledValue = parseEnabledFilter(enabledFilter); const subscriptionContentPlaceholder = [ t("支持格式:"), t("sing-box / Clash|Mihomo / URI(vmess:// vless:// trojan:// ss:// ...)或他们的 base64 格式"), "", t("HTTP/HTTPS/SOCKS 示例:"), t("1.2.3.4:8080:user:pass (HTTP 认证代理)"), t("http://user:pass@1.2.3.4:8080(HTTP 认证代理)"), t("https://user:pass@example.com:8443?sni=example.com(HTTPS + SNI)"), t("socks5://user:pass@1.2.3.4:1080"), t("socks5h://user:pass@example.com:1080"), ].join("\n"); const subscriptionsQuery = useQuery({ queryKey: ["subscriptions", enabledFilter, page, pageSize, search], queryFn: () => listSubscriptions({ enabled: enabledValue, limit: pageSize, offset: page * pageSize, keyword: search, }), refetchInterval: 30_000, placeholderData: (prev) => prev, }); const subscriptions = subscriptionsQuery.data?.items ?? EMPTY_SUBSCRIPTIONS; const totalSubscriptions = subscriptionsQuery.data?.total ?? 0; const totalPages = Math.max(1, Math.ceil(totalSubscriptions / pageSize)); const currentPage = Math.min(page, totalPages - 1); const selectedSubscription = useMemo(() => { if (!selectedSubscriptionId) { return null; } return subscriptions.find((item) => item.id === selectedSubscriptionId) ?? null; }, [selectedSubscriptionId, subscriptions]); const drawerVisible = drawerOpen && Boolean(selectedSubscription); const createForm = useForm({ resolver: zodResolver(subscriptionCreateSchema), defaultValues: { name: "", source_type: "remote", url: "", content: "", update_interval: "12h", ephemeral_node_evict_delay: "72h", enabled: true, ephemeral: false, incremental_alive_nodes: false, }, }); const createEphemeral = createForm.watch("ephemeral"); const createSourceType = createForm.watch("source_type"); const editForm = useForm({ resolver: zodResolver(subscriptionEditSchema), defaultValues: { name: "", source_type: "remote", url: "", content: "", update_interval: "12h", ephemeral_node_evict_delay: "72h", enabled: true, ephemeral: false, incremental_alive_nodes: false, }, }); const editEphemeral = editForm.watch("ephemeral"); const editSourceType = editForm.watch("source_type"); useEffect(() => { if (!selectedSubscription) { return; } editForm.reset(subscriptionToEditForm(selectedSubscription)); }, [selectedSubscription, editForm]); useEffect(() => { if (!drawerVisible) { return; } const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape") { return; } setDrawerOpen(false); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [drawerVisible]); const invalidateSubscriptions = async () => { await queryClient.invalidateQueries({ queryKey: ["subscriptions"] }); }; const invalidateSubscriptionsAndNodes = async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["subscriptions"] }), queryClient.invalidateQueries({ queryKey: ["nodes"] }), ]); }; const createMutation = useMutation({ mutationFn: createSubscription, onSuccess: async (created) => { await invalidateSubscriptions(); setCreateModalOpen(false); createForm.reset({ name: "", source_type: "remote", url: "", content: "", update_interval: LOCAL_SOURCE_UPDATE_INTERVAL, ephemeral_node_evict_delay: "72h", enabled: true, ephemeral: false, incremental_alive_nodes: false, }); showToast("success", t("订阅 {{name}} 创建成功", { name: created.name })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const updateMutation = useMutation({ mutationFn: async (formData: SubscriptionEditForm) => { if (!selectedSubscription) { throw new Error("请选择要编辑的订阅"); } const payload = { name: formData.name.trim(), update_interval: normalizeSubmitUpdateInterval(formData.source_type, formData.update_interval), ephemeral_node_evict_delay: formData.ephemeral_node_evict_delay.trim(), enabled: formData.enabled, ephemeral: formData.ephemeral, incremental_alive_nodes: formData.incremental_alive_nodes, ...(formData.source_type === "remote" ? { url: formData.url.trim() } : { content: formData.content }), }; return updateSubscription(selectedSubscription.id, payload); }, onSuccess: async (updated) => { await invalidateSubscriptions(); setSelectedSubscriptionId(updated.id); showToast("success", t("订阅 {{name}} 已更新", { name: updated.name })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const deleteMutation = useMutation({ mutationFn: async (subscription: Subscription) => { await deleteSubscription(subscription.id); return subscription; }, onSuccess: async (deleted) => { await invalidateSubscriptions(); if (selectedSubscriptionId === deleted.id) { setSelectedSubscriptionId(""); setDrawerOpen(false); } showToast("success", t("订阅 {{name}} 已删除", { name: deleted.name })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const deleteSubscriptionMutateAsync = deleteMutation.mutateAsync; const isDeletePending = deleteMutation.isPending; const refreshMutation = useMutation({ mutationFn: async (subscription: Subscription) => { await refreshSubscription(subscription.id); return subscription; }, onSuccess: async (subscription) => { await invalidateSubscriptions(); showToast("success", t("订阅 {{name}} 已手动刷新", { name: subscription.name })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const refreshSubscriptionMutateAsync = refreshMutation.mutateAsync; const markRefreshPending = useCallback((subscriptionId: string): boolean => { if (pendingRefreshIdsRef.current.has(subscriptionId)) { return false; } const next = new Set(pendingRefreshIdsRef.current); next.add(subscriptionId); pendingRefreshIdsRef.current = next; setPendingRefreshIds(next); return true; }, []); const clearRefreshPending = useCallback((subscriptionId: string) => { if (!pendingRefreshIdsRef.current.has(subscriptionId)) { return; } const next = new Set(pendingRefreshIdsRef.current); next.delete(subscriptionId); pendingRefreshIdsRef.current = next; setPendingRefreshIds(next); }, []); const isRefreshPending = useCallback((subscriptionId: string): boolean => pendingRefreshIds.has(subscriptionId), [pendingRefreshIds]); const cleanupCircuitOpenNodesMutation = useMutation({ mutationFn: async (subscription: Subscription) => { const cleanedCount = await cleanupSubscriptionCircuitOpenNodes(subscription.id); return { subscription, cleanedCount }; }, onSuccess: async ({ subscription, cleanedCount }) => { await invalidateSubscriptionsAndNodes(); if (cleanedCount > 0) { showToast("success", t("订阅 {{name}} 已清理 {{count}} 个节点", { name: subscription.name, count: cleanedCount })); return; } showToast("success", t("订阅 {{name}} 没有可清理的熔断或异常节点", { name: subscription.name })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const onCreateSubmit = createForm.handleSubmit(async (values) => { const payload = { name: values.name.trim(), source_type: values.source_type, update_interval: normalizeSubmitUpdateInterval(values.source_type, values.update_interval), ephemeral_node_evict_delay: values.ephemeral_node_evict_delay.trim(), enabled: values.enabled, ephemeral: values.ephemeral, incremental_alive_nodes: values.incremental_alive_nodes, ...(values.source_type === "remote" ? { url: values.url.trim() } : { content: values.content }), }; await createMutation.mutateAsync(payload); }); const onEditSubmit = editForm.handleSubmit(async (values) => { await updateMutation.mutateAsync(values); }); const handleDelete = useCallback(async (subscription: Subscription) => { const confirmed = window.confirm(t("确认删除订阅 {{name}}?关联节点会被清理。", { name: subscription.name })); if (!confirmed) { return; } await deleteSubscriptionMutateAsync(subscription); }, [deleteSubscriptionMutateAsync, t]); const handleCleanupCircuitOpenNodes = async (subscription: Subscription) => { const confirmed = window.confirm(t("确认立即清理订阅 {{name}} 中的熔断或异常节点?", { name: subscription.name })); if (!confirmed) { return; } await cleanupCircuitOpenNodesMutation.mutateAsync(subscription); }; const openDrawer = useCallback((subscription: Subscription) => { setSelectedSubscriptionId(subscription.id); setDrawerOpen(true); }, []); const handleRefresh = useCallback(async (subscription: Subscription) => { if (!markRefreshPending(subscription.id)) { return; } try { await refreshSubscriptionMutateAsync(subscription); } catch { // Mutation callbacks already surface the failure to the user. } finally { clearRefreshPending(subscription.id); } }, [clearRefreshPending, markRefreshPending, refreshSubscriptionMutateAsync]); const changePageSize = (next: number) => { setPageSize(next); setPage(0); }; const col = useMemo(() => createColumnHelper(), []); const subColumns = useMemo( () => [ col.accessor("name", { header: t("名称"), cell: (info) =>

{info.getValue()}

, }), col.accessor("url", { header: t("订阅源"), cell: (info) => { const s = info.row.original; if (s.source_type === "local") { return (

{t("本地订阅")}

); } return (

{extractHostname(info.getValue())}

); }, }), col.accessor("update_interval", { header: t("更新间隔"), cell: (info) => formatGoDuration(info.getValue()), }), col.display({ id: "node_count", header: t("节点数"), cell: (info) => { const s = info.row.original; return `${s.healthy_node_count} / ${s.node_count}`; }, }), col.display({ id: "status", header: t("状态"), cell: (info) => { const s = info.row.original; return (
{!s.enabled ? ( {t("已禁用")} ) : s.last_error ? ( {t("错误")} ) : ( {t("正常")} )}
); }, }), col.accessor("last_checked", { header: t("上次检查"), cell: (info) => formatRelativeTime(info.getValue() || ""), }), col.accessor("last_updated", { header: t("上次更新"), cell: (info) => formatRelativeTime(info.getValue() || ""), }), col.display({ id: "actions", header: t("操作"), cell: (info) => { const s = info.row.original; return (
event.stopPropagation()}>
); }, }), ], [col, handleDelete, handleRefresh, isDeletePending, isRefreshPending, openDrawer, t] ); return (

{t("订阅管理")}

{t("保障订阅按计划更新,异常时可一键刷新。")}

{t("订阅列表")}

{t("共 {{count}} 个订阅", { count: totalSubscriptions })}

{subscriptionsQuery.isLoading ?

{t("正在加载订阅数据...")}

: null} {subscriptionsQuery.isError ? (
{formatApiErrorMessage(subscriptionsQuery.error, t)}
) : null} {!subscriptionsQuery.isLoading && !subscriptions.length ? (

{t("没有匹配的订阅")}

) : null} {subscriptions.length ? ( s.id} className="data-table-subs" /> ) : null}
{drawerVisible && selectedSubscription ? (
setDrawerOpen(false)} > event.stopPropagation()}>

{selectedSubscription.name}

{selectedSubscription.id}

{selectedSubscription.enabled ? t("运行中") : t("已停用")}

{t("订阅配置")}

{editSourceType === "local" ? t("更新本地订阅配置、刷新周期与状态开关后点击保存。") : t("更新 URL、刷新周期与状态开关后点击保存。")}

{t("创建时间")}

{formatDateTime(selectedSubscription.created_at)}

{t("上次检查")}

{formatDateTime(selectedSubscription.last_checked || "")}

{t("上次更新")}

{formatDateTime(selectedSubscription.last_updated || "")}

{selectedSubscription.last_error ? (
{t("最近错误:{{message}}", { message: selectedSubscription.last_error })}
) : (
{t("最近一次刷新无错误")}
)}
{editForm.formState.errors.name?.message ? (

{t(editForm.formState.errors.name.message)}

) : null}
{editSourceType === "remote" ? ( <>
{editForm.formState.errors.update_interval?.message ? (

{t(editForm.formState.errors.update_interval.message)}

) : null}
{editForm.formState.errors.url?.message ? (

{t(editForm.formState.errors.url.message)}

) : null}
) : (