# -*- coding: utf-8 -*- """Isolated YouTube long-form (16:9) pipeline. Companion to Shorts: when Shorts records a room, optionally enqueue a 3–8 min landscape job. Never writes shorts_* / tiktok_* / x_clip_* tables. Default: disabled (yt_long_enabled=false) so online Shorts is untouched until an operator turns this on. """ from __future__ import annotations import asyncio import random import time from pathlib import Path from typing import Any from . import db from . import yt_long_db from .shorts_clip import resolve_stream_candidates from .shorts_oauth import channel_oauth_creds from .timeutil import push_date_from_ts from .yt_long_clip import record_landscape_clip from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC from .yt_long_upload import upload_youtube_long_mp4 def _rand_clip_sec(cfg: dict[str, Any]) -> int: try: lo = int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC) except Exception: lo = YT_LONG_MIN_SEC try: hi = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC) except Exception: hi = YT_LONG_MAX_SEC lo = max(YT_LONG_MIN_SEC, min(YT_LONG_MAX_SEC, lo)) hi = max(lo, min(YT_LONG_MAX_SEC, hi)) return random.randint(lo, hi) def _build_title(job: dict[str, Any], channel: dict[str, Any], cfg: dict[str, Any]) -> str: tpl = str( cfg.get("yt_long_title_template") or channel.get("title_template") or "{anchor} street food live" ) # Strip Shorts hashtags from inherited channel templates tpl = tpl.replace("#Shorts", "").replace("#shorts", "").strip() anchor = str(job.get("anchor_name") or job.get("room_id") or "live").strip() url = str(job.get("source_url") or "").strip() room = str(job.get("room_id") or "").strip() text = ( tpl.replace("{anchor}", anchor) .replace("{url}", url) .replace("{room}", room) .strip() ) return (text or f"{anchor} live")[:100] def _build_description(job: dict[str, Any], channel: dict[str, Any], cfg: dict[str, Any]) -> str: tpl = str( cfg.get("yt_long_description_template") or channel.get("description_template") or "{anchor}\n{url}" ) tpl = tpl.replace("#Shorts", "").replace("#shorts", "") anchor = str(job.get("anchor_name") or "").strip() url = str(job.get("source_url") or "").strip() return ( tpl.replace("{anchor}", anchor) .replace("{url}", url) .replace("{room}", str(job.get("room_id") or "")) .strip() )[:4900] def pick_yt_long_channel(cfg: dict[str, Any], push_date: str = "") -> dict[str, Any] | None: """Read-only pick from Shorts channels that have OAuth; own per-channel long-form quota.""" day = push_date or push_date_from_ts(time.time()) per_max = yt_long_db.yt_long_channel_daily_max(cfg) channels = db.list_shorts_channels(enabled=True) scored: list[tuple[float, dict[str, Any]]] = [] for ch in channels: cid = str(ch.get("id") or "") if not cid: continue creds = channel_oauth_creds(ch, cfg) if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")): continue used = yt_long_db.channel_quota_used(cid, day) if per_max > 0 and used >= per_max: continue scored.append((float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None scored.sort(key=lambda x: x[0]) # least recently assigned first return scored[0][1] def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]: """Safe companion enqueue. Never raises into Shorts. No-op when disabled.""" try: cfg = db.get_settings_map() if not cfg.get("yt_long_enabled"): return {"enqueued": False, "reason": "disabled"} if not cfg.get("yt_long_with_shorts", True): return {"enqueued": False, "reason": "with_shorts_off"} if yt_long_db.yt_long_quota_gap(cfg=cfg) <= 0: return {"enqueued": False, "reason": "quota_full"} room_id = str(job.get("room_id") or "").strip() day = str(job.get("push_date") or push_date_from_ts(time.time())) if cfg.get("yt_long_dedupe_room_day", True) and room_id and yt_long_db.has_job_for_room_day(room_id, day): return {"enqueued": False, "reason": "room_dedupe"} channel = pick_yt_long_channel(cfg, day) if not channel: return {"enqueued": False, "reason": "no_channel"} created = yt_long_db.create_yt_long_job( room_pk=str(job.get("room_pk") or ""), room_id=room_id, source_url=str(job.get("source_url") or ""), anchor_name=str(job.get("anchor_name") or ""), stream_url=str(job.get("stream_url") or ""), channel_pk=str(channel.get("id") or ""), shorts_job_id=str(job.get("id") or ""), push_date=day, ) return {"enqueued": True, "job_id": created.get("id"), "channel_pk": channel.get("id")} except Exception as exc: return {"enqueued": False, "reason": "error", "error": str(exc)[:200]} class YtLongPipeline: def __init__(self) -> None: self._task: asyncio.Task[None] | None = None self._stop = asyncio.Event() self._active_records = 0 self._active_uploads = 0 self.processed = 0 self.last_error = "" def status(self) -> dict[str, Any]: cfg = db.get_settings_map() day = push_date_from_ts(time.time()) return { "running": bool(self._task and not self._task.done()), "busy": self._active_records > 0 or self._active_uploads > 0, "enabled": bool(cfg.get("yt_long_enabled")), "processed": self.processed, "quota_gap": yt_long_db.yt_long_quota_gap(day, cfg), "quota_used": yt_long_db.yt_long_quota_used(day), "daily_max": yt_long_db.yt_long_daily_max(cfg), "channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "last_error": self.last_error, "stats": yt_long_db.yt_long_stats(day), "settings": { "yt_long_enabled": bool(cfg.get("yt_long_enabled")), "yt_long_with_shorts": bool(cfg.get("yt_long_with_shorts", True)), "yt_long_auto_upload": bool(cfg.get("yt_long_auto_upload", True)), "yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg), "yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "yt_long_min_sec": int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC), "yt_long_max_sec": int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC), "yt_long_dedupe_room_day": bool(cfg.get("yt_long_dedupe_room_day", True)), "yt_long_title_template": str(cfg.get("yt_long_title_template") or ""), "yt_long_description_template": str(cfg.get("yt_long_description_template") or ""), "yt_long_delete_clip_after_upload": bool( cfg.get("yt_long_delete_clip_after_upload", True) ), "yt_long_upload_min_gap_sec": int(cfg.get("yt_long_upload_min_gap_sec") or 900), }, } 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="yt-long-pipeline") async def stop(self) -> None: self._stop.set() t = self._task if t: try: await asyncio.wait_for(t, timeout=8) except Exception: t.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("yt_long_enabled"): await asyncio.sleep(5) continue try: yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=900) except Exception: pass try: yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800) except Exception: pass max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) while self._active_records < max_rec: pending = yt_long_db.list_pending_yt_long_jobs(limit=1) if not pending: break job = yt_long_db.claim_yt_long_job_record(str(pending[0].get("id") or "")) if not job: break self._active_records += 1 asyncio.create_task(self._run_record(job)) if cfg.get("yt_long_auto_upload", True): max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) while self._active_uploads < max_up: job = yt_long_db.claim_due_yt_long_upload() if not job: break self._active_uploads += 1 asyncio.create_task(self._run_upload(job)) except Exception as exc: self.last_error = str(exc)[:240] await asyncio.sleep(3.0) async def _run_record(self, job: dict[str, Any]) -> None: try: await self._do_record(job) self.processed += 1 except Exception as exc: self.last_error = str(exc)[:240] yt_long_db.update_yt_long_job( str(job.get("id") or ""), status="failed", error=str(exc)[:500], finished_at=time.time(), ) finally: self._active_records = max(0, self._active_records - 1) async def _do_record(self, job: dict[str, Any]) -> None: cfg = db.get_settings_map() jid = str(job.get("id") or "") cookie = str(cfg.get("dy_cookie") or "") candidates = await resolve_stream_candidates( source_url=str(job.get("source_url") or ""), stream_url=str(job.get("stream_url") or ""), cookie=cookie, prefer_fresh=True, max_candidates=8, ) if not candidates: yt_long_db.update_yt_long_job( jid, status="failed", error="无法获取直播流", finished_at=time.time(), ) return sec = _rand_clip_sec(cfg) outcome = await record_landscape_clip(job_id=jid, stream_urls=candidates, seconds=sec) if not outcome.get("ok"): yt_long_db.update_yt_long_job( jid, status="failed", error=str(outcome.get("error") or "录制失败")[:500], stream_url=str(outcome.get("stream_url") or ""), finished_at=time.time(), ) return clip_path = str(outcome.get("path") or "") gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) upload_at = time.time() + random.uniform(30, gap) if not cfg.get("yt_long_auto_upload", True): yt_long_db.update_yt_long_job( jid, status="recorded", clip_path=clip_path, clip_seconds=float(outcome.get("seconds") or sec), stream_url=str(outcome.get("stream_url") or ""), error="", ) return yt_long_db.update_yt_long_job( jid, status="scheduled", clip_path=clip_path, clip_seconds=float(outcome.get("seconds") or sec), stream_url=str(outcome.get("stream_url") or ""), upload_at=upload_at, error="", ) async def _run_upload(self, job: dict[str, Any]) -> None: try: await self._do_upload(job) except Exception as exc: self.last_error = str(exc)[:240] yt_long_db.update_yt_long_job( str(job.get("id") or ""), status="failed", error=str(exc)[:500], finished_at=time.time(), ) finally: self._active_uploads = max(0, self._active_uploads - 1) async def _do_upload(self, job: dict[str, Any]) -> None: cfg = db.get_settings_map() jid = str(job.get("id") or "") fresh = yt_long_db.get_yt_long_job(jid) or job if str(fresh.get("youtube_video_id") or "").strip(): yt_long_db.update_yt_long_job( jid, status="uploaded", finished_at=time.time(), error="", ) return clip = str(fresh.get("clip_path") or "") if not clip or not Path(clip).is_file(): raise ValueError("成片文件不存在") channel = db.get_shorts_channel(str(fresh.get("channel_pk") or "")) if not channel: channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or "")) if channel: yt_long_db.update_yt_long_job(jid, channel_pk=str(channel["id"])) if not channel: yt_long_db.update_yt_long_job( jid, status="recorded", error="无可用 YouTube 频道(需 Shorts 频道已授权)", ) return creds = channel_oauth_creds(channel, cfg) if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]): yt_long_db.update_yt_long_job( jid, status="scheduled", error="频道未授权 Google", ) return title = _build_title(fresh, channel, cfg) description = _build_description(fresh, channel, cfg) privacy = str(channel.get("privacy") or "public") proxy = "" try: from .shorts_socks import resolve_upload_socks_proxy proxy = resolve_upload_socks_proxy(cfg) or "" except Exception: proxy = "" result = await upload_youtube_long_mp4( file_path=clip, title=title, description=description, privacy=privacy, client_id=str(creds["client_id"]), client_secret=str(creds["client_secret"]), refresh_token=str(creds["refresh_token"]), proxy_url=proxy, ) vid = str(result.get("video_id") or "") url = str(result.get("url") or "") yt_long_db.update_yt_long_job( jid, status="uploaded", youtube_video_id=vid, youtube_url=url, title=title, description=description, error="", finished_at=time.time(), clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip, ) if cfg.get("yt_long_delete_clip_after_upload", True): try: Path(clip).unlink(missing_ok=True) except Exception: pass yt_long_pipeline = YtLongPipeline()