feat(ops): show Umami visit analytics on /ops like GA overview

Keep monitor/DNS/ntfy as a separate tab; analytics is read-only via Umami API.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 23:58:40 -05:00
parent d57a0e2acb
commit d8bf5658e6
3 changed files with 639 additions and 239 deletions

View File

@ -2437,6 +2437,40 @@ async def ops_snapshot() -> dict[str, Any]:
return await asyncio.to_thread(ops_panel.snapshot)
@app.get("/api/ops/analytics")
async def ops_analytics(
domain: str = Query(""),
range: str = Query("7d"), # noqa: A002 — API query name
) -> dict[str, Any]:
"""GA-like Umami visit stats for the ops web UI (read-only)."""
from . import ops_panel
range_key = (range or "7d").strip().lower()
if range_key not in {"24h", "7d", "30d", "90d"}:
raise HTTPException(400, "range 支持 24h/7d/30d/90d")
domain = (domain or "").strip().lower()
try:
if not domain:
return await asyncio.to_thread(ops_panel.analytics_overview, range_key)
umami = ops_panel.umami_config()
wid = ""
for s in ops_panel.SITES:
if s["domain"] == domain and s.get("umami_key"):
wid = umami["sites"].get(s["umami_key"], "")
break
if not wid:
raise HTTPException(404, f"未找到站点 {domain} 的 Umami website id")
data = await asyncio.to_thread(ops_panel.website_analytics, wid, range_key)
data["domain"] = domain
return data
except HTTPException:
raise
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except Exception as exc:
raise HTTPException(500, f"读取分析失败: {exc}") from exc
@app.post("/api/ops/ntfy")
async def ops_ntfy_send(body: dict[str, Any]) -> dict[str, Any]:
from . import ops_panel

View File

