diff --git a/backend/app/main.py b/backend/app/main.py index 509bea1..8bf8cd1 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2429,6 +2429,46 @@ async def notify_test() -> dict[str, Any]: return {"ok": True, "webhook": url} +@app.get("/api/ops") +async def ops_snapshot() -> dict[str, Any]: + """Umami / ntfy / DNS / systemd health snapshot for the ops control page.""" + from . import ops_panel + + return await asyncio.to_thread(ops_panel.snapshot) + + +@app.post("/api/ops/ntfy") +async def ops_ntfy_send(body: dict[str, Any]) -> dict[str, Any]: + from . import ops_panel + + title = str(body.get("title") or "DouyinWEB").strip()[:120] + message = str(body.get("message") or "").strip() + if not message: + raise HTTPException(400, "message 不能为空") + priority = str(body.get("priority") or "default").strip() or "default" + tags = str(body.get("tags") or "bell").strip() or "bell" + topic = body.get("topic") + topic_s = str(topic).strip() if topic else None + try: + return await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, topic_s) + 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/healthcheck") +async def ops_run_healthcheck() -> dict[str, Any]: + from . import ops_panel + + try: + return await asyncio.to_thread(ops_panel.run_healthcheck_script) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except Exception as exc: + raise HTTPException(500, f"健康检查失败: {exc}") from exc + + @app.get("/api/downloads") async def downloads_catalog() -> dict[str, Any]: from . import downloads as downloads_mod diff --git a/backend/app/notify.py b/backend/app/notify.py index 61cee01..b15affb 100644 --- a/backend/app/notify.py +++ b/backend/app/notify.py @@ -8,32 +8,81 @@ import httpx from . import db +def _event_allowed(event: str, cfg: dict[str, Any]) -> bool: + if event == "ops": + return True + if event == "live" and not cfg.get("notify_on_live", True): + return False + if event == "offline" and not cfg.get("notify_on_offline", False): + return False + if event == "risk" and not cfg.get("notify_on_risk", True): + return False + if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True): + return False + if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False): + return False + if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True): + return False + if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True): + return False + if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False): + return False + if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True): + return False + if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True): + return False + return True + + +async def send_ntfy_best_effort(event: str, payload: dict[str, Any]) -> None: + """Mirror events to self-hosted ntfy when /etc/nomadro/ntfy.env is present.""" + try: + from . import ops_panel + except Exception: + return + + title_map = { + "live": "开播", + "offline": "停播", + "risk": "风控", + "shorts_fail": "Shorts 失败", + "shorts_ok": "Shorts 成功", + "shorts_quota": "Shorts 配额", + "tiktok_fail": "TikTok 失败", + "tiktok_ok": "TikTok 成功", + "tiktok_limit": "TikTok 限额", + "watch_remind": "提醒", + "ops": "运维", + } + title = title_map.get(event, event) + message = str(payload.get("message") or event) + tags = "rotating_light" if event in {"risk", "shorts_fail", "tiktok_fail"} else "bell" + priority = "high" if event in {"risk", "shorts_fail", "tiktok_fail"} else "default" + + def _send() -> None: + try: + ops_panel.send_ntfy(title, message, priority, tags) + except Exception: + pass + + try: + asyncio.get_running_loop() + asyncio.create_task(asyncio.to_thread(_send)) + except RuntimeError: + await asyncio.to_thread(_send) + + async def send_webhook(event: str, payload: dict[str, Any]) -> None: cfg = db.get_settings_map() + if not _event_allowed(event, cfg): + return + + # ntfy mirror (does not require webhook URL) + await send_ntfy_best_effort(event, payload) + url = str(cfg.get("notify_webhook_url") or "").strip() if not url: return - if event == "live" and not cfg.get("notify_on_live", True): - return - if event == "offline" and not cfg.get("notify_on_offline", False): - return - if event == "risk" and not cfg.get("notify_on_risk", True): - return - if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True): - return - if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False): - return - if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True): - return - if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True): - return - if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False): - return - if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True): - return - if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True): - return - # allow ops/test always when URL configured body = { "event": event, diff --git a/backend/app/ops_panel.py b/backend/app/ops_panel.py new file mode 100644 index 0000000..91e273b --- /dev/null +++ b/backend/app/ops_panel.py @@ -0,0 +1,288 @@ +"""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 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(), + }, + } diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx index d6bf6cd..99989ca 100644 --- a/frontend/src/app/layout.tsx +++ b/frontend/src/app/layout.tsx @@ -48,6 +48,11 @@ export default function RootLayout({ children }: { children: React.ReactNode }) rel="stylesheet" /> +