"""Read-only client for an Uptime Kuma public status page.""" from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timezone import httpx DOWN, UP, PENDING, MAINTENANCE = 0, 1, 2, 3 ICONS = {DOWN: "❌", UP: "✅", PENDING: "🟡", MAINTENANCE: "🔧", None: "⏸"} @dataclass class Monitor: id: int name: str group: str type: str status: int | None = None # last heartbeat status, None = no data (paused) msg: str = "" ping: float | None = None last_time: datetime | None = None down_since: datetime | None = None uptime_24h: float | None = None recent: list[int] = field(default_factory=list) @property def icon(self) -> str: return ICONS.get(self.status, "❔") def _parse_time(s: str) -> datetime: # Kuma returns UTC as "YYYY-MM-DD HH:MM:SS.mmm" return datetime.fromisoformat(s.replace(" ", "T")).replace(tzinfo=timezone.utc) async def fetch_monitors(base_url: str, slug: str) -> list[Monitor]: async with httpx.AsyncClient(base_url=base_url.rstrip("/"), timeout=15) as client: page = (await client.get(f"/api/status-page/{slug}")).raise_for_status().json() beats = (await client.get(f"/api/status-page/heartbeat/{slug}")).raise_for_status().json() monitors = [] for group in page["publicGroupList"]: for m in group["monitorList"]: mon = Monitor(id=m["id"], name=m["name"], group=group["name"], type=m.get("type", "")) history = beats["heartbeatList"].get(str(m["id"]), []) if history: last = history[-1] mon.status, mon.msg, mon.ping = last["status"], last.get("msg") or "", last.get("ping") mon.last_time = _parse_time(last["time"]) mon.recent = [h["status"] for h in history[-10:]] if mon.status == DOWN: since = last for h in reversed(history): if h["status"] != DOWN: break since = h mon.down_since = _parse_time(since["time"]) mon.uptime_24h = beats["uptimeList"].get(f"{m['id']}_24") monitors.append(mon) return monitors