douyinWEB/backend/app/x_clips_db.py
eric f2b3242e7d feat: per-channel/account enable switches with job purge on disable
Shorts/yt-long use per-channel toggles; TikTok/X use account toggles. Turning off clears queued jobs and blocks sampling, recording, and uploads for that target.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 00:24:03 -05:00

612 lines
21 KiB
Python

# -*- coding: utf-8 -*-
"""X live-clip jobs DB — fully isolated from shorts_* / tiktok_*."""
from __future__ import annotations
import sqlite3
import time
import uuid
from typing import Any, Optional
from .db import _connect, _lock, _row_to_dict
from .timeutil import push_date_from_ts
from .x2_db import ensure_x2_tables
# Quota-consuming statuses (posting pipeline has claimed a daily slot)
_QUOTA_STATUSES = ("pending", "recording", "scheduled", "posting", "posted")
X_CLIPS_DAILY_DEFAULT = 20
def ensure_x_clips_tables(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS x_clip_jobs (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL DEFAULT '',
room_pk TEXT NOT NULL DEFAULT '',
room_id TEXT NOT NULL DEFAULT '',
source_url TEXT NOT NULL DEFAULT '',
anchor_name TEXT NOT NULL DEFAULT '',
stream_url TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
clip_path TEXT NOT NULL DEFAULT '',
clip_seconds REAL NOT NULL DEFAULT 0,
caption TEXT NOT NULL DEFAULT '',
media_key TEXT NOT NULL DEFAULT '',
media_url TEXT NOT NULL DEFAULT '',
x2_job_id TEXT NOT NULL DEFAULT '',
tweet_id TEXT NOT NULL DEFAULT '',
account_username TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
push_date TEXT NOT NULL DEFAULT '',
upload_at REAL NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
started_at REAL NOT NULL DEFAULT 0,
finished_at REAL NOT NULL DEFAULT 0
)
"""
)
cols = {r[1] for r in conn.execute("PRAGMA table_info(x_clip_jobs)").fetchall()}
if "account_username" not in cols:
conn.execute("ALTER TABLE x_clip_jobs ADD COLUMN account_username TEXT NOT NULL DEFAULT ''")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_status ON x_clip_jobs(status, created_at)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_date ON x_clip_jobs(push_date, status)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_room_day ON x_clip_jobs(room_id, push_date, status)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_upload ON x_clip_jobs(status, upload_at)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_x2 ON x_clip_jobs(x2_job_id)")
def x_clips_daily_max(cfg: dict[str, Any] | None = None) -> int:
from . import db
settings = cfg if cfg is not None else db.get_settings_map()
try:
v = int(settings.get("x_clips_daily_max") or X_CLIPS_DAILY_DEFAULT)
except Exception:
v = X_CLIPS_DAILY_DEFAULT
return max(1, min(100, v))
def x_clips_quota_used(push_date: str = "") -> int:
day = push_date or push_date_from_ts(time.time())
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
row = conn.execute(
f"""
SELECT COUNT(*) AS c FROM x_clip_jobs
WHERE push_date = ? AND status IN ({placeholders})
""",
(day, *_QUOTA_STATUSES),
).fetchone()
return int(row["c"]) if row else 0
finally:
conn.close()
def x_clips_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
day = push_date or push_date_from_ts(time.time())
return max(0, x_clips_daily_max(cfg) - x_clips_quota_used(day))
def has_x_clip_job_for_room_day(room_id: str, push_date: str) -> bool:
if not room_id:
return False
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
row = conn.execute(
"""
SELECT 1 FROM x_clip_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_x_clip_job(
*,
session_id: str = "",
room_pk: str = "",
room_id: str = "",
source_url: str = "",
anchor_name: str = "",
stream_url: str = "",
push_date: str = "",
account_username: 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()
acct = str(account_username or "").strip().lstrip("@")
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
if rid:
existing = conn.execute(
"""
SELECT 1 FROM x_clip_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 x_clip_jobs(
id, session_id, room_pk, room_id, source_url, anchor_name, stream_url,
status, clip_path, clip_seconds, caption, media_key, media_url, x2_job_id,
tweet_id, account_username, 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,
acct,
day,
now,
now,
),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM x_clip_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
def update_x_clip_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
allowed = {
"status",
"clip_path",
"clip_seconds",
"caption",
"media_key",
"media_url",
"x2_job_id",
"tweet_id",
"account_username",
"error",
"stream_url",
"attempts",
"started_at",
"finished_at",
"upload_at",
}
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
row = conn.execute("SELECT * FROM x_clip_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 x_clip_jobs SET {', '.join(sets)} WHERE id = ?", params)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM x_clip_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def get_x_clip_job(job_id: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
return _row_to_dict(conn.execute("SELECT * FROM x_clip_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def list_x_clip_jobs(
*,
status: str = "",
push_date: str = "",
session_id: str = "",
room_id: str = "",
account_username: str = "",
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
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 session_id.strip():
clauses.append("session_id = ?")
params.append(session_id.strip())
if room_id.strip():
clauses.append("room_id = ?")
params.append(room_id.strip())
acct = account_username.strip().lstrip("@")
if acct:
clauses.append("LOWER(account_username) = LOWER(?)")
params.append(acct)
where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
total = int(
conn.execute(f"SELECT COUNT(*) AS c FROM x_clip_jobs{where}", params).fetchone()["c"] or 0
)
lim = max(1, min(int(limit), 500))
off = max(0, int(offset))
rows = conn.execute(
f"""
SELECT * FROM x_clip_jobs{where}
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""",
(*params, lim, off),
).fetchall()
return {"total": total, "jobs": [_row_to_dict(r) for r in rows]}
finally:
conn.close()
def list_pending_x_clip_jobs(*, limit: int = 10) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
ensure_x2_tables(conn)
rows = conn.execute(
"""
SELECT j.* FROM x_clip_jobs j
LEFT JOIN x2_accounts a ON LOWER(TRIM(a.username)) = LOWER(TRIM(j.account_username))
WHERE j.status = 'pending'
AND (
TRIM(j.account_username) = ''
OR a.id IS NULL
OR a.enabled = 1
)
ORDER BY j.created_at ASC
LIMIT ?
""",
(max(1, min(int(limit), 50)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def claim_x_clip_job_record(job_id: str) -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
cur = conn.execute(
"""
UPDATE x_clip_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 x_clip_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def claim_due_x_clip_post() -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
ensure_x2_tables(conn)
row = conn.execute(
"""
SELECT j.* FROM x_clip_jobs j
LEFT JOIN x2_accounts a ON LOWER(TRIM(a.username)) = LOWER(TRIM(j.account_username))
WHERE j.status = 'scheduled'
AND j.clip_path != ''
AND IFNULL(j.x2_job_id, '') = ''
AND j.upload_at > 0
AND j.upload_at <= ?
AND (
TRIM(j.account_username) = ''
OR a.id IS NULL
OR a.enabled = 1
)
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 x_clip_jobs
SET status = 'posting', updated_at = ?, attempts = attempts + 1
WHERE id = ? AND status = 'scheduled' AND IFNULL(x2_job_id, '') = ''
""",
(now, jid),
)
if conn.total_changes == 0:
conn.rollback()
return None
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM x_clip_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
def claim_x_clip_job_manual_post(job_id: str) -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
row = conn.execute("SELECT * FROM x_clip_jobs WHERE id = ?", (job_id,)).fetchone()
if not row:
return None
st = str(row["status"] or "")
if st not in {"scheduled", "recorded", "posting", "failed"}:
return None
if not str(row["clip_path"] or "").strip() and not str(row["media_url"] or "").strip():
return None
if st == "posted":
return None
stale_before = now - 180
if st == "posting" and float(row["updated_at"] or 0) >= stale_before and str(row["x2_job_id"] or "").strip():
return None
conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'posting', upload_at = ?, attempts = attempts + 1,
error = '', finished_at = 0, updated_at = ?,
x2_job_id = CASE WHEN status = 'failed' THEN '' ELSE x2_job_id END
WHERE id = ? AND status IN ('scheduled', 'recorded', 'failed', 'posting')
AND (
status IN ('scheduled', 'recorded', 'failed')
OR (status = 'posting' 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 x_clip_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def list_posting_x_clip_jobs(*, limit: int = 30) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
rows = conn.execute(
"""
SELECT * FROM x_clip_jobs
WHERE status = 'posting' AND IFNULL(x2_job_id, '') != ''
ORDER BY updated_at ASC
LIMIT ?
""",
(max(1, min(int(limit), 100)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def reclaim_stale_x_clip_recordings(*, max_age_sec: float = 240) -> int:
cutoff = time.time() - max(60.0, float(max_age_sec))
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
cur = conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'pending', started_at = 0, error = 'recording_stale_reclaim', updated_at = ?
WHERE status = 'recording' AND updated_at < ?
""",
(time.time(), cutoff),
)
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()
def reclaim_stale_x_clip_posts(*, max_age_sec: float = 900, max_attempts: int = 3) -> int:
cutoff = time.time() - max(120.0, float(max_age_sec))
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
# Fail jobs that exceeded retry limit
conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'failed', error = '超过最大重试次数', updated_at = ?, finished_at = ?
WHERE status = 'posting' AND updated_at < ?
AND IFNULL(tweet_id, '') = ''
AND IFNULL(finished_at, 0) = 0
AND attempts >= ?
""",
(now, now, cutoff, max(1, int(max_attempts))),
)
cur = conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'scheduled', error = 'posting_stale_reclaim', updated_at = ?,
x2_job_id = '', media_key = CASE WHEN media_url != '' THEN media_key ELSE '' END
WHERE status = 'posting' AND updated_at < ?
AND IFNULL(tweet_id, '') = ''
AND IFNULL(finished_at, 0) = 0
AND attempts < ?
""",
(now, cutoff, max(1, int(max_attempts))),
)
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()
def x_clips_stats(push_date: str = "") -> dict[str, Any]:
day = push_date or push_date_from_ts(time.time())
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
rows = conn.execute(
"""
SELECT status, COUNT(*) AS c FROM x_clip_jobs
WHERE push_date = ?
GROUP BY status
""",
(day,),
).fetchall()
by_status = {str(r["status"]): int(r["c"]) for r in rows}
used_row = conn.execute(
f"""
SELECT COUNT(*) AS c FROM x_clip_jobs
WHERE push_date = ? AND status IN ({placeholders})
""",
(day, *_QUOTA_STATUSES),
).fetchone()
return {
"push_date": day,
"by_status": by_status,
"used": int(used_row["c"]) if used_row else 0,
}
finally:
conn.close()
def skip_remaining_scheduled_for_day(
push_date: str = "",
*,
reason: str = "x_daily_post_limit",
) -> int:
"""Mark today's scheduled (not yet dispatched) clip jobs as skipped."""
day = push_date or push_date_from_ts(time.time())
now = time.time()
err = str(reason or "x_daily_post_limit")[:500]
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
cur = conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'skipped', error = ?, finished_at = ?, updated_at = ?
WHERE push_date = ?
AND status IN ('scheduled', 'recorded', 'pending')
AND IFNULL(x2_job_id, '') = ''
""",
(err, now, now, day),
)
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()
def delete_x_clip_jobs_for_account(account_username: str) -> dict[str, int]:
"""Delete all X clip jobs for an account (keep account row)."""
uname = str(account_username or "").strip().lstrip("@")
if not uname:
return {"jobs": 0, "clips": 0}
clip_paths: list[str] = []
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
rows = conn.execute(
"""
SELECT id, clip_path FROM x_clip_jobs
WHERE LOWER(account_username) = LOWER(?)
""",
(uname,),
).fetchall()
for row in rows:
clip = str(row["clip_path"] or "").strip()
if clip:
clip_paths.append(clip)
cur = conn.execute(
"DELETE FROM x_clip_jobs WHERE LOWER(account_username) = LOWER(?)",
(uname,),
)
jobs = int(cur.rowcount or 0)
conn.commit()
finally:
conn.close()
clips = 0
from pathlib import Path
for raw in clip_paths:
try:
p = Path(str(raw).strip())
if p.is_file():
p.unlink()
clips += 1
except Exception:
pass
return {"jobs": jobs, "clips": clips}
def list_enabled_x_account_usernames() -> list[str]:
"""Usernames of X accounts that are enabled (default enabled if not in x2_accounts)."""
from . import x2_db
try:
accounts = x2_db.list_accounts(limit=200)
except Exception:
return []
return [
str(a.get("username") or "").strip().lstrip("@")
for a in accounts
if a.get("enabled") is not False and str(a.get("username") or "").strip()
]