@ -187,6 +187,189 @@ def umami_config() -> dict[str, Any]:
}
def _umami_request(
method: str,
path: str,
token: str | None = None,
data: dict[str, Any] | None = None,
query: dict[str, Any] | None = None,
timeout: float = 20.0,
) -> tuple[int, Any]:
base = umami_config()["url"].rstrip("/")
qs = ""
if query:
from urllib.parse import urlencode
qs = "?" + urlencode({k: v for k, v in query.items() if v is not None})
url = f"{base}{path}{qs}"
body = None if data is None else json.dumps(data).encode("utf-8")
headers = {"Accept": "application/json", "Content-Type": "application/json", "User-Agent": "DouyinWEB-Ops/1.0"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = Request(url, data=body, headers=headers, method=method)
try:
with urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", "replace")
return resp.status, (json.loads(raw) if raw else {})
except HTTPError as e:
raw = e.read().decode("utf-8", "replace")
try:
parsed: Any = json.loads(raw) if raw else {}
except json.JSONDecodeError:
parsed = {"raw": raw}
return e.code, parsed
def umami_login() -> str:
env = _read_env_file(UMAMI_ENV)
user = env.get("UMAMI_USER", "admin")
password = env.get("UMAMI_PASSWORD", "")
if not password:
raise ValueError("Umami 未配置密码(/etc/nomadro/umami.env)")
code, data = _umami_request("POST", "/api/auth/login", data={"username": user, "password": password})
if code != 200 or not isinstance(data, dict) or not data.get("token"):
raise ValueError(f"Umami 登录失败: HTTP {code} {data}")
return str(data["token"])
def _range_ms(range_key: str) -> tuple[int, int, str]:
end = int(time.time() * 1000)
key = (range_key or "7d").lower()
days = {"24h": 1, "7d": 7, "30d": 30, "90d": 90}.get(key, 7)
start = end - days * 24 * 60 * 60 * 1000
unit = "hour" if days <= 2 else "day"
return start, end, unit
def _metric_list(payload: Any, limit: int = 8) -> list[dict[str, Any]]:
rows = payload if isinstance(payload, list) else []
out = []
for row in rows[:limit]:
if not isinstance(row, dict):
continue
out.append({"name": row.get("x") or row.get("name") or "", "value": row.get("y") or row.get("visitors") or 0})
return out
def website_analytics(website_id: str, range_key: str = "7d") -> dict[str, Any]:
"""GA-like summary for one Umami website (stats + top metrics + series)."""
token = umami_login()
start, end, unit = _range_ms(range_key)
q = {"startAt": start, "endAt": end}
code_stats, stats = _umami_request("GET", f"/api/websites/{website_id}/stats", token=token, query=q)
code_active, active = _umami_request("GET", f"/api/websites/{website_id}/active", token=token)
code_pv, pageviews = _umami_request(
"GET",
f"/api/websites/{website_id}/pageviews",
token=token,
query={**q, "unit": unit, "timezone": "Asia/Shanghai"},
)
code_path, paths = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "path", "limit": 10}
)
code_ref, refs = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "referrer", "limit": 8}
)
code_country, countries = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "country", "limit": 8}
)
code_device, devices = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "device", "limit": 6}
)
code_browser, browsers = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "browser", "limit": 6}
)
stats_obj = stats if isinstance(stats, dict) else {}
pageviews_n = int(stats_obj.get("pageviews") or 0)
visitors_n = int(stats_obj.get("visitors") or 0)
visits_n = int(stats_obj.get("visits") or 0)
bounces_n = int(stats_obj.get("bounces") or 0)
totaltime = int(stats_obj.get("totaltime") or 0)
bounce_rate = round((bounces_n / visits_n) * 100, 1) if visits_n else 0.0
avg_visit_sec = round(totaltime / visits_n, 1) if visits_n else 0.0
series = []
if isinstance(pageviews, dict):
series = pageviews.get("pageviews") or []
return {
"website_id": website_id,
"range": range_key,
"start_at": start,
"end_at": end,
"ok": code_stats == 200,
"errors": {
"stats": None if code_stats == 200 else stats,
"active": None if code_active == 200 else active,
"pageviews": None if code_pv == 200 else pageviews,
"path": None if code_path == 200 else paths,
},
"active": int((active or {}).get("visitors") or 0) if isinstance(active, dict) else 0,
"stats": {
"pageviews": pageviews_n,
"visitors": visitors_n,
"visits": visits_n,
"bounces": bounces_n,
"bounce_rate": bounce_rate,
"avg_visit_sec": avg_visit_sec,
"totaltime": totaltime,
},
"series": series if isinstance(series, list) else [],
"top_paths": _metric_list(paths),
"top_referrers": _metric_list(refs),
"top_countries": _metric_list(countries),
"top_devices": _metric_list(devices),
"top_browsers": _metric_list(browsers),
"umami_url": umami_config()["url"],
}
def analytics_overview(range_key: str = "7d") -> dict[str, Any]:
"""Per-site overview cards for all tracked content/app domains."""
umami = umami_config()
token = None
try:
token = umami_login()
except ValueError as e:
return {"ok": False, "error": str(e), "range": range_key, "sites": []}
start, end, _unit = _range_ms(range_key)
rows = []
for s in SITES:
if s.get("kind") == "infra" or not s.get("umami_key"):
continue
wid = umami["sites"].get(s["umami_key"], "")
if not wid:
continue
code, stats = _umami_request(
"GET", f"/api/websites/{wid}/stats", token=token, query={"startAt": start, "endAt": end}
)
code_a, active = _umami_request("GET", f"/api/websites/{wid}/active", token=token)
stats_obj = stats if isinstance(stats, dict) and code == 200 else {}
rows.append(
{
"domain": s["domain"],
"role": s["role"],
"website_id": wid,
"ok": code == 200,
"active": int((active or {}).get("visitors") or 0) if isinstance(active, dict) and code_a == 200 else 0,
"pageviews": int(stats_obj.get("pageviews") or 0),
"visitors": int(stats_obj.get("visitors") or 0),
"visits": int(stats_obj.get("visits") or 0),
"bounces": int(stats_obj.get("bounces") or 0),
}
)
return {
"ok": True,
"range": range_key,
"start_at": start,
"end_at": end,
"sites": rows,
"umami_url": umami["url"],
}
def send_ntfy(title: str, message: str, priority: str = "default", tags: str = "bell", topic: str | None = None) -> dict[str, Any]:
cfg = ntfy_config()
env = _read_env_file(NTFY_ENV)

