"""运营:ntfy 状态 / 试推 — admin.nomadro.com 与 .cn 共用。""" from __future__ import annotations import asyncio import os import shutil import time from datetime import datetime, timezone from pathlib import Path import httpx from fastapi import APIRouter, Depends from fastapi.responses import JSONResponse from pydantic import BaseModel, Field from ebook_svc.config import settings from ebook_svc.core.security import require_admin from ebook_svc.services import ntfy as ntfy_svc router = APIRouter(prefix="/api/admin/ops", tags=["ops-admin"]) async def _probe(client: httpx.AsyncClient, name: str, url: str) -> dict: started = time.monotonic() try: response = await client.get(url) ok = 200 <= response.status_code < 300 if ok: try: payload = response.json() ok = isinstance(payload, dict) and payload.get('ok') is True except ValueError: ok = False status = response.status_code except httpx.HTTPError: ok, status = False, None return {"name": name, "ok": ok, "status": status, "latencyMs": round((time.monotonic() - started) * 1000)} def _resources() -> dict: disk = shutil.disk_usage(Path.cwd()) memory = None try: values = {} for line in Path('/proc/meminfo').read_text().splitlines(): key, value = line.split(':', 1) values[key] = int(value.split()[0]) * 1024 total = values['MemTotal'] available = values['MemAvailable'] memory = {"totalBytes": total, "usedBytes": total - available, "usedPercent": round((total - available) * 100 / total, 1)} except (OSError, ValueError, KeyError): pass try: load = list(os.getloadavg()) except (AttributeError, OSError): load = None return {"disk": {"totalBytes": disk.total, "usedBytes": disk.used, "usedPercent": round(disk.used * 100 / disk.total, 1)}, "memory": memory, "loadAverage": load, "cpuCount": os.cpu_count()} @router.get('/health') async def ops_health(_: str = Depends(require_admin)): # Fixed loopback targets; callers cannot probe arbitrary hosts or paths. async with httpx.AsyncClient(timeout=3.0, trust_env=False) as client: checks = await asyncio.gather( _probe(client, 'Next.js 门户', 'http://127.0.0.1:4003/api/health'), _probe(client, '业务 API', 'http://127.0.0.1:8010/health'), _probe(client, '社区服务', 'http://127.0.0.1:8020/health'), ) resources = await asyncio.to_thread(_resources) return JSONResponse({"ok": all(c['ok'] for c in checks), "checks": checks, "resources": resources, "checkedAt": datetime.now(timezone.utc).isoformat()}, headers={"Cache-Control": "no-store"}) class NtfyTestBody(BaseModel): title: str = Field(default="[WebAdmin] 试推", max_length=80) message: str = Field(default="admin.nomadro.com 通知通路正常", max_length=500) priority: int = Field(default=3, ge=1, le=5) tags: str | None = Field(default="white_check_mark,globe_with_meridians") @router.get("/ntfy") async def ntfy_status(_: str = Depends(require_admin)) -> dict: base = (settings.ntfy_base_url or "").rstrip("/") topic = (settings.ntfy_topic or "").strip().strip("/") return { "enabled": bool(settings.ntfy_enabled), "baseUrl": base, "topic": topic, "hasToken": bool((settings.ntfy_token or "").strip()), "publicHint": base + "/" + topic if base.startswith("https://") and topic else "", } @router.post("/ntfy/test") async def ntfy_test(body: NtfyTestBody, _: str = Depends(require_admin)) -> dict: from datetime import datetime, timezone, timedelta cst = timezone(timedelta(hours=8)) now = datetime.now(cst).strftime("%Y-%m-%d %H:%M:%S") rich = ntfy_svc.format_rich_message( headline=f"📣 {body.title or '试推'}", bullets=[ ("正文", body.message or "admin 通知通路正常"), ("时间", now), ("来源", "admin.ops.ntfy/test"), ], table=[ ("priority", str(body.priority)), ("markdown", "on"), ("icon", "nomadro icon-192"), ], links=[ ("打开后台", "https://admin.nomadro.com/"), ("订阅页", (settings.ntfy_base_url or "").rstrip("/") + "/" + (settings.ntfy_topic or "").strip().strip("/")), ], ) ok = await ntfy_svc.notify( rich, title=(body.title or "Nomadro 试推")[:80], tags=body.tags or "loudspeaker,white_check_mark", priority=body.priority, markdown=True, click="https://admin.nomadro.com/", actions=[ { "action": "view", "label": "打开后台", "url": "https://admin.nomadro.com/", "clear": True, } ], ) return { "ok": ok, "enabled": bool(settings.ntfy_enabled), "topic": (settings.ntfy_topic or "").strip(), "rich": True, }