From 7f4a1de2c484f555c4c047f006b9d81d4fa806e2 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 14 Aug 2026 11:40:12 -0500 Subject: [PATCH] =?UTF-8?q?fix:=20Shorts/TikTok=20=E7=AB=8B=E5=8D=B3?= =?UTF-8?q?=E5=8F=96=E6=A0=B7=E4=BB=8E=E5=BD=93=E5=89=8D=E6=8A=96=E9=9F=B3?= =?UTF-8?q?=E5=9C=A8=E6=92=AD=E7=AB=8B=E5=88=BB=E5=BC=80=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 手动取样不再只入队 1 条、也不再被 YouTube 上传配额拦住;点击后按在播直播间创建任务并马上开始录制。 Co-authored-by: Cursor --- backend/app/db.py | 32 +++++++++++- backend/app/main.py | 33 +++++++++---- backend/app/shorts_pipeline.py | 84 +++++++++++++++++++++++++++++++- backend/app/tiktok_db.py | 20 ++++++++ backend/app/tiktok_pipeline.py | 83 ++++++++++++++++++++++++++++++- desktop/src/pages/ShortsPage.tsx | 8 ++- frontend/src/app/shorts/page.tsx | 8 ++- frontend/src/app/tiktok/page.tsx | 8 ++- 8 files changed, 259 insertions(+), 17 deletions(-) diff --git a/backend/app/db.py b/backend/app/db.py index fc1a4ef..0bfda73 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -3311,7 +3311,12 @@ def room_ids_with_shorts_job_today(push_date: str) -> set[str]: conn.close() -def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None: +def pick_shorts_channel( + push_date: str, + cfg: dict[str, Any] | None = None, + *, + require_upload_quota: bool = True, +) -> dict[str, Any] | None: """Pick enabled channel with most room left today (Beijing day); under daily_min first.""" from .shorts_yt_quota import profile_id_for_channel, project_uploads_available @@ -3321,7 +3326,7 @@ def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> di scored: list[tuple[int, int, float, dict[str, Any]]] = [] for ch in channels: pid = profile_id_for_channel(ch) - if not project_uploads_available(cfg, profile_id=pid): + if require_upload_quota and not project_uploads_available(cfg, profile_id=pid): continue used = shorts_channel_upload_count(str(ch["id"]), push_date) daily_max = SHORTS_DAILY_FORCE @@ -3595,6 +3600,29 @@ def claim_pending_shorts_record() -> dict[str, Any] | None: conn.close() +def claim_shorts_job_record(job_id: str) -> dict[str, Any] | None: + now = time.time() + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE shorts_jobs + SET status = 'recording', attempts = attempts + 1, + started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END, + updated_at = ?, error = '' + WHERE id = ? AND status = 'pending' + """, + (now, now, job_id), + ) + conn.commit() + if cur.rowcount == 0: + return None + return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone()) + finally: + conn.close() + + def claim_next_shorts_job() -> dict[str, Any] | None: """Prefer due upload, then pending record.""" job = claim_due_shorts_upload() diff --git a/backend/app/main.py b/backend/app/main.py index 1d5bbdd..2b49e39 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -565,18 +565,22 @@ async def shorts_stop() -> dict[str, Any]: @app.post("/api/shorts/sample-now") async def shorts_sample_now() -> dict[str, Any]: - """Manually trigger one live-room sample tick (does not affect monitor).""" - from .shorts_pipeline import try_fill_daily_quota, try_sample_live_rooms + """Manually sample current Douyin lives and start recording immediately.""" + from .shorts_pipeline import sample_live_now cfg = db.get_settings_map() if not cfg.get("shorts_enabled"): raise HTTPException(400, "请先启用 Shorts") - n = try_sample_live_rooms(cfg) - qn = try_fill_daily_quota(cfg) + result = await asyncio.to_thread(sample_live_now, cfg) + recording = await shorts_pipeline.kick_pending_records(list(result.get("job_ids") or [])) st = shorts_pipeline.status() - st["just_enqueued"] = n + qn - st["just_sampled"] = n - st["just_quota_filled"] = qn + st["just_enqueued"] = int(result.get("enqueued") or 0) + st["just_sampled"] = int(result.get("enqueued") or 0) + st["just_quota_filled"] = 0 + st["live_count"] = int(result.get("live_count") or 0) + st["skipped_dedupe"] = int(result.get("skipped_dedupe") or 0) + st["recording"] = recording + st["reason"] = str(result.get("reason") or "") return st @@ -943,10 +947,19 @@ async def tiktok_stop() -> dict[str, Any]: @app.post("/api/tiktok/sample-now") async def tiktok_sample_now() -> dict[str, Any]: - from .tiktok_pipeline import try_sample_live_rooms + from .tiktok_pipeline import sample_live_now - n = await asyncio.to_thread(try_sample_live_rooms) - return {"ok": True, "enqueued": n, "status": tiktok_pipeline.status()} + result = await asyncio.to_thread(sample_live_now) + recording = await tiktok_pipeline.kick_pending_records(list(result.get("job_ids") or [])) + return { + "ok": True, + "enqueued": int(result.get("enqueued") or 0), + "live_count": int(result.get("live_count") or 0), + "skipped_dedupe": int(result.get("skipped_dedupe") or 0), + "recording": recording, + "reason": str(result.get("reason") or ""), + "status": tiktok_pipeline.status(), + } @app.get("/api/tiktok/channels") diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 536c23e..b6d70f3 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -57,6 +57,7 @@ def _enqueue_job( stream_url: str = "", cfg: dict[str, Any] | None = None, channel_pk: str = "", + require_upload_quota: bool = True, ) -> Optional[dict[str, Any]]: """Internal enqueue; never raises.""" try: @@ -80,7 +81,7 @@ def _enqueue_job( if used < daily_max: channel = ch if not channel: - channel = db.pick_shorts_channel(day, settings) + channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota) if not channel: return None sid = str((session or {}).get("id") or room.get("active_session_id") or "") @@ -177,6 +178,65 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: return 0 +def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: + """Manual sample from current Douyin lives; records even if YouTube upload quota is exhausted.""" + settings = cfg or db.get_settings_map() + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + live_count = len(rooms) + empty: dict[str, Any] = { + "enqueued": 0, + "job_ids": [], + "live_count": live_count, + "skipped_dedupe": 0, + "reason": "", + } + if not settings.get("shorts_enabled"): + empty["reason"] = "请先启用 Shorts" + return empty + if live_count <= 0: + empty["reason"] = "当前没有抖音在播直播间" + return empty + day = push_date_from_ts(time.time()) + any_live = settings.get("shorts_sample_any_live", True) + unused: list[dict[str, Any]] = [] + skipped = 0 + for room in rooms: + rid = str(room.get("room_id") or "") + if not rid: + continue + if not any_live and not _room_eligible(room, settings): + continue + if settings.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(rid, day): + skipped += 1 + continue + unused.append(room) + if not unused: + empty["skipped_dedupe"] = skipped + empty["reason"] = f"在播 {live_count} 间均已今日取样" + return empty + if not db.pick_shorts_channel(day, settings, require_upload_quota=False): + empty["skipped_dedupe"] = skipped + empty["reason"] = "没有可用 Shorts 频道(或今日配额已满)" + return empty + gap = max(1, db.shorts_total_quota_gap(day)) + batch = min(len(unused), gap, 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) + 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 "入队失败,请检查 Shorts 频道", + } + + def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: """Enqueue live-room clips toward each channel's daily_max before Beijing midnight.""" try: @@ -530,6 +590,28 @@ class ShortsPipeline: 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: diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index 8e2d656..e5bbb59 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -381,6 +381,26 @@ def claim_pending_tiktok_record() -> dict[str, Any] | None: conn.close() +def claim_tiktok_job_record(job_id: str) -> dict[str, Any] | None: + now = time.time() + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE tiktok_jobs SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1 + WHERE id = ? AND status = 'pending' + """, + (now, now, job_id), + ) + conn.commit() + if cur.rowcount == 0: + return None + return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone()) + finally: + conn.close() + + def claim_due_tiktok_upload() -> dict[str, Any] | None: now = time.time() with _lock: diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index 2a89297..9457978 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -42,10 +42,11 @@ def _enqueue_job( stream_url: str = "", cfg: dict[str, Any] | None = None, channel_pk: str = "", + force: bool = False, ) -> Optional[dict[str, Any]]: try: settings = cfg or db.get_settings_map() - if not settings.get("tiktok_enabled"): + if not force and not settings.get("tiktok_enabled"): return None room_id = str((session or {}).get("room_id") or room.get("room_id") or "") if room_id.startswith("yt:"): @@ -106,6 +107,64 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: return n +def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: + """Manual sample: enqueue current Douyin lives and return job ids for immediate record.""" + settings = cfg or db.get_settings_map() + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + live_count = len(rooms) + empty = { + "enqueued": 0, + "job_ids": [], + "live_count": live_count, + "skipped_dedupe": 0, + "reason": "", + } + if live_count <= 0: + empty["reason"] = "当前没有抖音在播直播间" + return empty + day = push_date_from_ts(time.time()) + if settings.get("tiktok_sample_any_live", True): + candidates = list(rooms) + else: + candidates = [r for r in rooms if _room_eligible(r, settings)] + unused: list[dict[str, Any]] = [] + skipped = 0 + for room in candidates: + rid = str(room.get("room_id") or "") + if not rid: + continue + if settings.get("tiktok_dedupe_room_day", True) and tiktok_db.has_tiktok_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 + if not tiktok_db.pick_tiktok_channel(day): + empty["skipped_dedupe"] = skipped + empty["reason"] = "没有可用 TikTok 账号(需 Cookie 且未满每日配额)" + return empty + gap = max(1, tiktok_db.tiktok_total_quota_gap(day)) + batch = min(len(unused), gap, 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, cfg=settings, force=True) + if job and job.get("id"): + job_ids.append(str(job["id"])) + reason = "" if job_ids else "入队失败,请检查 TikTok 账号 Cookie" + return { + "enqueued": len(job_ids), + "job_ids": job_ids, + "live_count": live_count, + "skipped_dedupe": skipped, + "reason": reason, + } + + class TikTokPipeline: def __init__(self) -> None: self._task: asyncio.Task | None = None @@ -166,6 +225,28 @@ class TikTokPipeline: 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 = max(1, int(cfg.get("tiktok_max_concurrent") or 1)) + + 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 = tiktok_db.claim_tiktok_job_record(jid) + if not job: + continue + self._active_records += 1 + asyncio.create_task(self._run_record(job)) + + asyncio.create_task(_drain()) + return min(len(ids), max_rec) + async def upload_job_now(self, job_id: str) -> dict[str, Any]: job = tiktok_db.claim_tiktok_job_manual_upload(job_id) if not job: diff --git a/desktop/src/pages/ShortsPage.tsx b/desktop/src/pages/ShortsPage.tsx index c6b7551..648cee0 100644 --- a/desktop/src/pages/ShortsPage.tsx +++ b/desktop/src/pages/ShortsPage.tsx @@ -760,7 +760,13 @@ export default function ShortsPage() { setBusy(true); try { const r = await fetchJson("/api/shorts/sample-now", { method: "POST" }); - setMsg(`取样入队 ${r.just_enqueued ?? 0}(录完后自动错峰排程)`); + const n = Number(r.just_enqueued ?? 0); + const live = Number(r.live_count ?? 0); + if (n > 0) { + setMsg(`正在从 ${live} 路在播中录制 ${n} 条(录完后自动错峰排程)`); + } else { + setError(String(r.reason || "没有可取样的在播直播间")); + } await load(); } catch (e) { setError((e as Error).message); diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index f528bf1..487f756 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -910,7 +910,13 @@ export default function ShortsPage() { setBusy(true); try { const r = await fetchJson("/api/shorts/sample-now", { method: "POST" }); - setMsg(`取样入队 ${r.just_enqueued ?? 0}(录完后自动错峰排程)`); + const n = Number(r.just_enqueued ?? 0); + const live = Number(r.live_count ?? 0); + if (n > 0) { + setMsg(`正在从 ${live} 路在播中录制 ${n} 条(录完后自动错峰排程)`); + } else { + setError(String(r.reason || "没有可取样的在播直播间")); + } await load(); } catch (e) { setError((e as Error).message); diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index 21f7af8..2f98978 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -288,7 +288,13 @@ export default function TikTokPage() { const sampleNow = async () => { const r = await fetchJson("/api/tiktok/sample-now", { method: "POST" }); - toast.push(`已取样 ${r.enqueued || 0} 条`, "ok"); + const n = Number(r.enqueued || 0); + const live = Number(r.live_count || 0); + if (n > 0) { + toast.push(`正在从 ${live} 路在播中录制 ${n} 条`, "ok"); + } else { + toast.push(String(r.reason || "没有可取样的在播直播间"), "err"); + } void load(); };