"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Activity, Bell, BarChart3, ExternalLink, Eye, Globe2, Loader2, MousePointerClick, Radar, RefreshCw, Server, ShieldCheck, Users, Wifi, } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useToast } from "@/components/Toast"; import { fetchJson, fmtTs } from "@/lib/api"; import { useAutoRefresh, useNow, type RefreshOpts } from "@/lib/realtime"; type Probe = { ok?: boolean | null; status?: number | null; ms?: number | null; error?: string; }; type SiteRow = { domain: string; role: string; kind: string; ips: string[]; dns_ok: boolean; expected_ip: string; umami_website_id?: string; health: Probe; }; type ServiceRow = { unit: string; label: string; state: string; ok: boolean; }; type OverviewSite = { domain: string; role: string; website_id: string; ok: boolean; active: number; pageviews: number; visitors: number; visits: number; bounces: number; }; type AnalyticsDetail = { domain?: string; website_id?: string; range?: string; ok?: boolean; active?: number; stats?: { pageviews?: number; visitors?: number; visits?: number; bounces?: number; bounce_rate?: number; avg_visit_sec?: number; }; series?: { x: string; y: number }[]; top_paths?: { name: string; value: number }[]; top_referrers?: { name: string; value: number }[]; top_countries?: { name: string; value: number }[]; top_devices?: { name: string; value: number }[]; top_browsers?: { name: string; value: number }[]; umami_url?: string; }; type OpsSnapshot = { generated_at?: number; server_ip?: string; host?: string; umami?: { url?: string; user?: string; script?: string; sites?: Record; heartbeat?: Probe; }; ntfy?: { configured?: boolean; base_url?: string; topic?: string; user?: string; has_token?: boolean; token_suffix?: string; health?: Probe; }; sites?: SiteRow[]; services?: ServiceRow[]; paths?: Record; }; const RANGES = [ { id: "24h", label: "24小时" }, { id: "7d", label: "7天" }, { id: "30d", label: "30天" }, { id: "90d", label: "90天" }, ]; function StatusDot({ ok }: { ok?: boolean | null }) { const color = ok === true ? "bg-teal-400 shadow-[0_0_10px_rgba(45,212,191,0.55)]" : ok === false ? "bg-rose-400" : "bg-slate-500"; return ; } function ProbeText({ p }: { p?: Probe }) { if (!p) return —; if (p.ok === true) return {p.status ?? "ok"} · {p.ms ?? "?"}ms; if (p.ok === false) return ( {p.status ?? "fail"} {p.error ? `· ${p.error}` : ""} {p.ms != null ? `· ${p.ms}ms` : ""} ); return n/a; } function fmtNum(n?: number) { const v = Number(n || 0); if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`; if (v >= 1_000) return `${(v / 1_000).toFixed(1)}k`; return String(v); } function fmtDuration(sec?: number) { const s = Math.max(0, Math.round(Number(sec || 0))); if (s < 60) return `${s}s`; const m = Math.floor(s / 60); const r = s % 60; return `${m}m ${r}s`; } function Sparkline({ series }: { series?: { x: string; y: number }[] }) { const pts = series || []; if (pts.length < 2) { return
暂无趋势数据(站点刚接入时常见)
; } const ys = pts.map((p) => Number(p.y || 0)); const max = Math.max(...ys, 1); const min = Math.min(...ys, 0); const w = 320; const h = 64; const path = pts .map((p, i) => { const x = (i / (pts.length - 1)) * w; const y = h - ((Number(p.y || 0) - min) / (max - min || 1)) * (h - 4) - 2; return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`; }) .join(" "); return ( ); } function MetricList({ title, rows }: { title: string; rows?: { name: string; value: number }[] }) { const list = rows || []; const max = Math.max(...list.map((r) => Number(r.value || 0)), 1); return (
{title}
{!list.length &&
暂无数据
}
    {list.map((r) => (
  • {r.name || "(direct)"} {fmtNum(r.value)}
  • ))}
); } export default function OpsPage() { const toast = useToast(); const now = useNow(1000); const [tab, setTab] = useState<"analytics" | "monitor">("analytics"); const [data, setData] = useState(null); const [overview, setOverview] = useState([]); const [detail, setDetail] = useState(null); const [domain, setDomain] = useState("dylive.nomadro.com"); const [range, setRange] = useState("7d"); const [loading, setLoading] = useState(true); const [syncing, setSyncing] = useState(false); const [live, setLive] = useState(true); const [lastOkAt, setLastOkAt] = useState(0); const [lastErr, setLastErr] = useState(""); const [busy, setBusy] = useState(""); const [title, setTitle] = useState("DouyinWEB 测试"); const [message, setMessage] = useState("来自 /ops 控制台的 ntfy 测试消息"); const [priority, setPriority] = useState("default"); const [pageVisible, setPageVisible] = useState(true); const inFlight = useRef(false); const domainRef = useRef(domain); const rangeRef = useRef(range); const tabRef = useRef(tab); domainRef.current = domain; rangeRef.current = range; tabRef.current = tab; useEffect(() => { const onVis = () => setPageVisible(document.visibilityState === "visible"); onVis(); document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, []); const loadSilent = useCallback(async (opts?: RefreshOpts) => { const silent = Boolean(opts?.silent); if (inFlight.current) return; inFlight.current = true; if (!silent) setLoading(true); else setSyncing(true); try { const tasks: Promise[] = []; // Always keep analytics fresh on analytics tab; monitor on monitor tab; // still refresh both lightly so switching tabs feels live. tasks.push( (async () => { const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}`); setOverview(ov?.sites || []); const d = await fetchJson( `/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}` ); setDetail(d); })() ); tasks.push( (async () => { const r = await fetchJson("/api/ops"); setData(r); })() ); await Promise.all(tasks); setLastOkAt(Date.now()); setLastErr(""); setLive(true); } catch (e) { setLive(false); setLastErr((e as Error).message || "同步失败"); if (!silent) toast.push((e as Error).message, "err"); } finally { inFlight.current = false; setLoading(false); setSyncing(false); } }, [toast]); // Poll server continuously while page is visible (no manual refresh required). useAutoRefresh(loadSilent, { intervalMs: tab === "analytics" ? 10000 : 12000, eventKinds: false, enabled: pageVisible, }); // When domain/range/tab changes, pull immediately (silent). useEffect(() => { if (!pageVisible) return; void loadSilent({ silent: true }); }, [domain, range, tab, pageVisible, loadSilent]); const dnsOkCount = useMemo(() => (data?.sites || []).filter((s) => s.dns_ok).length, [data]); const svcOkCount = useMemo(() => (data?.services || []).filter((s) => s.ok).length, [data]); const trackedDomains = useMemo( () => (data?.sites || []).filter((s) => s.kind !== "infra" && s.umami_website_id).map((s) => s.domain), [data] ); const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null; async function sendNtfy() { setBusy("ntfy"); try { await fetchJson("/api/ops/ntfy", { method: "POST", body: JSON.stringify({ title, message, priority, tags: "bell,desktop" }), }); toast.push("已发送到 ntfy", "ok"); } catch (e) { toast.push((e as Error).message, "err"); } finally { setBusy(""); } } async function runHealth() { setBusy("health"); try { const r = await fetchJson("/api/ops/healthcheck", { method: "POST" }); toast.push(r?.ok ? "健康检查已执行" : `健康检查结束 code=${r?.returncode}`, r?.ok ? "ok" : "err"); await loadSilent({ silent: true }); } catch (e) { toast.push((e as Error).message, "err"); } finally { setBusy(""); } } const st = detail?.stats; return (
Analytics + Ops

