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>
This commit is contained in:
eric 2026-08-22 04:08:32 -05:00
parent 5b45fc0aca
commit fd22339bff
3 changed files with 173 additions and 1 deletions

View File

@ -3145,6 +3145,8 @@ def touch_shorts_channel_live(
def sync_shorts_channel_lives_from_map(entries: dict[str, Any]) -> dict[str, int]:
"""Persist Shorts upload-channel live edges into sessions (same analytics as Douyin)."""
from .notify import fire_ntfy_youtube
started = 0
ended = 0
touched = 0
@ -3207,6 +3209,22 @@ def sync_shorts_channel_lives_from_map(entries: dict[str, Any]) -> dict[str, int
"url": live_url,
},
)
fire_ntfy_youtube(
"live",
{
"name": name,
"channel_type": "Shorts 上传频道",
"channel_id": str(ch.get("youtube_channel_id") or ""),
"title": title,
"live_url": live_url,
"video_id": vid,
"session_id": active_sid,
"shorts_channel_pk": pk,
"channel_url": f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}".rstrip("/"),
"detect_source": str(entry.get("source") or "youtubei"),
"url": live_url,
},
)
touch_shorts_channel_live(
pk,
last_status="live",
@ -3236,6 +3254,22 @@ def sync_shorts_channel_lives_from_map(entries: dict[str, Any]) -> dict[str, int
"duration_seconds": item.get("duration_seconds"),
},
)
fire_ntfy_youtube(
"offline",
{
"name": name,
"channel_type": "Shorts 上传频道",
"channel_id": str(ch.get("youtube_channel_id") or ""),
"title": str(item.get("title") or ch.get("last_title") or ""),
"live_url": str(ch.get("last_live_url") or live_url or ""),
"video_id": str(ch.get("last_live_video_id") or vid or ""),
"session_id": str(item.get("id") or ""),
"shorts_channel_pk": pk,
"channel_url": f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}".rstrip("/"),
"duration_seconds": item.get("duration_seconds"),
"detect_source": str(entry.get("source") or "youtubei"),
},
)
touch_shorts_channel_live(
pk,
last_status="offline",

View File

@ -1,11 +1,115 @@
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:

View File

@ -8,7 +8,7 @@ from typing import Any, Optional
from . import db
from . import pb_sync
from . import youtube_client
from .notify import send_webhook
from .notify import send_ntfy_youtube, send_webhook
from .youtube_client import YouTubeSvcError
from .timeutil import beijing_hour
@ -327,6 +327,23 @@ class YouTubeMonitorService:
"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:
@ -379,6 +396,23 @@ class YouTubeMonitorService:
"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: