diff --git a/backend/app/db.py b/backend/app/db.py index dbc5152..4e06710 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -283,6 +283,18 @@ def init_db() -> None: conn.execute( "ALTER TABLE tiktok_channels ADD COLUMN socks_profile_id TEXT NOT NULL DEFAULT ''" ) + if "platform_limit_at" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN platform_limit_at REAL NOT NULL DEFAULT 0" + ) + if "platform_limit_msg" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN platform_limit_msg TEXT NOT NULL DEFAULT ''" + ) + if "platform_limit_probe_at" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN platform_limit_probe_at REAL NOT NULL DEFAULT 0" + ) sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()} for col, ddl in [ ("oauth_ok", "INTEGER NOT NULL DEFAULT -1"), diff --git a/backend/app/main.py b/backend/app/main.py index b98416e..08683ec 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -837,6 +837,10 @@ def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: out["socks_profile_id"] = str(out.get("socks_profile_id") or "").strip() prof = tiktok_socks.get_socks_profile(out["socks_profile_id"]) out["socks_profile_label"] = str((prof or {}).get("label") or "") if out["socks_enabled"] else "" + out["platform_limit_at"] = float(out.get("platform_limit_at") or 0) + out["platform_limit_msg"] = str(out.get("platform_limit_msg") or "") + out["platform_limit_probe_at"] = float(out.get("platform_limit_probe_at") or 0) + out["platform_limited"] = out["platform_limit_at"] > 0 out.update(tiktok_session.cookie_age_info(ch, persist_backfill=True)) return out diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index a279bfd..5c3314a 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -109,6 +109,7 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No "title_template", "description_template", "privacy_level", "last_assigned_at", "oauth_ok", "oauth_checked_at", "oauth_error", "note", "cookie_saved_at", "socks_enabled", "socks_profile_id", + "platform_limit_at", "platform_limit_msg", "platform_limit_probe_at", } with _lock: conn = _connect() @@ -461,21 +462,163 @@ def claim_tiktok_job_record(job_id: str) -> dict[str, Any] | None: conn.close() -def claim_due_tiktok_upload() -> dict[str, Any] | None: +def mark_tiktok_platform_limit(channel_pk: str, message: str) -> dict[str, Any] | None: + msg = (message or "TikTok 官方限流").strip()[:400] + return update_tiktok_channel( + channel_pk, + platform_limit_at=time.time(), + platform_limit_msg=msg, + ) + + +def clear_tiktok_platform_limit(channel_pk: str) -> dict[str, Any] | None: + return update_tiktok_channel( + channel_pk, + platform_limit_at=0, + platform_limit_msg="", + platform_limit_probe_at=0, + ) + + +def channel_has_platform_limit(ch: dict[str, Any] | None) -> bool: + if not ch: + return False + return float(ch.get("platform_limit_at") or 0) > 0 + + +def list_tiktok_channels_needing_limit_probe(*, min_gap_sec: float = 3600.0) -> list[dict[str, Any]]: + """Channels currently platform-limited and due for an hourly upload probe.""" now = time.time() + gap = max(600.0, float(min_gap_sec or 3600.0)) + out: list[dict[str, Any]] = [] + for ch in list_tiktok_channels(enabled=True): + if not channel_has_platform_limit(ch): + continue + last = float(ch.get("platform_limit_probe_at") or 0) + # First probe after mark: wait at least min_gap from limit_at + if last <= 0: + last = float(ch.get("platform_limit_at") or 0) + if (now - last) < gap: + continue + out.append(ch) + return out + + +def claim_tiktok_limit_probe_job(channel_pk: str) -> dict[str, Any] | None: + """Claim one clip job for hourly platform-limit probe upload.""" + now = time.time() + pk = str(channel_pk or "").strip() + if not pk: + return None with _lock: conn = _connect() try: row = conn.execute( """ SELECT * FROM tiktok_jobs - WHERE status = 'scheduled' + WHERE channel_pk = ? AND clip_path != '' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' - AND upload_at > 0 - AND upload_at <= ? - ORDER BY upload_at ASC, created_at ASC + AND status IN ('scheduled', 'recorded', 'failed') + ORDER BY + CASE status WHEN 'scheduled' THEN 0 WHEN 'recorded' THEN 1 ELSE 2 END, + upload_at ASC, created_at ASC + LIMIT 1 + """, + (pk,), + ).fetchone() + if not row: + return None + jid = str(row["id"]) + conn.execute( + """ + UPDATE tiktok_jobs + SET status = 'uploading', upload_at = ?, attempts = attempts + 1, + error = 'platform_limit_probe', finished_at = 0, updated_at = ? + WHERE id = ? AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' + AND status IN ('scheduled', 'recorded', 'failed') + """, + (now, now, jid), + ) + if conn.total_changes == 0: + conn.rollback() + return None + conn.execute( + "UPDATE tiktok_channels SET platform_limit_probe_at = ?, updated_at = ? WHERE id = ?", + (now, now, pk), + ) + conn.commit() + return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone()) + finally: + conn.close() + + +def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int: + """Clear legacy soft-quota hold messages and put clips back on the upload schedule.""" + now = time.time() + n = 0 + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT id, channel_pk FROM tiktok_jobs + WHERE status = 'recorded' + AND clip_path != '' + AND IFNULL(tiktok_video_id,'') = '' + AND (error LIKE '%配额已满%') + ORDER BY created_at ASC + LIMIT ? + """, + (max(1, int(limit)),), + ).fetchall() + for row in rows: + jid = str(row["id"]) + conn.execute( + """ + UPDATE tiktok_jobs + SET status = 'scheduled', upload_at = ?, error = '', updated_at = ? + WHERE id = ? AND status = 'recorded' + """, + (now + 30 + n * 120, now, jid), + ) + if conn.total_changes: + n += 1 + # Also clear soft-quota message on already-scheduled rows + conn.execute( + """ + UPDATE tiktok_jobs + SET error = '', updated_at = ? + WHERE error LIKE '%配额已满%' + AND status IN ('scheduled', 'recorded') + """, + (now,), + ) + conn.commit() + finally: + conn.close() + return n + + +def claim_due_tiktok_upload() -> dict[str, Any] | None: + now = time.time() + with _lock: + conn = _connect() + try: + # Skip accounts currently under TikTok platform rate-limit (hourly probe handles those) + row = conn.execute( + """ + SELECT j.* FROM tiktok_jobs j + LEFT JOIN tiktok_channels c ON c.id = j.channel_pk + WHERE j.status = 'scheduled' + AND j.clip_path != '' + AND IFNULL(j.tiktok_video_id,'') = '' + AND IFNULL(j.tiktok_publish_id,'') = '' + AND j.upload_at > 0 + AND j.upload_at <= ? + AND IFNULL(c.platform_limit_at, 0) <= 0 + ORDER BY j.upload_at ASC, j.created_at ASC LIMIT 1 """, (now,), diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index a7bb75b..dbbba2e 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -14,7 +14,7 @@ from . import tiktok_session from .shorts_clip import record_clip, resolve_stream_candidates from .tiktok_schedule import pick_upload_at, schedule_board from .tiktok_socks import resolve_channel_socks_proxy -from .tiktok_upload import upload_tiktok_mp4 +from .tiktok_upload import is_platform_rate_limit, upload_tiktok_mp4 from .timeutil import push_date_from_ts @@ -185,6 +185,8 @@ class TikTokPipeline: self._last_sample_at = 0.0 self._last_oauth_check_at = 0.0 self._last_auto_retry_at = 0.0 + self._last_limit_probe_at = 0.0 + self._soft_quota_rescued = False self._upload_inflight: set[str] = set() def status(self) -> dict[str, Any]: @@ -274,17 +276,29 @@ class TikTokPipeline: try: await self._do_upload(job, manual=True) except Exception as exc: - tiktok_db.update_tiktok_job( - job_id, - status="failed", - error=str(exc)[:500], - finished_at=time.time(), - ) + err = str(exc)[:500] + ch_pk = str((job.get("channel_pk") or pk or "")).strip() + if ch_pk and is_platform_rate_limit(err): + tiktok_db.mark_tiktok_platform_limit(ch_pk, err) + tiktok_db.update_tiktok_job( + job_id, + status="recorded", + error=err, + finished_at=0, + ) + else: + tiktok_db.update_tiktok_job( + job_id, + status="failed", + error=err, + finished_at=time.time(), + ) raise fresh = tiktok_db.get_tiktok_job(job_id) if not fresh: raise ValueError("任务不存在") if str(fresh.get("status") or "") not in {"uploaded", "done"}: + # _do_upload may have soft-held as recorded under platform limit without raising raise ValueError(str(fresh.get("error") or "上传未完成")) return fresh @@ -328,6 +342,16 @@ class TikTokPipeline: tiktok_db.backfill_tiktok_job_channels(limit=20) except Exception: pass + if not self._soft_quota_rescued: + try: + tiktok_db.reschedule_soft_quota_held_jobs(limit=80) + except Exception: + pass + self._soft_quota_rescued = True + # Hourly: probe accounts that hit real TikTok platform limits + if (time.time() - self._last_limit_probe_at) >= 60: + self._last_limit_probe_at = time.time() + await self._maybe_probe_platform_limits(cfg) 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() @@ -347,23 +371,34 @@ class TikTokPipeline: self.last_error = str(exc)[:240] await asyncio.sleep(3) - async def _run_upload(self, job: dict[str, Any]) -> None: + async def _run_upload(self, job: dict[str, Any], *, probe: bool = False) -> None: jid = str(job.get("id") or "") if not jid or jid in self._upload_inflight: self._active_uploads = max(0, self._active_uploads - 1) return self._upload_inflight.add(jid) try: - await self._do_upload(job, manual=False) + await self._do_upload(job, manual=False, probe=probe) self.processed += 1 except Exception as exc: self.last_error = str(exc)[:240] - tiktok_db.update_tiktok_job( - jid, - status="failed", - error=str(exc)[:500], - finished_at=time.time(), - ) + err = str(exc)[:500] + ch_pk = str(job.get("channel_pk") or "") + if ch_pk and is_platform_rate_limit(err): + tiktok_db.mark_tiktok_platform_limit(ch_pk, err) + tiktok_db.update_tiktok_job( + jid, + status="recorded", + error=err, + finished_at=0, + ) + else: + tiktok_db.update_tiktok_job( + jid, + status="failed", + error=err, + finished_at=time.time(), + ) finally: self._upload_inflight.discard(jid) self._active_uploads = max(0, self._active_uploads - 1) @@ -466,18 +501,7 @@ class TikTokPipeline: 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 + # Soft target (official ~15) only affects channel picking / board, not hard-hold clips. upload_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=cfg) tiktok_db.update_tiktok_job( jid, @@ -500,7 +524,24 @@ class TikTokPipeline: error="" if ch_pk else "成片已保留,待分配 TikTok 账号", ) - async def _do_upload(self, job: dict[str, Any], *, manual: bool = False) -> None: + async def _maybe_probe_platform_limits(self, cfg: dict[str, Any]) -> None: + """Once per hour per limited account: try a real upload; success clears the prompt.""" + gap = max(3600.0, float(cfg.get("tiktok_platform_limit_probe_sec") or 3600)) + for ch in tiktok_db.list_tiktok_channels_needing_limit_probe(min_gap_sec=gap): + if self._active_uploads >= max(1, int(cfg.get("tiktok_max_concurrent") or 1)): + break + job = tiktok_db.claim_tiktok_limit_probe_job(str(ch.get("id") or "")) + if not job: + # No clip to probe — bump probe clock so we don't spin every minute + tiktok_db.update_tiktok_channel( + str(ch.get("id") or ""), + platform_limit_probe_at=time.time(), + ) + continue + self._active_uploads += 1 + asyncio.create_task(self._run_upload(job, probe=True)) + + async def _do_upload(self, job: dict[str, Any], *, manual: bool = False, probe: bool = False) -> None: cfg = db.get_settings_map() jid = str(job.get("id") or "") fresh = tiktok_db.get_tiktok_job(jid) or job @@ -514,20 +555,23 @@ class TikTokPipeline: clip = str(fresh.get("clip_path") or "") if not clip or not Path(clip).is_file(): raise ValueError("成片文件不存在") - channel = tiktok_db.ensure_tiktok_job_channel(fresh, require_quota=not manual) + channel = tiktok_db.ensure_tiktok_job_channel(fresh, require_quota=False) 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: + ch_pk = str(channel["id"]) + if ( + not manual + and not probe + and tiktok_db.channel_has_platform_limit(channel) + ): + # Hold auto uploads while platform-limited; hourly probe path bypasses this. tiktok_db.update_tiktok_job( jid, - status="recorded", - channel_pk=str(channel["id"]), - error="账号今日上传配额已满,成片已保留", + status="scheduled", + channel_pk=ch_pk, + upload_at=time.time() + 3600, + error=str(channel.get("platform_limit_msg") or "TikTok 官方限流,等待每小时试传"), ) return if not tiktok_session.channel_has_session(channel): @@ -538,14 +582,28 @@ class TikTokPipeline: if not tiktok_db.touch_tiktok_upload_lease(jid): return proxy = resolve_channel_socks_proxy(channel, cfg) or None - result = await upload_tiktok_mp4( - file_path=clip, - title=title, - description="", - privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"), - channel_pk=str(channel["id"]), - proxy=proxy, - ) + try: + result = await upload_tiktok_mp4( + file_path=clip, + title=title, + description="", + privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"), + channel_pk=ch_pk, + proxy=proxy, + ) + except Exception as exc: + err = str(exc)[:500] + if is_platform_rate_limit(err): + tiktok_db.mark_tiktok_platform_limit(ch_pk, err) + tiktok_db.update_tiktok_job( + jid, + status="recorded", + channel_pk=ch_pk, + error=err, + finished_at=0, + ) + return + raise pub = str(result.get("publish_id") or "").strip() or f"cookie-{jid[:12]}" vid = str(result.get("video_id") or "").strip() or pub if not tiktok_db.finalize_tiktok_upload( @@ -554,8 +612,10 @@ class TikTokPipeline: tiktok_video_id=vid, ): return + # Successful upload clears any platform-limit banner (hourly probe or normal) + tiktok_db.clear_tiktok_platform_limit(ch_pk) tiktok_db.update_tiktok_channel( - str(channel["id"]), + ch_pk, oauth_ok=1, oauth_checked_at=time.time(), oauth_error="", diff --git a/backend/app/tiktok_upload.py b/backend/app/tiktok_upload.py index 515ef02..d308dda 100644 --- a/backend/app/tiktok_upload.py +++ b/backend/app/tiktok_upload.py @@ -25,8 +25,8 @@ def _privacy_to_visibility(privacy_level: str) -> int: def _friendly_upload_error(log: str) -> str: text = str(log or "") low = text.lower() - if "2158" in text or "posting videos too fast" in low or "take a rest" in low: - return "TikTok 限流:发得太快(status 2158)。请至少等几小时后再手动传 1 条,不要连点" + if is_platform_rate_limit(text): + return "TikTok 官方限流:发得太快或达日上限(如 status 2158)。将每小时自动试传,成功后解除提示" if "login expired" in low or '"status_code": 8' in text: return "TikTok Cookie 已过期,请重新粘贴 sessionid" if "invalid parameters" in low: @@ -35,6 +35,26 @@ def _friendly_upload_error(log: str) -> str: return tail or "TikTok 上传失败" +def is_platform_rate_limit(err: str) -> bool: + """True when TikTok itself rejects for posting frequency / daily spam caps.""" + text = str(err or "") + low = text.lower() + needles = ( + "2158", + "posting videos too fast", + "take a rest", + "spam_risk", + "too_many_posts", + "spam_risk_too_many_posts", + "rate_limit", + "rate limit", + "daily upload", + "too many posts", + "官方限流", + ) + return any(n in low or n in text for n in needles) + + def _upload_sync( *, channel_pk: str, diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index f8d72e8..3842721 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -45,6 +45,10 @@ type Channel = { socks_enabled?: boolean; socks_profile_id?: string; socks_profile_label?: string; + platform_limited?: boolean; + platform_limit_at?: number; + platform_limit_msg?: string; + platform_limit_probe_at?: number; }; type SocksProfile = { @@ -995,7 +999,9 @@ export default function TikTokPage() {

