diff --git a/backend/app/db.py b/backend/app/db.py index 82d0551..46404fb 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -504,6 +504,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "yt_long_enabled": False, "yt_long_with_shorts": True, "yt_long_auto_upload": True, + "yt_long_live_sample": True, + "yt_long_live_sample_interval_sec": 180, + "yt_long_live_sample_batch": 1, "yt_long_daily_max": 3, "yt_long_channel_daily_max": 1, "yt_long_min_sec": 180, diff --git a/backend/app/main.py b/backend/app/main.py index a02db3b..700bd2f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1212,6 +1212,7 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st "yt_long_auto_upload", "yt_long_dedupe_room_day", "yt_long_delete_clip_after_upload", + "yt_long_live_sample", ): if k in raw: patch[k] = bool(raw[k]) @@ -1255,6 +1256,26 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st return yt_long_pipeline.status() +@app.post("/api/yt-long/sample-now") +async def yt_long_sample_now() -> dict[str, Any]: + from .yt_long_pipeline import sample_live_now + + result = await asyncio.to_thread(sample_live_now) + recording = await yt_long_pipeline.kick_pending_records(list(result.get("job_ids") or [])) + return {"ok": True, **result, "recording": recording, "status": yt_long_pipeline.status()} + + +@app.post("/api/yt-long/fill-quota") +async def yt_long_fill_quota() -> dict[str, Any]: + from . import yt_long_db + from .yt_long_pipeline import try_fill_daily_quota + + result = await asyncio.to_thread(try_fill_daily_quota) + pending = await _db(yt_long_db.list_pending_yt_long_jobs, limit=20) + recording = await yt_long_pipeline.kick_pending_records([str(j.get("id")) for j in pending]) + return {"ok": True, **result, "recording": recording, "status": yt_long_pipeline.status()} + + @app.get("/api/yt-long/jobs") async def yt_long_jobs_list( status: str = "", @@ -1279,16 +1300,17 @@ async def yt_long_jobs_list( async def yt_long_channels_list(enabled: Optional[bool] = None) -> dict[str, Any]: from . import yt_long_db + await _db(yt_long_db.sync_channels_from_shorts) rows = await _db(yt_long_db.list_yt_long_channels, enabled=enabled) return {"channels": [yt_long_db.public_yt_long_channel(c) for c in rows]} @app.post("/api/yt-long/channels/import-shorts") async def yt_long_channels_import_shorts() -> dict[str, Any]: - """Copy OAuth from Shorts channels into yt_long_channels only (Shorts untouched).""" + """Full sync copy of Shorts channels into yt_long_channels (Shorts untouched).""" from . import yt_long_db - result = await _db(yt_long_db.import_channels_from_shorts) + result = await _db(yt_long_db.sync_channels_from_shorts) return {"ok": True, **result} diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index 7820f38..8d8dbff 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -636,47 +636,85 @@ def delete_yt_long_channel(channel_pk: str) -> dict[str, int]: conn.close() -def import_channels_from_shorts() -> dict[str, Any]: - """Copy OAuth from Shorts channels into yt_long_channels (read Shorts, write only yt_long_*).""" +def sync_channels_from_shorts() -> dict[str, Any]: + """Copy/refresh Shorts channel rows into yt_long_channels (Shorts tables never written).""" from . import db created = 0 - skipped = 0 + updated = 0 for ch in db.list_shorts_channels(enabled=None): src = str(ch.get("id") or "") if not src: continue - existing = None + existing_id = "" with _lock: conn = _connect() try: ensure_yt_long_tables(conn) - existing = conn.execute( - "SELECT id FROM yt_long_channels WHERE source_shorts_channel_pk = ?", + row = conn.execute( + "SELECT id, daily_max FROM yt_long_channels WHERE source_shorts_channel_pk = ?", (src,), ).fetchone() + if row: + existing_id = str(row["id"]) + keep_dmax = int(row["daily_max"] or 1) + else: + keep_dmax = 1 finally: conn.close() - if existing: - skipped += 1 - continue - create_yt_long_channel( - name=str(ch.get("name") or "Shorts 频道").strip() + " · 长视频", - youtube_channel_id=str(ch.get("youtube_channel_id") or ""), - oauth_profile_id=str(ch.get("oauth_profile_id") or "A"), - client_id=str(ch.get("client_id") or ""), - client_secret=str(ch.get("client_secret") or ""), - refresh_token=str(ch.get("refresh_token") or ""), - enabled=bool(ch.get("enabled", True)), - daily_max=1, - title_template="{anchor} street food live", - description_template="{anchor}\n{url}\n#StreetFood #Live", - privacy=str(ch.get("privacy") or "public"), - note=f"imported from shorts:{src}", - source_shorts_channel_pk=src, - ) - created += 1 - return {"created": created, "skipped": skipped} + name = str(ch.get("name") or "频道").strip() or "频道" + payload = { + "name": name, + "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), + "oauth_profile_id": str(ch.get("oauth_profile_id") or "A"), + "client_id": str(ch.get("client_id") or ""), + "client_secret": str(ch.get("client_secret") or ""), + "refresh_token": str(ch.get("refresh_token") or ""), + "enabled": bool(ch.get("enabled", True)), + "daily_max": keep_dmax, + "privacy": str(ch.get("privacy") or "public"), + "note": f"synced from shorts:{src}", + "source_shorts_channel_pk": src, + } + if existing_id: + # Always refresh OAuth + identity from Shorts; keep local daily_max / templates + update_yt_long_channel( + existing_id, + name=payload["name"], + youtube_channel_id=payload["youtube_channel_id"], + oauth_profile_id=payload["oauth_profile_id"], + client_id=payload["client_id"], + client_secret=payload["client_secret"], + refresh_token=payload["refresh_token"], + enabled=payload["enabled"], + privacy=payload["privacy"], + note=payload["note"], + ) + updated += 1 + else: + create_yt_long_channel( + name=payload["name"], + youtube_channel_id=payload["youtube_channel_id"], + oauth_profile_id=payload["oauth_profile_id"], + client_id=payload["client_id"], + client_secret=payload["client_secret"], + refresh_token=payload["refresh_token"], + enabled=payload["enabled"], + daily_max=payload["daily_max"], + title_template="{anchor} street food live", + description_template="{anchor}\n{url}\n#StreetFood #Live", + privacy=payload["privacy"], + note=payload["note"], + source_shorts_channel_pk=src, + ) + created += 1 + return {"created": created, "updated": updated, "total": created + updated} + + +def import_channels_from_shorts() -> dict[str, Any]: + """Alias — always full sync (copy) from Shorts.""" + return sync_channels_from_shorts() + def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index 6a56ac4..8ee6661 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -190,6 +190,136 @@ def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]: 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 "" + 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 ""), + push_date=push_date, + ) + 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) + return jid + + +def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: + """Independent live sampling for long-form — does not touch Shorts jobs.""" + try: + settings = cfg or db.get_settings_map() + if not settings.get("yt_long_enabled"): + return 0 + if not settings.get("yt_long_live_sample", True): + return 0 + if yt_long_db.yt_long_quota_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))) + day = push_date_from_ts(time.time()) + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + candidates: list[dict[str, Any]] = [] + for room in rooms: + rid = str(room.get("room_id") or "") + if not rid: + continue + if settings.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day): + continue + candidates.append(room) + if not candidates: + return 0 + random.shuffle(candidates) + enqueued = 0 + for room in candidates: + if enqueued >= batch: + break + if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: + break + if _enqueue_from_room(room, settings, day): + enqueued += 1 + return enqueued + except Exception: + return 0 + + +def sample_live_now() -> dict[str, Any]: + settings = db.get_settings_map() + if not settings.get("yt_long_enabled"): + return {"enqueued": 0, "live_count": 0, "reason": "disabled", "job_ids": []} + try: + yt_long_db.sync_channels_from_shorts() + except Exception: + pass + patched = {**settings, "yt_long_live_sample": True} + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + day = push_date_from_ts(time.time()) + skipped = 0 + for room in rooms: + rid = str(room.get("room_id") or "") + if rid and patched.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day): + skipped += 1 + n = try_sample_live_rooms(patched) + pending = yt_long_db.list_pending_yt_long_jobs(limit=20) + reason = "" + if n: + reason = "ok" + elif yt_long_db.yt_long_quota_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: + reason = "no_live" + else: + reason = "enqueue_failed" + return { + "enqueued": n, + "live_count": len(rooms), + "skipped_dedupe": skipped, + "job_ids": [str(j.get("id")) for j in pending], + "reason": reason, + } + + +def try_fill_daily_quota() -> dict[str, Any]: + settings = db.get_settings_map() + if not settings.get("yt_long_enabled"): + return {"enqueued": 0, "gap": 0, "reason": "disabled"} + try: + yt_long_db.sync_channels_from_shorts() + except Exception: + pass + gap = yt_long_db.yt_long_quota_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} + total = 0 + rounds = 0 + while total < gap and rounds < 8: + 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"} + + class YtLongPipeline: def __init__(self) -> None: self._task: asyncio.Task[None] | None = None @@ -197,11 +327,17 @@ class YtLongPipeline: self._active_records = 0 self._active_uploads = 0 self.processed = 0 + self.sampled = 0 self.last_error = "" + self._last_sample_at = 0.0 def status(self) -> dict[str, Any]: cfg = db.get_settings_map() day = push_date_from_ts(time.time()) + try: + yt_long_db.sync_channels_from_shorts() + except Exception: + pass try: board = yt_long_db.channel_board(day) except Exception: @@ -211,6 +347,7 @@ class YtLongPipeline: "busy": self._active_records > 0 or self._active_uploads > 0, "enabled": bool(cfg.get("yt_long_enabled")), "processed": self.processed, + "sampled": self.sampled, "quota_gap": yt_long_db.yt_long_quota_gap(day, cfg), "quota_used": yt_long_db.yt_long_quota_used(day), "daily_max": yt_long_db.yt_long_daily_max(cfg), @@ -218,10 +355,14 @@ class YtLongPipeline: "last_error": self.last_error, "stats": yt_long_db.yt_long_stats(day), "board": board, + "douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)), "settings": { "yt_long_enabled": bool(cfg.get("yt_long_enabled")), "yt_long_with_shorts": bool(cfg.get("yt_long_with_shorts", True)), "yt_long_auto_upload": bool(cfg.get("yt_long_auto_upload", True)), + "yt_long_live_sample": bool(cfg.get("yt_long_live_sample", True)), + "yt_long_live_sample_interval_sec": int(cfg.get("yt_long_live_sample_interval_sec") or 180), + "yt_long_live_sample_batch": int(cfg.get("yt_long_live_sample_batch") or 1), "yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg), "yt_long_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), @@ -252,6 +393,21 @@ class YtLongPipeline: t.cancel() self._task = None + async def kick_pending_records(self, ids: list[str] | None = None) -> int: + pending = yt_long_db.list_pending_yt_long_jobs(limit=20) + if ids: + want = {str(x) for x in ids} + pending = [j for j in pending if str(j.get("id") or "") in want] + n = 0 + for job in pending: + claimed = yt_long_db.claim_yt_long_job_record(str(job.get("id") or "")) + if not claimed: + continue + self._active_records += 1 + asyncio.create_task(self._run_record(claimed)) + n += 1 + return n + async def _loop(self) -> None: while not self._stop.is_set(): try: @@ -259,6 +415,12 @@ class YtLongPipeline: if not cfg.get("yt_long_enabled"): await asyncio.sleep(5) continue + 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() + n = try_sample_live_rooms(cfg) + if n: + self.sampled += n try: yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=900) except Exception: diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index 147ddbc..b214385 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -93,6 +93,7 @@ type Status = { quota_gap?: number; daily_max?: number; last_error?: string; + douyin_live_count?: number; board?: { channels?: BoardChannel[]; total_gap?: number; push_date?: string }; settings?: Record; }; @@ -211,6 +212,37 @@ export default function YtLongPage() { } } + async function sampleNow() { + setBusy("sample"); + try { + const r = await fetchJson("/api/yt-long/sample-now", { method: "POST" }); + toast.push( + r.enqueued + ? `已取样入队 ${r.enqueued}(在播 ${r.live_count ?? "—"})` + : `未入队:${r.reason || "无候选"}(在播 ${r.live_count ?? 0})`, + r.enqueued ? "ok" : "warn", + ); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + + async function fillQuota() { + setBusy("fill"); + try { + const r = await fetchJson("/api/yt-long/fill-quota", { method: "POST" }); + toast.push(`补量入队 ${r.enqueued ?? 0}(剩余缺口 ${r.gap ?? "—"})`, "ok"); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + async function saveSettings() { setBusy("save"); try { @@ -235,15 +267,10 @@ export default function YtLongPage() { } async function importFromShorts() { - const ok = await confirm({ - title: "从 Shorts 导入频道", - message: "只复制 OAuth 到长视频独立频道表,不会修改 Shorts 频道或任务。", - }); - if (!ok) return; setBusy("import"); try { const r = await fetchJson("/api/yt-long/channels/import-shorts", { method: "POST" }); - toast.push(`导入完成:新建 ${r.created ?? 0} · 跳过 ${r.skipped ?? 0}`, "ok"); + toast.push(`已同步 Shorts 频道:新建 ${r.created ?? 0} · 更新 ${r.updated ?? 0}`, "ok"); await load(); } catch (e) { toast.push((e as Error).message, "err"); @@ -362,6 +389,23 @@ export default function YtLongPage() { 刷新 + + {st?.enabled ? (