from __future__ import annotations import asyncio import random import time from typing import Any, Optional from . import db from . import pb_sync from . import youtube_client from .notify import send_ntfy_youtube, send_webhook from .youtube_client import YouTubeSvcError from .timeutil import beijing_hour def _yt_room_id(group: dict[str, Any]) -> str: cid = str(group.get("channel_id") or "").strip() if cid: return f"yt:{cid}" key = str(group.get("channel_key") or group.get("handle") or group.get("id") or "").strip() return f"yt:{key}" class YouTubeMonitorService: """Poll enabled YouTube channel groups via youtubei.js sidecar; emit live/offline events.""" def __init__(self) -> None: self._task: Optional[asyncio.Task] = None self._stop = asyncio.Event() self.checked_total = 0 self.last_error = "" self.last_check_at = 0.0 self._last_request_at = 0.0 @property def running(self) -> bool: return self._task is not None and not self._task.done() def status(self, *, light: bool = False) -> dict[str, Any]: if light: data = db.youtube_monitor_status_data() cfg = data["settings"] stats = data["groups"] else: cfg = db.get_settings_map() stats = db.channel_groups_live_stats(platform="youtube") quiet = self._in_quiet_hours(cfg) return { "running": self.running, "yt_monitor_enabled": bool(cfg.get("yt_monitor_enabled", True)), "checked_total": self.checked_total, "last_error": self.last_error, "last_check_at": self.last_check_at, "quiet_hours_active": quiet, "groups": stats, "config": { "yt_offline_interval_sec": float(cfg.get("yt_offline_interval_sec", 180) or 180), "yt_live_interval_sec": float(cfg.get("yt_live_interval_sec", 90) or 90), "yt_batch_size": int(cfg.get("yt_batch_size", 8) or 8), "yt_request_gap_sec": float(cfg.get("yt_request_gap_sec", 2) or 2), "quiet_hours_enabled": bool(cfg.get("quiet_hours_enabled", False)), }, **({"desktop_light": True} if light else {}), } def status_light(self) -> dict[str, Any]: return self.status(light=True) async def start(self) -> None: if self.running: return self._stop.clear() self._task = asyncio.create_task(self._loop(), name="youtube-monitor") async def stop(self) -> None: self._stop.set() if self._task: try: await asyncio.wait_for(self._task, timeout=5) except Exception: self._task.cancel() self._task = None def _in_quiet_hours(self, cfg: dict[str, Any]) -> bool: if not cfg.get("quiet_hours_enabled", False): return False start = int(cfg.get("quiet_hours_start", 2) or 2) % 24 end = int(cfg.get("quiet_hours_end", 7) or 7) % 24 hour = beijing_hour() if start == end: return False if start < end: return start <= hour < end return hour >= start or hour < end def _next_interval(self, cfg: dict[str, Any], *, live: bool, errors: int) -> float: if errors > 0: base = float(cfg.get("error_backoff_base_sec", 60) or 60) cap = float(cfg.get("error_backoff_max_sec", 600) or 600) return min(cap, base * (2 ** min(errors, 3))) + random.uniform(0, 20) if live: base = float(cfg.get("yt_live_interval_sec", 90) or 90) else: base = float(cfg.get("yt_offline_interval_sec", 180) or 180) return max(45.0, base + random.uniform(-8, 8)) async def _throttle(self, cfg: dict[str, Any]) -> None: gap = float(cfg.get("yt_request_gap_sec", 2) or 2) wait = gap + random.uniform(0, max(0.0, gap * 0.4)) elapsed = time.time() - self._last_request_at if elapsed < wait: await asyncio.sleep(wait - elapsed) self._last_request_at = time.time() async def _loop(self) -> None: while not self._stop.is_set(): try: cfg = db.get_settings_map() if not cfg.get("yt_monitor_enabled", True): await asyncio.sleep(2) continue if self._in_quiet_hours(cfg): await asyncio.sleep(5) continue batch = max(1, min(20, int(cfg.get("yt_batch_size", 8) or 8))) due = db.due_channel_groups(platform="youtube", limit=batch) if not due: await asyncio.sleep(2) continue await self._throttle(cfg) await self.check_batch(due, cfg) except asyncio.CancelledError: raise except Exception as exc: self.last_error = str(exc)[:300] await asyncio.sleep(3) async def check_one(self, group_id: str) -> dict[str, Any]: group = db.get_channel_group(group_id) if not group: raise ValueError("分组不存在") cfg = db.get_settings_map() await self._throttle(cfg) return await self._check_group(group, cfg) async def check_batch(self, groups: list[dict[str, Any]], cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]: cfg = cfg or db.get_settings_map() if not groups: return [] # Prefer sidecar batch endpoint; fall back to sequential on failure inputs = [] by_input: dict[str, dict[str, Any]] = {} for g in groups: key = str(g.get("channel_url") or g.get("channel_key") or g.get("channel_id") or "").strip() if not key: continue inputs.append(key) by_input[key] = g results_map: dict[str, dict[str, Any]] = {} try: data = await youtube_client.batch_live(inputs) for item in data.get("results") or []: inp = str(item.get("input") or "") results_map[inp] = item except YouTubeSvcError: results_map = {} out: list[dict[str, Any]] = [] for key, group in by_input.items(): item = results_map.get(key) if item is None: # sequential fallback for this group try: await self._throttle(cfg) live = await youtube_client.channel_live(key) item = {"ok": True, **live, "input": key} except YouTubeSvcError as exc: item = {"ok": False, "error": str(exc), "input": key} out.append(await self._apply_result(group, item, cfg)) return out async def _check_group(self, group: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]: key = str(group.get("channel_url") or group.get("channel_key") or group.get("channel_id") or "").strip() try: live = await youtube_client.channel_live(key) item = {"ok": True, **live, "input": key} except YouTubeSvcError as exc: item = {"ok": False, "error": str(exc), "input": key} return await self._apply_result(group, item, cfg) async def _probe_group_url_list(self, group: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any] | None: """When channel tab says offline, scan group reference URLs for active streams.""" raw = group.get("urls") or [] if isinstance(raw, str): lines = [ln.strip() for ln in raw.replace("\r\n", "\n").split("\n")] elif isinstance(raw, list): lines = [str(x).strip() for x in raw] else: lines = [] urls = [u for u in lines if u and not u.startswith("#")][:6] if not urls: return None for url in urls: try: await self._throttle(cfg) data = await youtube_client.channel_live(url) if data.get("is_live"): live = data.get("live") or {} return { "ok": True, "input": url, "is_live": True, "channel_id": data.get("channel_id") or group.get("channel_id") or "", "title": data.get("title") or group.get("name") or "", "handle": data.get("handle") or group.get("handle") or "", "live": live if isinstance(live, dict) else {"url": url, "title": data.get("title") or ""}, "source": "url_list", } except YouTubeSvcError: continue return None async def _apply_result(self, group: dict[str, Any], item: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]: self.checked_total += 1 self.last_check_at = time.time() group_id = group["id"] display = group.get("name") or group.get("handle") or group.get("channel_key") or group_id yt_rid = _yt_room_id(group) if not item.get("ok", True) and item.get("error"): errors = int(group.get("error_count") or 0) + 1 self.last_error = str(item.get("error") or "")[:300] nxt = time.time() + self._next_interval(cfg, live=False, errors=errors) db.touch_channel_group( group_id, last_status="error", next_check_at=nxt, error_count=errors, last_error=self.last_error, active_session_id=str(group.get("active_session_id") or ""), last_live_video_id=str(group.get("last_live_video_id") or ""), last_live_url=str(group.get("last_live_url") or ""), ) if errors == 1 or errors % 5 == 0: db.add_event( kind="error", level="warn", message=f"YouTube 探测失败:{display} — {self.last_error}", room_id=yt_rid, room_pk=group_id, anchor_name=str(display), meta={"platform": "youtube", "group_id": group_id}, ) await self._sync_group_pb(group_id) return item is_live = bool(item.get("is_live")) if not is_live: alt = await self._probe_group_url_list(group, cfg) if alt: item = alt is_live = True live = item.get("live") or {} title = str(live.get("title") or item.get("title") or group.get("last_title") or "") live_url = str(live.get("url") or "") video_id = str(live.get("id") or "") channel_id = str(item.get("channel_id") or group.get("channel_id") or "") handle = str(item.get("handle") or group.get("handle") or "") if channel_id: yt_rid = f"yt:{channel_id}" anchor = str(item.get("title") or display) fresh = db.get_channel_group(group_id) or group prev = fresh.get("last_status") active_sid = str(fresh.get("active_session_id") or "") if is_live: if prev != "live" or not active_sid: session = db.start_session( room_pk=group_id, room_id=yt_rid, source_url=live_url or str(group.get("channel_url") or ""), anchor_name=anchor, title=title, metadata={ "platform": "youtube", "group_id": group_id, "channel_id": channel_id, "video_id": video_id, "live_url": live_url, }, ) active_sid = session["id"] if not session.get("_reused"): msg = f"YouTube 开播:{anchor}" if title: msg = f"YouTube 开播:{anchor} — {title}" db.add_event( kind="live", level="info", message=msg, room_id=yt_rid, room_pk=group_id, session_id=active_sid, anchor_name=anchor, meta={ "platform": "youtube", "group_id": group_id, "channel_id": channel_id, "video_id": video_id, "live_url": live_url, "url": live_url, }, ) await send_webhook( "live", { "message": msg, "room_id": yt_rid, "url": live_url or group.get("channel_url"), "session_id": active_sid, "anchor_name": anchor, "platform": "youtube", "group_id": group_id, }, ) await send_ntfy_youtube( "live", { "name": anchor or display, "channel_type": "YouTube 分组频道", "channel_id": channel_id, "handle": handle, "title": title, "live_url": live_url, "video_id": video_id, "session_id": active_sid, "group_id": group_id, "channel_url": str(group.get("channel_url") or ""), "detect_source": str(item.get("source") or "youtubei"), "url": live_url or str(group.get("channel_url") or ""), }, ) try: await pb_sync.sync_session(session) except Exception: pass nxt = time.time() + self._next_interval(cfg, live=True, errors=0) db.touch_channel_group( group_id, last_status="live", next_check_at=nxt, last_title=title, last_live_video_id=video_id, last_live_url=live_url, error_count=0, last_error="", active_session_id=active_sid, channel_id=channel_id, handle=handle, ) await self._sync_group_pb(group_id) else: ended_list = db.end_active_sessions_for_room( room_pk=group_id, room_id=yt_rid, end_reason="offline", ) for ended in ended_list: msg = f"YouTube 停播:{anchor}" db.add_event( kind="offline", level="info", message=msg, room_id=yt_rid, room_pk=group_id, session_id=ended.get("id") or "", anchor_name=anchor or ended.get("anchor_name") or "", meta={ "platform": "youtube", "group_id": group_id, "duration_seconds": ended.get("duration_seconds"), }, ) await send_webhook( "offline", { "message": msg, "room_id": yt_rid, "session_id": ended.get("id"), "duration_seconds": ended.get("duration_seconds"), "platform": "youtube", "group_id": group_id, }, ) await send_ntfy_youtube( "offline", { "name": anchor or display, "channel_type": "YouTube 分组频道", "channel_id": channel_id, "handle": handle, "title": str(ended.get("title") or fresh.get("last_title") or title or ""), "live_url": str(fresh.get("last_live_url") or live_url or ""), "video_id": str(fresh.get("last_live_video_id") or video_id or ""), "session_id": str(ended.get("id") or ""), "group_id": group_id, "channel_url": str(group.get("channel_url") or ""), "duration_seconds": ended.get("duration_seconds"), "detect_source": "youtubei", }, ) try: await pb_sync.sync_session(ended) except Exception: pass nxt = time.time() + self._next_interval(cfg, live=False, errors=0) db.touch_channel_group( group_id, last_status="offline", next_check_at=nxt, last_title=title, last_live_video_id="", last_live_url="", error_count=0, last_error="", active_session_id="", channel_id=channel_id, handle=handle, ) await self._sync_group_pb(group_id) return item async def _sync_group_pb(self, group_id: str) -> None: try: g = db.get_channel_group(group_id) if g: await pb_sync.sync_channel_group(g) except Exception: pass yt_monitor = YouTubeMonitorService()