douyinWEB/backend/app/shorts_pipeline.py
eric 1112a4d055 Handle YouTube Video Uploads daily quota (429) with project budget and pause-until-reset.
Add shorts_yt_quota module, Shorts UI quota banner, overview tweaks (hide upcoming opens, align events panel height), Electron desktop client scaffold, and deploy scripts; update README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 02:04:44 -05:00

1146 lines
44 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Isolated Shorts pipeline — optional side path, never blocks Douyin monitor.
Enable only via settings.shorts_enabled=True.
- On-live edge enqueue (optional)
- Random sample from currently-live rooms (default on)
Same room is only used once per Beijing day per channel pool.
All public entrypoints swallow exceptions so callers (monitor) stay safe.
"""
from __future__ import annotations
import asyncio
import random
import time
from typing import Any, Optional
from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_yt_quota import (
detect_and_block_from_recent_errors,
pause_uploads_until_reset,
project_uploads_available,
reserve_yt_upload_slot,
yt_upload_budget,
)
from .timeutil import format_beijing, next_youtube_quota_reset_ts
from .timeutil import push_date_from_ts
def _room_tags(room: dict[str, Any]) -> list[str]:
tags = room.get("tags") or []
if isinstance(tags, str):
return [t.strip() for t in tags.split(",") if t.strip()]
return [str(t).strip() for t in tags if str(t).strip()]
def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
trigger = str(cfg.get("shorts_trigger") or "tagged").strip().lower()
tags = _room_tags(room)
if trigger == "all":
return True
if trigger == "favorite":
return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts"} for t in tags)
tag = str(cfg.get("shorts_tag") or "shorts").strip() or "shorts"
return tag in tags or "shorts" in tags
def _enqueue_job(
*,
session: dict[str, Any] | None,
room: dict[str, Any],
stream_url: str = "",
cfg: dict[str, Any] | None = None,
channel_pk: str = "",
) -> Optional[dict[str, Any]]:
"""Internal enqueue; never raises."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return None
room_id = str((session or {}).get("room_id") or room.get("room_id") or "")
if room_id.startswith("yt:"):
return None
day = push_date_from_ts(float((session or {}).get("started_at") or time.time()))
if settings.get("shorts_dedupe_room_day", True) and room_id and db.has_shorts_job_for_room_day(room_id, day):
return None
channel: 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)
if not channel:
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
job = db.create_shorts_job(
session_id=sid,
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
room_id=room_id,
source_url=str((session or {}).get("source_url") or room.get("url") or ""),
anchor_name=str(
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
),
stream_url=str(stream_url or ""),
channel_pk=str(channel["id"]),
push_date=day,
)
try:
db.add_event(
kind="ops",
level="info",
message=f"Shorts 任务已入队:{job.get('anchor_name') or room_id}",
room_id=room_id,
room_pk=str(room.get("id") or ""),
session_id=sid,
anchor_name=str(job.get("anchor_name") or ""),
meta={"shorts_job_id": job.get("id"), "channel_pk": channel.get("id")},
)
except Exception:
pass
return job
except Exception:
return None
def try_enqueue_on_live(
*,
session: dict[str, Any],
room: dict[str, Any],
stream_url: str = "",
) -> Optional[dict[str, Any]]:
"""Fire-and-forget safe: returns job or None; never raises."""
try:
cfg = db.get_settings_map()
if not cfg.get("shorts_enabled"):
return None
if not _room_eligible(room, cfg):
return None
return _enqueue_job(session=session, room=room, stream_url=stream_url, cfg=cfg)
except Exception:
return None
def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
"""Pick random currently-live rooms and enqueue (dedupe room/day). Returns enqueued count."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return 0
if not settings.get("shorts_live_sample", True):
return 0
day = push_date_from_ts(time.time())
if not db.pick_shorts_channel(day, 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 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 project_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]:
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)
if ok_flag == 0 or not str(ch.get("refresh_token") or "").strip():
oauth_issues.append(
{
"id": ch.get("id"),
"name": ch.get("name"),
"oauth_ok": ok_flag,
"oauth_error": ch.get("oauth_error") or ("未授权" if not str(ch.get("refresh_token") or "").strip() else ""),
"oauth_checked_at": ch.get("oauth_checked_at") or 0,
}
)
except Exception:
pass
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
try:
detected, detected_until = detect_and_block_from_recent_errors(cfg)
if detected:
quota_blocked = True
quota_until = max(quota_until, detected_until)
except Exception:
pass
if not quota_blocked and is_upload_quota_error(self.last_error):
quota_until = next_youtube_quota_reset_ts()
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": quota_until})
except Exception:
pass
quota_blocked = True
last_error = quota_error_message() if quota_blocked else self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg)
return {
"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(),
"upload_quota_blocked": quota_blocked,
"upload_quota_blocked_until": quota_until,
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"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": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"douyin_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)
],
"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,
}
async def start(self) -> None:
if self._task and not self._task.done():
return
try:
detect_and_block_from_recent_errors()
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 _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))
quota_blocked_loop, _ = self._upload_quota_blocked(cfg)
if (
not quota_blocked_loop
and 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:
retry_at = 0.0
quota_blocked_loop, quota_until_loop = self._upload_quota_blocked(cfg)
if quota_blocked_loop:
retry_at = quota_until_loop + 300
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, retry_at=retry_at)
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)
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
if not quota_blocked and not project_uploads_available(cfg):
quota_until = pause_uploads_until_reset(cfg)
quota_blocked = True
job: dict[str, Any] | None = None
runner: str = ""
if not quota_blocked and self._active_uploads < upload_max:
job = db.claim_due_shorts_upload()
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(3)
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 _upload_quota_blocked(self, cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
settings = cfg if cfg is not None else db.get_settings_map()
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
now = time.time()
if until <= now:
if until > 0:
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": 0})
except Exception:
pass
return False, 0.0
return True, until
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
until = pause_uploads_until_reset(reason=quota_error_message())
friendly = quota_error_message()
jid = str(job.get("id") or "")
if jid:
db.update_shorts_job(
jid,
status="scheduled",
error=friendly,
upload_at=until + 300,
finished_at=0,
)
self.last_error = friendly
self._emit_shorts_event(
kind="shorts_quota",
level="warn",
message=f"Shorts 上传配额用尽,已暂停至 {format_beijing(until)}(太平洋 0 点重置)",
job=job,
extra={"error": raw_error[:200], "blocked_until": until},
)
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
"""Return True if handled (quota deferral)."""
msg = str(exc)
if is_upload_quota_error(msg):
self._pause_uploads_for_quota(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()
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
if quota_blocked:
raise ValueError(f"{quota_error_message()} 预计 {format_beijing(quota_until)} 恢复。")
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):
raise ValueError(quota_error_message()) 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"])
cookie = str(cfg.get("dy_cookie") or "")
stream = await resolve_stream_url(
source_url=str(job.get("source_url") or ""),
stream_url=str(job.get("stream_url") or ""),
cookie=cookie,
)
if not stream:
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)
outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec)
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 "")
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"])
yt_id = str(job.get("youtube_video_id") or "").strip()
if yt_id:
db.update_shorts_job(
jid,
status="uploaded",
error="",
clip_path="",
finished_at=float(job.get("finished_at") or 0) or time.time(),
)
return
clip = str(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(job.get("channel_pk") or ""))
if not channel:
self._mark_failed(job, "频道不存在")
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(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(job.get("anchor_name") or job.get("room_id") or "live")
url = str(job.get("source_url") or "")
title = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
if "#Shorts" not in title and "#shorts" not in title.lower():
title = f"{title} #Shorts"
if not reserve_yt_upload_slot(cfg):
pause_uploads_until_reset(cfg)
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()}")
result = await upload_shorts_mp4(
file_path=clip,
title=title,
description=desc,
privacy=str(channel.get("privacy") or "public"),
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
db.update_shorts_job(
jid,
status="uploaded",
youtube_video_id=str(result.get("video_id") or ""),
youtube_url=str(result.get("url") or ""),
error="",
finished_at=time.time(),
clip_path="",
)
if cfg.get("shorts_delete_clip_after_upload", True):
self._delete_clip(clip)
yt_url = str(result.get("url") or "")
self._emit_shorts_event(
kind="shorts_ok",
level="info",
message=f"Shorts 已上传:{yt_url or result.get('video_id')}",
job=job,
extra={"video_id": result.get("video_id"), "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()