# -*- coding: utf-8 -*- """Douyin live status map from monitor DB (rooms.last_status), no extra network probe.""" from __future__ import annotations import time from typing import Any from . import db _CACHE: dict[str, Any] = {"at": 0.0, "payload": None, "key": ""} _CACHE_TTL_SEC = 12.0 def _counts_as_live(row: dict[str, Any]) -> bool: if not row.get("enabled", True): return False rid = str(row.get("room_id") or "").strip() url = str(row.get("url") or "").strip() if db.is_blacklisted(rid, url): return False return str(row.get("last_status") or "").strip() == "live" def _entry(row: dict[str, Any]) -> dict[str, Any]: status = str(row.get("last_status") or "unknown").strip() or "unknown" rid = str(row.get("room_id") or "").strip() url = str(row.get("url") or "").strip() anchor = str(row.get("last_anchor") or row.get("note") or "").strip() avatar = str(row.get("avatar_url") or "").strip() live = _counts_as_live(row) return { "is_live": live, "last_status": "live" if live else (status if status != "live" else "offline"), "anchor": anchor, "url": url, "avatar_url": avatar, "last_checked_at": row.get("last_checked_at"), "active_session_id": str(row.get("active_session_id") or ""), "enabled": bool(row.get("enabled", True)), } def build_live_map(*, room_ids: list[str] | None = None, force: bool = False) -> dict[str, Any]: key = ",".join(sorted(room_ids or [])) now = time.time() cached = _CACHE.get("payload") if ( not force and isinstance(cached, dict) and _CACHE.get("key") == key and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC ): return cached rows = db.list_douyin_room_status_entries(room_ids=room_ids) entries: dict[str, dict[str, Any]] = {} live_count = 0 for row in rows: rid = str(row.get("room_id") or "").strip() if not rid: continue ent = _entry(row) entries[rid] = ent if ent["is_live"]: live_count += 1 payload: dict[str, Any] = { "ok": True, "checked_at": now, "live_count": live_count, "source": "monitor_db", "entries": entries, } _CACHE["at"] = now _CACHE["payload"] = payload _CACHE["key"] = key return payload