from __future__ import annotations import asyncio import threading import time from typing import Any import httpx from . import db from .timeutil import beijing_now NTFY_TOPIC = "dylive" _EVENT_NTFY: dict[str, tuple[str, str, str]] = { "live": ("抖音开播", "high", "red_circle,live"), "offline": ("抖音停播", "default", "white_circle,offline"), "risk": ("抖音风控", "high", "warning"), "shorts_fail": ("Shorts 失败", "high", "x"), "shorts_ok": ("Shorts 成功", "default", "white_check_mark"), "shorts_quota": ("Shorts 配额", "default", "chart_with_upwards_trend"), "tiktok_fail": ("TikTok 失败", "high", "x"), "tiktok_ok": ("TikTok 成功", "default", "white_check_mark"), "tiktok_limit": ("TikTok 限流", "high", "warning"), "tiktok_unaudited": ("TikTok 仅自己可见", "default", "lock"), "watch_remind": ("盯梢提醒", "default", "eyes"), "ops": ("系统测试", "default", "bell"), "ops_disk": ("磁盘预警", "high", "floppy_disk"), "ops_quota": ("配额预警", "default", "chart_with_upwards_trend"), "ops_backlog": ("任务积压", "default", "warning"), } def _notify_allowed(event: str, cfg: dict[str, Any]) -> bool: if event == "live" and not cfg.get("notify_on_live", True): return False if event == "offline" and not cfg.get("notify_on_offline", False): return False if event == "risk" and not cfg.get("notify_on_risk", True): return False if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True): return False if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False): return False if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True): return False if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True): return False if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False): return False if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True): return False if event == "tiktok_unaudited" and not cfg.get("notify_on_tiktok_unaudited", True): return False if event in {"ops_disk", "ops_quota", "ops_backlog"} and not cfg.get("ops_alerts_enabled", False): return False if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True): return False return True def _skip_generic_ntfy(event: str, payload: dict[str, Any]) -> bool: """YouTube live/offline uses dedicated detailed ntfy builder.""" if event not in {"live", "offline"}: return False if str(payload.get("platform") or "").lower() == "youtube": return True if payload.get("group_id") and not payload.get("room_pk"): return True return False def build_event_ntfy(event: str, payload: dict[str, Any]) -> tuple[str, str, str, str]: title, priority, tags = _EVENT_NTFY.get(event, (event, "default", "bell")) msg = str(payload.get("message") or event).strip() lines = [msg] for key, label in ( ("anchor_name", "主播"), ("room_id", "房间"), ("url", "链接"), ("session_id", "Session"), ("job_id", "任务"), ): val = payload.get(key) if val: lines.append(f"{label}:{val}") duration = payload.get("duration_seconds") if duration is not None: lines.append(f"时长:{_fmt_duration(duration)}") lines.append(f"时间:{beijing_now().strftime('%Y-%m-%d %H:%M:%S')} 北京时间") return title, "\n".join(lines), priority, tags def _fmt_duration(seconds: Any) -> str: total = max(0, int(float(seconds or 0))) h, rem = divmod(total, 3600) m, s = divmod(rem, 60) if h > 0: return f"{h}:{m:02d}:{s:02d}" return f"{m}:{s:02d}" def build_youtube_ntfy(event: str, fields: dict[str, Any]) -> tuple[str, str, str, str]: """Build (title, message, priority, tags) for YouTube live/offline ntfy.""" is_live = event == "live" title = "YouTube 开播" if is_live else "YouTube 停播" tags = "red_circle,live,tv" if is_live else "white_circle,offline,tv" priority = "high" if is_live else "default" name = str(fields.get("name") or fields.get("anchor_name") or "未知频道").strip() channel_type = str(fields.get("channel_type") or fields.get("kind") or "YouTube 频道").strip() channel_id = str(fields.get("channel_id") or "").strip() handle = str(fields.get("handle") or "").strip() stream_title = str(fields.get("title") or fields.get("stream_title") or "").strip() live_url = str(fields.get("live_url") or fields.get("url") or "").strip() video_id = str(fields.get("video_id") or "").strip() session_id = str(fields.get("session_id") or "").strip() group_id = str(fields.get("group_id") or fields.get("shorts_channel_pk") or "").strip() detect_source = str(fields.get("detect_source") or fields.get("source") or "").strip() duration = fields.get("duration_seconds") channel_url = str(fields.get("channel_url") or "").strip() now_label = beijing_now().strftime("%Y-%m-%d %H:%M:%S") lines = [ f"事件:{'开播' if is_live else '停播'}", f"频道:{name}", f"类型:{channel_type}", ] if channel_id: lines.append(f"Channel ID:{channel_id}") if handle: lines.append(f"Handle:{handle}") if channel_url: lines.append(f"频道页:{channel_url}") if stream_title: lines.append(f"直播标题:{stream_title}") if live_url: lines.append(f"直播链接:{live_url}") if video_id: lines.append(f"Video ID:{video_id}") if session_id: lines.append(f"Session:{session_id}") if group_id: lines.append(f"内部 ID:{group_id}") if detect_source: lines.append(f"检测来源:{detect_source}") if not is_live and duration is not None: lines.append(f"本场时长:{_fmt_duration(duration)}") lines.append(f"时间:{now_label} 北京时间") return title, "\n".join(lines), priority, tags async def send_ntfy_youtube(event: str, fields: dict[str, Any]) -> None: """Push detailed YouTube live/offline alert via server ntfy (if configured).""" if event not in {"live", "offline"}: return try: from . import ops_panel if not ops_panel.ntfy_config().get("configured"): return title, message, priority, tags = build_youtube_ntfy(event, fields) async def _send() -> None: try: await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, NTFY_TOPIC) except Exception: pass try: asyncio.get_running_loop() asyncio.create_task(_send()) except RuntimeError: await _send() except Exception: pass def fire_ntfy_youtube(event: str, fields: dict[str, Any]) -> None: """Schedule ntfy from sync code paths (db sync, etc.).""" def _run() -> None: try: asyncio.run(send_ntfy_youtube(event, fields)) except Exception: pass try: loop = asyncio.get_running_loop() loop.create_task(send_ntfy_youtube(event, fields)) except RuntimeError: threading.Thread(target=_run, daemon=True).start() def _skip_douyin_ntfy(event: str, payload: dict[str, Any], cfg: dict[str, Any]) -> bool: """Douyin live/offline ntfy can be toggled independently from webhook.""" if event not in {"live", "offline"}: return False if _skip_generic_ntfy(event, payload): return False return not cfg.get("notify_ntfy_on_douyin_live", False) async def send_ntfy_event(event: str, payload: dict[str, Any]) -> None: """Push project events to ntfy topic dylive (if server ntfy is configured).""" if _skip_generic_ntfy(event, payload): return cfg = db.get_settings_map() if _skip_douyin_ntfy(event, payload, cfg): return try: from . import ops_panel if not ops_panel.ntfy_config().get("configured"): return title, message, priority, tags = build_event_ntfy(event, payload) async def _send() -> None: try: await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, NTFY_TOPIC) except Exception: pass try: asyncio.get_running_loop() asyncio.create_task(_send()) except RuntimeError: await _send() except Exception: pass def _event_platform(event: str) -> str: if event.startswith("shorts"): return "shorts" if event.startswith("tiktok"): return "tiktok" if event.startswith("yt_long") or event.startswith("yt-long"): return "yt_long" if event.startswith("x"): return "x" if event in {"live", "offline", "risk"}: return "douyin" if event.startswith("ops"): return "ops" return "" async def send_webhook(event: str, payload: dict[str, Any]) -> None: """Notify via optional webhook URL and always via ntfy topic dylive when configured.""" cfg = db.get_settings_map() if not _notify_allowed(event, cfg): return url = str(cfg.get("notify_webhook_url") or "").strip() if url: standard = bool(cfg.get("notify_webhook_standard_json", False)) if standard: body = { "schema": "dylive.webhook.v1", "event": event, "ts": time.time(), "platform": str(payload.get("platform") or _event_platform(event)), "level": str(payload.get("level") or "info"), "message": str(payload.get("message") or event), "data": {k: v for k, v in payload.items() if k not in {"message", "level", "platform"}}, } else: body = { "event": event, "text": payload.get("message") or event, "payload": payload, } async def _post() -> None: try: async with httpx.AsyncClient(timeout=8.0, trust_env=False) as client: await client.post(url, json=body) except Exception: pass try: asyncio.get_running_loop() asyncio.create_task(_post()) except RuntimeError: await _post() await send_ntfy_event(event, payload)