# -*- coding: utf-8 -*- """Isolated TikTok pipeline — never touches Shorts or Douyin monitor.""" from __future__ import annotations import asyncio import random import time from pathlib import Path from typing import Any, Optional from . import db from . import tiktok_db 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 is_platform_rate_limit, upload_tiktok_mp4 from .timeutil import push_date_from_ts def _room_tags(room: dict[str, Any]) -> list[str]: tags = room.get("tags") or [] if isinstance(tags, str): return [t.strip() for t in tags.split(",") if t.strip()] return [str(t).strip() for t in tags if str(t).strip()] def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: trigger = str(cfg.get("tiktok_trigger") or "tagged").strip().lower() tags = _room_tags(room) if trigger == "all": return True if trigger == "favorite": return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts", "tiktok"} for t in tags) tag = str(cfg.get("tiktok_tag") or "shorts").strip() or "shorts" return tag in tags or "tiktok" in tags or "shorts" in tags def _enqueue_job( *, session: dict[str, Any] | None, room: dict[str, Any], stream_url: str = "", 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(room.get("room_id") or (session or {}).get("room_id") or "") if room_id.startswith("yt:"): return None 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 channel: dict[str, Any] | None = None if channel_pk: ch = tiktok_db.get_tiktok_channel(channel_pk) if ch and ch.get("enabled") and tiktok_session.channel_has_session(ch): used = tiktok_db.tiktok_channel_upload_count(channel_pk, day) if used < db.TIKTOK_DAILY_FORCE: channel = ch if not channel: # 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 "") return tiktok_db.create_tiktok_job( session_id=sid, room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""), room_id=room_id, source_url=str((session or {}).get("source_url") or room.get("url") or ""), anchor_name=str( (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 or {}).get("id") or ""), push_date=day, ) except Exception: return None def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: settings = cfg or db.get_settings_map() if not settings.get("tiktok_enabled") or not settings.get("tiktok_live_sample", True): return 0 batch = max(1, int(settings.get("tiktok_live_sample_batch") or 1)) rooms = db.list_live_douyin_rooms_for_shorts(limit=400) if settings.get("tiktok_sample_any_live", True): candidates = list(rooms) else: candidates = [r for r in rooms if _room_eligible(r, settings)] if not candidates: return 0 random.shuffle(candidates) n = 0 for room in candidates[: batch * 3]: if n >= batch: break sid = str(room.get("active_session_id") or "") session = db.get_session(sid) if sid else None if _enqueue_job(session=session, room=room, cfg=settings): n += 1 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 batch = min(len(unused), 3) 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, push_date=day, require_channel=False, ) if job and job.get("id"): job_ids.append(str(job["id"])) reason = "" if job_ids else "入队失败(可能已有同房间任务)" 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 self._stop = asyncio.Event() self._active_records = 0 self._active_uploads = 0 self.processed = 0 self.sampled = 0 self.last_error = "" 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]: cfg = db.get_settings_map() try: board = schedule_board(limit=30) except Exception: board = {} oauth_issues = [] for ch in tiktok_db.list_tiktok_channels(enabled=True): ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) if ok_flag == 0 or not tiktok_session.channel_has_session(ch): oauth_issues.append( { "id": ch.get("id"), "name": ch.get("name"), "oauth_error": ch.get("oauth_error") or "未授权", } ) return { "running": bool(self._task and not self._task.done()), "busy": self._active_records > 0 or self._active_uploads > 0, "enabled": bool(cfg.get("tiktok_enabled")), "processed": self.processed, "sampled": self.sampled, "quota_gap": tiktok_db.tiktok_total_quota_gap(), "last_error": self.last_error, "clip_sec": max(60, int(cfg.get("tiktok_clip_sec") or 60)), "douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)), "board": board, "oauth_issues": oauth_issues, "stats": tiktok_db.tiktok_stats(), } async def start(self) -> None: if self._task and not self._task.done(): return self._stop.clear() self._task = asyncio.create_task(self._loop(), name="tiktok-pipeline") async def stop(self) -> None: self._stop.set() if self._task: try: await asyncio.wait_for(self._task, timeout=5) except Exception: 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, *, 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, manual=True) except Exception as exc: 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 async def _loop(self) -> None: while not self._stop.is_set(): try: cfg = db.get_settings_map() if not cfg.get("tiktok_enabled"): await asyncio.sleep(5) continue interval = max(60.0, float(cfg.get("tiktok_live_sample_interval_sec") or 180)) if cfg.get("tiktok_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 session_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600)) if (time.time() - self._last_oauth_check_at) >= session_interval: self._last_oauth_check_at = time.time() for ch in tiktok_db.list_tiktok_channels(enabled=True): asyncio.create_task(asyncio.to_thread(tiktok_session.probe_channel_session, ch)) retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300)) if cfg.get("tiktok_auto_retry_failed") and (time.time() - self._last_auto_retry_at) >= retry_interval: self._last_auto_retry_at = time.time() for j in tiktok_db.list_auto_retry_tiktok_failed(limit=10): tiktok_db.update_tiktok_job( str(j["id"]), status="scheduled", upload_at=pick_upload_at(channel_pk=str(j.get("channel_pk") or ""), cfg=cfg), error="", ) try: 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 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() if not job: break self._active_uploads += 1 asyncio.create_task(self._run_upload(job)) # 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: break self._active_records += 1 asyncio.create_task(self._run_record(job)) except Exception as exc: self.last_error = str(exc)[:240] await asyncio.sleep(3) 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, probe=probe) self.processed += 1 except Exception as exc: self.last_error = str(exc)[:240] 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) async def _run_record(self, job: dict[str, Any]) -> None: try: await self._do_record(job) except Exception as exc: self.last_error = str(exc)[:240] tiktok_db.update_tiktok_job( str(job.get("id") or ""), status="failed", error=str(exc)[:500], finished_at=time.time(), ) finally: self._active_records = max(0, self._active_records - 1) async def _do_record(self, job: dict[str, Any]) -> None: cfg = db.get_settings_map() jid = str(job.get("id") or "") cookie = str(cfg.get("dy_cookie") or "") source = str(job.get("source_url") or "") async def _fresh_candidates() -> list[str]: return await resolve_stream_candidates( source_url=source, stream_url="", cookie=cookie, prefer_fresh=True, max_candidates=8, ) candidates = await _fresh_candidates() if not candidates: 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", error="无法获取直播流(可能已停播)", finished_at=time.time(), ) return # TikTok 素材最少录 1 分钟;多 CDN 线路按 DouyinLiveRecorder 方式试探 sec = max(60, int(cfg.get("tiktok_clip_sec") or 60)) outcome = await record_clip( job_id=f"tiktok_{jid[:8]}", stream_urls=candidates, seconds=sec, ) stream = str(outcome.get("stream_url") or (candidates[0] if candidates else "")) if not outcome.get("ok"): err = str(outcome.get("error") or "录制失败") low = err.lower() # 整批线路失败:重新拉房源再试一次(等价 DLR 换源) if any(x in low for x in ("404", "error opening", "server returned", "probe 404")) and "stream_ffmpeg_retry" not in str( job.get("error") or "" ): cands2 = await _fresh_candidates() # Prefer URLs not already tried fresh_only = [u for u in cands2 if u not in candidates] or cands2 if fresh_only: outcome2 = await record_clip( job_id=f"tiktok_{jid[:8]}r", stream_urls=fresh_only, seconds=sec, ) if outcome2.get("ok"): outcome = outcome2 stream = str(outcome2.get("stream_url") or fresh_only[0]) 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())) 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: # 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, status="scheduled", 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, channel_pk=ch_pk, error="" if ch_pk else "成片已保留,待分配 TikTok 账号", ) 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 if str(fresh.get("tiktok_video_id") or "").strip() or str(fresh.get("tiktok_publish_id") or "").strip(): tiktok_db.finalize_tiktok_upload( jid, tiktok_publish_id=str(fresh.get("tiktok_publish_id") or ""), tiktok_video_id=str(fresh.get("tiktok_video_id") or ""), ) return 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=False) if not channel: tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传") return 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="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): tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie") return # 文案只用账号「标题模板」原文,绝不自动拼直播间名/链接 title = str(channel.get("title_template") or "").strip() if not tiktok_db.touch_tiktok_upload_lease(jid): return proxy = resolve_channel_socks_proxy(channel, cfg) or None 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( jid, tiktok_publish_id=pub, 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( ch_pk, oauth_ok=1, oauth_checked_at=time.time(), oauth_error="", ) if cfg.get("tiktok_delete_clip_after_upload", True): try: Path(clip).unlink(missing_ok=True) except Exception: pass @staticmethod def _delete_clip(path: str) -> None: try: Path(path).unlink(missing_ok=True) except Exception: pass tiktok_pipeline = TikTokPipeline()