# -*- coding: utf-8 -*- """TikTok pipeline DB — isolated from shorts_* tables.""" from __future__ import annotations import sqlite3 import time import uuid from typing import Any, Optional from .db import TIKTOK_DAILY_FORCE, _connect, _lock, _row_to_dict from .timeutil import push_date_from_ts def _force_daily(v: int) -> int: return TIKTOK_DAILY_FORCE # 占用「今日上传配额」的状态:待录/录制中不算,避免取样把账号配额占满后无法再分配 _TIKTOK_QUOTA_STATUSES = ( "scheduled", "uploading", "uploaded", "done", ) def list_tiktok_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]: with _lock: conn = _connect() try: if enabled is None: rows = conn.execute( "SELECT * FROM tiktok_channels ORDER BY created_at ASC, name COLLATE NOCASE ASC" ).fetchall() else: rows = conn.execute( "SELECT * FROM tiktok_channels WHERE enabled = ? ORDER BY created_at ASC, name COLLATE NOCASE ASC", (1 if enabled else 0,), ).fetchall() return [_row_to_dict(r) for r in rows] # type: ignore finally: conn.close() def get_tiktok_channel(channel_pk: str) -> dict[str, Any] | None: with _lock: conn = _connect() try: return _row_to_dict(conn.execute("SELECT * FROM tiktok_channels WHERE id = ?", (channel_pk,)).fetchone()) finally: conn.close() def create_tiktok_channel( *, name: str, enabled: bool = True, daily_min: int = TIKTOK_DAILY_FORCE, daily_max: int = TIKTOK_DAILY_FORCE, title_template: str = "", description_template: str = "", privacy_level: str = "SELF_ONLY", note: str = "", socks_enabled: bool = False, socks_profile_id: str = "", ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) daily_min = _force_daily(daily_min) daily_max = _force_daily(daily_max) with _lock: conn = _connect() try: conn.execute( """ INSERT INTO tiktok_channels( id, name, tiktok_open_id, tiktok_username, client_key, client_secret, refresh_token, access_token, token_expires_at, enabled, daily_min, daily_max, 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, created_at, updated_at ) VALUES (?, ?, '', '', '', '', '', '', 0, ?, ?, ?, ?, ?, ?, 0, -1, 0, '', ?, 0, ?, ?, ?, ?) """, ( cid, (name or "").strip() or "TikTok 账号", 1 if enabled else 0, daily_min, daily_max, title_template, description_template, (privacy_level or "SELF_ONLY").strip(), (note or "").strip(), 1 if socks_enabled else 0, str(socks_profile_id or "").strip(), now, now, ), ) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_channels WHERE id = ?", (cid,)).fetchone()) # type: ignore finally: conn.close() def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | None: allowed = { "name", "tiktok_open_id", "tiktok_username", "client_key", "client_secret", "refresh_token", "access_token", "token_expires_at", "enabled", "daily_min", "daily_max", "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", "tiktok_uid", "nickname", "avatar_url", "follower_count", "following_count", "video_count", "heart_count", "profile_fetched_at", "profile_error", } with _lock: conn = _connect() try: row = conn.execute("SELECT * FROM tiktok_channels WHERE id = ?", (channel_pk,)).fetchone() if not row: return None sets: list[str] = [] params: list[Any] = [] for k, v in fields.items(): if k not in allowed or v is None: continue if k in {"daily_min", "daily_max"}: v = _force_daily(int(v)) if k in {"enabled", "socks_enabled"}: v = 1 if v else 0 if k == "oauth_ok" and v is not None: v = int(v) if k == "socks_profile_id": v = str(v or "").strip() if k in {"follower_count", "following_count", "video_count", "heart_count"}: v = int(v or 0) if k in {"tiktok_uid", "nickname", "avatar_url", "profile_error", "tiktok_username"}: v = str(v or "").strip() sets.append(f"{k} = ?") params.append(v) if not sets: return _row_to_dict(row) sets.append("updated_at = ?") params.append(time.time()) params.append(channel_pk) conn.execute(f"UPDATE tiktok_channels SET {', '.join(sets)} WHERE id = ?", params) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_channels WHERE id = ?", (channel_pk,)).fetchone()) finally: conn.close() def delete_tiktok_channel(channel_pk: str) -> bool: with _lock: conn = _connect() try: cur = conn.execute("DELETE FROM tiktok_channels WHERE id = ?", (channel_pk,)) conn.commit() return cur.rowcount > 0 finally: conn.close() 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 IN ({placeholders}) """, (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, *, 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) if not channels: return None scored: list[tuple[int, int, float, dict[str, Any]]] = [] for ch in channels: if not tiktok_session.channel_has_session(ch): continue used = tiktok_channel_upload_count(str(ch["id"]), push_date) daily_max = TIKTOK_DAILY_FORCE if require_quota and used >= daily_max: continue daily_min = TIKTOK_DAILY_FORCE under = 0 if used < daily_min else 1 scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None scored.sort(key=lambda x: (x[0], x[1], x[2])) 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 for ch in list_tiktok_channels(enabled=True): used = tiktok_channel_upload_count(str(ch["id"]), day) gap += max(0, TIKTOK_DAILY_FORCE - used) return gap # ---------- jobs ---------- def has_tiktok_job_for_room_day(room_id: str, push_date: str) -> bool: if not room_id: return False with _lock: conn = _connect() try: row = conn.execute( """ SELECT 1 FROM tiktok_jobs WHERE room_id = ? AND push_date = ? AND status NOT IN ('failed', 'skipped') LIMIT 1 """, (room_id, push_date), ).fetchone() return bool(row) finally: conn.close() def create_tiktok_job( *, session_id: str, room_pk: str = "", room_id: str = "", source_url: str = "", anchor_name: str = "", stream_url: str = "", channel_pk: str = "", push_date: str = "", ) -> dict[str, Any] | None: now = time.time() jid = str(uuid.uuid4()) day = push_date or push_date_from_ts(now) rid = str(room_id or "").strip() with _lock: conn = _connect() try: if rid: existing = conn.execute( """ SELECT 1 FROM tiktok_jobs WHERE room_id = ? AND push_date = ? AND status NOT IN ('failed', 'skipped') LIMIT 1 """, (rid, day), ).fetchone() if existing: return None conn.execute( """ INSERT INTO tiktok_jobs( id, session_id, room_pk, room_id, source_url, anchor_name, stream_url, channel_pk, status, clip_path, clip_seconds, tiktok_publish_id, tiktok_video_id, error, push_date, upload_at, attempts, created_at, updated_at, started_at, finished_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, 0, ?, ?, 0, 0) """, (jid, session_id, room_pk, rid, source_url, anchor_name, stream_url, channel_pk, day, now, now), ) if channel_pk: conn.execute( "UPDATE tiktok_channels SET last_assigned_at = ?, updated_at = ? WHERE id = ?", (now, now, channel_pk), ) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone()) # type: ignore finally: conn.close() def update_tiktok_job(job_id: str, **fields: Any) -> dict[str, Any] | None: allowed = { "status", "clip_path", "clip_seconds", "tiktok_publish_id", "tiktok_video_id", "error", "channel_pk", "stream_url", "attempts", "started_at", "finished_at", "upload_at", } with _lock: conn = _connect() try: row = conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone() if not row: return None sets: list[str] = [] params: list[Any] = [] for k, v in fields.items(): if k not in allowed or v is None: continue sets.append(f"{k} = ?") params.append(v) if not sets: return _row_to_dict(row) sets.append("updated_at = ?") params.append(time.time()) params.append(job_id) conn.execute(f"UPDATE tiktok_jobs SET {', '.join(sets)} WHERE id = ?", params) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone()) finally: conn.close() def get_tiktok_job(job_id: str) -> dict[str, Any] | None: with _lock: conn = _connect() try: return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone()) finally: conn.close() def list_tiktok_jobs( *, status: str = "", push_date: str = "", channel_pk: str = "", limit: int = 100, offset: int = 0, ) -> dict[str, Any]: with _lock: conn = _connect() try: clauses: list[str] = [] params: list[Any] = [] if status.strip(): clauses.append("status = ?") params.append(status.strip()) if push_date.strip(): clauses.append("push_date = ?") params.append(push_date.strip()) if channel_pk.strip(): clauses.append("channel_pk = ?") params.append(channel_pk.strip()) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" total = conn.execute(f"SELECT COUNT(*) AS c FROM tiktok_jobs {where}", params).fetchone()["c"] rows = conn.execute( f"SELECT * FROM tiktok_jobs {where} ORDER BY created_at DESC LIMIT ? OFFSET ?", [*params, max(1, min(limit, 500)), max(0, offset)], ).fetchall() return {"jobs": [_row_to_dict(r) for r in rows], "total": int(total)} finally: conn.close() def tiktok_stats(push_date: str = "") -> dict[str, Any]: day = push_date or push_date_from_ts(time.time()) with _lock: conn = _connect() try: rows = conn.execute( "SELECT status, COUNT(*) AS c FROM tiktok_jobs WHERE push_date = ? GROUP BY status", (day,), ).fetchall() by_status = {str(r["status"]): int(r["c"]) for r in rows} return {"push_date": day, "by_status": by_status, "total": sum(by_status.values())} finally: conn.close() def claim_pending_tiktok_record() -> dict[str, Any] | None: now = time.time() with _lock: conn = _connect() try: row = conn.execute( """ SELECT * FROM tiktok_jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1 """ ).fetchone() if not row: return None jid = str(row["id"]) conn.execute( """ UPDATE tiktok_jobs SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1 WHERE id = ? AND status = 'pending' """, (now, now, jid), ) if conn.total_changes == 0: conn.rollback() return None conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone()) finally: 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 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 channel_pk = ? AND clip_path != '' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' 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,), ).fetchone() if not row: return None jid = str(row["id"]) conn.execute( """ UPDATE tiktok_jobs SET status = 'uploading', updated_at = ?, attempts = attempts + 1 WHERE id = ? AND status = 'scheduled' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' """, (now, jid), ) if conn.total_changes == 0: conn.rollback() return None conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone()) finally: conn.close() def claim_tiktok_job_manual_upload(job_id: str) -> dict[str, Any] | None: now = time.time() with _lock: conn = _connect() try: row = conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone() if not row: return None st = str(row["status"] or "") if st not in {"scheduled", "recorded", "uploading", "failed"}: return None if not str(row["clip_path"] or "").strip(): return None if str(row["tiktok_video_id"] or "").strip() or str(row["tiktok_publish_id"] or "").strip(): return None stale_before = now - 180 if st == "uploading" and float(row["updated_at"] or 0) >= stale_before: return None conn.execute( """ UPDATE tiktok_jobs SET status = 'uploading', upload_at = ?, attempts = attempts + 1, error = '', finished_at = 0, updated_at = ? WHERE id = ? AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' AND ( status IN ('scheduled', 'recorded', 'failed') OR (status = 'uploading' AND updated_at < ?) ) """, (now, now, job_id, stale_before), ) if conn.total_changes == 0: conn.rollback() return None conn.commit() return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone()) finally: conn.close() def touch_tiktok_upload_lease(job_id: str) -> bool: now = time.time() with _lock: conn = _connect() try: cur = conn.execute( """ UPDATE tiktok_jobs SET updated_at = ? WHERE id = ? AND status = 'uploading' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' """, (now, job_id), ) conn.commit() return cur.rowcount > 0 finally: conn.close() def finalize_tiktok_upload( job_id: str, *, tiktok_publish_id: str = "", tiktok_video_id: str = "", ) -> bool: now = time.time() pub = str(tiktok_publish_id or "").strip() vid = str(tiktok_video_id or "").strip() or pub if not pub: pub = vid or f"cookie-{job_id[:12]}" if not vid: vid = pub with _lock: conn = _connect() try: cur = conn.execute( """ UPDATE tiktok_jobs SET status = 'uploaded', tiktok_publish_id = ?, tiktok_video_id = ?, error = '', finished_at = ?, updated_at = ?, clip_path = '' WHERE id = ? AND IFNULL(tiktok_video_id,'') = '' AND status IN ('uploading', 'scheduled', 'failed', 'recorded') """, (pub, vid, now, now, job_id), ) conn.commit() return cur.rowcount > 0 finally: 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)) now = time.time() with _lock: conn = _connect() try: cur = conn.execute( """ UPDATE tiktok_jobs SET status = 'failed', error = '上传超时已中止,未再次发送(防止重复发布)', finished_at = ?, updated_at = ? WHERE status = 'uploading' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' AND updated_at < ? """, (now, now, cutoff), ) conn.commit() return int(cur.rowcount) finally: conn.close() def list_auto_retry_tiktok_failed(*, limit: int = 20) -> list[dict[str, Any]]: with _lock: conn = _connect() try: rows = conn.execute( """ SELECT * FROM tiktok_jobs WHERE status = 'failed' AND clip_path != '' AND IFNULL(tiktok_video_id,'') = '' AND IFNULL(tiktok_publish_id,'') = '' AND attempts < 5 ORDER BY updated_at ASC LIMIT ? """, (max(1, limit),), ).fetchall() return [_row_to_dict(r) for r in rows] # type: ignore finally: conn.close()