# -*- coding: utf-8 -*- """Isolated Shorts pipeline — optional side path, never blocks Douyin monitor. Enable only via settings.shorts_enabled=True. Live-clip upload rules: 1. Different channels MAY share one Douyin live room; each gets a distinct clip_offset window (0–15s / 15–30s / …) so materials are never identical. 2. Same channel cannot reuse the same room twice per Beijing day. 3. Same channel uploads spaced >10 minutes (hard floor). 4. Within Beijing calendar day, aggressively fill until daily_min is met. - On-live edge enqueue (optional) - Random sample from currently-live rooms (default on) - Quota fill toward daily_min first, then daily_max """ from __future__ import annotations import asyncio import random import threading 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, blocked_profile_ids, clear_all_upload_self_blocks, clear_stale_quota_errors_for_open_profiles, 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 from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota from .shorts_schedule import CHANNEL_GAP_FLOOR_SEC 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 _is_offline_stream_error(err: str) -> bool: e = str(err or "") low = e.lower() if "无法获取直播流" in e or "已停播" in e: return True if "probe 404" in low or "server returned 404" in low: return True if "connection timed out" in low and ("opening input" in low or "http" in low): return True return False def _live_room_map() -> dict[str, dict[str, Any]]: out: dict[str, dict[str, Any]] = {} try: for r in db.list_live_douyin_rooms_for_shorts(limit=500): rid = str(r.get("room_id") or "").strip() if rid: out[rid] = r except Exception: return {} return out def _try_rebind_shorts_job_to_live(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> bool: """If job's room is offline, point it at another live room for the same channel.""" jid = str(job.get("id") or "") ch_id = str(job.get("channel_pk") or "") day = str(job.get("push_date") or push_date_from_ts(time.time())) old_rid = str(job.get("room_id") or "") if not jid or not ch_id: return False live = _live_room_map() if old_rid and old_rid in live: return False settings = cfg or db.get_settings_map() clip_sec = int(settings.get("shorts_clip_sec") or 15) for room in live.values(): new_rid = str(room.get("room_id") or "") if not new_rid or new_rid == old_rid: continue if db.has_shorts_job_for_room_day(new_rid, day, ch_id): continue try: clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts") except Exception: pass offset = db.next_shorts_room_clip_offset(new_rid, day, clip_sec=clip_sec) sid = str(room.get("active_session_id") or "") session = db.get_session(sid) if sid else None db.update_shorts_job( jid, status="pending", room_id=new_rid, room_pk=str(room.get("id") or ""), session_id=sid, 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="", clip_path="", clip_seconds=0, clip_offset_sec=offset, error="rebind:1 原直播间已停播,已换源重录", finished_at=0, upload_at=0, youtube_video_id="", youtube_url="", ) return True return False def _skip_offline_shorts_job(job: dict[str, Any], *, reason: str = "直播间已停播,已释放当日名额") -> None: db.update_shorts_job( str(job["id"]), status="skipped", error=reason, stream_url="", clip_path="", finished_at=time.time(), upload_at=0, ) def skip_or_rebind_offline_pending(cfg: dict[str, Any] | None = None, *, limit: int = 40) -> dict[str, int]: """Pending jobs whose rooms left live map → rebind or skip (free pipeline).""" settings = cfg or db.get_settings_map() day = push_date_from_ts(time.time()) live = _live_room_map() data = db.list_shorts_jobs(push_date=day, status="pending", limit=max(1, min(limit, 120)), offset=0) rebound = 0 skipped = 0 for job in data.get("jobs") or []: rid = str(job.get("room_id") or "") if rid and rid in live: continue if _try_rebind_shorts_job_to_live(job, settings): rebound += 1 else: _skip_offline_shorts_job(job) skipped += 1 return {"rebound": rebound, "skipped": skipped} 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()) # Legacy global room-day lock (off by default). Prefer channel-scoped uniqueness # so multiple channels can share one live room with distinct clip offsets. dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) if dedupe_global 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") and db.shorts_channel_oauth_ready(ch): used = db.shorts_channel_upload_count(channel_pk, day) uploaded = db.shorts_channel_uploaded_count(channel_pk, day) daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE) if daily_max < daily_min: daily_max = daily_min if used < daily_max and uploaded < 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 # Same channel + same room today is OK when clip offsets differ (create_shorts_job # dedupes on room+channel+offset). Only hard-skip when global room-day lock is on. ch_id = str((channel or {}).get("id") or "") clip_sec = int(settings.get("shorts_clip_sec") or 15) try: clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts") except Exception: pass offset = 0 if room_id and not dedupe_global: offset = db.next_shorts_room_clip_offset(room_id, day, clip_sec=clip_sec) 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=ch_id, push_date=day, clip_offset_sec=offset, dedupe_room_global=dedupe_global, ) 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 currently-live rooms and enqueue. Same room may feed multiple channels with distinct clip offsets unless shorts_dedupe_room_day is on. Recording does **not** require YouTube Data API upload quota — only the upload worker respects profile blocks. Otherwise a Gmail quota burn stops 待录 forever while 缺 N stays high. """ 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 # Uploads frozen → do not keep enqueueing samples into scheduled. if ShortsPipeline._all_channel_profiles_upload_blocked(settings): return 0 day = push_date_from_ts(time.time()) # Pipeline room left (pending→done), ignore upload API self-blocks. if not db.pick_shorts_channel(day, settings, require_upload_quota=False): 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) dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) used = db.room_ids_with_shorts_job_today(day) if dedupe_global else set() 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 # Prefer rooms with fewer Shorts jobs today (still allow reuse when not global-dedupe). if not dedupe_global: candidates.sort( key=lambda r: db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day) and 1 or 0 ) random.shuffle(candidates) else: random.shuffle(candidates) enqueued = 0 for room in candidates[: max(batch * 3, batch)]: if enqueued >= batch: 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, require_upload_quota=False, ) if job: enqueued += 1 if dedupe_global: used.add(str(room.get("room_id") or "")) if not db.pick_shorts_channel(day, settings, require_upload_quota=False): 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", False) 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 "入队失败(可能已有同房间任务)", } _quota_fill_lock = threading.Lock() def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: """Enqueue live-room clips toward daily_min first, then daily_max (Beijing day). Same live room may be shared across channels; each job gets a distinct clip_offset (0–15s / 15–30s / …) so materials are never identical. Prefer rooms with fewer jobs today for diversity. When behind daily_min, raise batch size. """ # Non-blocking: overlapping fills (52s+ previously) pegged a whole core forever. if not _quota_fill_lock.acquire(blocking=False): return 0 try: settings = cfg or db.get_settings_map() if not settings.get("shorts_enabled"): return 0 # All OAuth Clients cool-down → stop stuffing pipeline (disk / CPU waste). if ShortsPipeline._all_channel_profiles_upload_blocked(settings): return 0 day = push_date_from_ts(time.time()) summary = db.shorts_channels_quota_summary(day) under_min = [r for r in summary if not r.get("min_met") and int(r.get("gap") or 0) > 0] need_any = [r for r in summary if int(r.get("gap") or 0) > 0] if not need_any: return 0 if not db.pick_shorts_channel(day, settings, require_upload_quota=False): 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))) gap_total = sum(int(r.get("gap") or 0) for r in need_any) min_gap = sum(max(0, int(r.get("daily_min") or 0) - int(r.get("used") or 0)) for r in under_min) # Hard cap — large batches + N×DB in the loop previously burned 50s+/tick. base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 6)) if under_min: base_batch = max(base_batch, min(len(under_min), 6)) if day_progress > 0.7 and under_min: base_batch = max(base_batch, min(8, gap_total, max(min_gap, 1))) base_batch = min(base_batch, 8) # Backlog gate: don't keep stuffing when workers are already behind. try: st = db.shorts_stats(day) or {} by = st.get("by_status") or st.get("status") or {} if isinstance(by, dict): backlog = int(by.get("pending") or 0) + int(by.get("recording") or 0) else: backlog = 0 except Exception: backlog = 0 # Hard stop so fill never outruns recorders (was flooding 30+ pending). backlog_cap = 12 if backlog >= backlog_cap: return 0 base_batch = min(base_batch, max(1, backlog_cap - backlog)) any_live = settings.get("shorts_sample_any_live", True) dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) used_rooms = db.room_ids_with_shorts_job_today(day) if dedupe_global else set() rooms = db.list_live_douyin_rooms_for_shorts(limit=80) candidates: list[dict[str, Any]] = [] for room in rooms: rid = str(room.get("room_id") or "") if not rid or rid in used_rooms: 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 rooms_with_job = used_rooms if dedupe_global else db.room_ids_with_shorts_job_today(day) if not dedupe_global: candidates.sort( key=lambda r: ( 1 if str(r.get("room_id") or "") in rooms_with_job else 0, random.random(), ) ) else: random.shuffle(candidates) target_ids = [str(r["id"]) for r in under_min] + [ str(r["id"]) for r in need_any if r.get("min_met") ] if not target_ids: return 0 # Prefetch — avoid per-attempt get_channel / count / has_job queries. channels = { str(c.get("id") or ""): c for c in (db.list_shorts_channels(enabled=True) or []) if str(c.get("id") or "") } pipeline_by = {str(r["id"]): int(r.get("pipeline") or 0) for r in summary} uploaded_by = {str(r["id"]): int(r.get("uploaded") or 0) for r in summary} max_by = {str(r["id"]): int(r.get("daily_max") or SHORTS_DAILY_FORCE) for r in summary} occupied = db.shorts_job_room_channel_pairs_today(day) enqueued = 0 ti = 0 room_cycle = list(candidates) attempts = 0 max_attempts = max(base_batch * 2, len(target_ids)) while enqueued < base_batch and attempts < max_attempts: attempts += 1 room = room_cycle[(attempts - 1) % len(room_cycle)] rid = str(room.get("room_id") or "") assigned = False for _ in range(len(target_ids)): tid = target_ids[ti % len(target_ids)] ti += 1 ch = channels.get(tid) if not ch or not ch.get("enabled"): continue daily_max = max_by.get(tid, SHORTS_DAILY_FORCE) if pipeline_by.get(tid, 0) >= daily_max or uploaded_by.get(tid, 0) >= daily_max: continue if rid and (rid, tid) in occupied: continue if dedupe_global and rid in used_rooms: continue 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, channel_pk=tid, require_upload_quota=False, ) if job: enqueued += 1 occupied.add((rid, tid)) pipeline_by[tid] = int(pipeline_by.get(tid, 0)) + 1 if dedupe_global and rid: used_rooms.add(rid) assigned = True break if not assigned and dedupe_global: continue return enqueued except Exception: return 0 finally: try: _quota_fill_lock.release() except Exception: pass 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_housekeep_at = 0.0 self._upload_max_cached_at = 0.0 self._upload_max_cached_val = 2 self._record_max_cached_at = 0.0 self._record_max_cached_val = 1 self._catchup_cached_at = 0.0 self._catchup_cached_val = False self._under_min_cached_at = 0.0 self._under_min_cached_val = False 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 _end_of_day_catchup(cfg: dict[str, Any] | None = None) -> bool: try: from .shorts_schedule import fleet_pace_plan plan = fleet_pace_plan(cfg=cfg) if plan.get("behind") or plan.get("urgent"): return True from .timeutil import beijing_day_bounds day = push_date_from_ts(time.time()) _, day_end = beijing_day_bounds(day) if day_end - time.time() > 2400: return False return db.shorts_total_quota_gap(day) > 0 except Exception: return False def _catchup_cached(self, cfg: dict[str, Any]) -> bool: """Return last housekeep-computed catchup flag — never recompute on hot path.""" if self._catchup_cached_at <= 0: return False return bool(self._catchup_cached_val) @staticmethod def _all_channel_profiles_upload_blocked(cfg: dict[str, Any] | None = None) -> bool: """True when every enabled channel's OAuth profile is in YouTube upload cool-down. Recording into scheduled while uploads are frozen fills disk; pause fill/record then. """ try: settings = cfg or db.get_settings_map() blocked = blocked_profile_ids(settings) if not blocked: return False chs = db.list_shorts_channels(enabled=True) or [] if not chs: return False for ch in chs: if not db.shorts_channel_oauth_ready(ch): continue pid = profile_id_for_channel(ch) if pid not in blocked: return False # At least one oauth-ready channel exists and all such are blocked. return any(db.shorts_channel_oauth_ready(ch) for ch in chs) except Exception: return False @staticmethod def _upload_max(cfg: dict[str, Any], *, catchup: bool | None = None) -> int: explicit = int(cfg.get("shorts_upload_max_concurrent") or 0) if explicit > 0: base = max(1, min(explicit, 5)) else: base = max(2, int(cfg.get("shorts_max_concurrent") or 1)) if catchup is None: catchup = ShortsPipeline._end_of_day_catchup(cfg) if catchup: return min(5, max(base, 4)) return base def _upload_max_cached(self, cfg: dict[str, Any]) -> int: """Never call fleet_pace_plan here — housekeep refreshes the cache in a thread.""" now = time.time() if now - self._upload_max_cached_at < 45.0 and self._upload_max_cached_at > 0: return max(1, int(self._upload_max_cached_val)) explicit = int(cfg.get("shorts_upload_max_concurrent") or 0) if explicit > 0: base = max(1, min(explicit, 5)) else: base = max(2, int(cfg.get("shorts_max_concurrent") or 1)) if self._catchup_cached(cfg): base = min(5, max(base, 4)) self._upload_max_cached_val = base self._upload_max_cached_at = now return max(1, base) @staticmethod def _record_max(cfg: dict[str, Any], *, catchup: bool | None = None) -> int: base = max(1, int(cfg.get("shorts_max_concurrent") or 1)) if catchup is None: catchup = ShortsPipeline._end_of_day_catchup(cfg) if catchup: # Cap hard — 5 parallel resolve/record pegs a small VPS. return min(2, max(base, 2)) return base def _record_max_cached(self, cfg: dict[str, Any]) -> int: """Never call fleet_pace_plan here — housekeep refreshes the cache in a thread.""" now = time.time() if now - self._record_max_cached_at < 45.0 and self._record_max_cached_at > 0: return max(1, int(self._record_max_cached_val)) base = max(1, int(cfg.get("shorts_max_concurrent") or 1)) if self._catchup_cached(cfg): base = min(2, max(base, 2)) self._record_max_cached_val = base self._record_max_cached_at = now return max(1, base) 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: from .shorts_upload import is_transient_oauth_error_message 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 "授权中" in err: continue if has_rt and ok_flag == 0 and is_transient_oauth_error_message(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")] cool_profiles = [r for r in yt_by_profile if r.get("blocked")] cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0) try: from . import douyin_live # Prefer warm cache; never force a full rebuild on UI poll. 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), # API cool-down only (real YouTube 429) — manual upload never gated "upload_quota_blocked": bool(cool_profiles), "upload_quota_blocked_until": cool_until, "upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_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_quota_cooldown_sec": int( float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600) ), "yt_upload_limit": yt_limit, "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, "yt_quota_by_profile": yt_by_profile, "reauth_needed": list(cfg.get("shorts_reauth_needed") or [])[:20], "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 CHANNEL_GAP_FLOOR_SEC), "channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC), "max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)), "upload_max_concurrent": self._upload_max_cached(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, } try: from .shorts_schedule import fleet_pace_plan pace = fleet_pace_plan(cfg=cfg) payload["pace"] = pace if pace.get("behind") or pace.get("urgent"): payload["upload_min_gap_sec"] = float( pace.get("recommended_global_gap_sec") or payload["upload_min_gap_sec"] ) payload["channel_min_gap_sec"] = float( pace.get("recommended_channel_gap_sec") or payload["channel_min_gap_sec"] ) except Exception: pass 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: from .shorts_upload import is_transient_oauth_error_message 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 "授权中" in err: continue if has_rt and ok_flag == 0 and is_transient_oauth_error_message(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: live_count = len(db.list_live_douyin_rooms_for_shorts(limit=50) or []) 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")] cool_profiles = [r for r in yt_by_profile if r.get("blocked")] cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0) 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": bool(cool_profiles), "upload_quota_blocked_until": cool_until, "upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_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_quota_cooldown_sec": int(float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600)), "yt_upload_limit": yt_limit, "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, "yt_quota_by_profile": yt_by_profile, "reauth_needed": list(cfg.get("shorts_reauth_needed") or [])[:20], "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() # Restart leaves DB rows in `recording` with no owner — requeue before loop. db.reset_orphan_shorts_recordings() except Exception: pass self._active_records = 0 self._active_uploads = 0 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: # Never touch SQLite on the asyncio thread — workers holding db._lock # would freeze /api/health and look like a full site outage. cfg = await asyncio.to_thread(db.get_settings_map) if not cfg.get("shorts_enabled"): await asyncio.sleep(5) continue try: await asyncio.to_thread(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 = await asyncio.to_thread(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) try: # Cache under-min probe — full quota summary every tick burned a core. now_ts = time.time() if now_ts - self._under_min_cached_at >= 30.0: day_now = push_date_from_ts(now_ts) summary_now = await asyncio.to_thread(db.shorts_channels_quota_summary, day_now) self._under_min_cached_val = any(not r.get("min_met") for r in summary_now) self._under_min_cached_at = now_ts if self._under_min_cached_val: # Behind daily_min: fill a bit more often, but never sub-minute (CPU thrash). quota_interval = min(quota_interval, 90.0) from .timeutil import beijing_day_bounds day_now = push_date_from_ts(now_ts) ds, de = beijing_day_bounds(day_now) prog = max(0.0, min(1.0, (now_ts - ds) / max(1.0, de - ds))) if prog > 0.7: quota_interval = 75.0 except Exception: pass if (time.time() - self._last_quota_fill_at) >= quota_interval: self._last_quota_fill_at = time.time() # Heavy SQLite + room scans must not block asyncio (API health / UI). qn = await asyncio.to_thread(try_fill_daily_quota, cfg) if qn: self.quota_filled += qn try: await asyncio.to_thread(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 = await asyncio.to_thread(self._auto_retry_failed, cfg) if n: self.auto_retried += n except Exception: pass # Legacy recorded clips without upload_at → schedule irregularly # Heavy SQLite housekeep must not run on the asyncio thread every tick. if (time.time() - self._last_housekeep_at) >= 45.0: self._last_housekeep_at = time.time() def _housekeep() -> None: try: self._backfill_schedules(cfg) except Exception: pass try: from .shorts_schedule import pull_forward_due_uploads pull_forward_due_uploads(cfg) except Exception: pass try: skip_or_rebind_offline_pending(cfg, limit=40) except Exception: pass try: db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0) except Exception: pass try: db.reclaim_stale_shorts_recordings(max_age_sec=180) except Exception: pass try: db.reconcile_missing_shorts_clips(limit=40) except Exception: pass try: db.reconcile_false_failed_shorts(limit=40) except Exception: pass try: catchup = bool(self._end_of_day_catchup(cfg)) self._catchup_cached_val = catchup self._catchup_cached_at = time.time() self._upload_max_cached_val = int(self._upload_max(cfg, catchup=catchup)) self._upload_max_cached_at = time.time() self._record_max_cached_val = int(self._record_max(cfg, catchup=catchup)) self._record_max_cached_at = time.time() except Exception: pass await asyncio.to_thread(_housekeep) record_max = self._record_max_cached(cfg) upload_max = self._upload_max_cached(cfg) uploads_frozen = False try: uploads_frozen = await asyncio.to_thread( self._all_channel_profiles_upload_blocked, cfg ) except Exception: uploads_frozen = False job: dict[str, Any] | None = None runner: str = "" if self._active_uploads < upload_max: # Skip Clients in YouTube-API cool-down (manual upload still allowed). skip = await asyncio.to_thread(blocked_profile_ids, cfg) job = await asyncio.to_thread( db.claim_due_shorts_upload, skip_profile_ids=skip or None ) if job: runner = "upload" # All Clients cool-down → stop filming into scheduled (disk fill). if not job and not uploads_frozen and self._active_records < record_max: try: from .host_metrics import clip_encode_defer_reason defer_rec = await asyncio.to_thread(clip_encode_defer_reason) except Exception: defer_rec = "" if not defer_rec: job = await asyncio.to_thread( db.claim_pending_shorts_record, max_concurrent=record_max ) if job: runner = "record" if not job: # Uploads frozen + no upload claim → idle longer (no fill/record spin). await asyncio.sleep(8.0 if uploads_frozen else 2.0) 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)) # Pace claims — skip/rebind paths finish in ms and otherwise peg the loop. await asyncio.sleep(0.75) 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: """On real YouTube 429: cool down this Client's auto-uploads; ntfy at most once per window.""" from .shorts_yt_quota import defer_profile_shorts_uploads, mark_api_quota_cooldown pid = profile_id_for_job(job) until, should_notify = mark_api_quota_cooldown( profile_id=pid, reason=str(raw_error or "")[:160], ) try: defer_profile_shorts_uploads( pid, until, reason=f"Client {pid} 接口配额冷静至北京时间后重试", ) except Exception: pass 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) 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] if should_notify: left_min = max(1, int((until - time.time()) / 60)) self._emit_shorts_event( kind="shorts_quota", level="warn", message=( f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传);" f"自动上传冷静约 {left_min} 分钟后再试" ), job=job, extra={ "error": raw_error[:200], "oauth_profile_id": pid, "cool_until": until, }, ) 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"]) # Cheap offline gate before any Douyin/SSL resolve (avoids CPU spin). try: live = _live_room_map() rid = str(job.get("room_id") or "") if rid and rid not in live: if _try_rebind_shorts_job_to_live(job, cfg): return _skip_offline_shorts_job(job) return except Exception: pass # Shared clips disk with yt-long — refuse record when critically low (no setting change). 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: db.update_shorts_job( jid, status="pending", error=f"disk_low:{free_gb:.1f}GB", started_at=0, updated_at=time.time(), ) return except Exception: pass # Isolated companion: enqueue 9:16 long-form master (never raises into Shorts). try: from .yt_long_pipeline import try_enqueue_from_shorts await asyncio.to_thread(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: # Room already offline → rebind to another live source or free the slot. if _try_rebind_shorts_job_to_live(job, cfg): return live = _live_room_map() rid = str(job.get("room_id") or "") if rid and rid not in live: _skip_offline_shorts_job(job) return err = str(job.get("error") or "") # Backoff: claim_pending skips stream_retry for 120s after updated_at. 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="", started_at=0, updated_at=time.time(), ) return # Still listed live but no playable URL — free slot, don't keep failing. _skip_offline_shorts_job(job, reason="无法解析直播流,已释放当日名额") 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 # Distinct live window relative to job create time: # offset 0 → capture immediately; 15 → wait until t0+15s; 30 → t0+30s … # So A/B/C from the same room never get the identical live segment. try: offset = max(0.0, float(job.get("clip_offset_sec") or 0)) except (TypeError, ValueError): offset = 0.0 if offset > 0: try: created = float(job.get("created_at") or time.time()) except (TypeError, ValueError): created = time.time() delay = max(0.0, (created + offset) - time.time()) delay = min(delay, float(15 * 20)) if delay > 0.5: await asyncio.sleep(delay) 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 "录制失败") if _is_offline_stream_error(err): if _try_rebind_shorts_job_to_live(job, cfg): return live = _live_room_map() rid = str(job.get("room_id") or "") if not rid or rid not in live: _skip_offline_shorts_job(job, reason=f"直播流失效已停播,已释放名额({err[:80]})") return 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[:200]}, ) 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()