douyinWEB/backend/app/shorts_pipeline.py
eric 89e5ecc98b Add global daily min/max quota controls for Shorts, TikTok, yt-long, and X.
Operators can set defaults once and optionally sync all channel cards instead of editing each one.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 05:49:24 -05:00

1434 lines
56 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_candidates
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_socks import resolve_upload_socks_proxy
from .shorts_yt_quota import (
any_profile_uploads_available,
clear_all_upload_self_blocks,
clear_stale_quota_errors_for_open_profiles,
pause_uploads_until_reset,
profile_id_for_channel,
profile_id_for_job,
quota_budgets_by_profile,
reserve_yt_upload_slot,
yt_upload_budget,
)
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)
if "tiktok_only" in tags or "x_only" in tags:
return False
tag = str(cfg.get("shorts_tag") or "shorts").strip() or "shorts"
return tag in tags or "shorts" in tags or "both" in tags
def _enqueue_job(
*,
session: dict[str, Any] | None,
room: dict[str, Any],
stream_url: str = "",
cfg: dict[str, Any] | None = None,
channel_pk: str = "",
require_upload_quota: bool = True,
push_date: str = "",
require_channel: bool = True,
) -> 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(room.get("room_id") or (session or {}).get("room_id") or "")
if room_id.startswith("yt:"):
return None
day = str(push_date or "").strip() or push_date_from_ts(time.time())
# Global dedup: same room_id can only be enqueued ONCE per Beijing day across ALL channels
if settings.get("shorts_dedupe_room_day", True) and room_id:
if db.has_shorts_job_for_room_day(room_id, day):
return None
channel: dict[str, Any] | None = None
if channel_pk:
ch = db.get_shorts_channel(channel_pk)
if ch and ch.get("enabled"):
used = db.shorts_channel_upload_count(channel_pk, day)
daily_max = db.SHORTS_DAILY_FORCE
if used < daily_max:
channel = ch
if not channel:
channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota)
if require_channel and 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 or {}).get("id") or ""),
push_date=day,
)
if not job:
return None
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 or {}).get("id") or ""},
)
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, settings):
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, settings):
break
return enqueued
except Exception:
return 0
def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Manual sample from current Douyin lives; records even if YouTube upload quota is exhausted."""
settings = cfg or db.get_settings_map()
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
live_count = len(rooms)
empty: dict[str, Any] = {
"enqueued": 0,
"job_ids": [],
"live_count": live_count,
"skipped_dedupe": 0,
"reason": "",
}
if not settings.get("shorts_enabled"):
empty["reason"] = "请先启用 Shorts"
return empty
if live_count <= 0:
empty["reason"] = "当前没有抖音在播直播间"
return empty
day = push_date_from_ts(time.time())
any_live = settings.get("shorts_sample_any_live", True)
unused: list[dict[str, Any]] = []
skipped = 0
for room in rooms:
rid = str(room.get("room_id") or "")
if not rid:
continue
if not any_live and not _room_eligible(room, settings):
continue
if settings.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(rid, day):
skipped += 1
continue
unused.append(room)
if not unused:
empty["skipped_dedupe"] = skipped
empty["reason"] = f"在播 {live_count} 间均已今日取样"
return empty
batch = min(len(unused), 8)
random.shuffle(unused)
job_ids: list[str] = []
for room in unused[: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,
require_upload_quota=False,
push_date=day,
require_channel=False,
)
if job and job.get("id"):
job_ids.append(str(job["id"]))
return {
"enqueued": len(job_ids),
"job_ids": job_ids,
"live_count": live_count,
"skipped_dedupe": skipped,
"reason": "" if job_ids else "入队失败(可能已有同房间任务)",
}
def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
"""Enqueue live-room clips toward each channel's daily_max before Beijing midnight."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return 0
if not any_profile_uploads_available(settings):
return 0
day = push_date_from_ts(time.time())
gap_total = db.shorts_total_quota_gap(day)
if gap_total <= 0:
return 0
if not db.pick_shorts_channel(day, settings):
return 0
from .timeutil import beijing_day_bounds
day_start, day_end = beijing_day_bounds(day)
now = time.time()
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 9))
if day_progress > 0.55:
base_batch = max(base_batch, min(gap_total, 6))
if day_progress > 0.75:
base_batch = max(base_batch, min(gap_total, 10))
if day_progress > 0.88:
base_batch = max(base_batch, min(gap_total, 16))
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:
if enqueued >= base_batch:
break
if not db.pick_shorts_channel(day, settings):
break
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 ""))
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._active_records = 0
self._active_uploads = 0
self._last_sample_at = 0.0
self._last_quota_fill_at = 0.0
self._last_quota_alert_at = 0.0
self._last_oauth_check_at = 0.0
self._last_auto_retry_at = 0.0
self.last_error = ""
self.processed = 0
self.sampled = 0
self.quota_filled = 0
self.auto_retried = 0
def reset_counters(self) -> None:
self.processed = 0
self.sampled = 0
self.quota_filled = 0
def _maybe_alert_quota_behind(self, cfg: dict[str, Any]) -> None:
"""Throttle alert when enabled channels fall behind Beijing-day pace."""
if not cfg.get("notify_on_shorts_quota", True):
return
interval = max(900.0, float(cfg.get("shorts_quota_alert_interval_sec") or 1800))
now = time.time()
if (now - self._last_quota_alert_at) < interval:
return
from .shorts_schedule import schedule_board
board = schedule_board(limit=10)
behind = [
c
for c in (board.get("channels") or [])
if c.get("enabled") and c.get("behind_pace") and not c.get("min_met")
]
if not behind:
return
# Only alert after ~20% of Beijing day has passed
if float(board.get("day_progress") or 0) < 0.2:
return
self._last_quota_alert_at = now
names = "、".join(str(c.get("name") or "频道") for c in behind[:4])
more = f" 等 {len(behind)} 个" if len(behind) > 4 else ""
msg = f"Shorts 配额落后:{names}{more}(北京日进度 {int(float(board.get('day_progress') or 0) * 100)}%)"
try:
db.add_event(
kind="shorts_quota",
level="warn",
message=msg,
meta={
"behind_count": len(behind),
"channel_ids": [str(c.get("id") or "") for c in behind],
"push_date": board.get("push_date"),
"day_progress": board.get("day_progress"),
},
)
except Exception:
pass
try:
from .notify import send_webhook
asyncio.create_task(
send_webhook(
"shorts_quota",
{
"message": msg,
"behind_count": len(behind),
"push_date": board.get("push_date"),
},
)
)
except Exception:
pass
async def _probe_oauth(self, cfg: dict[str, Any]) -> None:
try:
from . import shorts_oauth
data = await shorts_oauth.probe_all_enabled_channels(cfg)
failed = int(data.get("failed") or 0)
if failed <= 0:
return
names = []
for r in data.get("results") or []:
if r.get("ok") or r.get("skipped"):
continue
ch = db.get_shorts_channel(str(r.get("channel_id") or ""))
names.append(str((ch or {}).get("name") or r.get("channel_id") or "频道"))
msg = f"Shorts OAuth 异常:{'、'.join(names[:4])}" + (f" 等 {failed} 个" if failed > 4 else "")
db.add_event(
kind="shorts_fail",
level="warn",
message=msg,
meta={"oauth_failed": failed, "channel_names": names},
)
try:
from .notify import send_webhook
asyncio.create_task(send_webhook("shorts_fail", {"message": msg, "oauth_failed": failed}))
except Exception:
pass
except Exception as exc:
self.last_error = f"OAuth 探测失败: {exc}"[:300]
def _auto_retry_failed(self, cfg: dict[str, Any]) -> int:
from pathlib import Path
from .shorts_schedule import pick_upload_at
max_att = int(cfg.get("shorts_auto_retry_max_attempts") or 3)
jobs = db.list_auto_retry_failed_jobs(max_attempts=max_att, limit=5)
n = 0
for job in jobs:
jid = str(job.get("id") or "")
if not jid:
continue
clip = str(job.get("clip_path") or "").strip()
try:
if clip and Path(clip).is_file():
upload_at = pick_upload_at(
channel_pk=str(job.get("channel_pk") or ""),
push_date=str(job.get("push_date") or ""),
cfg=cfg,
)
db.update_shorts_job(
jid,
status="scheduled",
error="",
finished_at=0,
youtube_video_id="",
youtube_url="",
upload_at=upload_at,
)
else:
db.update_shorts_job(
jid,
status="pending",
clip_path="",
clip_seconds=0,
error="自动重试:重新排队录制",
finished_at=0,
youtube_video_id="",
youtube_url="",
upload_at=0,
)
n += 1
except Exception:
continue
return n
@staticmethod
def _upload_max(cfg: dict[str, Any]) -> int:
explicit = int(cfg.get("shorts_upload_max_concurrent") or 0)
if explicit > 0:
return max(1, min(explicit, 5))
return max(2, int(cfg.get("shorts_max_concurrent") or 1))
@staticmethod
def _record_max(cfg: dict[str, Any]) -> int:
return max(1, int(cfg.get("shorts_max_concurrent") or 1))
def status(self) -> dict[str, Any]:
now = time.time()
cached = getattr(self, "_status_cache", None)
cache_at = float(getattr(self, "_status_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 2.0:
return cached
cfg = db.get_settings_map()
try:
stats = db.shorts_stats()
except Exception:
stats = {}
try:
history = db.shorts_stats_history(days=7)
except Exception:
history = {}
try:
failed_groups = db.shorts_failed_groups(limit=40)
except Exception:
failed_groups = {}
try:
channel_perf = db.shorts_channel_performance(days=7)
except Exception:
channel_perf = {}
try:
heatmap = db.shorts_upload_heatmap(days=1)
except Exception:
heatmap = {}
try:
from .shorts_schedule import schedule_board
board = schedule_board(limit=30)
except Exception:
board = {}
oauth_issues = []
try:
for ch in db.list_shorts_channels(enabled=True):
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
err = str(ch.get("oauth_error") or "")
has_rt = bool(str(ch.get("refresh_token") or "").strip())
if has_rt and "重授权中" in err:
continue
if not has_rt or ok_flag == 0:
oauth_issues.append(
{
"id": ch.get("id"),
"name": ch.get("name"),
"oauth_ok": ok_flag,
"oauth_error": err or ("未授权" if not has_rt else ""),
"oauth_checked_at": ch.get("oauth_checked_at") or 0,
}
)
except Exception:
pass
# Mutations belong in the worker loop / start(), not on every UI poll GET.
last_error = self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
live_rooms = []
try:
live_rooms = [
{
"room_id": r.get("room_id"),
"anchor": r.get("last_anchor") or r.get("last_title") or r.get("room_id"),
"session_id": r.get("active_session_id"),
}
for r in db.list_live_douyin_rooms_for_shorts(limit=12)
]
if live_count <= 0:
live_count = len(live_rooms)
except Exception:
pass
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"active_jobs": self._active_records + self._active_uploads,
"active_records": self._active_records,
"active_uploads": self._active_uploads,
"enabled": bool(cfg.get("shorts_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"quota_filled": self.quota_filled,
"auto_retried": self.auto_retried,
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
"quota_gap": db.shorts_total_quota_gap(),
"quota_defaults": db.shorts_quota_defaults(cfg),
# Informational only — never gates manual/worker uploads
"upload_quota_blocked": False,
"upload_quota_blocked_until": 0,
"upload_quota_blocked_profiles": [],
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"yt_quota_by_profile": yt_by_profile,
"last_error": 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)),
"douyin_live_count": live_count,
"douyin_live_rooms": live_rooms,
"upload_spread": bool(cfg.get("shorts_upload_spread", True)),
"upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or 720),
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400),
"max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)),
"upload_max_concurrent": self._upload_max(cfg),
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)),
"stats": stats,
"board": board,
"history": history,
"failed_groups": failed_groups,
"channel_perf": channel_perf,
"heatmap": heatmap,
"oauth_issues": oauth_issues,
}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
def status_light(self) -> dict[str, Any]:
"""Poll-friendly counters without schedule board / heatmap / history."""
now = time.time()
cached = getattr(self, "_status_light_cache", None)
cache_at = float(getattr(self, "_status_light_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 1.5:
return cached
cfg = db.get_settings_map()
try:
stats = db.shorts_stats()
except Exception:
stats = {}
oauth_issues = []
try:
for ch in db.list_shorts_channels(enabled=True):
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
err = str(ch.get("oauth_error") or "")
has_rt = bool(str(ch.get("refresh_token") or "").strip())
if has_rt and "重授权中" in err:
continue
if not has_rt or ok_flag == 0:
oauth_issues.append(
{
"id": ch.get("id"),
"name": ch.get("name"),
"oauth_ok": ok_flag,
"oauth_error": err or ("未授权" if not has_rt else ""),
"oauth_checked_at": ch.get("oauth_checked_at") or 0,
}
)
except Exception:
pass
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"active_jobs": self._active_records + self._active_uploads,
"active_records": self._active_records,
"active_uploads": self._active_uploads,
"enabled": bool(cfg.get("shorts_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"quota_filled": self.quota_filled,
"auto_retried": self.auto_retried,
"quota_gap": db.shorts_total_quota_gap(),
"upload_quota_blocked": False,
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"yt_quota_by_profile": yt_by_profile,
"last_error": self.last_error,
"douyin_live_count": live_count,
"stats": stats,
"oauth_issues": oauth_issues,
"light": True,
}
# Reuse heavy analytics from recent full status if still warm.
full = getattr(self, "_status_cache", None)
full_at = float(getattr(self, "_status_cache_at", 0) or 0)
if isinstance(full, dict) and (now - full_at) < 60:
for key in ("board", "history", "failed_groups", "channel_perf", "heatmap", "douyin_live_rooms"):
if key in full:
payload[key] = full[key]
self._status_light_cache = payload
self._status_light_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
return
try:
clear_all_upload_self_blocks()
clear_stale_quota_errors_for_open_profiles()
db.purge_orphan_shorts_jobs(limit=500)
db.dedupe_shorts_jobs_room_day()
except Exception:
pass
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 kick_pending_records(self, job_ids: list[str]) -> int:
ids = [str(j) for j in job_ids if str(j).strip()]
if not ids:
return 0
cfg = db.get_settings_map()
max_rec = self._record_max(cfg)
async def _drain() -> None:
leftover = list(ids)
while leftover:
while self._active_records >= max_rec:
await asyncio.sleep(0.25)
jid = leftover.pop(0)
job = db.claim_shorts_job_record(jid)
if not job:
continue
self._active_records += 1
asyncio.create_task(self._run_job(job, cfg))
asyncio.create_task(_drain())
return min(len(ids), max_rec)
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
try:
db.enforce_shorts_daily_force()
except Exception:
pass
# 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
quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120)
quota_interval = max(60.0, quota_interval)
if (time.time() - self._last_quota_fill_at) >= quota_interval:
self._last_quota_fill_at = time.time()
qn = try_fill_daily_quota(cfg)
if qn:
self.quota_filled += qn
try:
self._maybe_alert_quota_behind(cfg)
except Exception:
pass
oauth_interval = max(600.0, float(cfg.get("shorts_oauth_check_interval_sec") or 3600))
if (time.time() - self._last_oauth_check_at) >= oauth_interval:
self._last_oauth_check_at = time.time()
asyncio.create_task(self._probe_oauth(cfg))
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
# Auto-retry failed jobs even if some Clients are quota-blocked (skip happens at claim)
if cfg.get("shorts_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
self._last_auto_retry_at = time.time()
try:
n = self._auto_retry_failed(cfg)
if n:
self.auto_retried += n
except Exception:
pass
# Legacy recorded clips without upload_at → schedule irregularly
try:
self._backfill_schedules(cfg)
except Exception:
pass
try:
n = db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0)
if n:
self.last_error = ""
except Exception:
pass
try:
missing = db.reconcile_missing_shorts_clips(limit=80)
if missing:
self.last_error = ""
except Exception:
pass
try:
healed = db.reconcile_false_failed_shorts(limit=80)
if healed:
self.last_error = ""
except Exception:
pass
record_max = self._record_max(cfg)
upload_max = self._upload_max(cfg)
job: dict[str, Any] | None = None
runner: str = ""
if self._active_uploads < upload_max:
# Never skip profiles for local quota — YouTube API decides
job = db.claim_due_shorts_upload(skip_profile_ids=None)
if job:
runner = "upload"
if not job and self._active_records < record_max:
job = db.claim_pending_shorts_record()
if job:
runner = "record"
if not job:
await asyncio.sleep(2)
continue
if runner == "upload":
self._active_uploads += 1
asyncio.create_task(self._run_upload_only(job, cfg))
else:
self._active_records += 1
asyncio.create_task(self._run_job(job, cfg))
except asyncio.CancelledError:
break
except Exception as exc:
self.last_error = str(exc)[:300]
await asyncio.sleep(5)
async def _run_job(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
try:
await self._process(job, cfg)
self.processed += 1
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
str(job["id"]),
status="uploaded",
error="",
clip_path="",
)
return
self._requeue_missing_clip(job)
return
self.last_error = str(exc)[:300]
finally:
self._active_records = max(0, self._active_records - 1)
def _backfill_schedules(self, cfg: dict[str, Any]) -> None:
"""Move recorded/clip-ready jobs without a slot onto staggered schedule."""
if not cfg.get("shorts_auto_upload", True):
return
from .shorts_schedule import pick_upload_at
from .timeutil import beijing_day_bounds
day = push_date_from_ts(time.time())
_, day_end = beijing_day_bounds(day)
data = db.list_shorts_jobs(push_date=day, status="recorded", limit=50, offset=0)
for job in data.get("jobs") or []:
if float(job.get("upload_at") or 0) > 0 and str(job.get("status")) == "scheduled":
continue
if not str(job.get("clip_path") or "").strip():
continue
upload_at = pick_upload_at(
channel_pk=str(job.get("channel_pk") or ""),
push_date=str(job.get("push_date") or day),
cfg=cfg,
)
db.update_shorts_job(
str(job["id"]),
status="scheduled",
upload_at=upload_at,
error="",
)
data2 = db.list_shorts_jobs(push_date=day, status="scheduled", limit=80, offset=0)
for job in data2.get("jobs") or []:
ch_pk = str(job.get("channel_pk") or "")
upload_at = float(job.get("upload_at") or 0)
if not str(job.get("clip_path") or "").strip():
continue
if upload_at <= 0:
upload_at = pick_upload_at(
channel_pk=ch_pk,
push_date=str(job.get("push_date") or day),
cfg=cfg,
)
db.update_shorts_job(str(job["id"]), upload_at=upload_at)
continue
if upload_at >= day_end - 30:
upload_at = pick_upload_at(
channel_pk=ch_pk,
push_date=str(job.get("push_date") or day),
cfg=cfg,
)
db.update_shorts_job(str(job["id"]), upload_at=upload_at)
@staticmethod
def _emit_shorts_event(
*,
kind: str,
level: str,
message: str,
job: dict[str, Any],
extra: dict[str, Any] | None = None,
) -> None:
try:
meta = {"shorts_job_id": str(job.get("id") or ""), **(extra or {})}
db.add_event(
kind=kind,
level=level,
message=message,
room_id=str(job.get("room_id") or ""),
session_id=str(job.get("session_id") or ""),
anchor_name=str(job.get("anchor_name") or job.get("room_id") or ""),
meta=meta,
)
except Exception:
pass
try:
from .notify import send_webhook
asyncio.create_task(
send_webhook(
kind,
{
"message": message,
"job_id": str(job.get("id") or ""),
"anchor_name": str(job.get("anchor_name") or ""),
"room_id": str(job.get("room_id") or ""),
**(extra or {}),
},
)
)
except Exception:
pass
def _record_quota_api_feedback(self, job: dict[str, Any], raw_error: str) -> None:
"""Surface YouTube 429 on the job only — never self-pause the Client."""
pid = profile_id_for_job(job)
# Keep local counter in sync for UI; do not set blocked_until / defer siblings
pause_uploads_until_reset(profile_id=pid, reason="")
try:
from . import yt_long_db
# Shorts + yt-long share YouTube Data API → shrink long daily target to 4/ch
yt_long_db.mark_yt_long_api_limited(reason=str(raw_error or "")[:160])
yt_long_db.reconcile_yt_long_upload_caps()
except Exception:
pass
friendly = quota_error_message(pid)
# Prefer raw API body when present so operators see the real interface reply
api_snip = (raw_error or "").strip()
if api_snip and api_snip != friendly:
err_text = f"{friendly} | 接口:{api_snip[:280]}"
else:
err_text = friendly
jid = str(job.get("id") or "")
if jid:
db.update_shorts_job(
jid,
status="failed",
error=err_text[:400],
finished_at=time.time(),
)
self.last_error = err_text[:300]
self._emit_shorts_event(
kind="shorts_quota",
level="warn",
message=f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传)",
job=job,
extra={"error": raw_error[:200], "oauth_profile_id": pid},
)
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
"""Return True if handled as YouTube quota API feedback (no local pause)."""
msg = str(exc)
if is_upload_quota_error(msg):
self._record_quota_api_feedback(job, msg)
return True
return False
def _mark_failed(self, job: dict[str, Any], error: str) -> None:
jid = str(job["id"])
err = str(error or "失败")[:300]
self.last_error = err
db.update_shorts_job(jid, status="failed", error=err, finished_at=time.time())
anchor = str(job.get("anchor_name") or job.get("room_id") or "素材")
self._emit_shorts_event(
kind="shorts_fail",
level="error",
message=f"Shorts 失败:{anchor} — {err[:120]}",
job=job,
extra={"error": err},
)
@staticmethod
def _requeue_missing_clip(job: dict[str, Any], *, manual: bool = False) -> None:
"""Clip file gone — reset to pending for re-record."""
jid = str(job["id"])
db.update_shorts_job(
jid,
status="pending",
clip_path="",
clip_seconds=0,
upload_at=0,
error="成片已丢失,已重新排队录制",
finished_at=0,
)
if manual:
raise ValueError("成片文件已丢失,已重新入队录制,请稍后刷新")
async def _wait_upload_done(self, job_id: str, *, timeout_sec: float = 120.0) -> dict[str, Any] | None:
"""Poll until job leaves uploading (uploaded/failed/requeued)."""
deadline = time.time() + max(10.0, float(timeout_sec))
while time.time() < deadline:
job = db.get_shorts_job(job_id)
if not job:
return None
st = str(job.get("status") or "")
if st in {"uploaded", "done", "failed", "pending"}:
return job
if st != "uploading":
return job
await asyncio.sleep(1)
return db.get_shorts_job(job_id)
async def upload_job_now(self, job_id: str) -> dict[str, Any]:
"""Manually upload a recorded/scheduled clip immediately."""
from pathlib import Path
try:
db.reclaim_stale_shorts_uploads(max_age_sec=120)
db.reconcile_missing_shorts_clips(limit=50)
except Exception:
pass
job = db.get_shorts_job(job_id)
if not job:
raise ValueError("任务不存在")
clip = str(job.get("clip_path") or "").strip()
if not clip:
raise ValueError("尚未录制成片,无法上传")
if not Path(clip).is_file():
self._requeue_missing_clip(job, manual=True)
st = str(job.get("status") or "")
if st not in {"scheduled", "recorded", "uploading"}:
raise ValueError(f"状态 {st} 不可手动上传")
cfg = db.get_settings_map()
# No local quota gate — always attempt YouTube; show API feedback on failure
upload_max = self._upload_max(cfg)
if st == "uploading":
waited = await self._wait_upload_done(job_id, timeout_sec=120)
if waited:
wst = str(waited.get("status") or "")
if wst in {"uploaded", "done"}:
return waited
if wst == "failed":
raise ValueError(str(waited.get("error") or "上传失败"))
if wst == "pending":
raise ValueError(str(waited.get("error") or "成片已丢失,已重新排队录制"))
job = db.get_shorts_job(job_id) or job
st = str(job.get("status") or "")
if st == "uploaded":
return job
claimed = db.claim_shorts_job_manual_upload(job_id)
if not claimed:
if st == "uploading":
waited = await self._wait_upload_done(job_id, timeout_sec=90)
if waited and str(waited.get("status") or "") in {"uploaded", "done"}:
return waited
raise ValueError("任务已被其他进程占用或状态已变更")
if self._active_uploads >= upload_max:
wait_sec = 0
while self._active_uploads >= upload_max and wait_sec < 12:
await asyncio.sleep(1)
wait_sec += 1
if self._active_uploads >= upload_max:
db.update_shorts_job(
job_id,
status="scheduled",
upload_at=time.time(),
error="",
)
raise ValueError("上传队列繁忙,请 5 秒后重试")
self._active_uploads += 1
try:
await self._do_upload(claimed, cfg)
self.processed += 1
done = db.get_shorts_job(job_id) or claimed
if str(done.get("status") or "") not in {"uploaded", "done"}:
waited = await self._wait_upload_done(job_id, timeout_sec=15)
if waited:
done = waited
return done
except Exception as exc:
if self._handle_upload_error(claimed, exc):
done = db.get_shorts_job(job_id) or claimed
raise ValueError(str(done.get("error") or quota_error_message(profile_id_for_job(claimed)))) from exc
if "成片文件不存在" in str(exc):
refreshed = db.get_shorts_job(job_id) or claimed
if str(refreshed.get("youtube_video_id") or "").strip():
db.update_shorts_job(job_id, status="uploaded", error="", clip_path="")
return refreshed
self._requeue_missing_clip(claimed, manual=True)
self.last_error = str(exc)[:300]
self._mark_failed(claimed, self.last_error)
raise ValueError(self.last_error) from exc
finally:
self._active_uploads = max(0, self._active_uploads - 1)
async def _run_upload_only(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
try:
await self._do_upload(job, cfg)
self.processed += 1
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
str(job["id"]),
status="uploaded",
error="",
clip_path="",
)
return
self._requeue_missing_clip(job)
return
self._mark_failed(job, str(exc)[:300])
finally:
self._active_uploads = max(0, self._active_uploads - 1)
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 "")
# Only upload when claim already flipped to uploading (due slot)
if status == "uploading":
await self._do_upload(job, cfg)
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
str(job["id"]),
status="uploaded",
error="",
clip_path="",
)
return
self._requeue_missing_clip(job)
return
self._mark_failed(job, str(exc)[:300])
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
# Isolated companion: enqueue 9:16 long-form master (never raises into Shorts).
try:
from .yt_long_pipeline import try_enqueue_from_shorts
try_enqueue_from_shorts(job)
except Exception:
pass
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,
)
stream = candidates[0] if candidates else ""
if not stream:
err = str(job.get("error") or "")
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
db.update_shorts_job(
jid,
status="pending",
error="stream_retry:1",
stream_url="",
)
return
db.update_shorts_job(
jid,
status="failed",
error="无法获取直播流(可能已停播)",
finished_at=time.time(),
)
self._emit_shorts_event(
kind="shorts_fail",
level="error",
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — 无法获取直播流",
job=job,
extra={"error": "无法获取直播流(可能已停播)"},
)
return
sec = int(cfg.get("shorts_clip_sec") or 15)
try:
room_pk = str(job.get("room_pk") or "")
room = db.get_room(room_pk) if room_pk else None
if not room and job.get("room_id"):
# best-effort by room_id
for r in db.list_live_douyin_rooms_for_shorts(limit=500):
if str(r.get("room_id") or "") == str(job.get("room_id") or ""):
room = r
break
sec = db.room_clip_seconds(room, default=sec, platform="shorts")
except Exception:
pass
outcome = await record_clip(job_id=jid, stream_urls=candidates, seconds=sec)
stream = str(outcome.get("stream_url") or stream)
if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败")
db.update_shorts_job(
jid,
status="failed",
error=err,
stream_url=stream,
finished_at=time.time(),
)
self._emit_shorts_event(
kind="shorts_fail",
level="error",
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — {err[:80]}",
job=job,
extra={"error": err},
)
return
clip_path = str(outcome.get("path") or "")
try:
from .clip_quality import assert_clip_quality
assert_clip_quality(clip_path)
except ValueError as qerr:
db.update_shorts_job(
jid,
status="failed",
clip_path=clip_path,
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
error=str(qerr)[:500],
finished_at=time.time(),
)
self._emit_shorts_event(
kind="shorts_fail",
level="error",
message=f"Shorts 成片质量不合格:{job.get('anchor_name') or job.get('room_id') or jid} — {str(qerr)[:80]}",
job=job,
extra={"error": str(qerr)},
)
return
if not cfg.get("shorts_auto_upload", True):
db.update_shorts_job(
jid,
status="recorded",
clip_path=clip_path,
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
error="",
)
return
# Stagger upload across the day (default) — never burst immediately
from .shorts_schedule import pick_upload_at
upload_at = pick_upload_at(
channel_pk=str(job.get("channel_pk") or ""),
push_date=str(job.get("push_date") or ""),
cfg=cfg,
)
db.update_shorts_job(
jid,
status="scheduled",
clip_path=clip_path,
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
upload_at=upload_at,
error="",
)
async def _do_upload(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
from pathlib import Path
jid = str(job["id"])
# Re-read: refuse if already uploaded or lease lost (prevents duplicate YouTube inserts)
fresh = db.get_shorts_job(jid) or job
yt_id = str(fresh.get("youtube_video_id") or "").strip()
if yt_id:
db.update_shorts_job(
jid,
status="uploaded",
error="",
clip_path="",
finished_at=float(fresh.get("finished_at") or 0) or time.time(),
)
return
if str(fresh.get("status") or "") != "uploading":
return
if not db.touch_shorts_upload_lease(jid):
return
clip = str(fresh.get("clip_path") or job.get("clip_path") or "")
if not clip:
self._mark_failed(job, "无成片路径")
return
if not Path(clip).is_file():
raise ValueError("成片文件不存在,已重新排队录制")
channel = db.get_shorts_channel(str(fresh.get("channel_pk") or job.get("channel_pk") or ""))
if not channel:
channel = db.pick_shorts_channel(
str(fresh.get("push_date") or job.get("push_date") or ""),
cfg,
require_upload_quota=True,
)
if channel:
db.update_shorts_job(jid, channel_pk=str(channel["id"]))
if not channel:
db.update_shorts_job(
jid,
status="recorded",
error="成片已保留,待分配 Shorts 频道后再上传",
)
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="scheduled" if float(fresh.get("upload_at") or job.get("upload_at") or 0) else "recorded",
error="频道未授权 Google,已保留成片待上传",
)
return
title_tpl = str(channel.get("title_template") or "{anchor} #Shorts")
desc_tpl = str(channel.get("description_template") or "")
anchor = str(fresh.get("anchor_name") or job.get("anchor_name") or job.get("room_id") or "live")
url = str(fresh.get("source_url") or job.get("source_url") or "")
from . import caption_pool
picked = caption_pool.pick_caption(
"shorts",
custom=title_tpl,
anchor=anchor,
url=url,
room=str(fresh.get("room_id") or job.get("room_id") or ""),
)
title = str(picked.get("text") or "").strip() or 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"[:100]
pid = profile_id_for_channel(channel)
reserve_yt_upload_slot(cfg, profile_id=pid)
stop_hb = asyncio.Event()
async def _heartbeat() -> None:
while not stop_hb.is_set():
try:
await asyncio.wait_for(stop_hb.wait(), timeout=20.0)
break
except asyncio.TimeoutError:
if not db.touch_shorts_upload_lease(jid):
break
hb_task = asyncio.create_task(_heartbeat(), name=f"shorts-upload-hb-{jid[:8]}")
result: dict[str, Any] | None = None
try:
# Final gate right before Google API — never double-insert
if not db.touch_shorts_upload_lease(jid):
return
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"],
proxy_url=resolve_upload_socks_proxy(cfg),
)
finally:
stop_hb.set()
hb_task.cancel()
try:
await hb_task
except asyncio.CancelledError:
pass
except Exception:
pass
if not result:
return
vid = str(result.get("video_id") or "")
yt_url = str(result.get("url") or "")
won = db.finalize_shorts_upload(jid, youtube_video_id=vid, youtube_url=yt_url)
if not won:
# Peer already finalized — do not treat as failure; avoid deleting their state
return
if cfg.get("shorts_delete_clip_after_upload", True):
self._delete_clip(clip)
self._emit_shorts_event(
kind="shorts_ok",
level="info",
message=f"Shorts 已上传:{yt_url or vid}",
job=fresh,
extra={"video_id": vid, "youtube_url": yt_url},
)
@staticmethod
def _delete_clip(path: str) -> None:
try:
from pathlib import Path
p = Path(path)
if p.is_file():
p.unlink()
except Exception:
pass
shorts_pipeline = ShortsPipeline()