diff --git a/backend/app/db.py b/backend/app/db.py index 0bfda73..8b3b81f 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -2889,8 +2889,8 @@ def purge_orphan_shorts_jobs(*, limit: int = 500) -> dict[str, int]: SELECT j.id, j.clip_path FROM shorts_jobs j LEFT JOIN shorts_channels c ON c.id = j.channel_pk - WHERE c.id IS NULL - OR TRIM(COALESCE(j.channel_pk, '')) = '' + WHERE TRIM(COALESCE(j.channel_pk, '')) != '' + AND c.id IS NULL ORDER BY j.updated_at DESC LIMIT ? """, diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index b6d70f3..5ad7454 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -58,16 +58,18 @@ def _enqueue_job( 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((session or {}).get("room_id") or room.get("room_id") or "") + room_id = str(room.get("room_id") or (session or {}).get("room_id") or "") if room_id.startswith("yt:"): return None - day = push_date_from_ts(float((session or {}).get("started_at") or time.time())) + day = str(push_date or "").strip() or push_date_from_ts(time.time()) # Global dedup: same room_id can only be enqueued ONCE per Beijing day across ALL channels if settings.get("shorts_dedupe_room_day", True) and room_id: if db.has_shorts_job_for_room_day(room_id, day): @@ -82,7 +84,7 @@ def _enqueue_job( channel = ch if not channel: channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota) - if not channel: + if require_channel and not channel: return None sid = str((session or {}).get("id") or room.get("active_session_id") or "") job = db.create_shorts_job( @@ -94,7 +96,7 @@ def _enqueue_job( (session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or "" ), stream_url=str(stream_url or ""), - channel_pk=str(channel["id"]), + channel_pk=str((channel or {}).get("id") or ""), push_date=day, ) if not job: @@ -108,7 +110,7 @@ def _enqueue_job( room_pk=str(room.get("id") or ""), session_id=sid, anchor_name=str(job.get("anchor_name") or ""), - meta={"shorts_job_id": job.get("id"), "channel_pk": channel.get("id")}, + meta={"shorts_job_id": job.get("id"), "channel_pk": (channel or {}).get("id") or ""}, ) except Exception: pass @@ -214,18 +216,21 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: 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) + 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) + 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 { @@ -233,7 +238,7 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: "job_ids": job_ids, "live_count": live_count, "skipped_dedupe": skipped, - "reason": "" if job_ids else "入队失败,请检查 Shorts 频道", + "reason": "" if job_ids else "入队失败(可能已有同房间任务)", } @@ -1158,10 +1163,19 @@ class ShortsPipeline: raise ValueError("成片文件不存在,已重新排队录制") channel = db.get_shorts_channel(str(fresh.get("channel_pk") or job.get("channel_pk") or "")) if not channel: - clip_gone = clip - db.purge_orphan_shorts_jobs(limit=50) - if clip_gone: - self._delete_clip(clip_gone) + 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 diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index 9457978..162d0b2 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -43,15 +43,17 @@ def _enqueue_job( cfg: dict[str, Any] | None = None, channel_pk: str = "", force: bool = False, + push_date: str = "", + require_channel: bool = True, ) -> Optional[dict[str, Any]]: try: settings = cfg or db.get_settings_map() 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 "") + room_id = str(room.get("room_id") or (session or {}).get("room_id") or "") if room_id.startswith("yt:"): return None - day = push_date_from_ts(float((session or {}).get("started_at") or time.time())) + day = str(push_date or "").strip() or push_date_from_ts(time.time()) if settings.get("tiktok_dedupe_room_day", True) and room_id: if tiktok_db.has_tiktok_job_for_room_day(room_id, day): return None @@ -64,7 +66,7 @@ def _enqueue_job( channel = ch if not channel: channel = tiktok_db.pick_tiktok_channel(day) - if not channel: + if require_channel and not channel: return None sid = str((session or {}).get("id") or room.get("active_session_id") or "") return tiktok_db.create_tiktok_job( @@ -76,7 +78,7 @@ def _enqueue_job( (session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or "" ), stream_url=str(stream_url or ""), - channel_pk=str(channel["id"]), + channel_pk=str((channel or {}).get("id") or ""), push_date=day, ) except Exception: @@ -141,21 +143,23 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: 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) + 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, cfg=settings, force=True) + job = _enqueue_job( + session=session, + room=room, + cfg=settings, + force=True, + push_date=day, + require_channel=False, + ) if job and job.get("id"): job_ids.append(str(job["id"])) - reason = "" if job_ids else "入队失败,请检查 TikTok 账号 Cookie" + reason = "" if job_ids else "入队失败(可能已有同房间任务)" return { "enqueued": len(job_ids), "job_ids": job_ids, @@ -403,7 +407,12 @@ class TikTokPipeline: raise ValueError("成片文件不存在") channel = tiktok_db.get_tiktok_channel(str(fresh.get("channel_pk") or "")) if not channel: - raise ValueError("账号不存在") + channel = tiktok_db.pick_tiktok_channel(str(fresh.get("push_date") or push_date_from_ts(time.time()))) + if channel: + tiktok_db.update_tiktok_job(jid, channel_pk=str(channel["id"])) + if not channel: + tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传") + return if not tiktok_session.channel_has_session(channel): tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie") return