douyinWEB/backend/app/shorts_pipeline.py
eric 47d17aee3c Document YouTube groups and Shorts side-path; sync dual-platform pipeline.
Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md.

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

359 lines
13 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.

# -*- coding: utf-8 -*-
"""Isolated Shorts pipeline — optional side path, never blocks Douyin monitor.
Enable only via settings.shorts_enabled=True.
- On-live edge enqueue (optional)
- Random sample from currently-live rooms (default on)
Same room is only used once per Beijing day per channel pool.
All public entrypoints swallow exceptions so callers (monitor) stay safe.
"""
from __future__ import annotations
import asyncio
import random
import time
from typing import Any, Optional
from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_upload import upload_shorts_mp4
from .timeutil import push_date_from_ts
def _room_tags(room: dict[str, Any]) -> list[str]:
tags = room.get("tags") or []
if isinstance(tags, str):
return [t.strip() for t in tags.split(",") if t.strip()]
return [str(t).strip() for t in tags if str(t).strip()]
def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
trigger = str(cfg.get("shorts_trigger") or "tagged").strip().lower()
tags = _room_tags(room)
if trigger == "all":
return True
if trigger == "favorite":
return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts"} for t in tags)
tag = str(cfg.get("shorts_tag") or "shorts").strip() or "shorts"
return tag in tags or "shorts" in tags
def _enqueue_job(
*,
session: dict[str, Any] | None,
room: dict[str, Any],
stream_url: str = "",
cfg: dict[str, Any] | None = None,
) -> Optional[dict[str, Any]]:
"""Internal enqueue; never raises."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return None
room_id = str((session or {}).get("room_id") or room.get("room_id") or "")
if room_id.startswith("yt:"):
return None
day = push_date_from_ts(float((session or {}).get("started_at") or time.time()))
if settings.get("shorts_dedupe_room_day", True) and room_id and db.has_shorts_job_for_room_day(room_id, day):
return None
channel = db.pick_shorts_channel(day)
if not channel:
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
job = db.create_shorts_job(
session_id=sid,
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
room_id=room_id,
source_url=str((session or {}).get("source_url") or room.get("url") or ""),
anchor_name=str(
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
),
stream_url=str(stream_url or ""),
channel_pk=str(channel["id"]),
push_date=day,
)
try:
db.add_event(
kind="ops",
level="info",
message=f"Shorts 任务已入队:{job.get('anchor_name') or room_id}",
room_id=room_id,
room_pk=str(room.get("id") or ""),
session_id=sid,
anchor_name=str(job.get("anchor_name") or ""),
meta={"shorts_job_id": job.get("id"), "channel_pk": channel.get("id")},
)
except Exception:
pass
return job
except Exception:
return None
def try_enqueue_on_live(
*,
session: dict[str, Any],
room: dict[str, Any],
stream_url: str = "",
) -> Optional[dict[str, Any]]:
"""Fire-and-forget safe: returns job or None; never raises."""
try:
cfg = db.get_settings_map()
if not cfg.get("shorts_enabled"):
return None
if not _room_eligible(room, cfg):
return None
return _enqueue_job(session=session, room=room, stream_url=stream_url, cfg=cfg)
except Exception:
return None
def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
"""Pick random currently-live rooms and enqueue (dedupe room/day). Returns enqueued count."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return 0
if not settings.get("shorts_live_sample", True):
return 0
day = push_date_from_ts(time.time())
if not db.pick_shorts_channel(day):
return 0
batch = max(1, min(int(settings.get("shorts_live_sample_batch") or 1), 5))
any_live = settings.get("shorts_sample_any_live", True)
used = db.room_ids_with_shorts_job_today(day)
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
candidates: list[dict[str, Any]] = []
for room in rooms:
rid = str(room.get("room_id") or "")
if not rid or rid in used:
continue
if not any_live and not _room_eligible(room, settings):
continue
if any_live or _room_eligible(room, settings):
candidates.append(room)
if not candidates:
return 0
random.shuffle(candidates)
enqueued = 0
for room in candidates[:batch]:
sid = str(room.get("active_session_id") or "")
session = db.get_session(sid) if sid else None
job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings)
if job:
enqueued += 1
used.add(str(room.get("room_id") or ""))
# stop if channel full after this assign
if not db.pick_shorts_channel(day):
break
return enqueued
except Exception:
return 0
class ShortsPipeline:
"""Background worker; idle when shorts_enabled is false."""
def __init__(self) -> None:
self._task: asyncio.Task | None = None
self._stop = asyncio.Event()
self._busy = False
self._last_sample_at = 0.0
self.last_error = ""
self.processed = 0
self.sampled = 0
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
try:
stats = db.shorts_stats()
except Exception:
stats = {}
return {
"running": bool(self._task and not self._task.done()),
"busy": self._busy,
"enabled": bool(cfg.get("shorts_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"last_error": self.last_error,
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
"live_sample": bool(cfg.get("shorts_live_sample", True)),
"sample_any_live": bool(cfg.get("shorts_sample_any_live", True)),
"stats": stats,
}
async def start(self) -> None:
if self._task and not self._task.done():
return
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="shorts-pipeline")
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
async def _loop(self) -> None:
while not self._stop.is_set():
try:
cfg = db.get_settings_map()
if not cfg.get("shorts_enabled"):
await asyncio.sleep(5)
continue
# Random sample from currently-live rooms (does not touch monitor loop)
interval = float(cfg.get("shorts_live_sample_interval_sec") or 180)
interval = max(60.0, interval)
if cfg.get("shorts_live_sample", True) and (time.time() - self._last_sample_at) >= interval:
self._last_sample_at = time.time()
n = try_sample_live_rooms(cfg)
if n:
self.sampled += n
max_c = max(1, int(cfg.get("shorts_max_concurrent") or 1))
if self._busy:
await asyncio.sleep(1)
continue
_ = max_c
job = db.claim_next_shorts_job()
if not job:
await asyncio.sleep(2)
continue
self._busy = True
try:
await self._process(job, cfg)
self.processed += 1
finally:
self._busy = False
except asyncio.CancelledError:
break
except Exception as exc:
self.last_error = str(exc)[:300]
await asyncio.sleep(3)
async def _process(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
status = str(job.get("status") or "")
try:
if status == "recording":
await self._do_record(job, cfg)
job = db.get_shorts_job(jid) or job
status = str(job.get("status") or "")
if status == "uploading" or (
status == "recorded" and cfg.get("shorts_auto_upload", True)
):
if status == "recorded":
db.update_shorts_job(jid, status="uploading")
job = db.get_shorts_job(jid) or job
await self._do_upload(job, cfg)
except Exception as exc:
self.last_error = str(exc)[:300]
db.update_shorts_job(
jid,
status="failed",
error=self.last_error,
finished_at=time.time(),
)
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
cookie = str(cfg.get("dy_cookie") or "")
stream = await resolve_stream_url(
source_url=str(job.get("source_url") or ""),
stream_url=str(job.get("stream_url") or ""),
cookie=cookie,
)
if not stream:
db.update_shorts_job(
jid,
status="failed",
error="无法获取直播流(可能已停播)",
finished_at=time.time(),
)
return
sec = int(cfg.get("shorts_clip_sec") or 15)
outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec)
if not outcome.get("ok"):
db.update_shorts_job(
jid,
status="failed",
error=str(outcome.get("error") or "录制失败"),
stream_url=stream,
finished_at=time.time(),
)
return
next_status = "uploading" if cfg.get("shorts_auto_upload", True) else "recorded"
db.update_shorts_job(
jid,
status=next_status,
clip_path=str(outcome.get("path") or ""),
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
error="",
)
async def _do_upload(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
clip = str(job.get("clip_path") or "")
if not clip:
db.update_shorts_job(jid, status="failed", error="无成片路径", finished_at=time.time())
return
channel = db.get_shorts_channel(str(job.get("channel_pk") or ""))
if not channel:
db.update_shorts_job(jid, status="failed", error="频道不存在", finished_at=time.time())
return
from .shorts_oauth import channel_oauth_creds
creds = channel_oauth_creds(channel, cfg)
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
db.update_shorts_job(
jid,
status="recorded",
error="频道未授权 Google,已保留成片待上传",
)
return
title_tpl = str(channel.get("title_template") or "{anchor} #Shorts")
desc_tpl = str(channel.get("description_template") or "")
anchor = str(job.get("anchor_name") or job.get("room_id") or "live")
url = str(job.get("source_url") or "")
title = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
if "#Shorts" not in title and "#shorts" not in title.lower():
title = f"{title} #Shorts"
result = await upload_shorts_mp4(
file_path=clip,
title=title,
description=desc,
privacy=str(channel.get("privacy") or "public"),
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
db.update_shorts_job(
jid,
status="uploaded",
youtube_video_id=str(result.get("video_id") or ""),
youtube_url=str(result.get("url") or ""),
error="",
finished_at=time.time(),
)
try:
db.add_event(
kind="ops",
level="info",
message=f"Shorts 已上传:{result.get('url')}",
room_id=str(job.get("room_id") or ""),
session_id=str(job.get("session_id") or ""),
anchor_name=anchor,
meta={"shorts_job_id": jid, "video_id": result.get("video_id")},
)
except Exception:
pass
shorts_pipeline = ShortsPipeline()