访问数据与运维

页面打开时自动与服务器同步(访问数据约 10s、监控约 12s),无需手动刷新。切换标签页离开时暂停轮询。

{pageVisible ? (live ? "实时同步中" : "同步异常") : "已暂停(标签页不可见)"} {syncing ? "拉取中…" : agoSec == null ? "等待首次同步" : `上次更新 ${agoSec}s 前`} {lastErr ? {lastErr} : null}
打开 Umami 完整后台
{tab === "analytics" && ( <>
各站点概览
{RANGES.map((r) => ( ))}
{overview.map((s) => ( ))} {!overview.length && (
{loading ? "加载访问数据…" : "暂无概览(确认 Umami 已采集到流量)"}
)}
站点详情 · {domain}
类似 GA 的摘要指标与排行
{[ { label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye }, { label: "独立访客", value: fmtNum(st?.visitors), icon: Users }, { label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick }, { label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity }, { label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar }, ].map((card) => (
{card.label}
{card.value}
))}
浏览量趋势 当前在线 {detail?.active ?? 0}
)} {tab === "monitor" && ( <>
Umami
ntfy
topic {data?.ntfy?.topic}
DNS / 服务
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
域名 · DNS · 探测
{(data?.sites || []).map((s) => ( ))}
域名 DNS 健康 Umami ID
{s.domain}
{s.role}
{(s.ips || []).join(", ") || "—"}
{s.umami_website_id || "—"}
systemd 服务
{(data?.services || []).map((s) => (
{s.label}
{s.unit}
{s.state}
))}
发送 ntfy
setTitle(e.target.value)} className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none" placeholder="标题" />