douyinWEB/backend/app/ops_panel.py
eric b5a6907b85 feat(ops): 站点概览卡片点击弹窗查看访客详情
弹窗含 PV/访客/趋势及页面、来源、地区、城市、语言、设备、OS、浏览器等排行。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 03:07:58 -05:00

492 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Ops panel: Umami / ntfy / DNS / site health for DouyinWEB control UI."""
from __future__ import annotations
import json
import os
import socket
import subprocess
import time
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
SERVER_IP = "107.173.30.245"
NTFY_ENV = Path("/etc/nomadro/ntfy.env")
UMAMI_ENV = Path("/etc/nomadro/umami.env")
UMAMI_SITES = Path("/etc/nomadro/umami-sites.env")
# Public web surfaces managed on this host
SITES: list[dict[str, str]] = [
{
"domain": "nomadro.com",
"role": "Nomadro 英文 WP + 中文 Next(分流)",
"umami_key": "UMAMI_ID_NOMADRO_COM",
"health_url": "https://nomadro.com/",
"kind": "content",
},
{
"domain": "portal.nomadro.com",
"role": "Nomadro Next 直连",
"umami_key": "UMAMI_ID_PORTAL_NOMADRO_COM",
"health_url": "https://portal.nomadro.com/",
"kind": "content",
},
{
"domain": "dylive.nomadro.com",
"role": "DouyinWEB / LiveRadar",
"umami_key": "UMAMI_ID_DYLIVE_NOMADRO_COM",
"health_url": "https://dylive.nomadro.com/login",
"kind": "app",
},
{
"domain": "nomadro.live",
"role": "TikTok Promo",
"umami_key": "UMAMI_ID_NOMADRO_LIVE",
"health_url": "https://nomadro.live/",
"kind": "app",
},
{
"domain": "wx.nomadro.com",
"role": "HackRobot",
"umami_key": "UMAMI_ID_WX_NOMADRO_COM",
"health_url": "https://wx.nomadro.com/",
"kind": "app",
},
{
"domain": "x.nomadro.com",
"role": "XAuto",
"umami_key": "UMAMI_ID_X_NOMADRO_COM",
"health_url": "https://x.nomadro.com/",
"kind": "app",
},
{
"domain": "umami.nomadro.com",
"role": "Umami 分析后台",
"umami_key": "",
"health_url": "https://umami.nomadro.com/api/heartbeat",
"kind": "infra",
},
{
"domain": "ntfy.nomadro.com",
"role": "ntfy 通知服务",
"umami_key": "",
"health_url": "https://ntfy.nomadro.com/v1/health",
"kind": "infra",
},
{
"domain": "s3.nomadro.com",
"role": "SeaweedFS S3",
"umami_key": "",
"health_url": "",
"kind": "infra",
},
{
"domain": "feiniu.nomadro.com",
"role": "S3 别名",
"umami_key": "",
"health_url": "",
"kind": "infra",
},
]
SERVICES = [
("caddy", "Caddy TLS / 反代"),
("docker", "Docker"),
("douyinweb-web", "DouyinWEB Next"),
("douyinweb-api", "DouyinWEB API"),
("nomadro", "Nomadro Next"),
("nomadro-router", "受众分流"),
("tiktok-promo-frontend", "TikTok Promo"),
("hackrobot-web", "HackRobot"),
("xauto-web", "XAuto"),
]
def _read_env_file(path: Path) -> dict[str, str]:
out: dict[str, str] = {}
if not path.is_file():
return out
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
out[k.strip()] = v.strip().strip('"').strip("'")
except OSError:
pass
return out
def _http_probe(url: str, timeout: float = 8.0) -> dict[str, Any]:
if not url:
return {"ok": None, "status": None, "ms": None, "error": "no url"}
t0 = time.monotonic()
try:
req = Request(url, headers={"User-Agent": "DouyinWEB-Ops/1.0"}, method="GET")
with urlopen(req, timeout=timeout) as resp:
body = resp.read(200)
ms = int((time.monotonic() - t0) * 1000)
return {"ok": 200 <= resp.status < 400, "status": resp.status, "ms": ms, "snippet": body[:80].decode("utf-8", "replace")}
except HTTPError as e:
ms = int((time.monotonic() - t0) * 1000)
return {"ok": False, "status": e.code, "ms": ms, "error": str(e.reason)}
except Exception as e: # noqa: BLE001
ms = int((time.monotonic() - t0) * 1000)
return {"ok": False, "status": None, "ms": ms, "error": str(e)}
def _resolve_a(domain: str) -> list[str]:
try:
infos = socket.getaddrinfo(domain, 443, type=socket.SOCK_STREAM)
ips = sorted({i[4][0] for i in infos if ":" not in i[4][0]})
return ips
except OSError as e:
return [f"error:{e}"]
def _systemctl_active(unit: str) -> dict[str, Any]:
try:
r = subprocess.run(
["systemctl", "is-active", unit],
capture_output=True,
text=True,
timeout=5,
check=False,
)
state = (r.stdout or r.stderr or "").strip() or "unknown"
return {"unit": unit, "state": state, "ok": state == "active"}
except Exception as e: # noqa: BLE001
return {"unit": unit, "state": "error", "ok": False, "error": str(e)}
def ntfy_config() -> dict[str, Any]:
env = _read_env_file(NTFY_ENV)
token = env.get("NTFY_TOKEN", "")
return {
"configured": bool(token),
"base_url": env.get("NTFY_BASE_URL", "https://ntfy.nomadro.com"),
"topic": env.get("NTFY_TOPIC", "server-alerts"),
"user": env.get("NTFY_USER", ""),
"has_token": bool(token),
# never expose full token to UI — only suffix
"token_suffix": token[-6:] if len(token) >= 6 else ("*" * len(token)),
}
def umami_config() -> dict[str, Any]:
env = _read_env_file(UMAMI_ENV)
sites = _read_env_file(UMAMI_SITES)
return {
"url": env.get("UMAMI_URL", "https://umami.nomadro.com"),
"user": env.get("UMAMI_USER", "admin"),
"has_password": bool(env.get("UMAMI_PASSWORD")),
"script": sites.get("UMAMI_SCRIPT", "https://umami.nomadro.com/script.js"),
"sites": {k: v for k, v in sites.items() if k.startswith("UMAMI_ID_")},
}
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}
)
code_os, oses = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "os", "limit": 6}
)
code_lang, langs = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "language", "limit": 8}
)
code_city, cities = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "city", "limit": 8}
)
code_title, titles = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "title", "limit": 8}
)
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,
"os": None if code_os == 200 else oses,
"language": None if code_lang == 200 else langs,
"city": None if code_city == 200 else cities,
"title": None if code_title == 200 else titles,
},
"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),
"top_os": _metric_list(oses),
"top_languages": _metric_list(langs),
"top_cities": _metric_list(cities),
"top_titles": _metric_list(titles),
"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)
token = env.get("NTFY_TOKEN", "")
if not token:
raise ValueError("ntfy 未配置:缺少 /etc/nomadro/ntfy.env 中的 NTFY_TOKEN")
base = cfg["base_url"].rstrip("/")
use_topic = topic or cfg["topic"]
url = f"{base}/{use_topic}"
body = message.encode("utf-8")
req = Request(
url,
data=body,
method="POST",
headers={
"Authorization": f"Bearer {token}",
"Title": title,
"Priority": priority,
"Tags": tags,
},
)
try:
with urlopen(req, timeout=15) as resp:
raw = resp.read().decode("utf-8", "replace")
try:
parsed = json.loads(raw) if raw else {}
except json.JSONDecodeError:
parsed = {"raw": raw}
return {"ok": True, "status": resp.status, "topic": use_topic, "response": parsed}
except HTTPError as e:
raise ValueError(f"ntfy 发送失败 HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:200]}") from e
except URLError as e:
raise ValueError(f"ntfy 连接失败: {e}") from e
def run_healthcheck_script() -> dict[str, Any]:
script = Path("/usr/local/bin/nomadro-healthcheck")
if not script.is_file():
raise ValueError("未安装 /usr/local/bin/nomadro-healthcheck")
r = subprocess.run([str(script)], capture_output=True, text=True, timeout=120, check=False)
return {
"ok": r.returncode == 0,
"returncode": r.returncode,
"stdout": (r.stdout or "")[-2000:],
"stderr": (r.stderr or "")[-1000:],
}
def snapshot() -> dict[str, Any]:
umami = umami_config()
ntfy = ntfy_config()
site_rows = []
for s in SITES:
ips = _resolve_a(s["domain"])
dns_ok = SERVER_IP in ips
probe = _http_probe(s["health_url"]) if s.get("health_url") else {"ok": None, "status": None, "ms": None}
wid = umami["sites"].get(s["umami_key"], "") if s.get("umami_key") else ""
site_rows.append(
{
**s,
"ips": ips,
"dns_ok": dns_ok,
"expected_ip": SERVER_IP,
"umami_website_id": wid,
"health": probe,
}
)
services = [_systemctl_active(u) for u, _label in SERVICES]
for svc, (_u, label) in zip(services, SERVICES):
svc["label"] = label
return {
"generated_at": time.time(),
"server_ip": SERVER_IP,
"umami": {
**umami,
"heartbeat": _http_probe("https://umami.nomadro.com/api/heartbeat"),
},
"ntfy": {
**ntfy,
"health": _http_probe("https://ntfy.nomadro.com/v1/health"),
},
"sites": site_rows,
"services": services,
"paths": {
"ntfy_env": str(NTFY_ENV),
"umami_env": str(UMAMI_ENV),
"umami_sites": str(UMAMI_SITES),
"healthcheck": "/usr/local/bin/nomadro-healthcheck",
"notify": "/usr/local/bin/notify-ntfy",
},
"host": socket.gethostname(),
"env_hint": {
"DY_API_HOST": os.environ.get("DY_API_HOST", ""),
"has_ntfy_env": NTFY_ENV.is_file(),
"has_umami_env": UMAMI_ENV.is_file(),
},
}