diff --git a/backend/app/clip_cascade.py b/backend/app/clip_cascade.py index c13eb06..b5bb1d0 100644 --- a/backend/app/clip_cascade.py +++ b/backend/app/clip_cascade.py @@ -130,7 +130,6 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, from . import db from . import tiktok_db from . import yt_long_db - from . import x_clips_db settings_map = cfg if cfg is not None else db.get_settings_map() shorts_n = 0 @@ -143,17 +142,18 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or []) except Exception: tiktok_n = 0 - yt_long = int(yt_long_db.yt_long_daily_max(settings_map) or 0) + yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0) shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE) tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE) try: x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20)) except Exception: x_need = 20 - # One master can feed all platforms once → masters needed = max(...) - source_need = max(yt_long, shorts_need, tiktok_need, x_need, 0) + # One master feeds all platforms once → masters needed = max(...) + source_need = max(yt_upload, shorts_need, tiktok_need, x_need, 0) return { - "yt_long": yt_long, + "yt_long": yt_upload, + "yt_long_upload": yt_upload, "shorts": shorts_need, "tiktok": tiktok_need, "x": x_need, @@ -164,29 +164,25 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, def ensure_source_covers_platforms(cfg: dict[str, Any] | None = None) -> dict[str, Any]: - """Report (and optionally raise) yt_long_daily_max so masters ≥ platform quotas. - - Auto-raise only when yt_long_auto_match_source=True (default off) to avoid - suddenly uploading hundreds of long YouTube videos. - """ + """Always keep yt_long_source_daily_max ≥ max(platform quotas); never raise upload cap.""" from . import db from . import yt_long_db settings_map = cfg if cfg is not None else db.get_settings_map() need = estimate_platform_daily_need(settings_map) - current = int(yt_long_db.yt_long_daily_max(settings_map) or 0) target = int(need["source_masters"]) + current = int(yt_long_db.yt_long_source_daily_max(settings_map) or 0) + upload_cap = int(yt_long_db.yt_long_daily_max(settings_map) or 0) if not bool(settings_map.get("clip_cascade_enabled", True)): - return {"ok": True, "adjusted": False, "from": current, "to": current, **need} - if not bool(settings_map.get("yt_long_auto_match_source", False)): - return {"ok": True, "adjusted": False, "from": current, "to": current, **need} + # Without cascade, source only needs to cover YouTube long uploads + target = upload_cap try: - hard_cap = max(42, min(200, int(settings_map.get("yt_long_source_cap") or 200))) + hard_cap = max(42, min(300, int(settings_map.get("yt_long_source_cap") or 200))) except Exception: hard_cap = 200 - new_max = min(hard_cap, max(current, target)) - if new_max > current: - db.update_settings_map({"yt_long_daily_max": new_max}) + new_max = min(hard_cap, max(upload_cap, target)) + if new_max != int(settings_map.get("yt_long_source_daily_max") or 0): + db.update_settings_map({"yt_long_source_daily_max": new_max}) return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need} return {"ok": True, "adjusted": False, "from": current, "to": current, **need} diff --git a/backend/app/db.py b/backend/app/db.py index 10b1af5..2a77302 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -507,17 +507,18 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "yt_long_auto_upload": True, "yt_long_live_sample": True, "yt_long_live_sample_interval_sec": 180, - "yt_long_live_sample_batch": 2, + "yt_long_live_sample_batch": 3, "yt_long_daily_max": 42, + "yt_long_source_daily_max": 42, "yt_long_channel_daily_max": 3, "yt_long_min_sec": 180, "yt_long_max_sec": 480, "yt_long_dedupe_room_day": True, - "yt_long_max_concurrent": 2, + "yt_long_max_concurrent": 3, "yt_long_upload_min_gap_sec": 900, "yt_long_delete_clip_after_upload": False, "yt_long_landscape_16x9": False, - "yt_long_auto_match_source": False, + "yt_long_auto_match_source": True, "yt_long_source_cap": 200, "yt_long_title_template": "", "yt_long_description_template": "", diff --git a/backend/app/main.py b/backend/app/main.py index c99fa87..54cc7ec 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1231,6 +1231,16 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"]))) except Exception: raise HTTPException(400, "daily_max 无效") from None + if "yt_long_source_daily_max" in raw: + try: + patch["yt_long_source_daily_max"] = max(0, min(300, int(raw["yt_long_source_daily_max"]))) + except Exception: + raise HTTPException(400, "source_daily_max 无效") from None + if "yt_long_source_cap" in raw: + try: + patch["yt_long_source_cap"] = max(42, min(300, int(raw["yt_long_source_cap"]))) + except Exception: + raise HTTPException(400, "source_cap 无效") from None if "yt_long_channel_daily_max" in raw: try: patch["yt_long_channel_daily_max"] = max(0, min(50, int(raw["yt_long_channel_daily_max"]))) diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index dec1983..2b8b9f3 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -10,8 +10,8 @@ from typing import Any, Optional from .db import _connect, _lock, _row_to_dict from .timeutil import push_date_from_ts -# Quota-consuming statuses for daily long-form caps -_QUOTA_STATUSES = ( +# Quota-consuming statuses for master *recording* (source material) +_SOURCE_STATUSES = ( "pending", "recording", "recorded", @@ -19,9 +19,18 @@ _QUOTA_STATUSES = ( "uploading", "uploaded", ) +# Statuses that count toward YouTube *upload* caps (channel + global) +_UPLOAD_STATUSES = ( + "scheduled", + "uploading", + "uploaded", +) +# Back-compat alias +_QUOTA_STATUSES = _SOURCE_STATUSES -YT_LONG_DAILY_DEFAULT = 42 # 14 channels × 3 long videos +YT_LONG_DAILY_DEFAULT = 42 # YouTube long upload: 14 channels × 3 YT_LONG_CHANNEL_DEFAULT = 3 +YT_LONG_SOURCE_DEFAULT = 42 # raised automatically to cover cascade platforms YT_LONG_MIN_SEC = 180 # 3 min YT_LONG_MAX_SEC = 480 # 8 min @@ -103,6 +112,7 @@ def ensure_yt_long_tables(conn: sqlite3.Connection) -> None: def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: + """YouTube long-form *upload* daily cap (not master recording cap).""" from . import db settings = cfg if cfg is not None else db.get_settings_map() @@ -113,6 +123,25 @@ def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: return max(0, min(200, v)) +def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int: + """Master recording daily cap — must cover cascade platform needs.""" + from . import db + + settings = cfg if cfg is not None else db.get_settings_map() + upload_cap = yt_long_daily_max(settings) + try: + v = int(settings.get("yt_long_source_daily_max") or 0) + except Exception: + v = 0 + if v <= 0: + v = max(upload_cap, YT_LONG_SOURCE_DEFAULT) + try: + hard = max(42, min(300, int(settings.get("yt_long_source_cap") or 200))) + except Exception: + hard = 200 + return max(upload_cap, min(hard, v)) + + def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int: from . import db @@ -124,9 +153,9 @@ def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int: return max(0, min(50, v)) -def yt_long_quota_used(push_date: str = "") -> int: +def yt_long_source_used(push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) - placeholders = ",".join("?" for _ in _QUOTA_STATUSES) + placeholders = ",".join("?" for _ in _SOURCE_STATUSES) with _lock: conn = _connect() try: @@ -136,21 +165,56 @@ def yt_long_quota_used(push_date: str = "") -> int: SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND status IN ({placeholders}) """, - (day, *_QUOTA_STATUSES), + (day, *_SOURCE_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() -def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: +def yt_long_source_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: day = push_date or push_date_from_ts(time.time()) - return max(0, yt_long_daily_max(cfg) - yt_long_quota_used(day)) + return max(0, yt_long_source_daily_max(cfg) - yt_long_source_used(day)) + + +def yt_long_upload_used(push_date: str = "") -> int: + day = push_date or push_date_from_ts(time.time()) + placeholders = ",".join("?" for _ in _UPLOAD_STATUSES) + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + row = conn.execute( + f""" + SELECT COUNT(*) AS c FROM yt_long_jobs + WHERE push_date = ? AND status IN ({placeholders}) + """, + (day, *_UPLOAD_STATUSES), + ).fetchone() + return int(row["c"]) if row else 0 + finally: + conn.close() + + +def yt_long_upload_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: + day = push_date or push_date_from_ts(time.time()) + return max(0, yt_long_daily_max(cfg) - yt_long_upload_used(day)) + + +def yt_long_quota_used(push_date: str = "") -> int: + """UI/compat: YouTube upload usage.""" + return yt_long_upload_used(push_date) + + +def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: + """UI/compat: YouTube upload remaining.""" + return yt_long_upload_gap(push_date, cfg) def channel_quota_used(channel_pk: str, push_date: str = "") -> int: + """Per-channel YouTube upload usage (cascade-only masters do not count).""" day = push_date or push_date_from_ts(time.time()) - placeholders = ",".join("?" for _ in _QUOTA_STATUSES) + placeholders = ",".join("?" for _ in _UPLOAD_STATUSES) with _lock: conn = _connect() try: @@ -160,13 +224,38 @@ def channel_quota_used(channel_pk: str, push_date: str = "") -> int: SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) """, - (day, channel_pk, *_QUOTA_STATUSES), + (day, channel_pk, *_UPLOAD_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() +def list_cascade_only_ready(limit: int = 20, push_date: str = "") -> list[dict[str, Any]]: + """Recorded masters waiting for a YouTube upload slot.""" + day = push_date or push_date_from_ts(time.time()) + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + rows = conn.execute( + """ + SELECT * FROM yt_long_jobs + WHERE push_date = ? + AND status = 'recorded' + AND clip_path != '' + AND IFNULL(youtube_video_id, '') = '' + AND (upload_at = 0 OR error = 'cascade_only') + ORDER BY created_at ASC + LIMIT ? + """, + (day, max(1, min(100, int(limit)))), + ).fetchall() + return [_row_to_dict(r) for r in rows] # type: ignore + finally: + conn.close() + + def has_job_for_room_day(room_id: str, push_date: str) -> bool: if not room_id: return False diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index 79aa702..6959f6b 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -149,62 +149,61 @@ def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]: return {"enqueued": False, "reason": "disabled"} if not cfg.get("yt_long_with_shorts", True): return {"enqueued": False, "reason": "with_shorts_off"} - if yt_long_db.yt_long_quota_gap(cfg=cfg) <= 0: - return {"enqueued": False, "reason": "quota_full"} + if yt_long_db.yt_long_source_gap(cfg=cfg) <= 0: + return {"enqueued": False, "reason": "source_full"} room_id = str(job.get("room_id") or "").strip() day = str(job.get("push_date") or push_date_from_ts(time.time())) if cfg.get("yt_long_dedupe_room_day", True) and room_id and yt_long_db.has_job_for_room_day(room_id, day): return {"enqueued": False, "reason": "room_dedupe"} - channel = pick_yt_long_channel(cfg, day) - if not channel: - return {"enqueued": False, "reason": "no_channel"} + # Channel only required when we still have YouTube upload slots + channel = pick_yt_long_channel(cfg, day) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None created = yt_long_db.create_yt_long_job( room_pk=str(job.get("room_pk") or ""), room_id=room_id, source_url=str(job.get("source_url") or ""), anchor_name=str(job.get("anchor_name") or ""), stream_url=str(job.get("stream_url") or ""), - channel_pk=str(channel.get("id") or ""), + channel_pk=str((channel or {}).get("id") or ""), shorts_job_id=str(job.get("id") or ""), push_date=day, ) - try: - yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) - except Exception: - pass + if channel: + try: + yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) + except Exception: + pass _emit( "yt_long_ops", "info", f"长视频入队:{created.get('anchor_name') or room_id}", created, ) - return {"enqueued": True, "job_id": created.get("id"), "channel_pk": channel.get("id")} + return {"enqueued": True, "job_id": created.get("id"), "channel_pk": (channel or {}).get("id")} except Exception as exc: return {"enqueued": False, "reason": "error", "error": str(exc)[:200]} def _enqueue_from_room(room: dict[str, Any], cfg: dict[str, Any], push_date: str) -> str: - channel = pick_yt_long_channel(cfg, push_date) - if not channel: - return "" rid = str(room.get("room_id") or "").strip() if not rid: return "" if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, push_date): return "" + channel = pick_yt_long_channel(cfg, push_date) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None created = yt_long_db.create_yt_long_job( room_pk=str(room.get("id") or room.get("room_pk") or ""), room_id=rid, source_url=str(room.get("url") or room.get("source_url") or ""), anchor_name=str(room.get("last_anchor") or room.get("anchor_name") or ""), stream_url=str(room.get("stream_url") or ""), - channel_pk=str(channel.get("id") or ""), + channel_pk=str((channel or {}).get("id") or ""), push_date=push_date, ) - try: - yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) - except Exception: - pass + if channel: + try: + yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) + except Exception: + pass jid = str(created.get("id") or "") if jid: _emit("yt_long_ops", "info", f"长视频取样入队:{created.get('anchor_name') or rid}", created) @@ -219,11 +218,9 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: return 0 if not settings.get("yt_long_live_sample", True): return 0 - if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: + if yt_long_db.yt_long_source_gap(cfg=settings) <= 0: return 0 - if not pick_yt_long_channel(settings): - return 0 - batch = max(1, min(5, int(settings.get("yt_long_live_sample_batch") or 1))) + batch = max(1, min(8, int(settings.get("yt_long_live_sample_batch") or 1))) day = push_date_from_ts(time.time()) rooms = db.list_live_douyin_rooms_for_shorts(limit=400) candidates: list[dict[str, Any]] = [] @@ -241,7 +238,7 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: for room in candidates: if enqueued >= batch: break - if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: + if yt_long_db.yt_long_source_gap(cfg=settings) <= 0: break if _enqueue_from_room(room, settings, day): enqueued += 1 @@ -258,6 +255,13 @@ def sample_live_now() -> dict[str, Any]: yt_long_db.sync_channels_from_shorts() except Exception: pass + try: + from .clip_cascade import ensure_source_covers_platforms + + ensure_source_covers_platforms(settings) + settings = db.get_settings_map() + except Exception: + pass patched = {**settings, "yt_long_live_sample": True} rooms = db.list_live_douyin_rooms_for_shorts(limit=400) day = push_date_from_ts(time.time()) @@ -271,10 +275,8 @@ def sample_live_now() -> dict[str, Any]: reason = "" if n: reason = "ok" - elif yt_long_db.yt_long_quota_gap(cfg=patched) <= 0: + elif yt_long_db.yt_long_source_gap(cfg=patched) <= 0: reason = "no_quota" - elif not pick_yt_long_channel(patched): - reason = "no_channel" elif skipped and skipped >= len(rooms) and len(rooms) > 0: reason = "all_deduped" elif not rooms: @@ -284,8 +286,7 @@ def sample_live_now() -> dict[str, Any]: reason_zh = { "ok": "已入队", "disabled": "模块未启用", - "no_quota": "今日全局配额已满", - "no_channel": "没有可用已授权频道", + "no_quota": "今日母片配额已满", "all_deduped": "今日在播房间均已入队,请等待排队任务录制", "no_live": "当前没有抖音在播源", "enqueue_failed": "入队失败", @@ -298,6 +299,8 @@ def sample_live_now() -> dict[str, Any]: "job_ids": [str(j.get("id")) for j in pending], "reason": reason, "reason_zh": reason_zh, + "source_gap": yt_long_db.yt_long_source_gap(cfg=patched), + "upload_gap": yt_long_db.yt_long_upload_gap(cfg=patched), } @@ -309,19 +312,31 @@ def try_fill_daily_quota() -> dict[str, Any]: yt_long_db.sync_channels_from_shorts() except Exception: pass - gap = yt_long_db.yt_long_quota_gap(cfg=settings) + try: + from .clip_cascade import ensure_source_covers_platforms + + ensure_source_covers_platforms(settings) + settings = db.get_settings_map() + except Exception: + pass + gap = yt_long_db.yt_long_source_gap(cfg=settings) if gap <= 0: return {"enqueued": 0, "gap": 0, "reason": "quota_full"} - patched = {**settings, "yt_long_live_sample_batch": min(gap, 5), "yt_long_live_sample": True} + patched = {**settings, "yt_long_live_sample_batch": min(gap, 8), "yt_long_live_sample": True} total = 0 rounds = 0 - while total < gap and rounds < 8: + while total < gap and rounds < 12: rounds += 1 n = try_sample_live_rooms(patched) if n <= 0: break total += n - return {"enqueued": total, "gap": yt_long_db.yt_long_quota_gap(cfg=settings), "reason": "ok" if total else "no_candidates"} + return { + "enqueued": total, + "gap": yt_long_db.yt_long_source_gap(cfg=settings), + "upload_gap": yt_long_db.yt_long_upload_gap(cfg=settings), + "reason": "ok" if total else "no_candidates", + } class YtLongPipeline: @@ -349,8 +364,10 @@ class YtLongPipeline: board = {"channels": [], "total_gap": 0, "push_date": day} cascade_need: dict[str, Any] = {} try: - from .clip_cascade import estimate_platform_daily_need + from .clip_cascade import estimate_platform_daily_need, ensure_source_covers_platforms + ensure_source_covers_platforms(cfg) + cfg = db.get_settings_map() cascade_need = estimate_platform_daily_need(cfg) except Exception: cascade_need = {} @@ -360,9 +377,14 @@ class YtLongPipeline: "enabled": bool(cfg.get("yt_long_enabled")), "processed": self.processed, "sampled": self.sampled, - "quota_gap": yt_long_db.yt_long_quota_gap(day, cfg), - "quota_used": yt_long_db.yt_long_quota_used(day), + "quota_gap": yt_long_db.yt_long_upload_gap(day, cfg), + "quota_used": yt_long_db.yt_long_upload_used(day), "daily_max": yt_long_db.yt_long_daily_max(cfg), + "source_gap": yt_long_db.yt_long_source_gap(day, cfg), + "source_used": yt_long_db.yt_long_source_used(day), + "source_daily_max": yt_long_db.yt_long_source_daily_max(cfg), + "upload_gap": yt_long_db.yt_long_upload_gap(day, cfg), + "upload_used": yt_long_db.yt_long_upload_used(day), "channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "last_error": self.last_error, "stats": yt_long_db.yt_long_stats(day), @@ -377,6 +399,7 @@ class YtLongPipeline: "yt_long_live_sample_interval_sec": int(cfg.get("yt_long_live_sample_interval_sec") or 180), "yt_long_live_sample_batch": int(cfg.get("yt_long_live_sample_batch") or 1), "yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg), + "yt_long_source_daily_max": yt_long_db.yt_long_source_daily_max(cfg), "yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "yt_long_min_sec": int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC), "yt_long_max_sec": int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC), @@ -443,6 +466,13 @@ class YtLongPipeline: interval = max(60.0, float(cfg.get("yt_long_live_sample_interval_sec") or 180)) if cfg.get("yt_long_live_sample", True) and (time.time() - self._last_sample_at) >= interval: self._last_sample_at = time.time() + try: + from .clip_cascade import ensure_source_covers_platforms + + ensure_source_covers_platforms(cfg) + cfg = db.get_settings_map() + except Exception: + pass n = try_sample_live_rooms(cfg) if n: self.sampled += n @@ -468,25 +498,46 @@ class YtLongPipeline: max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") - # If in-flight + done already fills daily_max, soft-skip leftover pending + # Soft-skip leftover pending when master (source) quota is full try: from .timeutil import push_date_from_ts as _pday - dmax = yt_long_db.yt_long_daily_max(cfg) + smax = yt_long_db.yt_long_source_daily_max(cfg) day = _pday(time.time()) - inflight = 0 - for st_name in ("recording", "recorded", "scheduled", "uploading", "uploaded"): - inflight += yt_long_db.count_yt_long_jobs_by_status(st_name, push_date=day) - if dmax > 0 and inflight >= dmax: + if smax > 0 and yt_long_db.yt_long_source_used(day) >= smax: for pj in yt_long_db.list_pending_yt_long_jobs(limit=30): yt_long_db.update_yt_long_job( str(pj.get("id") or ""), status="skipped", - error="daily_quota_full", + error="source_quota_full", finished_at=time.time(), ) except Exception: pass + # Promote cascade-only masters into YouTube upload slots when available + try: + ugap = yt_long_db.yt_long_upload_gap(cfg=cfg) + if ugap > 0 and cfg.get("yt_long_auto_upload", True): + for cj in yt_long_db.list_cascade_only_ready(limit=min(10, ugap)): + if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0: + break + ch = pick_yt_long_channel(cfg, str(cj.get("push_date") or "")) + if not ch: + break + gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) + yt_long_db.update_yt_long_job( + str(cj.get("id") or ""), + status="scheduled", + channel_pk=str(ch["id"]), + upload_at=time.time() + random.uniform(20, gap), + error="", + ) + try: + yt_long_db.update_yt_long_channel(str(ch["id"]), last_assigned_at=time.time()) + except Exception: + pass + except Exception: + pass while self._active_records < max_rec and db_recording < max_rec: pending = yt_long_db.list_pending_yt_long_jobs(limit=1) if not pending: @@ -558,45 +609,55 @@ class YtLongPipeline: _emit("yt_long_fail", "error", f"长视频录制失败:{job.get('anchor_name') or jid} — {err[:80]}", job) return clip_path = str(outcome.get("path") or "") - gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) - upload_at = time.time() + random.uniform(30, gap) - if not cfg.get("yt_long_auto_upload", True): - yt_long_db.update_yt_long_job( - jid, - status="recorded", - clip_path=clip_path, - clip_seconds=float(outcome.get("seconds") or sec), - stream_url=str(outcome.get("stream_url") or ""), - error="", - ) - fresh = yt_long_db.get_yt_long_job(jid) or {**job, "clip_path": clip_path, "clip_seconds": sec} - try: - from .clip_cascade import cascade_from_yt_long - - await cascade_from_yt_long(fresh, cfg) - except Exception: - pass - return - yt_long_db.update_yt_long_job( - jid, - status="scheduled", - clip_path=clip_path, - clip_seconds=float(outcome.get("seconds") or sec), - stream_url=str(outcome.get("stream_url") or ""), - upload_at=upload_at, - error="", - ) - fresh = yt_long_db.get_yt_long_job(jid) or { + fresh_base = { **job, "clip_path": clip_path, "clip_seconds": float(outcome.get("seconds") or sec), + "stream_url": str(outcome.get("stream_url") or ""), } + # Always cascade first (TikTok / Shorts / X reuse this master) + yt_long_db.update_yt_long_job( + jid, + status="recorded", + clip_path=clip_path, + clip_seconds=float(outcome.get("seconds") or sec), + stream_url=str(outcome.get("stream_url") or ""), + error="", + ) + fresh = yt_long_db.get_yt_long_job(jid) or fresh_base try: from .clip_cascade import cascade_from_yt_long await cascade_from_yt_long(fresh, cfg) except Exception: pass + if not cfg.get("yt_long_auto_upload", True): + return + # Only schedule YouTube long upload when upload quota remains + if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0: + yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0) + return + channel = None + if str(fresh.get("channel_pk") or "").strip(): + channel = yt_long_db.get_yt_long_channel(str(fresh.get("channel_pk") or "")) + if not channel: + channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or "")) + if not channel: + yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0) + return + gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) + upload_at = time.time() + random.uniform(30, gap) + yt_long_db.update_yt_long_job( + jid, + status="scheduled", + channel_pk=str(channel["id"]), + upload_at=upload_at, + error="", + ) + try: + yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) + except Exception: + pass async def _run_upload(self, job: dict[str, Any]) -> None: try: diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index 26529ba..f5abd62 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -406,8 +406,16 @@ export default function YtLongPage() {