"""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.parse import urlencode 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") _snapshot_cache: dict[str, Any] | None = None _snapshot_cache_at = 0.0 _SNAPSHOT_TTL_SEC = 20.0 # 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", "dylive"), "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"] # Title/tags may contain UTF-8; query params avoid latin-1 header encoding errors. qs = urlencode({"title": title, "priority": priority, "tags": tags}) url = f"{base}/{use_topic}?{qs}" body = message.encode("utf-8") req = Request( url, data=body, method="POST", headers={"Authorization": f"Bearer {token}"}, ) 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(*, force: bool = False) -> dict[str, Any]: global _snapshot_cache, _snapshot_cache_at now = time.time() if ( not force and _snapshot_cache is not None and (now - _snapshot_cache_at) < _SNAPSHOT_TTL_SEC ): return dict(_snapshot_cache) from concurrent.futures import ThreadPoolExecutor, as_completed umami = umami_config() ntfy = ntfy_config() def _site_row(s: dict[str, str]) -> dict[str, Any]: 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 "" return { **s, "ips": ips, "dns_ok": dns_ok, "expected_ip": SERVER_IP, "umami_website_id": wid, "health": probe, } site_rows: list[dict[str, Any]] = [] services: list[dict[str, Any]] = [] extra: dict[str, Any] = {} with ThreadPoolExecutor(max_workers=12) as pool: site_futs = {pool.submit(_site_row, s): i for i, s in enumerate(SITES)} svc_futs = {pool.submit(_systemctl_active, u): i for i, (u, _label) in enumerate(SERVICES)} fut_umami = pool.submit(_http_probe, "https://umami.nomadro.com/api/heartbeat") fut_ntfy = pool.submit(_http_probe, "https://ntfy.nomadro.com/v1/health") fut_netdata = pool.submit(_http_probe, "http://127.0.0.1:19999/netdata/api/v1/info") site_rows = [None] * len(SITES) # type: ignore[list-item] for fut in as_completed(site_futs): site_rows[site_futs[fut]] = fut.result() services = [None] * len(SERVICES) # type: ignore[list-item] for fut in as_completed(svc_futs): services[svc_futs[fut]] = fut.result() extra["umami_hb"] = fut_umami.result() extra["ntfy_h"] = fut_ntfy.result() extra["netdata"] = fut_netdata.result() for svc, (_u, label) in zip(services, SERVICES): if isinstance(svc, dict): svc["label"] = label out = { "generated_at": now, "server_ip": SERVER_IP, "umami": { **umami, "heartbeat": extra.get("umami_hb"), }, "ntfy": { **ntfy, "health": extra.get("ntfy_h"), }, "sites": site_rows, "services": services, "netdata": extra.get("netdata"), "paths": { "ntfy_env": str(NTFY_ENV), "umami_env": str(UMAMI_ENV), "umami_sites": str(UMAMI_SITES), "netdata_url": "/netdata/", "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(), }, "cache_ttl_sec": _SNAPSHOT_TTL_SEC, } _snapshot_cache = out _snapshot_cache_at = time.time() return dict(out)