douyinWEB/backend/app/yt_long_pipeline.py
2026-08-21 07:57:52 -05:00

895 lines
37 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 YouTube long-form (default 9:16) pipeline.
Records 3–8 min masters; optionally cascades cuts to TikTok / Shorts / X
via clip_cascade (each platform keeps its own tables and quotas).
Default: disabled (yt_long_enabled=false) 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_long_clip
from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC
from .yt_long_monetize import ensure_ypp_and_monetize
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
# Channel template wins; global settings only as fallback when channel is empty
title_tpl = str(channel.get("title_template") or cfg.get("yt_long_title_template") or "").strip()
desc_tpl = str(channel.get("description_template") or cfg.get("yt_long_description_template") or "").strip()
# Ignore legacy global placeholders so the 100 SEO pool is used by default
if title_tpl in {"{anchor} street food live", "{anchor}"}:
title_tpl = ""
if desc_tpl in {"{anchor}\n{url}", "{anchor}\n{url}\n#StreetFood #Live"}:
desc_tpl = ""
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)
# daily_max <= 0 means closed for new assigns (not unlimited)
if dmax <= 0 or 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_source_gap(cfg=cfg) <= 0:
return {"enqueued": False, "reason": "source_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 only required when we still have YouTube upload slots
channel = pick_yt_long_channel(cfg, day) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None
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 or {}).get("id") or ""),
shorts_job_id=str(job.get("id") or ""),
push_date=day,
)
if channel:
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 or {}).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:
rid = str(room.get("room_id") or "").strip()
if not rid:
return ""
need_upload = yt_long_db.yt_long_upload_gap(cfg=cfg) > 0
if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.room_blocks_yt_long_sample(
rid, push_date, need_upload_slots=need_upload
):
return ""
channel = pick_yt_long_channel(cfg, push_date) if need_upload else None
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 or {}).get("id") or ""),
push_date=push_date,
)
# create() may return an already-finished job; only count real pending work
if str(created.get("status") or "") != "pending":
return ""
jid = str(created.get("id") or "")
if channel:
try:
yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time())
except Exception:
pass
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_source_gap(cfg=settings) <= 0:
return 0
upload_gap = yt_long_db.yt_long_upload_gap(cfg=settings)
need_upload = upload_gap > 0
# Catch up faster when YouTube long slots remain
base_batch = max(1, min(8, int(settings.get("yt_long_live_sample_batch") or 1)))
batch = max(base_batch, min(8, upload_gap)) if need_upload else base_batch
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.room_blocks_yt_long_sample(
rid, day, need_upload_slots=need_upload
):
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_source_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
try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(settings)
settings = db.get_settings_map()
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())
need_upload = yt_long_db.yt_long_upload_gap(cfg=patched) > 0
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.room_blocks_yt_long_sample(
rid, day, need_upload_slots=need_upload
):
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_source_gap(cfg=patched) <= 0:
reason = "no_quota"
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": "今日母片配额已满",
"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,
"source_gap": yt_long_db.yt_long_source_gap(cfg=patched),
"upload_gap": yt_long_db.yt_long_upload_gap(cfg=patched),
}
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
try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(settings)
settings = db.get_settings_map()
except Exception:
pass
gap = yt_long_db.yt_long_source_gap(cfg=settings)
if gap <= 0:
return {"enqueued": 0, "gap": 0, "reason": "quota_full"}
patched = {**settings, "yt_long_live_sample_batch": min(gap, 8), "yt_long_live_sample": True}
# Prefer filling YouTube upload gap when source still has room
upload_gap = yt_long_db.yt_long_upload_gap(cfg=settings)
if upload_gap > 0:
patched["yt_long_live_sample_batch"] = max(
int(patched["yt_long_live_sample_batch"]), min(8, upload_gap)
)
total = 0
rounds = 0
while total < max(gap, upload_gap) and rounds < 12:
rounds += 1
n = try_sample_live_rooms(patched)
if n <= 0:
break
total += n
return {
"enqueued": total,
"gap": yt_long_db.yt_long_source_gap(cfg=settings),
"upload_gap": yt_long_db.yt_long_upload_gap(cfg=settings),
"pending": len(yt_long_db.list_pending_yt_long_jobs(limit=50)),
"reason": "ok" if total else "no_candidates",
"reason_zh": "已重新入队待录" if total else "当前没有可取样的在播源",
}
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
self._last_retention_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:
yt_long_db.reconcile_yt_long_upload_caps(cfg)
cfg = db.get_settings_map()
except Exception:
pass
try:
board = yt_long_db.channel_board(day)
except Exception:
board = {"channels": [], "total_gap": 0, "push_date": day}
cascade_need: dict[str, Any] = {}
try:
from .clip_cascade import estimate_platform_daily_need, ensure_source_covers_platforms
ensure_source_covers_platforms(cfg)
cfg = db.get_settings_map()
cascade_need = estimate_platform_daily_need(cfg)
except Exception:
cascade_need = {}
limited = yt_long_db.youtube_api_upload_limited(cfg)
effective_ch = yt_long_db.effective_yt_long_channel_daily_max(cfg)
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_upload_gap(day, cfg),
"quota_used": yt_long_db.yt_long_upload_used(day),
"daily_max": yt_long_db.yt_long_daily_max(cfg),
"source_gap": yt_long_db.yt_long_source_gap(day, cfg),
"source_used": yt_long_db.yt_long_source_used(day),
"source_daily_max": yt_long_db.yt_long_source_daily_max(cfg),
"upload_gap": yt_long_db.yt_long_upload_gap(day, cfg),
"upload_used": yt_long_db.yt_long_upload_used(day),
"channel_daily_max": effective_ch,
"channel_daily_max_normal": yt_long_db.YT_LONG_CHANNEL_DEFAULT,
"api_quota_limited": limited,
"last_error": self.last_error,
"stats": yt_long_db.yt_long_stats(day),
"board": board,
"cascade_need": cascade_need,
"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_source_daily_max": yt_long_db.yt_long_source_daily_max(cfg),
"yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg),
"yt_long_channel_daily_effective": effective_ch,
"yt_long_api_quota_limited": limited,
"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),
"yt_long_landscape_16x9": bool(cfg.get("yt_long_landscape_16x9", False)),
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
"yt_long_monetize_when_ypp": bool(cfg.get("yt_long_monetize_when_ypp", True)),
"clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 24),
"clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 12),
},
}
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))
# Never reclaim active long recordings here (3–8 min + encode); loop handles orphans safely
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
try:
yt_long_db.reconcile_yt_long_upload_caps(cfg)
cfg = db.get_settings_map()
except Exception:
pass
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()
try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(cfg)
cfg = db.get_settings_map()
except Exception:
pass
n = try_sample_live_rooms(cfg)
if n:
self.sampled += n
try:
# Long clips are 3–8 min (+ ffmpeg slack); reclaim only true orphans
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(720, max_clip + 240))
except Exception:
pass
try:
yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800)
except Exception:
pass
if (time.time() - self._last_retention_at) >= 600:
self._last_retention_at = time.time()
try:
from .clip_retention import purge_stale_clips
purge_stale_clips(cfg)
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")
# Soft-skip leftover pending when master (source) quota is full
try:
from .timeutil import push_date_from_ts as _pday
smax = yt_long_db.yt_long_source_daily_max(cfg)
day = _pday(time.time())
if smax > 0 and yt_long_db.yt_long_source_used(day) >= smax:
for pj in yt_long_db.list_pending_yt_long_jobs(limit=30):
yt_long_db.update_yt_long_job(
str(pj.get("id") or ""),
status="skipped",
error="source_quota_full",
finished_at=time.time(),
)
except Exception:
pass
# Promote cascade-only masters into YouTube upload slots when available
try:
ugap = yt_long_db.yt_long_upload_gap(cfg=cfg)
if ugap > 0 and cfg.get("yt_long_auto_upload", True):
for cj in yt_long_db.list_cascade_only_ready(limit=min(10, ugap)):
if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0:
break
ch = pick_yt_long_channel(cfg, str(cj.get("push_date") or ""))
if not ch:
break
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
yt_long_db.update_yt_long_job(
str(cj.get("id") or ""),
status="scheduled",
channel_pk=str(ch["id"]),
upload_at=time.time() + random.uniform(20, gap),
error="",
)
try:
yt_long_db.update_yt_long_channel(str(ch["id"]), last_assigned_at=time.time())
except Exception:
pass
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
try:
from .clip_retention import disk_ok_for_record, purge_stale_clips
ok_disk, free_gb = disk_ok_for_record(cfg)
if not ok_disk:
purge_stale_clips(cfg)
ok_disk, free_gb = disk_ok_for_record(cfg)
if not ok_disk:
yt_long_db.update_yt_long_job(
jid,
status="pending",
error=f"disk_low:{free_gb:.1f}GB",
started_at=0,
)
return
except Exception:
pass
sec = _rand_clip_sec(cfg)
# Prefer shorter masters when disk is getting tight (<16GB free)
try:
from .clip_retention import disk_free_gb
if disk_free_gb() < 16.0:
sec = min(sec, max(YT_LONG_MIN_SEC, int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC) + 60))
except Exception:
pass
outcome = await record_long_clip(job_id=jid, stream_urls=candidates, seconds=sec, cfg=cfg)
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 "")
fresh_base = {
**job,
"clip_path": clip_path,
"clip_seconds": float(outcome.get("seconds") or sec),
"stream_url": str(outcome.get("stream_url") or ""),
}
# Always cascade first (TikTok / Shorts / X reuse this master)
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="",
)
fresh = yt_long_db.get_yt_long_job(jid) or fresh_base
try:
from .clip_cascade import cascade_from_yt_long
await cascade_from_yt_long(fresh, cfg)
except Exception:
pass
if not cfg.get("yt_long_auto_upload", True):
return
def _drop_master_after_cascade() -> None:
"""Cascade-only masters are not uploaded to YT — free disk ASAP."""
try:
from .clip_retention import unlink_clip
unlink_clip(clip_path, clear_refs=True)
except Exception:
pass
# Only schedule YouTube long upload when upload quota remains
if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0:
yt_long_db.update_yt_long_job(
jid,
status="recorded",
error="cascade_only:当日上传名额已满,只做了切片,未传YouTube",
upload_at=0,
clip_path="",
)
_drop_master_after_cascade()
return
channel = None
if str(fresh.get("channel_pk") or "").strip():
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 not channel:
yt_long_db.update_yt_long_job(
jid,
status="recorded",
error="cascade_only:当日上传名额已满,只做了切片,未传YouTube",
upload_at=0,
clip_path="",
)
_drop_master_after_cascade()
return
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
upload_at = time.time() + random.uniform(30, gap)
yt_long_db.update_yt_long_job(
jid,
status="scheduled",
channel_pk=str(channel["id"]),
upload_at=upload_at,
error="",
)
try:
yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time())
except Exception:
pass
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]
msg = str(exc)
if "QUOTA_EXCEEDED" in msg or "quotaExceeded" in msg:
try:
from .shorts_yt_quota import pause_uploads_until_reset, profile_id_for_channel
ch = yt_long_db.get_yt_long_channel(str(job.get("channel_pk") or ""))
pid = profile_id_for_channel(ch) if ch else "A"
pause_uploads_until_reset(profile_id=pid, reason=msg[:160])
yt_long_db.mark_yt_long_api_limited(reason=msg[:160])
yt_long_db.reconcile_yt_long_upload_caps()
except Exception:
pass
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",
upload_at=time.time() + 1800,
error="频道未授权 Google(已延后 30 分钟再试)",
)
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 "")
monetize_note = ""
if cfg.get("yt_long_monetize_when_ypp", True) and vid:
try:
mon = await ensure_ypp_and_monetize(
client_id=str(creds["client_id"]),
client_secret=str(creds["client_secret"]),
refresh_token=str(creds["refresh_token"]),
video_id=vid,
channel_row=channel,
proxy_url=proxy,
)
if mon.get("monetized"):
monetize_note = "ypp_monetize_on"
elif mon.get("skipped"):
monetize_note = f"ypp_skip:{mon.get('skipped')}"
elif mon.get("monetize_error") or mon.get("error"):
monetize_note = f"ypp_monetize_fail:{(mon.get('monetize_error') or mon.get('error') or '')[:120]}"
except Exception as exc:
monetize_note = f"ypp_monetize_err:{str(exc)[:120]}"
yt_long_db.update_yt_long_job(
jid,
status="uploaded",
youtube_video_id=vid,
youtube_url=url,
title=title,
description=description,
error=monetize_note,
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}"
+ (f"({monetize_note})" if monetize_note else ""),
fresh,
{"youtube_url": url, "video_id": vid, "monetize": monetize_note},
)
if cfg.get("yt_long_delete_clip_after_upload", True):
try:
from .clip_retention import unlink_clip
unlink_clip(clip, clear_refs=False)
except Exception:
try:
Path(clip).unlink(missing_ok=True)
except Exception:
pass
yt_long_pipeline = YtLongPipeline()