diff --git a/backend/app/main.py b/backend/app/main.py index 8446b0f..f8a49b0 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -48,6 +48,7 @@ from .models import ( TikTokJobsBulkBody, TikTokOAuthConfig, TikTokSessionBody, + TikTokUploadNowBody, YouTubeVideoUpdate, ) from .monitor import monitor @@ -844,7 +845,10 @@ def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None: out["clip_ready"] = bool(clip) and Path(clip).is_file() ch = tiktok_db.get_tiktok_channel(str(out.get("channel_pk") or "")) or {} if ch: - out["channel_name"] = ch.get("name") or "" + out["channel_name"] = ch.get("name") or ch.get("tiktok_username") or "" + else: + out["channel_name"] = "" + out["channel_pending"] = not bool(str(out.get("channel_pk") or "").strip()) return out @@ -1080,9 +1084,10 @@ async def tiktok_job_retry(job_id: str) -> dict[str, Any]: @app.post("/api/tiktok/jobs/{job_id}/upload-now") -async def tiktok_job_upload_now(job_id: str) -> dict[str, Any]: +async def tiktok_job_upload_now(job_id: str, body: TikTokUploadNowBody | None = None) -> dict[str, Any]: + channel_pk = str((body.channel_pk if body else "") or "").strip() try: - job = await tiktok_pipeline.upload_job_now(job_id) + job = await tiktok_pipeline.upload_job_now(job_id, channel_pk=channel_pk) except ValueError as exc: raise HTTPException(400, str(exc)) from exc except Exception as exc: diff --git a/backend/app/models.py b/backend/app/models.py index d683592..87749eb 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -306,6 +306,10 @@ class TikTokJobsBulkBody(BaseModel): action: str = "retry" # retry | upload_now +class TikTokUploadNowBody(BaseModel): + channel_pk: str = "" + + class YouTubeVideoUpdate(BaseModel): title: Optional[str] = None description: Optional[str] = None diff --git a/backend/app/shorts_clip.py b/backend/app/shorts_clip.py index c480df0..80ef7cd 100644 --- a/backend/app/shorts_clip.py +++ b/backend/app/shorts_clip.py @@ -18,11 +18,29 @@ def _headers_arg() -> str: ) -async def resolve_stream_url(*, source_url: str = "", stream_url: str = "", cookie: str = "") -> str: - url = (stream_url or "").strip() - if url: - return url +async def resolve_stream_url( + *, + source_url: str = "", + stream_url: str = "", + cookie: str = "", + prefer_fresh: bool = False, +) -> str: + """Resolve a playable Douyin live URL. + + Douyin CDN links expire / 404 quickly. When recording, prefer_fresh=True so we + always re-check the live page instead of trusting a queued stream_url. + """ src = (source_url or "").strip() + cached = (stream_url or "").strip() + if prefer_fresh and src: + result = await check_room(src, cookie=cookie) + if result.get("ok") and result.get("is_live"): + fresh = str(result.get("stream_url") or "").strip() + if fresh: + return fresh + return "" + if cached: + return cached if not src: return "" result = await check_room(src, cookie=cookie) diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index e841846..e1204b9 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -15,7 +15,13 @@ def _force_daily(v: int) -> int: return TIKTOK_DAILY_FORCE -# ---------- channels ---------- +# 占用「今日上传配额」的状态:待录/录制中不算,避免取样把账号配额占满后无法再分配 +_TIKTOK_QUOTA_STATUSES = ( + "scheduled", + "uploading", + "uploaded", + "done", +) def list_tiktok_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]: with _lock: @@ -141,23 +147,30 @@ def delete_tiktok_channel(channel_pk: str) -> bool: def tiktok_channel_upload_count(channel_pk: str, push_date: str) -> int: + """Jobs that consume today's upload quota (排程/上传中/已上传).""" + placeholders = ",".join("?" for _ in _TIKTOK_QUOTA_STATUSES) with _lock: conn = _connect() try: row = conn.execute( - """ + f""" SELECT COUNT(*) AS c FROM tiktok_jobs WHERE channel_pk = ? AND push_date = ? - AND status NOT IN ('failed', 'skipped') + AND status IN ({placeholders}) """, - (channel_pk, push_date), + (channel_pk, push_date, *_TIKTOK_QUOTA_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() -def pick_tiktok_channel(push_date: str) -> dict[str, Any] | None: +def pick_tiktok_channel( + push_date: str, + *, + require_quota: bool = True, +) -> dict[str, Any] | None: + """Pick enabled Cookie-ready channel. If require_quota, skip channels at daily upload max.""" from . import tiktok_session channels = list_tiktok_channels(enabled=True) @@ -169,7 +182,7 @@ def pick_tiktok_channel(push_date: str) -> dict[str, Any] | None: continue used = tiktok_channel_upload_count(str(ch["id"]), push_date) daily_max = TIKTOK_DAILY_FORCE - if used >= daily_max: + if require_quota and used >= daily_max: continue daily_min = TIKTOK_DAILY_FORCE under = 0 if used < daily_min else 1 @@ -180,6 +193,45 @@ def pick_tiktok_channel(push_date: str) -> dict[str, Any] | None: return scored[0][3] +def ensure_tiktok_job_channel(job: dict[str, Any] | None, *, require_quota: bool = False) -> dict[str, Any] | None: + """Attach a TikTok channel to job if missing. Returns channel row or None.""" + j = job or {} + jid = str(j.get("id") or "") + day = str(j.get("push_date") or "") or push_date_from_ts(time.time()) + pk = str(j.get("channel_pk") or "").strip() + if pk: + ch = get_tiktok_channel(pk) + if ch and ch.get("enabled"): + return ch + ch = pick_tiktok_channel(day, require_quota=require_quota) + if not ch and require_quota: + # fallback soft-assign so UI/ops still have an owner account + ch = pick_tiktok_channel(day, require_quota=False) + if ch and jid: + update_tiktok_job(jid, channel_pk=str(ch["id"])) + return ch + + +def backfill_tiktok_job_channels(*, push_date: str = "", limit: int = 50) -> int: + """Assign channels to jobs that were enqueued without channel_pk.""" + day = push_date or push_date_from_ts(time.time()) + data = list_tiktok_jobs(push_date=day, limit=500, offset=0) + n = 0 + for j in data.get("jobs") or []: + if n >= limit: + break + if str(j.get("channel_pk") or "").strip(): + continue + if str(j.get("status") or "") in {"failed", "skipped", "uploaded", "done"}: + continue + # Prefer hard quota for jobs about to upload; soft for pending/recording pool + need_hard = str(j.get("status") or "") in {"scheduled", "uploading", "recorded"} + ch = ensure_tiktok_job_channel(j, require_quota=need_hard) + if ch: + n += 1 + return n + + def tiktok_total_quota_gap(push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) gap = 0 @@ -534,6 +586,49 @@ def finalize_tiktok_upload( conn.close() +def reclaim_stale_tiktok_recordings(*, max_age_sec: float = 240) -> int: + """Fail or requeue recordings stuck longer than expected (1min clip + buffer).""" + now = time.time() + cutoff = now - max(120.0, float(max_age_sec)) + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT id, attempts FROM tiktok_jobs + WHERE status = 'recording' AND started_at > 0 AND started_at < ? + """, + (cutoff,), + ).fetchall() + n = 0 + for row in rows: + attempts = int(row["attempts"] or 0) + if attempts <= 1: + conn.execute( + """ + UPDATE tiktok_jobs + SET status = 'pending', error = '录制超时,自动重试', updated_at = ?, started_at = 0 + WHERE id = ? AND status = 'recording' + """, + (now, row["id"]), + ) + else: + conn.execute( + """ + UPDATE tiktok_jobs + SET status = 'failed', error = '录制卡死超时', finished_at = ?, updated_at = ? + WHERE id = ? AND status = 'recording' + """, + (now, now, row["id"]), + ) + n += conn.total_changes + if n: + conn.commit() + return n + finally: + conn.close() + + def reclaim_stale_tiktok_uploads(*, max_age_sec: float = 900) -> int: """Only use updated_at (upload lease), never recording started_at.""" cutoff = time.time() - max(600.0, float(max_age_sec)) diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index 343844a..645c3c5 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -65,7 +65,10 @@ def _enqueue_job( if used < db.TIKTOK_DAILY_FORCE: channel = ch if not channel: - channel = tiktok_db.pick_tiktok_channel(day) + # Prefer under upload-quota; if all full, soft-assign so job still has an owner account + channel = tiktok_db.pick_tiktok_channel(day, require_quota=True) + if not channel: + channel = tiktok_db.pick_tiktok_channel(day, require_quota=False) if require_channel and not channel: return None sid = str((session or {}).get("id") or room.get("active_session_id") or "") @@ -143,7 +146,7 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: empty["skipped_dedupe"] = skipped empty["reason"] = f"在播 {live_count} 间均已今日取样" return empty - batch = min(len(unused), 8) + batch = min(len(unused), 3) random.shuffle(unused) job_ids: list[str] = [] for room in unused[:batch]: @@ -252,12 +255,23 @@ class TikTokPipeline: asyncio.create_task(_drain()) return min(len(ids), max_rec) - async def upload_job_now(self, job_id: str) -> dict[str, Any]: + async def upload_job_now(self, job_id: str, *, channel_pk: str = "") -> dict[str, Any]: + pk = str(channel_pk or "").strip() + if pk: + ch = tiktok_db.get_tiktok_channel(pk) + if not ch or not ch.get("enabled"): + raise ValueError("所选 TikTok 账号不存在或已停用") + if not tiktok_session.channel_has_session(ch): + raise ValueError("所选账号未配置 Cookie") + tiktok_db.update_tiktok_job(job_id, channel_pk=pk) job = tiktok_db.claim_tiktok_job_manual_upload(job_id) if not job: raise ValueError("任务不可立即上传(需要成片且未发布;上传中卡住的可强制重试)") + if pk and str(job.get("channel_pk") or "") != pk: + tiktok_db.update_tiktok_job(job_id, channel_pk=pk) + job = {**job, "channel_pk": pk} try: - await self._do_upload(job) + await self._do_upload(job, manual=True) except Exception as exc: tiktok_db.update_tiktok_job( job_id, @@ -305,6 +319,14 @@ class TikTokPipeline: tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=900) except Exception: pass + try: + tiktok_db.reclaim_stale_tiktok_recordings(max_age_sec=240) + except Exception: + pass + try: + tiktok_db.backfill_tiktok_job_channels(limit=20) + except Exception: + pass max_up = max(1, int(cfg.get("tiktok_max_concurrent") or 1)) while self._active_uploads < max_up: job = tiktok_db.claim_due_tiktok_upload() @@ -312,7 +334,8 @@ class TikTokPipeline: break self._active_uploads += 1 asyncio.create_task(self._run_upload(job)) - max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1)) + # 1 分钟成片时并发 1 会把队列拖很长,后面房间容易下播;最多 2 路并行录制 + max_rec = max(1, min(2, int(cfg.get("tiktok_max_concurrent") or 1) + 1)) while self._active_records < max_rec: job = tiktok_db.claim_pending_tiktok_record() if not job: @@ -330,7 +353,7 @@ class TikTokPipeline: return self._upload_inflight.add(jid) try: - await self._do_upload(job) + await self._do_upload(job, manual=False) self.processed += 1 except Exception as exc: self.last_error = str(exc)[:240] @@ -362,12 +385,29 @@ class TikTokPipeline: cfg = db.get_settings_map() jid = str(job.get("id") or "") cookie = str(cfg.get("dy_cookie") or "") - stream = await resolve_stream_url( - source_url=str(job.get("source_url") or ""), - stream_url=str(job.get("stream_url") or ""), - cookie=cookie, - ) + source = str(job.get("source_url") or "") + + async def _fresh_stream() -> str: + return await resolve_stream_url( + source_url=source, + stream_url="", + cookie=cookie, + prefer_fresh=True, + ) + + stream = await _fresh_stream() if not stream: + err = str(job.get("error") or "") + # 取样入队时在播,真正开录时可能已下播或取流抖动:给一次重排队 + if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900: + tiktok_db.update_tiktok_job( + jid, + status="pending", + error="stream_retry:1", + stream_url="", + started_at=0, + ) + return tiktok_db.update_tiktok_job( jid, status="failed", @@ -375,22 +415,56 @@ class TikTokPipeline: finished_at=time.time(), ) return + # TikTok 素材最少录 1 分钟 sec = max(60, int(cfg.get("tiktok_clip_sec") or 60)) outcome = await record_clip(job_id=f"tiktok_{jid[:8]}", stream_url=stream, seconds=sec) if not outcome.get("ok"): - tiktok_db.update_tiktok_job( - jid, - status="failed", - error=str(outcome.get("error") or "录制失败")[:500], - finished_at=time.time(), - ) - return + err = str(outcome.get("error") or "录制失败") + low = err.lower() + # CDN 链接 404 / 打开失败:立刻换新流再试一次 + if any(x in low for x in ("404", "error opening", "server returned")) and "stream_ffmpeg_retry" not in str( + job.get("error") or "" + ): + stream2 = await _fresh_stream() + if stream2 and stream2 != stream: + outcome2 = await record_clip(job_id=f"tiktok_{jid[:8]}r", stream_url=stream2, seconds=sec) + if outcome2.get("ok"): + outcome = outcome2 + stream = stream2 + err = "" + else: + err = str(outcome2.get("error") or err) + if err: + tiktok_db.update_tiktok_job(jid, error="stream_ffmpeg_retry:1") + if not outcome.get("ok"): + tiktok_db.update_tiktok_job( + jid, + status="failed", + error=err[:500], + stream_url="", + finished_at=time.time(), + ) + return + out_path = str(outcome.get("path") or "") seconds = float(outcome.get("seconds") or sec) day = str(job.get("push_date") or push_date_from_ts(time.time())) - ch_pk = str(job.get("channel_pk") or "") - if cfg.get("tiktok_auto_upload", True): + channel = tiktok_db.ensure_tiktok_job_channel(job, require_quota=False) + ch_pk = str((channel or {}).get("id") or job.get("channel_pk") or "") + if cfg.get("tiktok_auto_upload", True) and ch_pk: + used = tiktok_db.tiktok_channel_upload_count(ch_pk, day) + if used >= db.TIKTOK_DAILY_FORCE: + tiktok_db.update_tiktok_job( + jid, + status="recorded", + clip_path=out_path, + clip_seconds=seconds, + stream_url=stream, + channel_pk=ch_pk, + error="账号今日上传配额已满,成片已保留", + ) + return upload_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=cfg) tiktok_db.update_tiktok_job( jid, @@ -398,15 +472,22 @@ class TikTokPipeline: clip_path=out_path, clip_seconds=seconds, stream_url=stream, + channel_pk=ch_pk, upload_at=upload_at, error="", ) else: tiktok_db.update_tiktok_job( - jid, status="recorded", clip_path=out_path, clip_seconds=seconds, stream_url=stream, error="" + jid, + status="recorded", + clip_path=out_path, + clip_seconds=seconds, + stream_url=stream, + channel_pk=ch_pk, + error="" if ch_pk else "成片已保留,待分配 TikTok 账号", ) - async def _do_upload(self, job: dict[str, Any]) -> None: + async def _do_upload(self, job: dict[str, Any], *, manual: bool = False) -> None: cfg = db.get_settings_map() jid = str(job.get("id") or "") fresh = tiktok_db.get_tiktok_job(jid) or job @@ -420,14 +501,22 @@ class TikTokPipeline: clip = str(fresh.get("clip_path") or "") if not clip or not Path(clip).is_file(): raise ValueError("成片文件不存在") - channel = tiktok_db.get_tiktok_channel(str(fresh.get("channel_pk") or "")) - if not channel: - 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"])) + channel = tiktok_db.ensure_tiktok_job_channel(fresh, require_quota=not manual) if not channel: tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传") return + day = str(fresh.get("push_date") or push_date_from_ts(time.time())) + used = tiktok_db.tiktok_channel_upload_count(str(channel["id"]), day) + # current job is already in uploading → exclude self when judging remaining slots + others = max(0, used - 1) + if not manual and others >= db.TIKTOK_DAILY_FORCE: + tiktok_db.update_tiktok_job( + jid, + status="recorded", + channel_pk=str(channel["id"]), + error="账号今日上传配额已满,成片已保留", + ) + return if not tiktok_session.channel_has_session(channel): tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie") return diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index 2c71ad9..dd08be2 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -444,8 +444,9 @@ export default function TikTokPage() { uploadUx.confirmUpload(channelPk)} busy={uploadUx.busy} />
@@ -898,7 +899,9 @@ export default function TikTokPage() { jobs.map((j) => ( {j.anchor_name || "—"} - {j.channel_name || "—"} + + {j.channel_name || (j.channel_pk ? "—" : "待分配")} + {Number(j.clip_seconds || 0) > 0 ? ( fmtDuration(Number(j.clip_seconds)) diff --git a/frontend/src/components/TikTokUploadUx.tsx b/frontend/src/components/TikTokUploadUx.tsx index bb45409..9976dbe 100644 --- a/frontend/src/components/TikTokUploadUx.tsx +++ b/frontend/src/components/TikTokUploadUx.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { AlertCircle, CheckCircle2, @@ -26,6 +26,15 @@ export type TikTokUploadTarget = { title_template?: string; }; +export type TikTokUploadChannelOption = { + id: string; + name: string; + tiktok_username?: string; + enabled?: boolean; + authorized?: boolean; + title_template?: string; +}; + type UploadPhase = "idle" | "uploading" | "success" | "failed"; type UploadTrack = { @@ -109,9 +118,10 @@ export function useTikTokUpload(onRefresh: () => Promise) { ); const startUpload = useCallback( - async (target: TikTokUploadTarget) => { + async (target: TikTokUploadTarget, channelPk = "") => { const id = target.id; const label = labelOf(target); + const pk = String(channelPk || target.channel_pk || "").trim(); setConfirmTarget(null); patchTrack(id, { phase: "uploading", startedAt: Date.now(), error: "" }); @@ -120,7 +130,10 @@ export function useTikTokUpload(onRefresh: () => Promise) { pollRef.current = ac; try { - const data = await fetchJson(`/api/tiktok/jobs/${id}/upload-now`, { method: "POST" }); + const data = await fetchJson(`/api/tiktok/jobs/${id}/upload-now`, { + method: "POST", + body: JSON.stringify({ channel_pk: pk }), + }); const job = data.job || data; const st = String(job.status || ""); if (st === "uploaded" || st === "done") { @@ -152,29 +165,53 @@ export function useTikTokUpload(onRefresh: () => Promise) { confirmTarget, openConfirm: setConfirmTarget, cancelConfirm: () => setConfirmTarget(null), - confirmUpload: () => confirmTarget && void startUpload(confirmTarget), + confirmUpload: (channelPk?: string) => confirmTarget && void startUpload(confirmTarget, channelPk || ""), tracks, - retryUpload: (target: TikTokUploadTarget) => void startUpload(target), + retryUpload: (target: TikTokUploadTarget) => void startUpload(target, target.channel_pk || ""), busy: Object.values(tracks).some((t) => t.phase === "uploading"), }; } export function TikTokUploadConfirmModal({ target, + channels, onCancel, onConfirm, busy, }: { target: TikTokUploadTarget | null; + channels: TikTokUploadChannelOption[]; onCancel: () => void; - onConfirm: () => void; + onConfirm: (channelPk: string) => void; busy?: boolean; }) { + const readyChannels = useMemo( + () => channels.filter((c) => c.enabled !== false && c.authorized), + [channels], + ); + const [channelPk, setChannelPk] = useState(""); + + useEffect(() => { + if (!target) { + setChannelPk(""); + return; + } + const preferred = String(target.channel_pk || "").trim(); + if (preferred && readyChannels.some((c) => c.id === preferred)) { + setChannelPk(preferred); + return; + } + setChannelPk(readyChannels[0]?.id || ""); + }, [target, readyChannels]); + if (!target) return null; const label = labelOf(target); const scheduled = target.upload_at ? fmtTs(Number(target.upload_at)) : "未排程"; const duration = Number(target.clip_seconds || 0) > 0 ? fmtDuration(Number(target.clip_seconds)) : "未知"; + const selected = readyChannels.find((c) => c.id === channelPk); + const caption = selected?.title_template || target.title_template || ""; + const canSubmit = Boolean(channelPk) && target.clip_ready !== false && !busy; return (
{label}
+
-
目标账号 · {target.channel_name || "—"}
素材时长 · {duration}
原错峰排程 · {scheduled}
{target.clip_ready === false ? "成片状态 · 等待录制完成" : "成片状态 · 已就绪"}
- {target.title_template ?
发布文案 · {target.title_template}
: null} + {caption ?
发布文案 · {caption}
:
发布文案 · (空)
}
{target.clip_ready !== false && target.id ? (
@@ -232,8 +288,8 @@ export function TikTokUploadConfirmModal({