douyinWEB/backend/app/tiktok_db.py
eric d8fdeaa71c TikTok: Cookie 上传(TiktokAutoUploader),替代开发者 OAuth
账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 10:16:20 -05:00

525 lines
18 KiB
Python

# -*- 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
# ---------- channels ----------
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 = "{anchor} #fyp",
description_template: str = "{anchor}\n{url}",
privacy_level: str = "SELF_ONLY",
note: 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, created_at, updated_at
) VALUES (?, ?, '', '', '', '', '', '', 0, ?, ?, ?, ?, ?, ?, 0, -1, 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(),
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",
}
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 == "enabled":
v = 1 if v else 0
if k == "oauth_ok" and v is not None:
v = int(v)
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:
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c FROM tiktok_jobs
WHERE channel_pk = ? AND push_date = ?
AND status NOT IN ('failed', 'skipped')
""",
(channel_pk, push_date),
).fetchone()
return int(row["c"]) if row else 0
finally:
conn.close()
def pick_tiktok_channel(push_date: str) -> dict[str, Any] | None:
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 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 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_due_tiktok_upload() -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT * FROM tiktok_jobs
WHERE status = 'scheduled'
AND clip_path != ''
AND tiktok_video_id = ''
AND upload_at > 0
AND upload_at <= ?
ORDER BY upload_at ASC, 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 = ? WHERE id = ? AND status = 'scheduled'",
(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"} or not str(row["clip_path"] or "").strip():
return None
if str(row["tiktok_video_id"] or "").strip():
return None
conn.execute(
"UPDATE tiktok_jobs SET status = 'uploading', upload_at = ?, updated_at = ? WHERE id = ?",
(now, now, job_id),
)
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 tiktok_video_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()
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 status = 'uploading' AND tiktok_video_id = ''
""",
(tiktok_publish_id, tiktok_video_id, now, now, job_id),
)
conn.commit()
return cur.rowcount > 0
finally:
conn.close()
def reclaim_stale_tiktok_uploads(*, max_age_sec: float = 900) -> int:
cutoff = time.time() - max(60.0, float(max_age_sec))
now = time.time()
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE tiktok_jobs
SET status = 'scheduled', error = '', updated_at = ?
WHERE status = 'uploading'
AND tiktok_video_id = ''
AND COALESCE(NULLIF(started_at, 0), updated_at) < ?
""",
(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 tiktok_video_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()