From d8bf5658e6d419f217a20f88fcc1aa30f34372dc Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 23:58:40 -0500 Subject: [PATCH] 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 --- backend/app/main.py | 34 ++ backend/app/ops_panel.py | 183 ++++++++++ frontend/src/app/ops/page.tsx | 661 ++++++++++++++++++++++------------ 3 files changed, 639 insertions(+), 239 deletions(-) diff --git a/backend/app/main.py b/backend/app/main.py index 8bf8cd1..9297587 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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 diff --git a/backend/app/ops_panel.py b/backend/app/ops_panel.py index 91e273b..40bc4ee 100644 --- a/backend/app/ops_panel.py +++ b/backend/app/ops_panel.py @@ -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) diff --git a/frontend/src/app/ops/page.tsx b/frontend/src/app/ops/page.tsx index 125b05c..3947738 100644 --- a/frontend/src/app/ops/page.tsx +++ b/frontend/src/app/ops/page.tsx @@ -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; }; +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 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 [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 [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 (
-
Infrastructure
-

站点运维台

+
Analytics + Ops
+

访问数据与运维

- Umami 分析、ntfy 通知、DNS 解析与核心服务状态。数据来自本机探测与{" "} - /etc/nomadro/*。 + Umami 提供类似 Google Analytics 的 PV / 访客 / 来源 / 设备统计(偏隐私、无广告画像)。下方可切换「访问数据」与「监控」。

-
- 主机 {data?.host || "—"} - 期望 IP {data?.server_ip || "—"} - {data?.generated_at ? fmtTs(data.generated_at) : ""} -
- -
-
- -
- -
-
- ntfy -
-
- - -
-
- topic {data?.ntfy?.topic || "—"} · token …{data?.ntfy?.token_suffix || ""} -
- - 打开 ntfy - -
-
-
- DNS / 服务 -
-
- DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0} -
-
期望 A 记录 → {data?.server_ip}
-
+
+ +
+ +
-
-
+ {tab === "analytics" && ( + <>
-
- - 域名 · DNS · Umami · 探测 +
+
各站点概览
+
+ {RANGES.map((r) => ( + + ))} +
-
- - - - - - - - - - - {(data?.sites || []).map((s) => ( - - - - - - - ))} - {!data?.sites?.length && ( - - - - )} - -
域名DNS健康Umami ID
- - {s.domain} - -
{s.role}
-
-
- - - {(s.ips || []).join(", ") || "—"} - -
-
- - - {s.umami_website_id || "—"} -
- {loading ? "加载中…" : "暂无数据"} -
-
-
- -
-
- - systemd 服务 -
-
- {(data?.services || []).map((s) => ( -
+ {overview.map((s) => ( + ))} -
-
-
- -
-
-
- - 发送 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 focus:border-teal-400/40" - /> - -