# -*- 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 .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_yt_long_copy(job: dict[str, Any], channel: dict[str, Any], cfg: dict[str, Any]) -> dict[str, str]: """Random SEO title + description (independent rolls; +1 channel custom each).""" from .yt_long_seo import pick_yt_long_seo title_tpl = str(cfg.get("yt_long_title_template") or channel.get("title_template") or "") desc_tpl = str(cfg.get("yt_long_description_template") or channel.get("description_template") or "") 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() picked = pick_yt_long_seo( title_custom=title_tpl, desc_custom=desc_tpl, anchor=anchor, room=room, url=url, ) return { "title": str(picked.get("title") or f"{anchor} street food")[:100], "description": str(picked.get("description") or "")[:4900], "title_source": str(picked.get("title_source") or ""), "description_source": str(picked.get("description_source") or ""), } def pick_yt_long_channel(cfg: dict[str, Any], push_date: str = "") -> dict[str, Any] | None: """Pick from isolated yt_long_channels that have OAuth refresh_token.""" day = push_date or push_date_from_ts(time.time()) channels = yt_long_db.list_yt_long_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_creds(ch, cfg) if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")): continue try: dmax = max(0, int(ch.get("daily_max") or 0)) except Exception: dmax = 0 used = yt_long_db.channel_quota_used(cid, day) if dmax > 0 and used >= dmax: continue scored.append((float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None scored.sort(key=lambda x: x[0]) return scored[0][1] def _channel_creds(channel: dict[str, Any], cfg: dict[str, Any]) -> dict[str, str]: """Resolve OAuth like Shorts, but never writes shorts_channels.""" from .shorts_oauth import get_oauth_profile, list_oauth_profiles refresh = str(channel.get("refresh_token") or "").strip() client_id = str(channel.get("client_id") or "").strip() client_secret = str(channel.get("client_secret") or "").strip() pid = str(channel.get("oauth_profile_id") or "").strip().upper() if pid: prof = get_oauth_profile(pid, cfg) if prof: if not client_id: client_id = str(prof.get("client_id") or "").strip() if not client_secret: client_secret = str(prof.get("client_secret") or "").strip() if not (client_id and client_secret): # fallback profile A / global — read-only for row in list_oauth_profiles(cfg, public=False): if row.get("id") == "A" and row.get("client_id") and row.get("client_secret"): client_id = client_id or str(row["client_id"]) client_secret = client_secret or str(row["client_secret"]) break if not (client_id and client_secret): client_id = client_id or str(cfg.get("shorts_oauth_client_id") or "").strip() client_secret = client_secret or str(cfg.get("shorts_oauth_client_secret") or "").strip() return {"client_id": client_id, "client_secret": client_secret, "refresh_token": refresh} def _emit(kind: str, level: str, message: str, job: dict[str, Any] | None = None, extra: dict | None = None) -> None: try: meta = dict(extra or {}) meta["module"] = "yt_long" if job: meta["job_id"] = job.get("id") meta["channel_pk"] = job.get("channel_pk") db.add_event( kind=kind, level=level, message=message, room_id=str((job or {}).get("room_id") or ""), room_pk=str((job or {}).get("room_pk") or ""), anchor_name=str((job or {}).get("anchor_name") or ""), meta=meta, ) except Exception: pass 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, ) try: yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) except Exception: pass _emit( "yt_long_ops", "info", f"长视频入队:{created.get('anchor_name') or room_id}", created, ) 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]} def _enqueue_from_room(room: dict[str, Any], cfg: dict[str, Any], push_date: str) -> str: channel = pick_yt_long_channel(cfg, push_date) if not channel: return "" rid = str(room.get("room_id") or "").strip() if not rid: return "" if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, push_date): return "" created = yt_long_db.create_yt_long_job( room_pk=str(room.get("id") or room.get("room_pk") or ""), room_id=rid, source_url=str(room.get("url") or room.get("source_url") or ""), anchor_name=str(room.get("last_anchor") or room.get("anchor_name") or ""), stream_url=str(room.get("stream_url") or ""), channel_pk=str(channel.get("id") or ""), push_date=push_date, ) try: yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) except Exception: pass jid = str(created.get("id") or "") if jid: _emit("yt_long_ops", "info", f"长视频取样入队:{created.get('anchor_name') or rid}", created) return jid def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: """Independent live sampling for long-form — does not touch Shorts jobs.""" try: settings = cfg or db.get_settings_map() if not settings.get("yt_long_enabled"): return 0 if not settings.get("yt_long_live_sample", True): return 0 if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: return 0 if not pick_yt_long_channel(settings): return 0 batch = max(1, min(5, int(settings.get("yt_long_live_sample_batch") or 1))) day = push_date_from_ts(time.time()) 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: continue if settings.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day): continue candidates.append(room) if not candidates: return 0 random.shuffle(candidates) enqueued = 0 for room in candidates: if enqueued >= batch: break if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: break if _enqueue_from_room(room, settings, day): enqueued += 1 return enqueued except Exception: return 0 def sample_live_now() -> dict[str, Any]: settings = db.get_settings_map() if not settings.get("yt_long_enabled"): return {"enqueued": 0, "live_count": 0, "reason": "disabled", "job_ids": []} try: yt_long_db.sync_channels_from_shorts() except Exception: pass patched = {**settings, "yt_long_live_sample": True} rooms = db.list_live_douyin_rooms_for_shorts(limit=400) day = push_date_from_ts(time.time()) skipped = 0 for room in rooms: rid = str(room.get("room_id") or "") if rid and patched.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day): skipped += 1 n = try_sample_live_rooms(patched) pending = yt_long_db.list_pending_yt_long_jobs(limit=20) reason = "" if n: reason = "ok" elif yt_long_db.yt_long_quota_gap(cfg=patched) <= 0: reason = "no_quota" elif not pick_yt_long_channel(patched): reason = "no_channel" elif skipped and skipped >= len(rooms) and len(rooms) > 0: reason = "all_deduped" elif not rooms: reason = "no_live" else: reason = "enqueue_failed" reason_zh = { "ok": "已入队", "disabled": "模块未启用", "no_quota": "今日全局配额已满", "no_channel": "没有可用已授权频道", "all_deduped": "今日在播房间均已入队,请等待排队任务录制", "no_live": "当前没有抖音在播源", "enqueue_failed": "入队失败", }.get(reason, reason) return { "enqueued": n, "live_count": len(rooms), "skipped_dedupe": skipped, "pending_jobs": len(pending), "job_ids": [str(j.get("id")) for j in pending], "reason": reason, "reason_zh": reason_zh, } def try_fill_daily_quota() -> dict[str, Any]: settings = db.get_settings_map() if not settings.get("yt_long_enabled"): return {"enqueued": 0, "gap": 0, "reason": "disabled"} try: yt_long_db.sync_channels_from_shorts() except Exception: pass gap = yt_long_db.yt_long_quota_gap(cfg=settings) if gap <= 0: return {"enqueued": 0, "gap": 0, "reason": "quota_full"} patched = {**settings, "yt_long_live_sample_batch": min(gap, 5), "yt_long_live_sample": True} total = 0 rounds = 0 while total < gap and rounds < 8: rounds += 1 n = try_sample_live_rooms(patched) if n <= 0: break total += n return {"enqueued": total, "gap": yt_long_db.yt_long_quota_gap(cfg=settings), "reason": "ok" if total else "no_candidates"} 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.sampled = 0 self.last_error = "" self._last_sample_at = 0.0 def status(self) -> dict[str, Any]: cfg = db.get_settings_map() day = push_date_from_ts(time.time()) try: yt_long_db.sync_channels_from_shorts() except Exception: pass try: board = yt_long_db.channel_board(day) except Exception: board = {"channels": [], "total_gap": 0, "push_date": day} 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, "sampled": self.sampled, "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), "board": board, "douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)), "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_live_sample": bool(cfg.get("yt_long_live_sample", True)), "yt_long_live_sample_interval_sec": int(cfg.get("yt_long_live_sample_interval_sec") or 180), "yt_long_live_sample_batch": int(cfg.get("yt_long_live_sample_batch") or 1), "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 kick_pending_records(self, ids: list[str] | None = None) -> int: cfg = db.get_settings_map() max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) try: yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=180) except Exception: pass db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") slots = max(0, max_rec - max(self._active_records, db_recording)) if slots <= 0: return 0 pending = yt_long_db.list_pending_yt_long_jobs(limit=20) if ids: want = {str(x) for x in ids} pending = [j for j in pending if str(j.get("id") or "") in want] n = 0 for job in pending: if n >= slots or self._active_records >= max_rec: break claimed = yt_long_db.claim_yt_long_job_record(str(job.get("id") or "")) if not claimed: continue self._active_records += 1 asyncio.create_task(self._run_record(claimed)) n += 1 return n 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 interval = max(60.0, float(cfg.get("yt_long_live_sample_interval_sec") or 180)) if cfg.get("yt_long_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 try: # Long clips are 3–8 min; reclaim orphans after ~10 min wall clock max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC) yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(600, max_clip + 120)) 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)) db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") # If DB has more recording rows than live tasks, they are orphans — force reclaim if db_recording > self._active_records: try: yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=90) db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") except Exception: pass while self._active_records < max_rec and db_recording < 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 db_recording += 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"): err = str(outcome.get("error") or "录制失败")[:500] yt_long_db.update_yt_long_job( jid, status="failed", error=err, stream_url=str(outcome.get("stream_url") or ""), finished_at=time.time(), ) _emit("yt_long_fail", "error", f"长视频录制失败:{job.get('anchor_name') or jid} — {err[:80]}", job) 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(), ) _emit( "yt_long_fail", "error", f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}", job, ) 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 = yt_long_db.get_yt_long_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="无可用长视频频道(请先在「长视频」页导入/创建频道)", ) return creds = _channel_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 copy = build_yt_long_copy(fresh, channel, cfg) title = copy["title"] description = copy["description"] 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, ) _emit( "yt_long_ok", "info", f"长视频已上传:{fresh.get('anchor_name') or jid} → {url}", fresh, {"youtube_url": url, "video_id": vid}, ) if cfg.get("yt_long_delete_clip_after_upload", True): try: Path(clip).unlink(missing_ok=True) except Exception: pass yt_long_pipeline = YtLongPipeline()