View File

@ -4,13 +4,17 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import {
Activity,
Bell,
BarChart3,
ExternalLink,
Eye,
Globe2,
Loader2,
MousePointerClick,
Radar,
RefreshCw,
Server,
ShieldCheck,
Users,
} from "lucide-react";
import { Shell } from "@/components/Shell";
@ -42,6 +46,41 @@ type ServiceRow = {
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;
@ -67,6 +106,13 @@ type OpsSnapshot = {
paths?: Record<string, string>;
};
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";
@ -85,33 +131,118 @@ function ProbeText({ p }: { p?: Probe }) {
return <span className="text-slate-500">n/a</span>;
}
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 <div className="flex h-16 items-center text-xs text-slate-500">暂无趋势数据(站点刚接入时常见)</div>;
}
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 (
<svg viewBox={`0 0 ${w} ${h}`} className="h-16 w-full overflow-visible">
<path d={path} fill="none" stroke="rgba(45,212,191,0.9)" strokeWidth="2" />
</svg>
);
}
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 (
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-2 text-xs font-medium text-slate-300">{title}</div>
{!list.length && <div className="text-xs text-slate-500">暂无数据</div>}
<ul className="space-y-2">
{list.map((r) => (
<li key={`${title}-${r.name}`}>
<div className="mb-0.5 flex justify-between gap-2 text-[11px]">
<span className="truncate text-slate-200">{r.name || "(direct)"}</span>
<span className="shrink-0 text-slate-400">{fmtNum(r.value)}</span>
</div>
<div className="h-1 overflow-hidden rounded bg-white/5">
<div className="h-full rounded bg-gradient-to-r from-teal-400/80 to-sky-400/70" style={{ width: `${(Number(r.value) / max) * 100}%` }} />
</div>
</li>
))}
</ul>
</div>
);
}
export default function OpsPage() {
const toast = useToast();
const [tab, setTab] = useState<"analytics" | "monitor">("analytics");
const [data, setData] = useState<OpsSnapshot | null>(null);
const [overview, setOverview] = useState<OverviewSite[]>([]);
const [detail, setDetail] = useState<AnalyticsDetail | null>(null);
const [domain, setDomain] = useState("dylive.nomadro.com");
const [range, setRange] = useState("7d");
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState("");
const [title, setTitle] = useState("DouyinWEB 测试");
const [message, setMessage] = useState("来自 /ops 控制台的 ntfy 测试消息");
const [priority, setPriority] = useState("default");
const load = useCallback(async () => {
const loadMonitor = useCallback(async () => {
const r = await fetchJson("/api/ops");
setData(r);
}, []);
const loadAnalytics = useCallback(async () => {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(range)}`);
setOverview(ov?.sites || []);
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(range)}&domain=${encodeURIComponent(domain)}`
);
setDetail(d);
}, [domain, range]);
const loadAll = useCallback(async () => {
setLoading(true);
try {
const r = await fetchJson("/api/ops");
setData(r);
await Promise.all([loadMonitor(), loadAnalytics()]);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setLoading(false);
}
}, [toast]);
}, [loadAnalytics, loadMonitor, toast]);
useEffect(() => {
void load();
}, [load]);
void loadAll();
}, [loadAll]);
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]
);
async function sendNtfy() {
setBusy("ntfy");
@ -133,7 +264,7 @@ export default function OpsPage() {
try {
const r = await fetchJson("/api/ops/healthcheck", { method: "POST" });
toast.push(r?.ok ? "健康检查已执行" : `健康检查结束 code=${r?.returncode}`, r?.ok ? "ok" : "err");
await load();
await loadMonitor();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
@ -141,279 +272,331 @@ export default function OpsPage() {
}
}
const st = detail?.stats;
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-5 pb-8">
<div className="rounded-3xl border border-white/10 bg-black/30 p-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Infrastructure</div>
<h1 className="font-display text-2xl font-semibold text-white">站点运维台</h1>
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Analytics + Ops</div>
<h1 className="font-display text-2xl font-semibold text-white">访问数据与运维</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
Umami 分析、ntfy 通知、DNS 解析与核心服务状态。数据来自本机探测与{" "}
<code className="text-slate-300">/etc/nomadro/*</code>。
Umami 提供类似 Google Analytics 的 PV / 访客 / 来源 / 设备统计(偏隐私、无广告画像)。下方可切换「访问数据」与「监控」。
</p>
<div className="mt-2 flex flex-wrap gap-3 text-xs text-slate-400">
<span>主机 {data?.host || "—"}</span>
<span>期望 IP {data?.server_ip || "—"}</span>
<span>{data?.generated_at ? fmtTs(data.generated_at) : ""}</span>
</div>
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={!!busy}
onClick={() => void load()}
disabled={!!busy || loading}
onClick={() => void loadAll()}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-200"
>
<RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
刷新
</button>
<button
type="button"
disabled={!!busy}
onClick={() => void runHealth()}
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-2 text-xs font-semibold text-[#0b1220]"
>
{busy === "health" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Activity className="h-3.5 w-3.5" />}
跑健康检查
</button>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-3">
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.umami?.heartbeat?.ok} />
<ProbeText p={data?.umami?.heartbeat} />
</div>
<a
href={data?.umami?.url || "https://umami.nomadro.com"}
target="_blank"
rel="noreferrer"
className="mt-2 inline-flex items-center gap-1 text-xs text-sky-300 hover:underline"
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-2 text-xs font-semibold text-[#0b1220]"
>
打开分析台 <ExternalLink className="h-3 w-3" />
打开 Umami 完整后台 <ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.ntfy?.health?.ok} />
<ProbeText p={data?.ntfy?.health} />
</div>
<div className="mt-1 text-[11px] text-slate-500">
topic {data?.ntfy?.topic || "—"} · token …{data?.ntfy?.token_suffix || ""}
</div>
<a
href={data?.ntfy?.base_url || "https://ntfy.nomadro.com"}
target="_blank"
rel="noreferrer"
className="mt-2 inline-flex items-center gap-1 text-xs text-sky-300 hover:underline"
>
打开 ntfy <ExternalLink className="h-3 w-3" />
</a>
</div>
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
</div>
<div className="mt-1 text-sm text-white">
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
</div>
<div className="mt-1 text-[11px] text-slate-500">期望 A 记录 → {data?.server_ip}</div>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => setTab("analytics")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "analytics" ? "bg-teal-400/20 text-teal-200 ring-1 ring-teal-300/30" : "bg-white/5 text-slate-400"}`}
>
<BarChart3 className="mr-1 inline h-3.5 w-3.5" />
访问数据
</button>
<button
type="button"
onClick={() => setTab("monitor")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "monitor" ? "bg-amber-400/20 text-amber-100 ring-1 ring-amber-300/30" : "bg-white/5 text-slate-400"}`}
>
<ShieldCheck className="mr-1 inline h-3.5 w-3.5" />
监控 / DNS / ntfy
</button>
</div>
</div>
<div className="grid gap-5 lg:grid-cols-5">
<div className="space-y-5 lg:col-span-3">
{tab === "analytics" && (
<>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Globe2 className="h-4 w-4 text-sky-300" />
域名 · DNS · Umami · 探测
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="text-sm font-medium text-white">各站点概览</div>
<div className="flex flex-wrap gap-1.5">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => setRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"}`}
>
{r.label}
</button>
))}
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left text-xs">
<thead className="text-slate-500">
<tr className="border-b border-white/10">
<th className="py-2 pr-2 font-medium">域名</th>
<th className="py-2 pr-2 font-medium">DNS</th>
<th className="py-2 pr-2 font-medium">健康</th>
<th className="py-2 font-medium">Umami ID</th>
</tr>
</thead>
<tbody>
{(data?.sites || []).map((s) => (
<tr key={s.domain} className="border-b border-white/5 align-top">
<td className="py-2.5 pr-2">
<a
href={`https://${s.domain}`}
target="_blank"
rel="noreferrer"
className="font-medium text-sky-200 hover:underline"
>
{s.domain}
</a>
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
</td>
<td className="py-2.5 pr-2">
<div className="flex items-center gap-1.5">
<StatusDot ok={s.dns_ok} />
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
{(s.ips || []).join(", ") || "—"}
</span>
</div>
</td>
<td className="py-2.5 pr-2">
<ProbeText p={s.health} />
</td>
<td className="py-2.5 font-mono text-[10px] text-slate-400">
{s.umami_website_id || "—"}
</td>
</tr>
))}
{!data?.sites?.length && (
<tr>
<td colSpan={4} className="py-6 text-center text-slate-500">
{loading ? "加载中…" : "暂无数据"}
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-amber-300" />
systemd 服务
</div>
<div className="grid gap-2 sm:grid-cols-2">
{(data?.services || []).map((s) => (
<div
key={s.unit}
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{overview.map((s) => (
<button
key={s.domain}
type="button"
onClick={() => setDomain(s.domain)}
className={`rounded-2xl border p-3 text-left transition ${
domain === s.domain ? "border-teal-300/40 bg-teal-400/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.05]"
}`}
>
<div>
<div className="text-sm text-slate-100">{s.label}</div>
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{s.domain}</div>
<span className="text-[10px] text-teal-300">在线 {s.active}</span>
</div>
<div className="flex items-center gap-2 text-xs">
<StatusDot ok={s.ok} />
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
<div className="mt-0.5 truncate text-[11px] text-slate-500">{s.role}</div>
<div className="mt-3 grid grid-cols-3 gap-2 text-center">
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.pageviews)}</div>
<div className="text-[10px] text-slate-500">浏览量</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visitors)}</div>
<div className="text-[10px] text-slate-500">访客</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visits)}</div>
<div className="text-[10px] text-slate-500">访问</div>
</div>
</div>
</div>
</button>
))}
</div>
</section>
</div>
<div className="space-y-5 lg:col-span-2">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Bell className="h-4 w-4 text-amber-300" />
发送 ntfy
</div>
<div className="space-y-2">
<label className="block text-[11px] text-slate-500">标题</label>
<input
value={title}
onChange={(e) => 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 focus:border-teal-400/40"
/>
<label className="block text-[11px] text-slate-500">内容</label>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none focus:border-teal-400/40"
/>
<label className="block text-[11px] text-slate-500">优先级</label>
<select
value={priority}
onChange={(e) => setPriority(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"
>
<option value="min">min</option>
<option value="low">low</option>
<option value="default">default</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
<button
type="button"
disabled={!!busy || !data?.ntfy?.configured}
onClick={() => void sendNtfy()}
className="mt-1 inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
>
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
推送到 {data?.ntfy?.topic || "server-alerts"}
</button>
{!data?.ntfy?.configured && (
<p className="text-[11px] text-rose-300">服务器尚未配置 ntfy token(/etc/nomadro/ntfy.env)</p>
{!overview.length && (
<div className="col-span-full py-8 text-center text-sm text-slate-500">
{loading ? "加载访问数据…" : "暂无概览(确认 Umami 已采集到流量)"}
</div>
)}
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-2 text-sm font-medium text-white">快速链接 / 路径</div>
<ul className="space-y-1.5 text-xs text-slate-400">
<li>
Umami 脚本:<code className="text-slate-300">{data?.umami?.script}</code>
</li>
<li>
配置:
<code className="text-slate-300"> {data?.paths?.umami_env}</code>
</li>
<li>
站点 ID:
<code className="text-slate-300"> {data?.paths?.umami_sites}</code>
</li>
<li>
ntfy:
<code className="text-slate-300"> {data?.paths?.ntfy_env}</code>
</li>
<li>
CLI:
<code className="text-slate-300"> notify-ntfy / nomadro-healthcheck</code>
</li>
</ul>
<div className="mt-3 flex flex-wrap gap-2">
<a
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
href="https://umami.nomadro.com"
target="_blank"
rel="noreferrer"
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-sm font-medium text-white">站点详情 · {domain}</div>
<div className="text-[11px] text-slate-500">类似 GA 的摘要指标与排行</div>
</div>
<select
value={domain}
onChange={(e) => setDomain(e.target.value)}
className="rounded-xl border border-white/10 bg-black/40 px-3 py-1.5 text-xs text-white"
>
Umami
</a>
<a
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
href="https://ntfy.nomadro.com"
target="_blank"
rel="noreferrer"
>
ntfy
</a>
<a
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
href="https://nomadro.com"
target="_blank"
rel="noreferrer"
>
nomadro.com
</a>
{(trackedDomains.length ? trackedDomains : [domain]).map((d) => (
<option key={d} value={d}>
{d}
</option>
))}
</select>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ 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) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="mt-4 rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail?.active ?? 0}</span>
</div>
<Sparkline series={detail?.series} />
</div>
<div className="mt-4 grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail?.top_paths} />
<MetricList title="来源 Referrer" rows={detail?.top_referrers} />
<MetricList title="国家 / 地区" rows={detail?.top_countries} />
<MetricList title="设备" rows={detail?.top_devices} />
<MetricList title="浏览器" rows={detail?.top_browsers} />
</div>
</section>
</div>
</div>
</>
)}
{tab === "monitor" && (
<>
<div className="grid gap-3 sm:grid-cols-3">
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.umami?.heartbeat?.ok} />
<ProbeText p={data?.umami?.heartbeat} />
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.ntfy?.health?.ok} />
<ProbeText p={data?.ntfy?.health} />
</div>
<div className="mt-1 text-[11px] text-slate-500">topic {data?.ntfy?.topic}</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
</div>
<div className="mt-1 text-sm text-white">
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
</div>
<button
type="button"
disabled={!!busy}
onClick={() => void runHealth()}
className="mt-2 inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-200"
>
{busy === "health" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Activity className="h-3 w-3" />}
跑健康检查
</button>
</div>
</div>
<div className="grid gap-5 lg:grid-cols-5">
<div className="space-y-5 lg:col-span-3">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Globe2 className="h-4 w-4 text-sky-300" />
域名 · DNS · 探测
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left text-xs">
<thead className="text-slate-500">
<tr className="border-b border-white/10">
<th className="py-2 pr-2 font-medium">域名</th>
<th className="py-2 pr-2 font-medium">DNS</th>
<th className="py-2 pr-2 font-medium">健康</th>
<th className="py-2 font-medium">Umami ID</th>
</tr>
</thead>
<tbody>
{(data?.sites || []).map((s) => (
<tr key={s.domain} className="border-b border-white/5 align-top">
<td className="py-2.5 pr-2">
<div className="font-medium text-sky-200">{s.domain}</div>
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
</td>
<td className="py-2.5 pr-2">
<div className="flex items-center gap-1.5">
<StatusDot ok={s.dns_ok} />
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
{(s.ips || []).join(", ") || "—"}
</span>
</div>
</td>
<td className="py-2.5 pr-2">
<ProbeText p={s.health} />
</td>
<td className="py-2.5 font-mono text-[10px] text-slate-400">{s.umami_website_id || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-amber-300" />
systemd 服务
</div>
<div className="grid gap-2 sm:grid-cols-2">
{(data?.services || []).map((s) => (
<div
key={s.unit}
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
>
<div>
<div className="text-sm text-slate-100">{s.label}</div>
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
</div>
<div className="flex items-center gap-2 text-xs">
<StatusDot ok={s.ok} />
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
</div>
</div>
))}
</div>
</section>
</div>
<div className="space-y-5 lg:col-span-2">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Bell className="h-4 w-4 text-amber-300" />
发送 ntfy
</div>
<div className="space-y-2">
<input
value={title}
onChange={(e) => 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="标题"
/>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
/>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
>
<option value="min">min</option>
<option value="low">low</option>
<option value="default">default</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
<button
type="button"
disabled={!!busy || !data?.ntfy?.configured}
onClick={() => void sendNtfy()}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
>
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
推送到 {data?.ntfy?.topic || "server-alerts"}
</button>
</div>
<div className="mt-3 text-[11px] text-slate-500">
主机 {data?.host} · {data?.generated_at ? fmtTs(data.generated_at) : ""}
</div>
</section>
</div>
</div>
</>
)}
</div>
</Shell>
);