账号配额({channels.length})

- 北京日 {beijingWindow || "—"} · 每账号 15 条/日(官方 Direct Post 约数) + + 北京日 {beijingWindow || "—"} · 软目标 15 条/日(官方约数);仅撞官方限流时提示 +
{displayChannels.map((ch) => { @@ -1007,9 +1013,11 @@ export default function TikTokPage() { className={`rounded-xl border bg-gradient-to-br from-white/[0.04] to-transparent p-3 ${ full?.enabled === false ? "border-white/10 opacity-60" - : ch.max_met - ? "border-teal-500/30" - : "border-white/10" + : full?.platform_limited + ? "border-amber-500/40" + : ch.max_met + ? "border-teal-500/30" + : "border-white/10" }`} >
@@ -1030,6 +1038,16 @@ export default function TikTokPage() { ? `SOCKS · ${full.socks_profile_label || full.socks_profile_id || "已启用"}` : "SOCKS · 直连"}
+ {full?.platform_limited ? ( +
+ 官方限流中 + {full.platform_limit_msg ? `:${full.platform_limit_msg}` : ""} + 。每小时自动试传,成功即解除。 + {full.platform_limit_probe_at + ? ` 上次试传 ${fmtTs(full.platform_limit_probe_at)}` + : ""} +
+ ) : null}