douyinWEB/backend/app/notify.py
eric fd22339bff Send detailed ntfy alerts on all YouTube channel live start and end.
Cover group channels via youtube_monitor and Shorts upload channels via live-map sync with rich message fields.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 04:08:32 -05:00

161 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import asyncio
import threading
from typing import Any
import httpx
from . import db
from .timeutil import beijing_now
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)
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()
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
"""Existing webhook notifier — unchanged behavior (ops/ntfy is a separate module)."""
cfg = db.get_settings_map()
url = str(cfg.get("notify_webhook_url") or "").strip()
if not url:
return
if event == "live" and not cfg.get("notify_on_live", True):
return
if event == "offline" and not cfg.get("notify_on_offline", False):
return
if event == "risk" and not cfg.get("notify_on_risk", True):
return
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
return
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
return
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
return
if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True):
return
if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False):
return
if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True):
return
if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True):
return
# allow ops/test always when URL configured
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()