douyinWEB/backend/app/douyin_live.py
eric 5b45fc0aca Add real-time Douyin live status map and badges across card UIs.
Expose /api/douyin/live-map from monitor DB with SSE-triggered client refresh, and show live/offline badges on assign, rooms, anchors, slots, and overview cards.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 03:33:46 -05:00

64 lines
1.8 KiB
Python

# -*- 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 = 8.0
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()
return {
"is_live": status == "live",
"last_status": status,
"anchor": anchor,
"url": url,
"last_checked_at": row.get("last_checked_at"),
"active_session_id": str(row.get("active_session_id") or ""),
}
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