diff --git a/backend/app/db.py b/backend/app/db.py index 1822515..ad3c496 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -15,6 +15,7 @@ _lock = threading.RLock() # Each Shorts channel is forced to exactly this many slots per Beijing day. SHORTS_DAILY_FORCE = 9 +TIKTOK_DAILY_FORCE = 9 def _force_daily_quota(value: Any = None) -> int: @@ -206,6 +207,65 @@ def init_db() -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_upload ON shorts_jobs(status, upload_at)" ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_day ON shorts_jobs(room_id, push_date, status)" + ) + conn.execute( + """ + CREATE TABLE IF NOT EXISTS tiktok_channels ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + tiktok_open_id TEXT NOT NULL DEFAULT '', + tiktok_username TEXT NOT NULL DEFAULT '', + client_key TEXT NOT NULL DEFAULT '', + client_secret TEXT NOT NULL DEFAULT '', + refresh_token TEXT NOT NULL DEFAULT '', + access_token TEXT NOT NULL DEFAULT '', + token_expires_at REAL NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + daily_min INTEGER NOT NULL DEFAULT 9, + daily_max INTEGER NOT NULL DEFAULT 9, + title_template TEXT NOT NULL DEFAULT '{anchor} #fyp', + description_template TEXT NOT NULL DEFAULT '{anchor}\n{url}', + privacy_level TEXT NOT NULL DEFAULT 'SELF_ONLY', + last_assigned_at REAL NOT NULL DEFAULT 0, + oauth_ok INTEGER NOT NULL DEFAULT -1, + oauth_checked_at REAL NOT NULL DEFAULT 0, + oauth_error TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + created_at REAL NOT NULL, + updated_at REAL NOT NULL + ); + + CREATE TABLE IF NOT EXISTS tiktok_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 '', + channel_pk TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + clip_path TEXT NOT NULL DEFAULT '', + clip_seconds REAL NOT NULL DEFAULT 0, + tiktok_publish_id TEXT NOT NULL DEFAULT '', + tiktok_video_id 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 + ); + CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_status ON tiktok_jobs(status, created_at); + CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_date ON tiktok_jobs(push_date, channel_pk); + CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_room_day ON tiktok_jobs(room_id, push_date, status); + CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_upload ON tiktok_jobs(status, upload_at); + """ + ) 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"), @@ -238,6 +298,10 @@ def init_db() -> None: dedupe_active_sessions() except Exception: pass + try: + dedupe_shorts_jobs_room_day() + except Exception: + pass def enforce_shorts_daily_force() -> int: @@ -326,6 +390,43 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "shorts_yt_upload_blocked_until": 0, "shorts_yt_uploads_pt_date": "", "shorts_yt_uploads_pt_count": 0, + # Shorts upload SOCKS5 (optional, default off — does not affect monitor) + "shorts_upload_socks_enabled": False, + "shorts_upload_socks_profile_id": "residential-1", + "shorts_upload_socks_profiles": [ + { + "id": "residential-1", + "label": "静态住宅 IP", + "type": "socks5", + "server": "185.124.61.35", + "port": 43676, + "username": "V0sI3BsI1bxgKRx", + "password": "QGwGeRTAa9YcVhM", + } + ], + # TikTok pipeline (fully isolated from Shorts) + "tiktok_enabled": False, + "tiktok_clip_sec": 15, + "tiktok_trigger": "tagged", + "tiktok_tag": "shorts", + "tiktok_dedupe_room_day": True, + "tiktok_max_concurrent": 1, + "tiktok_auto_upload": True, + "tiktok_live_sample": True, + "tiktok_live_sample_interval_sec": 180, + "tiktok_live_sample_batch": 1, + "tiktok_sample_any_live": True, + "tiktok_upload_spread": True, + "tiktok_upload_min_gap_sec": 720, + "tiktok_channel_min_gap_sec": 2400, + "tiktok_delete_clip_after_upload": True, + "tiktok_auto_retry_failed": True, + "tiktok_auto_retry_max_attempts": 3, + "tiktok_auto_retry_interval_sec": 300, + "tiktok_oauth_check_interval_sec": 3600, + "tiktok_oauth_client_key": "", + "tiktok_oauth_client_secret": "", + "tiktok_oauth_redirect_uri": "https://dylive.nomadro.com/api/tiktok/oauth/callback", } for key, value in defaults.items(): row = conn.execute("SELECT 1 FROM kv_settings WHERE key = ?", (key,)).fetchone() @@ -2575,14 +2676,21 @@ def channel_groups_live_stats(*, platform: str = "youtube") -> dict[str, Any]: # ---------- Shorts pipeline ---------- def list_shorts_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]: + """Stable order for UI cards: created_at ASC (never reshuffle on assign/live checks).""" with _lock: conn = _connect() try: if enabled is None: - rows = conn.execute("SELECT * FROM shorts_channels ORDER BY updated_at DESC").fetchall() + rows = conn.execute( + "SELECT * FROM shorts_channels ORDER BY created_at ASC, name COLLATE NOCASE ASC, id ASC" + ).fetchall() else: rows = conn.execute( - "SELECT * FROM shorts_channels WHERE enabled = ? ORDER BY updated_at DESC", + """ + SELECT * FROM shorts_channels + WHERE enabled = ? + ORDER BY created_at ASC, name COLLATE NOCASE ASC, id ASC + """, (1 if enabled else 0,), ).fetchall() return [_row_to_dict(r) for r in rows] # type: ignore @@ -2709,16 +2817,100 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: conn.close() -def delete_shorts_channel(channel_pk: str) -> None: +def _unlink_shorts_clip_paths(paths: list[str]) -> int: + """Best-effort delete local clip files. Safe outside DB lock.""" + from pathlib import Path + + deleted = 0 + for raw in paths: + path = str(raw or "").strip() + if not path: + continue + try: + p = Path(path) + if p.is_file(): + p.unlink() + deleted += 1 + except Exception: + pass + return deleted + + +def delete_shorts_jobs_for_channel(channel_pk: str) -> dict[str, int]: + """Delete all Shorts jobs for a channel and unlink their clip files.""" + pk = str(channel_pk or "").strip() + if not pk: + return {"jobs": 0, "clips": 0} + clip_paths: list[str] = [] with _lock: conn = _connect() try: - conn.execute("DELETE FROM shorts_channels WHERE id = ?", (channel_pk,)) + rows = conn.execute( + "SELECT id, clip_path FROM shorts_jobs WHERE channel_pk = ?", + (pk,), + ).fetchall() + for row in rows: + clip = str(row["clip_path"] or "").strip() + if clip: + clip_paths.append(clip) + conn.execute("DELETE FROM shorts_jobs WHERE channel_pk = ?", (pk,)) + jobs = int(conn.total_changes) conn.commit() finally: conn.close() + clips = _unlink_shorts_clip_paths(clip_paths) + return {"jobs": jobs, "clips": clips} +def delete_shorts_channel(channel_pk: str) -> dict[str, int]: + """Delete channel and cascade: jobs + local clip materials.""" + pk = str(channel_pk or "").strip() + stats = delete_shorts_jobs_for_channel(pk) + with _lock: + conn = _connect() + try: + conn.execute("DELETE FROM shorts_channels WHERE id = ?", (pk,)) + stats["channel"] = int(conn.total_changes) + conn.commit() + finally: + conn.close() + return stats + + +def purge_orphan_shorts_jobs(*, limit: int = 500) -> dict[str, int]: + """Remove jobs whose channel_pk no longer exists; delete clip files too.""" + clip_paths: list[str] = [] + job_ids: list[str] = [] + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT j.id, j.clip_path + FROM shorts_jobs j + LEFT JOIN shorts_channels c ON c.id = j.channel_pk + WHERE c.id IS NULL + OR TRIM(COALESCE(j.channel_pk, '')) = '' + ORDER BY j.updated_at DESC + LIMIT ? + """, + (max(1, min(int(limit), 2000)),), + ).fetchall() + for row in rows: + job_ids.append(str(row["id"])) + clip = str(row["clip_path"] or "").strip() + if clip: + clip_paths.append(clip) + if job_ids: + placeholders = ",".join("?" for _ in job_ids) + conn.execute(f"DELETE FROM shorts_jobs WHERE id IN ({placeholders})", tuple(job_ids)) + jobs = len(job_ids) + conn.commit() + finally: + conn.close() + clips = _unlink_shorts_clip_paths(clip_paths) + return {"jobs": jobs, "clips": clips} + def touch_shorts_channel_live( channel_pk: str, *, @@ -3044,6 +3236,63 @@ def list_live_douyin_rooms_for_shorts(*, limit: int = 300) -> list[dict[str, Any conn.close() +def dedupe_shorts_jobs_room_day() -> int: + """Keep one active job per room_id+push_date; mark extras skipped (prefer uploaded).""" + now = time.time() + skipped = 0 + with _lock: + conn = _connect() + try: + groups = conn.execute( + """ + SELECT room_id, push_date, COUNT(*) AS c + FROM shorts_jobs + WHERE room_id != '' + AND status NOT IN ('failed', 'skipped') + GROUP BY room_id, push_date + HAVING c > 1 + """ + ).fetchall() + for g in groups: + rows = conn.execute( + """ + SELECT id, status, youtube_video_id, created_at, finished_at + FROM shorts_jobs + WHERE room_id = ? AND push_date = ? + AND status NOT IN ('failed', 'skipped') + ORDER BY + CASE WHEN youtube_video_id != '' THEN 0 ELSE 1 END, + CASE WHEN status = 'uploaded' THEN 0 ELSE 1 END, + created_at ASC + """, + (g["room_id"], g["push_date"]), + ).fetchall() + if len(rows) <= 1: + continue + keep_id = rows[0]["id"] + for row in rows[1:]: + # Never skip a job that already has a YouTube id unless keeper also has one + if str(row["youtube_video_id"] or "").strip() and not str(rows[0]["youtube_video_id"] or "").strip(): + continue + conn.execute( + """ + UPDATE shorts_jobs + SET status = 'skipped', + error = '同房间同日重复任务已跳过', + updated_at = ?, + finished_at = CASE WHEN finished_at = 0 THEN ? ELSE finished_at END + WHERE id = ? AND id != ? AND status NOT IN ('failed', 'skipped', 'uploaded') + AND youtube_video_id = '' + """, + (now, now, row["id"], keep_id), + ) + skipped += int(conn.total_changes) + conn.commit() + return skipped + finally: + conn.close() + + def room_ids_with_shorts_job_today(push_date: str) -> set[str]: with _lock: conn = _connect() @@ -3139,13 +3388,32 @@ def create_shorts_job( stream_url: str = "", channel_pk: str = "", push_date: str = "", -) -> dict[str, Any]: + force: bool = False, +) -> dict[str, Any] | None: + """Create a Shorts job. Same room_id + Beijing day is unique unless force=True. + + Returns None when a non-failed/skipped job already exists for that room/day. + """ 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 and not force: + existing = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE room_id = ? AND push_date = ? + AND status NOT IN ('failed', 'skipped') + ORDER BY created_at ASC + LIMIT 1 + """, + (rid, day), + ).fetchone() + if existing: + return None conn.execute( """ INSERT INTO shorts_jobs( @@ -3158,7 +3426,7 @@ def create_shorts_job( jid, session_id, room_pk, - room_id, + rid, source_url, anchor_name, stream_url, @@ -3234,7 +3502,7 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict """ SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id FROM shorts_jobs j - LEFT JOIN shorts_channels c ON c.id = j.channel_pk + INNER JOIN shorts_channels c ON c.id = j.channel_pk WHERE j.status = 'scheduled' AND j.clip_path != '' AND j.youtube_video_id = '' @@ -3250,7 +3518,7 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict """ SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id FROM shorts_jobs j - LEFT JOIN shorts_channels c ON c.id = j.channel_pk + INNER JOIN shorts_channels c ON c.id = j.channel_pk WHERE j.status = 'recorded' AND j.clip_path != '' AND j.youtube_video_id = '' @@ -3335,9 +3603,12 @@ def claim_next_shorts_job() -> dict[str, Any] | None: return claim_pending_shorts_record() -def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0, retry_at: float = 0) -> int: - """Reset stuck uploading jobs back to scheduled.""" - cutoff = time.time() - max(60.0, float(max_age_sec)) +def reclaim_stale_shorts_uploads(*, max_age_sec: float = 900.0, retry_at: float = 0) -> int: + """Reset truly stuck uploading jobs back to scheduled. + + Uses updated_at (heartbeat during upload). Default 15min — never reclaim a live upload. + """ + cutoff = time.time() - max(300.0, float(max_age_sec)) now = time.time() upload_at = float(retry_at or now) with _lock: @@ -3346,11 +3617,15 @@ def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0, retry_at: float cur = conn.execute( """ UPDATE shorts_jobs - SET status = 'scheduled', upload_at = ?, error = '', updated_at = ? + SET status = 'scheduled', + upload_at = ?, + error = '上传超时已重排(未完成)', + updated_at = ?, + started_at = 0 WHERE status = 'uploading' AND clip_path != '' AND youtube_video_id = '' - AND COALESCE(NULLIF(started_at, 0), updated_at) < ? + AND updated_at < ? """, (upload_at, now, cutoff), ) @@ -3473,10 +3748,10 @@ def claim_shorts_job_manual_upload(job_id: str) -> dict[str, Any] | None: def has_shorts_job_for_room_day(room_id: str, push_date: str, channel_id: str = "") -> bool: - """Return True if this channel already has a non-failed job for room_id on push_date. + """Return True if a non-failed job already exists for room_id on push_date. - Dedup scope: channel_id + room_id + push_date (Beijing day 00:00-24:00). - If channel_id is empty, falls back to global room_id + push_date dedup. + Dedup scope defaults to global room_id + push_date (Beijing day). + Optional channel_id filters by channel_pk (column name is channel_pk). """ if not room_id: return False @@ -3487,7 +3762,7 @@ def has_shorts_job_for_room_day(room_id: str, push_date: str, channel_id: str = row = conn.execute( """ SELECT 1 FROM shorts_jobs - WHERE room_id = ? AND push_date = ? AND channel_id = ? + WHERE room_id = ? AND push_date = ? AND channel_pk = ? AND status NOT IN ('failed', 'skipped') LIMIT 1 """, @@ -3508,6 +3783,64 @@ def has_shorts_job_for_room_day(room_id: str, push_date: str, channel_id: str = conn.close() +def touch_shorts_upload_lease(job_id: str) -> bool: + """Heartbeat while uploading. False if job already finished / not uploading.""" + now = time.time() + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE shorts_jobs + SET updated_at = ? + WHERE id = ? + AND status = 'uploading' + AND youtube_video_id = '' + """, + (now, job_id), + ) + conn.commit() + return int(cur.rowcount) > 0 + finally: + conn.close() + + +def finalize_shorts_upload( + job_id: str, + *, + youtube_video_id: str, + youtube_url: str = "", +) -> bool: + """Atomically mark uploaded. False if another worker already finalized.""" + now = time.time() + vid = str(youtube_video_id or "").strip() + if not vid: + return False + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE shorts_jobs + SET status = 'uploaded', + youtube_video_id = ?, + youtube_url = ?, + error = '', + finished_at = ?, + updated_at = ?, + clip_path = '' + WHERE id = ? + AND youtube_video_id = '' + AND status IN ('uploading', 'scheduled', 'recorded') + """, + (vid, str(youtube_url or ""), now, now, job_id), + ) + conn.commit() + return int(cur.rowcount) > 0 + finally: + conn.close() + + def shorts_stats(push_date: str = "") -> dict[str, Any]: day = push_date or push_date_from_ts(time.time()) with _lock: diff --git a/backend/app/main.py b/backend/app/main.py index db89403..961909e 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -23,7 +23,7 @@ from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Stre from fastapi.staticfiles import StaticFiles import httpx -from . import cookie_loader, db, pb_sync, shorts_oauth, youtube_client, youtube_manage +from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage from .config import settings from .cover import cover_path_for, ensure_session_cover from .douyin import check_room @@ -43,6 +43,10 @@ from .models import ( ShortsChannelCreate, ShortsChannelUpdate, ShortsJobsBulkBody, + TikTokChannelCreate, + TikTokChannelUpdate, + TikTokJobsBulkBody, + TikTokOAuthConfig, YouTubeVideoUpdate, ) from .monitor import monitor @@ -61,6 +65,8 @@ from .session_auth import ( ) from .youtube_monitor import yt_monitor from .shorts_pipeline import shorts_pipeline +from .tiktok_pipeline import tiktok_pipeline +from . import tiktok_oauth from .timeutil import stamp_beijing @@ -119,9 +125,17 @@ async def lifespan(_: FastAPI): await shorts_pipeline.start() except Exception: pass + try: + await tiktok_pipeline.start() + except Exception: + pass asyncio.create_task(_start_workers()) yield + try: + await tiktok_pipeline.stop() + except Exception: + pass try: await shorts_pipeline.stop() except Exception: @@ -375,11 +389,19 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]: """Mask OAuth secrets in settings API responses.""" + from . import shorts_socks + out = dict(cfg) secret = str(out.get("shorts_oauth_client_secret") or "") if secret and not str(secret).startswith("***"): out["shorts_oauth_client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else "***" out["shorts_oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True) + out["shorts_upload_socks_profiles"] = shorts_socks.list_socks_profiles(cfg, public=True) + out["shorts_upload_socks_enabled"] = bool(cfg.get("shorts_upload_socks_enabled")) + out["shorts_upload_socks_profile_id"] = str(cfg.get("shorts_upload_socks_profile_id") or "") + tt_secret = str(out.get("tiktok_oauth_client_secret") or "") + if tt_secret and not tt_secret.startswith("***"): + out["tiktok_oauth_client_secret"] = ("***" + tt_secret[-4:]) if len(tt_secret) > 4 else "***" return out @@ -601,8 +623,8 @@ async def shorts_channels_update(channel_pk: str, body: ShortsChannelUpdate) -> @app.delete("/api/shorts/channels/{channel_pk}") async def shorts_channels_delete(channel_pk: str) -> dict[str, Any]: - db.delete_shorts_channel(channel_pk) - return {"ok": True} + stats = db.delete_shorts_channel(channel_pk) + return {"ok": True, **stats} @app.get("/api/shorts/jobs") @@ -701,10 +723,17 @@ async def shorts_jobs_bulk(body: ShortsJobsBulkBody) -> dict[str, Any]: @app.post("/api/shorts/reconcile") async def shorts_reconcile() -> dict[str, Any]: + orphans = db.purge_orphan_shorts_jobs(limit=500) missing = db.reconcile_missing_shorts_clips(limit=200) healed = db.reconcile_false_failed_shorts(limit=200) - stale = db.reclaim_stale_shorts_uploads(max_age_sec=180) - return {"missing_clips": missing, "false_failed": healed, "stale_uploads": stale} + stale = db.reclaim_stale_shorts_uploads(max_age_sec=900) + return { + "orphan_jobs": orphans.get("jobs", 0), + "orphan_clips": orphans.get("clips", 0), + "missing_clips": missing, + "false_failed": healed, + "stale_uploads": stale, + } @app.get("/api/shorts/stats/history") @@ -781,6 +810,268 @@ async def shorts_schedule() -> dict[str, Any]: return schedule_board(limit=40) +# ---------- TikTok (fully isolated from Shorts) ---------- + +def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: + if not ch: + return None + out = dict(ch) + for k in ("client_secret", "refresh_token", "access_token"): + v = str(out.get(k) or "") + out[f"has_{k}"] = bool(v.strip()) + if v: + out[k] = ("***" + v[-4:]) if len(v) > 4 else "***" + out["authorized"] = bool(str(ch.get("refresh_token") or "").strip()) + out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1) + return out + + +def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None: + if not job: + return None + from pathlib import Path + from . import tiktok_db + + out = dict(job) + clip = str(out.get("clip_path") or "").strip() + out["clip_ready"] = bool(clip) and Path(clip).is_file() + ch = tiktok_db.get_tiktok_channel(str(out.get("channel_pk") or "")) or {} + if ch: + out["channel_name"] = ch.get("name") or "" + return out + + +@app.get("/api/tiktok/status") +async def tiktok_status() -> dict[str, Any]: + st = await asyncio.to_thread(tiktok_pipeline.status) + cfg = await _db(db.get_settings_map) + st["oauth_configured"] = tiktok_oauth.oauth_configured(cfg) + st["oauth_redirect_uri"] = tiktok_oauth.resolve_redirect_uri("https://dylive.nomadro.com") + st["setup"] = tiktok_oauth.setup_checklist(cfg) + st["channels"] = [_public_tiktok_channel(c) for c in (await _db(tiktok_db.list_tiktok_channels))] + return st + + +@app.get("/api/tiktok/setup") +async def tiktok_setup() -> dict[str, Any]: + cfg = await _db(db.get_settings_map) + return tiktok_oauth.setup_checklist(cfg) + + +@app.post("/api/tiktok/oauth/config") +async def tiktok_oauth_config(body: TikTokOAuthConfig) -> dict[str, Any]: + patch: dict[str, Any] = {} + key = str(body.client_key or "").strip() + secret = str(body.client_secret or "").strip() + if key: + patch["tiktok_oauth_client_key"] = key + if secret and not secret.startswith("***"): + patch["tiktok_oauth_client_secret"] = secret + if not patch: + raise HTTPException(400, "请填写 Client Key / Client Secret") + cfg = await _db(db.update_settings_map, patch) + return {"ok": True, "oauth_configured": tiktok_oauth.oauth_configured(cfg)} + + +@app.get("/api/tiktok/oauth/start") +async def tiktok_oauth_start(channel_pk: str, request: Request) -> RedirectResponse: + try: + url = tiktok_oauth.build_authorize_url(channel_pk=channel_pk, request_base=_request_public_base(request)) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + return RedirectResponse(url, status_code=302) + + +@app.get("/api/tiktok/oauth/callback") +async def tiktok_oauth_callback( + request: Request, + code: str = "", + state: str = "", + error: str = "", +) -> RedirectResponse: + base = _request_public_base(request) + if error: + return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote(error)}", status_code=302) + if not code or not state: + return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote('缺少 code/state')}", status_code=302) + try: + result = await tiktok_oauth.exchange_code(code=code, state=state, request_base=base) + title = quote(str(result.get("username") or "ok")) + return RedirectResponse(f"{base}/tiktok?oauth=ok&title={title}", status_code=302) + except Exception as exc: + return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote(str(exc)[:180])}", status_code=302) + + +@app.post("/api/tiktok/oauth/probe") +async def tiktok_oauth_probe(channel_pk: str = "") -> dict[str, Any]: + from . import tiktok_db + + if channel_pk.strip(): + ch = tiktok_db.get_tiktok_channel(channel_pk.strip()) + if not ch: + raise HTTPException(404, "账号不存在") + return await tiktok_oauth.probe_channel_oauth(ch) + results = [] + for ch in tiktok_db.list_tiktok_channels(enabled=True): + if str(ch.get("refresh_token") or "").strip(): + results.append(await tiktok_oauth.probe_channel_oauth(ch)) + return {"checked": len(results), "results": results} + + +@app.post("/api/tiktok/start") +async def tiktok_start() -> dict[str, Any]: + db.update_settings_map({"tiktok_enabled": True}) + try: + await tiktok_pipeline.start() + except Exception: + pass + return tiktok_pipeline.status() + + +@app.post("/api/tiktok/stop") +async def tiktok_stop() -> dict[str, Any]: + db.update_settings_map({"tiktok_enabled": False}) + return tiktok_pipeline.status() + + +@app.post("/api/tiktok/sample-now") +async def tiktok_sample_now() -> dict[str, Any]: + from .tiktok_pipeline import try_sample_live_rooms + + n = await asyncio.to_thread(try_sample_live_rooms) + return {"ok": True, "enqueued": n, "status": tiktok_pipeline.status()} + + +@app.get("/api/tiktok/channels") +async def tiktok_channels_list() -> dict[str, Any]: + from . import tiktok_db + + rows = await _db(tiktok_db.list_tiktok_channels) + return {"channels": [_public_tiktok_channel(c) for c in rows]} + + +@app.post("/api/tiktok/channels") +async def tiktok_channels_create(body: TikTokChannelCreate) -> dict[str, Any]: + from . import tiktok_db + + ch = await _db( + tiktok_db.create_tiktok_channel, + name=body.name, + enabled=body.enabled, + title_template=body.title_template, + description_template=body.description_template, + privacy_level=body.privacy_level, + note=body.note, + ) + return {"ok": True, "channel": _public_tiktok_channel(ch)} + + +@app.patch("/api/tiktok/channels/{channel_pk}") +async def tiktok_channels_update(channel_pk: str, body: TikTokChannelUpdate) -> dict[str, Any]: + from . import tiktok_db + + patch = body.model_dump(exclude_none=True) + if not patch: + raise HTTPException(400, "无更新字段") + ch = await _db(tiktok_db.update_tiktok_channel, channel_pk, **patch) + if not ch: + raise HTTPException(404, "账号不存在") + return {"ok": True, "channel": _public_tiktok_channel(ch)} + + +@app.delete("/api/tiktok/channels/{channel_pk}") +async def tiktok_channels_delete(channel_pk: str) -> dict[str, Any]: + from . import tiktok_db + + ok = await _db(tiktok_db.delete_tiktok_channel, channel_pk) + if not ok: + raise HTTPException(404, "账号不存在") + return {"ok": True} + + +@app.get("/api/tiktok/jobs") +async def tiktok_jobs_list( + status: str = "", + push_date: str = "", + channel_pk: str = "", + limit: int = Query(50, ge=1, le=500), + offset: int = Query(0, ge=0), +) -> dict[str, Any]: + from . import tiktok_db + + data = await _db( + tiktok_db.list_tiktok_jobs, + status=status, + push_date=push_date, + channel_pk=channel_pk, + limit=limit, + offset=offset, + ) + data["jobs"] = [_enrich_tiktok_job(j) for j in data.get("jobs") or []] + return data + + +@app.get("/api/tiktok/jobs/{job_id}") +async def tiktok_job_detail(job_id: str) -> dict[str, Any]: + from . import tiktok_db + + job = await _db(tiktok_db.get_tiktok_job, job_id) + if not job: + raise HTTPException(404, "任务不存在") + return {"job": _enrich_tiktok_job(job)} + + +@app.get("/api/tiktok/jobs/{job_id}/clip") +async def tiktok_job_clip(job_id: str) -> FileResponse: + from . import tiktok_db + + job = tiktok_db.get_tiktok_job(job_id) + if not job: + raise HTTPException(404, "任务不存在") + clip = str(job.get("clip_path") or "").strip() + if not clip or not os.path.isfile(clip): + raise HTTPException(404, "成片不存在") + return FileResponse(clip, media_type="video/mp4", filename=os.path.basename(clip)) + + +@app.post("/api/tiktok/jobs/{job_id}/retry") +async def tiktok_job_retry(job_id: str) -> dict[str, Any]: + from . import tiktok_db + from .tiktok_schedule import pick_upload_at + + job = tiktok_db.get_tiktok_job(job_id) + if not job: + raise HTTPException(404, "任务不存在") + clip = str(job.get("clip_path") or "").strip() + if clip and os.path.isfile(clip): + updated = tiktok_db.update_tiktok_job( + job_id, + status="scheduled", + upload_at=pick_upload_at(channel_pk=str(job.get("channel_pk") or "")), + error="", + finished_at=0, + ) + else: + updated = tiktok_db.update_tiktok_job(job_id, status="pending", error="", finished_at=0, clip_path="") + return {"ok": True, "job": _enrich_tiktok_job(updated)} + + +@app.post("/api/tiktok/jobs/{job_id}/upload-now") +async def tiktok_job_upload_now(job_id: str) -> dict[str, Any]: + try: + job = await tiktok_pipeline.upload_job_now(job_id) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + return {"ok": True, "job": _enrich_tiktok_job(job)} + + +@app.get("/api/tiktok/schedule") +async def tiktok_schedule_api() -> dict[str, Any]: + from .tiktok_schedule import schedule_board + + return schedule_board(limit=40) + + @app.post("/api/monitor/check/{room_pk}") async def monitor_check_one(room_pk: str) -> dict[str, Any]: room = db.get_room(room_pk) @@ -808,6 +1099,13 @@ async def patch_settings(body: SettingsUpdate) -> dict[str, Any]: patch["shorts_oauth_profiles"] = shorts_oauth.merge_oauth_profiles_patch( patch.get("shorts_oauth_profiles"), existing ) + if "shorts_upload_socks_profiles" in patch: + from . import shorts_socks + + existing = await asyncio.to_thread(db.get_settings_map) + patch["shorts_upload_socks_profiles"] = shorts_socks.merge_socks_profiles_patch( + patch.get("shorts_upload_socks_profiles"), existing + ) cfg = await asyncio.to_thread(db.update_settings_map, patch) return _public_settings(cfg) diff --git a/backend/app/models.py b/backend/app/models.py index c13af7f..1eaa5e0 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -230,6 +230,9 @@ class SettingsUpdate(BaseModel): shorts_oauth_redirect_uri: Optional[str] = None shorts_oauth_profiles: Optional[list[dict[str, Any]]] = None shorts_gcp_project_id: Optional[str] = None + shorts_upload_socks_enabled: Optional[bool] = None + shorts_upload_socks_profile_id: Optional[str] = None + shorts_upload_socks_profiles: Optional[list[dict[str, Any]]] = None class ShortsChannelCreate(BaseModel): @@ -269,6 +272,34 @@ class ShortsJobsBulkBody(BaseModel): action: str = "retry" # retry | upload_now +class TikTokOAuthConfig(BaseModel): + client_key: str = "" + client_secret: str = "" + + +class TikTokChannelCreate(BaseModel): + name: str = "TikTok 账号" + enabled: bool = True + title_template: str = "{anchor} #fyp" + description_template: str = "{anchor}\n{url}" + privacy_level: str = "SELF_ONLY" + note: str = "" + + +class TikTokChannelUpdate(BaseModel): + name: Optional[str] = None + enabled: Optional[bool] = None + title_template: Optional[str] = None + description_template: Optional[str] = None + privacy_level: Optional[str] = None + note: Optional[str] = None + + +class TikTokJobsBulkBody(BaseModel): + job_ids: list[str] + action: str = "retry" # retry | upload_now + + class YouTubeVideoUpdate(BaseModel): title: Optional[str] = None description: Optional[str] = None diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py new file mode 100644 index 0000000..3e74049 --- /dev/null +++ b/backend/app/tiktok_db.py @@ -0,0 +1,522 @@ +# -*- 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: + 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 str(ch.get("refresh_token") or "").strip(): + 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() diff --git a/backend/app/tiktok_oauth.py b/backend/app/tiktok_oauth.py new file mode 100644 index 0000000..1505065 --- /dev/null +++ b/backend/app/tiktok_oauth.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +"""TikTok OAuth — click-to-authorize, stores tokens on channel.""" +from __future__ import annotations + +import secrets +import time +from typing import Any +from urllib.parse import urlencode + +import httpx + +from . import db +from . import tiktok_db + +TIKTOK_SCOPES = "user.info.basic,video.publish" + +_oauth_states: dict[str, tuple[str, float, str, str]] = {} + + +def _cfg() -> dict[str, Any]: + return db.get_settings_map() + + +def resolve_client_key_secret(cfg: dict[str, Any] | None = None) -> tuple[str, str]: + settings = cfg or _cfg() + key = str(settings.get("tiktok_oauth_client_key") or "").strip() + secret = str(settings.get("tiktok_oauth_client_secret") or "").strip() + return key, secret + + +def oauth_configured(cfg: dict[str, Any] | None = None) -> bool: + key, secret = resolve_client_key_secret(cfg) + return bool(key and secret) + + +def resolve_redirect_uri(request_base: str = "") -> str: + cfg = _cfg() + custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip() + if custom: + return custom.rstrip("/") + base = (request_base or "").rstrip("/") + if base: + return f"{base}/api/tiktok/oauth/callback" + return "https://dylive.nomadro.com/api/tiktok/oauth/callback" + + +def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]: + settings = cfg or _cfg() + key, secret = resolve_client_key_secret(settings) + redirect = resolve_redirect_uri() + return { + "oauth_configured": bool(key and secret), + "redirect_uri": redirect, + "scopes": TIKTOK_SCOPES.split(","), + "steps": [ + { + "id": "register", + "title": "注册 TikTok 开发者应用", + "url": "https://developers.tiktok.com/apps", + "done": bool(key), + }, + { + "id": "scopes", + "title": "申请 video.publish 权限(Direct Post)", + "url": "https://developers.tiktok.com/doc/content-posting-api-get-started", + "done": bool(key), + }, + { + "id": "redirect", + "title": f"配置 Redirect URI:{redirect}", + "url": "https://developers.tiktok.com/apps", + "done": bool(key), + }, + { + "id": "credentials", + "title": "填写 Client Key / Client Secret", + "done": bool(key and secret), + }, + { + "id": "account", + "title": "添加 TikTok 账号并点击授权", + "done": len(tiktok_db.list_tiktok_channels()) > 0 + and any(str(c.get("refresh_token") or "").strip() for c in tiktok_db.list_tiktok_channels()), + }, + ], + "note_unaudited": "未审核应用只能发布 SELF_ONLY(仅自己可见),审核通过后可改为 PUBLIC_TO_EVERYONE。", + } + + +def build_authorize_url(*, channel_pk: str, request_base: str = "") -> str: + cfg = _cfg() + client_key, client_secret = resolve_client_key_secret(cfg) + if not client_key or not client_secret: + raise ValueError("请先在 TikTok 页面填写 Client Key / Client Secret") + channel = tiktok_db.get_tiktok_channel(channel_pk) + if not channel: + raise ValueError("账号不存在") + now = time.time() + for k, packed in list(_oauth_states.items()): + if packed[1] < now: + _oauth_states.pop(k, None) + state = secrets.token_urlsafe(24) + _oauth_states[state] = (channel_pk, now + 600, client_key, client_secret) + params = { + "client_key": client_key, + "redirect_uri": resolve_redirect_uri(request_base), + "response_type": "code", + "scope": TIKTOK_SCOPES, + "state": state, + } + return "https://www.tiktok.com/v2/auth/authorize/?" + urlencode(params) + + +async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]: + packed = _oauth_states.pop(state, None) + if not packed: + raise ValueError("授权 state 无效或已过期,请重新点击授权") + channel_pk, exp, client_key, client_secret = packed + if exp < time.time(): + raise ValueError("授权已过期,请重新点击授权") + redirect_uri = resolve_redirect_uri(request_base) + async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client: + resp = await client.post( + "https://open.tiktokapis.com/v2/oauth/token/", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data={ + "client_key": client_key, + "client_secret": client_secret, + "code": code, + "grant_type": "authorization_code", + "redirect_uri": redirect_uri, + }, + ) + data = resp.json() if resp.content else {} + if resp.status_code >= 400 or not data.get("access_token"): + err = data.get("error_description") or data.get("message") or data or resp.text + raise ValueError(f"换取 token 失败: {err}") + access = str(data.get("access_token") or "") + refresh = str(data.get("refresh_token") or "").strip() + open_id = str(data.get("open_id") or "") + expires_in = int(data.get("expires_in") or 86400) + if not refresh: + channel = tiktok_db.get_tiktok_channel(channel_pk) or {} + refresh = str(channel.get("refresh_token") or "").strip() + if not refresh: + raise ValueError("未拿到 refresh_token,请撤销授权后重试") + + username = "" + try: + info = await client.get( + "https://open.tiktokapis.com/v2/user/info/", + params={"fields": "open_id,display_name,username"}, + headers={"Authorization": f"Bearer {access}"}, + ) + info_data = info.json() if info.content else {} + user = (info_data.get("data") or {}).get("user") or {} + username = str(user.get("display_name") or user.get("username") or "") + except Exception: + pass + + patch: dict[str, Any] = { + "client_key": client_key, + "client_secret": client_secret, + "refresh_token": refresh, + "access_token": access, + "token_expires_at": time.time() + max(300, expires_in - 60), + "tiktok_open_id": open_id, + "oauth_ok": 1, + "oauth_checked_at": time.time(), + "oauth_error": "", + } + if open_id: + patch["tiktok_open_id"] = open_id + if username: + ch = tiktok_db.get_tiktok_channel(channel_pk) or {} + if not str(ch.get("name") or "").strip() or ch.get("name") == "TikTok 账号": + patch["name"] = username + patch["tiktok_username"] = username + updated = tiktok_db.update_tiktok_channel(channel_pk, **patch) + return {"ok": True, "channel": updated, "username": username, "open_id": open_id} + + +def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]: + settings = cfg or _cfg() + g_key, g_secret = resolve_client_key_secret(settings) + return { + "client_key": str(channel.get("client_key") or g_key).strip(), + "client_secret": str(channel.get("client_secret") or g_secret).strip(), + "refresh_token": str(channel.get("refresh_token") or "").strip(), + "access_token": str(channel.get("access_token") or "").strip(), + "token_expires_at": str(channel.get("token_expires_at") or 0), + } + + +async def refresh_access_token( + *, + client_key: str, + client_secret: str, + refresh_token: str, +) -> dict[str, str]: + if not (client_key and client_secret and refresh_token): + raise ValueError("缺少 TikTok OAuth 凭证") + async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client: + resp = await client.post( + "https://open.tiktokapis.com/v2/oauth/token/", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data={ + "client_key": client_key, + "client_secret": client_secret, + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + data = resp.json() if resp.content else {} + if resp.status_code >= 400 or not data.get("access_token"): + raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}") + return { + "access_token": str(data["access_token"]), + "refresh_token": str(data.get("refresh_token") or refresh_token), + "expires_in": str(data.get("expires_in") or 86400), + "open_id": str(data.get("open_id") or ""), + } + + +async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]: + creds = channel_oauth_creds(channel, cfg) + cid = str(channel.get("id") or "") + now = time.time() + if not cid: + return {"ok": False, "error": "账号 ID 缺失"} + if not creds["refresh_token"]: + tiktok_db.update_tiktok_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error="未授权") + return {"ok": False, "error": "未授权", "channel_id": cid} + try: + tok = await refresh_access_token( + client_key=creds["client_key"], + client_secret=creds["client_secret"], + refresh_token=creds["refresh_token"], + ) + tiktok_db.update_tiktok_channel( + cid, + access_token=tok["access_token"], + refresh_token=tok["refresh_token"], + token_expires_at=now + max(300, int(tok.get("expires_in") or 86400) - 60), + oauth_ok=1, + oauth_checked_at=now, + oauth_error="", + ) + return {"ok": True, "channel_id": cid} + except Exception as exc: + err = str(exc)[:240] + tiktok_db.update_tiktok_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err) + return {"ok": False, "error": err, "channel_id": cid} diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py new file mode 100644 index 0000000..be2cb79 --- /dev/null +++ b/backend/app/tiktok_pipeline.py @@ -0,0 +1,367 @@ +# -*- 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_oauth +from .shorts_clip import record_clip, resolve_stream_url +from .tiktok_schedule import pick_upload_at, schedule_board +from .tiktok_upload import 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 = "", +) -> Optional[dict[str, Any]]: + try: + settings = cfg or db.get_settings_map() + if not settings.get("tiktok_enabled"): + return None + room_id = str((session or {}).get("room_id") or room.get("room_id") or "") + if room_id.startswith("yt:"): + return None + day = push_date_from_ts(float((session or {}).get("started_at") or 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 str(ch.get("refresh_token") or "").strip(): + used = tiktok_db.tiktok_channel_upload_count(channel_pk, day) + if used < db.TIKTOK_DAILY_FORCE: + channel = ch + if not channel: + channel = tiktok_db.pick_tiktok_channel(day) + if 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["id"]), + 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 + + +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 + + 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 str(ch.get("refresh_token") or "").strip(): + 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": int(cfg.get("tiktok_clip_sec") or 15), + "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 upload_job_now(self, job_id: str) -> dict[str, Any]: + job = tiktok_db.claim_tiktok_job_manual_upload(job_id) + if not job: + raise ValueError("任务不可立即上传(需 scheduled/recorded 且有成片)") + await self._do_upload(job) + fresh = tiktok_db.get_tiktok_job(job_id) + if not fresh: + raise ValueError("任务不存在") + if str(fresh.get("status") or "") not in {"uploaded", "done"}: + 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 + oauth_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600)) + if (time.time() - self._last_oauth_check_at) >= oauth_interval: + self._last_oauth_check_at = time.time() + for ch in tiktok_db.list_tiktok_channels(enabled=True): + if str(ch.get("refresh_token") or "").strip(): + asyncio.create_task(tiktok_oauth.probe_channel_oauth(ch, cfg)) + retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300)) + if cfg.get("tiktok_auto_retry_failed", True) 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 + 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)) + max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 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]) -> None: + try: + await self._do_upload(job) + self.processed += 1 + 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_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 "") + stream = await resolve_stream_url( + source_url=str(job.get("source_url") or ""), + stream_url=str(job.get("stream_url") or ""), + cookie=cookie, + ) + if not stream: + tiktok_db.update_tiktok_job( + jid, + status="failed", + error="无法获取直播流(可能已停播)", + finished_at=time.time(), + ) + return + sec = max(5, int(cfg.get("tiktok_clip_sec") or 15)) + outcome = await record_clip(job_id=f"tiktok_{jid[:8]}", stream_url=stream, seconds=sec) + if not outcome.get("ok"): + tiktok_db.update_tiktok_job( + jid, + status="failed", + error=str(outcome.get("error") or "录制失败")[:500], + 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())) + ch_pk = str(job.get("channel_pk") or "") + if cfg.get("tiktok_auto_upload", True): + 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, + upload_at=upload_at, + error="", + ) + else: + tiktok_db.update_tiktok_job( + jid, status="recorded", clip_path=out_path, clip_seconds=seconds, stream_url=stream, error="" + ) + + async def _do_upload(self, job: dict[str, Any]) -> None: + cfg = db.get_settings_map() + jid = str(job.get("id") or "") + fresh = tiktok_db.get_tiktok_job(jid) or job + clip = str(fresh.get("clip_path") or "") + if not clip or not Path(clip).is_file(): + raise ValueError("成片文件不存在") + channel = tiktok_db.get_tiktok_channel(str(fresh.get("channel_pk") or "")) + if not channel: + raise ValueError("账号不存在") + creds = tiktok_oauth.channel_oauth_creds(channel, cfg) + if not creds["refresh_token"]: + tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未授权") + return + title_tpl = str(channel.get("title_template") or "{anchor} #fyp") + desc_tpl = str(channel.get("description_template") or "") + anchor = str(fresh.get("anchor_name") or fresh.get("room_id") or "live") + url = str(fresh.get("source_url") or "") + title = title_tpl.replace("{anchor}", anchor).replace("{url}", url) + desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url) + if not tiktok_db.touch_tiktok_upload_lease(jid): + return + result = await upload_tiktok_mp4( + file_path=clip, + title=title, + description=desc, + privacy_level=str(channel.get("privacy_level") or "SELF_ONLY"), + client_key=creds["client_key"], + client_secret=creds["client_secret"], + refresh_token=creds["refresh_token"], + access_token=creds["access_token"], + token_expires_at=float(creds.get("token_expires_at") or 0), + ) + if not tiktok_db.finalize_tiktok_upload( + jid, + tiktok_publish_id=str(result.get("publish_id") or ""), + tiktok_video_id=str(result.get("video_id") or ""), + ): + return + tiktok_db.update_tiktok_channel( + str(channel["id"]), + access_token=str(result.get("access_token") or creds["access_token"]), + refresh_token=str(result.get("refresh_token") or creds["refresh_token"]), + token_expires_at=time.time() + 82800, + ) + 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() diff --git a/backend/app/tiktok_schedule.py b/backend/app/tiktok_schedule.py new file mode 100644 index 0000000..db25396 --- /dev/null +++ b/backend/app/tiktok_schedule.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +"""TikTok upload scheduling — Beijing day staggered slots.""" +from __future__ import annotations + +import random +import time +from pathlib import Path +from typing import Any + +from . import db +from . import tiktok_db +from .db import TIKTOK_DAILY_FORCE +from .timeutil import beijing_day_bounds, beijing_from_ts, push_date_from_ts + + +def _day_end_ts(push_date: str) -> float: + return beijing_day_bounds(push_date)[1] + + +def _occupied_slots(push_date: str) -> list[tuple[float, str]]: + data = tiktok_db.list_tiktok_jobs(push_date=push_date, limit=500, offset=0) + slots: list[tuple[float, str]] = [] + for j in data.get("jobs") or []: + st = str(j.get("status") or "") + ch = str(j.get("channel_pk") or "") + if st in {"scheduled", "recorded", "uploading"}: + ts = float(j.get("upload_at") or 0) or float(j.get("updated_at") or 0) + if ts > 0: + slots.append((ts, ch)) + elif st in {"uploaded", "done"}: + ts = float(j.get("finished_at") or j.get("updated_at") or 0) + if ts > 0: + slots.append((ts, ch)) + return slots + + +def pick_upload_at(*, channel_pk: str, push_date: str = "", cfg: dict[str, Any] | None = None) -> float: + settings = cfg or db.get_settings_map() + now = time.time() + day = push_date or push_date_from_ts(now) + day_end = _day_end_ts(day) + latest = day_end - 45 + if not settings.get("tiktok_upload_spread", True): + return min(now + random.uniform(20, 120), latest) + global_min = max(300.0, float(settings.get("tiktok_upload_min_gap_sec") or 720)) + channel_min = max(global_min, float(settings.get("tiktok_channel_min_gap_sec") or 2400)) + earliest = now + random.uniform(180, 1500) + if earliest >= latest: + earliest = now + random.uniform(30, max(90.0, global_min * 0.4)) + slots = _occupied_slots(day) + + def conflicts(ts: float) -> bool: + for other_ts, other_ch in slots: + gap = abs(ts - other_ts) + if gap < global_min * 0.9: + return True + if other_ch == channel_pk and gap < channel_min * 0.9: + return True + return False + + window_end = max(earliest + 60, latest) + for _ in range(48): + cand = random.uniform(earliest, window_end) + if not conflicts(cand): + return float(min(cand, latest)) + last_ts = max((s[0] for s in slots), default=now) + return float(min(max(earliest, last_ts + global_min), latest)) + + +def schedule_board(limit: int = 24) -> dict[str, Any]: + day = push_date_from_ts(time.time()) + now = time.time() + day_start, day_end = beijing_day_bounds(day) + data = tiktok_db.list_tiktok_jobs(push_date=day, limit=500, offset=0) + upcoming: list[dict[str, Any]] = [] + by_ch: dict[str, dict[str, int]] = {} + for j in data.get("jobs") or []: + ch = str(j.get("channel_pk") or "") + st = str(j.get("status") or "") + bucket = by_ch.setdefault(ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) + if st not in {"failed", "skipped"}: + bucket["used"] += 1 + if st in {"uploaded", "done"}: + bucket["uploaded"] += 1 + if st == "scheduled": + bucket["scheduled"] += 1 + if st in {"pending", "recording"}: + bucket["pending"] += 1 + clip = str(j.get("clip_path") or "").strip() + clip_ready = bool(clip) and Path(clip).is_file() + if st in {"scheduled", "recorded"} and clip_ready: + upcoming.append(j) + upcoming.sort(key=lambda x: float(x.get("upload_at") or x.get("updated_at") or 0)) + channels = tiktok_db.list_tiktok_channels(enabled=None) + channel_map = {str(c["id"]): c for c in channels} + enriched = [] + for j in upcoming: + if len(enriched) >= limit: + break + pk = str(j.get("channel_pk") or "") + ch = channel_map.get(pk, {}) + if not ch: + continue + clip = str(j.get("clip_path") or "").strip() + enriched.append( + { + "id": j.get("id"), + "upload_at": j.get("upload_at"), + "anchor_name": j.get("anchor_name"), + "room_id": j.get("room_id"), + "channel_pk": pk, + "channel_name": ch.get("name") or "", + "status": j.get("status"), + "clip_ready": bool(clip) and Path(clip).is_file(), + "can_upload_now": str(j.get("status") or "") in {"scheduled", "recorded"}, + } + ) + channel_rows = [] + day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start))) + total_gap = 0 + for c in channels: + cid = str(c["id"]) + stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) + used = int(stats["used"]) + gap = max(0, TIKTOK_DAILY_FORCE - used) + if c.get("enabled"): + total_gap += gap + channel_rows.append( + { + "id": cid, + "name": c.get("name"), + "tiktok_username": c.get("tiktok_username"), + "enabled": bool(c.get("enabled")), + "authorized": bool(str(c.get("refresh_token") or "").strip()), + "daily_min": TIKTOK_DAILY_FORCE, + "daily_max": TIKTOK_DAILY_FORCE, + "gap": gap, + "max_met": used >= TIKTOK_DAILY_FORCE, + **stats, + } + ) + return { + "push_date": day, + "now": now, + "seconds_left": max(0, int(day_end - now)), + "day_progress": round(day_progress, 4), + "total_gap": total_gap, + "beijing_window": f"{day} 00:00–24:00", + "upcoming": enriched, + "channels": channel_rows, + "beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"), + } diff --git a/backend/app/tiktok_upload.py b/backend/app/tiktok_upload.py new file mode 100644 index 0000000..14b30a3 --- /dev/null +++ b/backend/app/tiktok_upload.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +"""TikTok video upload via Content Posting API (Direct Post).""" +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import httpx + +from . import tiktok_oauth + + +async def _ensure_access_token( + *, + client_key: str, + client_secret: str, + refresh_token: str, + access_token: str = "", + token_expires_at: float = 0, +) -> tuple[str, str]: + import time + + if access_token and token_expires_at > time.time() + 120: + return access_token, refresh_token + tok = await tiktok_oauth.refresh_access_token( + client_key=client_key, + client_secret=client_secret, + refresh_token=refresh_token, + ) + return tok["access_token"], tok.get("refresh_token") or refresh_token + + +async def query_creator_info(access_token: str) -> dict[str, Any]: + async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client: + resp = await client.post( + "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json; charset=UTF-8", + }, + json={}, + ) + data = resp.json() if resp.content else {} + if resp.status_code >= 400: + err = (data.get("error") or {}).get("message") or data or resp.text + raise ValueError(f"查询创作者信息失败: {err}") + return (data.get("data") or {}) + + +async def upload_tiktok_mp4( + *, + file_path: str, + title: str, + description: str = "", + privacy_level: str = "SELF_ONLY", + client_key: str = "", + client_secret: str = "", + refresh_token: str = "", + access_token: str = "", + token_expires_at: float = 0, + disable_duet: bool = False, + disable_comment: bool = False, + disable_stitch: bool = False, +) -> dict[str, Any]: + path = Path(file_path) + if not path.is_file(): + raise ValueError("成片文件不存在") + access, new_refresh = await _ensure_access_token( + client_key=client_key, + client_secret=client_secret, + refresh_token=refresh_token, + access_token=access_token, + token_expires_at=token_expires_at, + ) + creator = await query_creator_info(access) + allowed = creator.get("privacy_level_options") or ["SELF_ONLY"] + pl = privacy_level if privacy_level in allowed else (allowed[0] if allowed else "SELF_ONLY") + + try: + size = path.stat().st_size + raw = path.read_bytes() + except FileNotFoundError as exc: + raise ValueError("成片文件不存在") from exc + + chunk_size = min(size, 10 * 1024 * 1024) or size + chunk_count = max(1, (size + chunk_size - 1) // chunk_size) + + init_body = { + "post_info": { + "title": (title or "video")[:150], + "description": (description or "")[:2200], + "privacy_level": pl, + "disable_duet": disable_duet, + "disable_comment": disable_comment, + "disable_stitch": disable_stitch, + "video_cover_timestamp_ms": 1000, + }, + "source_info": { + "source": "FILE_UPLOAD", + "video_size": size, + "chunk_size": chunk_size, + "total_chunk_count": chunk_count, + }, + } + + async with httpx.AsyncClient(timeout=300.0, trust_env=False) as client: + init = await client.post( + "https://open.tiktokapis.com/v2/post/publish/video/init/", + headers={ + "Authorization": f"Bearer {access}", + "Content-Type": "application/json; charset=UTF-8", + }, + json=init_body, + ) + init_data = init.json() if init.content else {} + if init.status_code >= 400: + err = (init_data.get("error") or {}).get("message") or init_data or init.text + raise ValueError(f"初始化上传失败: {str(err)[:400]}") + upload_url = (init_data.get("data") or {}).get("upload_url") or "" + publish_id = (init_data.get("data") or {}).get("publish_id") or "" + if not upload_url or not publish_id: + raise ValueError(f"初始化上传失败: 缺少 upload_url/publish_id") + + headers = { + "Content-Type": "video/mp4", + "Content-Length": str(size), + "Content-Range": f"bytes 0-{size - 1}/{size}", + } + put = await client.put(upload_url, headers=headers, content=raw) + if put.status_code >= 400: + raise ValueError(f"上传视频失败: {put.text[:400]}") + + # Poll publish status + for _ in range(60): + st_resp = await client.post( + "https://open.tiktokapis.com/v2/post/publish/status/fetch/", + headers={ + "Authorization": f"Bearer {access}", + "Content-Type": "application/json; charset=UTF-8", + }, + json={"publish_id": publish_id}, + ) + st_data = st_resp.json() if st_resp.content else {} + status = str((st_data.get("data") or {}).get("status") or "") + if status in {"PUBLISH_COMPLETE", "SEND_TO_USER_INBOX"}: + break + if status in {"FAILED"}: + fail = (st_data.get("data") or {}).get("fail_reason") or status + raise ValueError(f"TikTok 发布失败: {fail}") + await asyncio.sleep(3) + else: + raise ValueError("TikTok 发布超时,请稍后在 TikTok 查看") + + return { + "ok": True, + "publish_id": publish_id, + "video_id": publish_id, + "access_token": access, + "refresh_token": new_refresh, + "privacy_level": pl, + } diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx new file mode 100644 index 0000000..dbbfe44 --- /dev/null +++ b/frontend/src/app/tiktok/page.tsx @@ -0,0 +1,751 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import Link from "next/link"; +import { + CheckCircle2, + Circle, + Clock3, + ExternalLink, + KeyRound, + Loader2, + Music2, + Plus, + RefreshCw, + Trash2, + Upload, + Zap, +} from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useToast } from "@/components/Toast"; +import { PageLoader } from "@/components/ui"; +import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; + +type SetupStep = { id: string; title: string; url?: string; done: boolean }; + +type Channel = { + id: string; + name: string; + tiktok_username?: string; + enabled?: boolean; + authorized?: boolean; + oauth_ok?: number; + oauth_error?: string; + privacy_level?: string; + title_template?: string; + description_template?: string; + note?: string; +}; + +type BoardChannel = { + id: string; + name?: string; + tiktok_username?: string; + enabled?: boolean; + authorized?: boolean; + used: number; + scheduled: number; + uploaded: number; + pending: number; + gap?: number; + max_met?: boolean; + daily_max?: number; +}; + +type Upcoming = { + id: string; + anchor_name?: string; + channel_name?: string; + upload_at?: number; + status?: string; + can_upload_now?: boolean; +}; + +type Job = { + id: string; + anchor_name?: string; + channel_name?: string; + status?: string; + push_date?: string; + error?: string; + clip_ready?: boolean; + tiktok_publish_id?: string; + created_at?: number; + finished_at?: number; +}; + +export default function TikTokPage() { + const toast = useToast(); + const confirm = useConfirm(); + const leftPanelRef = useRef(null); + const rightPanelRef = useRef(null); + + const [loading, setLoading] = useState(true); + const [status, setStatus] = useState(null); + const [channels, setChannels] = useState([]); + const [jobs, setJobs] = useState([]); + const [jobTotal, setJobTotal] = useState(0); + + const [clientKey, setClientKey] = useState(""); + const [clientSecret, setClientSecret] = useState(""); + const [savingCreds, setSavingCreds] = useState(false); + + const [showForm, setShowForm] = useState(false); + const [editId, setEditId] = useState(""); + const [formName, setFormName] = useState("TikTok 账号"); + const [formPrivacy, setFormPrivacy] = useState("SELF_ONLY"); + const [formTitle, setFormTitle] = useState("{anchor} #fyp"); + const [formDesc, setFormDesc] = useState("{anchor}\n{url}"); + + const [uploadingId, setUploadingId] = useState(""); + + const load = useCallback(async () => { + const iso = todayBeijingISO(); + const [st, j] = await Promise.all([ + fetchJson("/api/tiktok/status"), + fetchJson(`/api/tiktok/jobs?push_date=${iso}&limit=30`), + ]); + setStatus(st); + setChannels(st?.channels || []); + setJobs(j?.jobs || []); + setJobTotal(j?.total || 0); + setLoading(false); + }, []); + + useEffect(() => { + void load(); + const t = setInterval(() => void load(), 12000); + return () => clearInterval(t); + }, [load]); + + useEffect(() => { + const left = leftPanelRef.current; + const right = rightPanelRef.current; + if (!left || !right) return; + const sync = () => { + right.style.maxHeight = `${left.getBoundingClientRect().height}px`; + }; + sync(); + const ro = new ResizeObserver(sync); + ro.observe(left); + return () => ro.disconnect(); + }); + + useEffect(() => { + const params = new URLSearchParams(window.location.search); + const oauth = params.get("oauth"); + if (oauth === "ok") { + toast.success(`TikTok 授权成功:${params.get("title") || ""}`); + window.history.replaceState({}, "", "/tiktok"); + } else if (oauth === "error") { + toast.error(`授权失败:${params.get("msg") || ""}`); + window.history.replaceState({}, "", "/tiktok"); + } + }, [toast]); + + const setup = status?.setup; + const setupDone = setup?.steps?.every((s: SetupStep) => s.done); + const board = status?.board || {}; + const boardChannels: BoardChannel[] = board.channels || []; + const upcoming: Upcoming[] = board.upcoming || []; + const beijingWindow = board.beijing_window || ""; + const oauthConfigured = status?.oauth_configured; + const redirectUri = status?.oauth_redirect_uri || ""; + + const togglePipeline = async () => { + const on = status?.enabled; + await fetchJson(on ? "/api/tiktok/stop" : "/api/tiktok/start", { method: "POST" }); + toast.success(on ? "TikTok 已暂停" : "TikTok 已启动"); + void load(); + }; + + const saveCredentials = async () => { + if (!clientKey.trim()) { + toast.error("请填写 Client Key"); + return; + } + setSavingCreds(true); + try { + await fetchJson("/api/tiktok/oauth/config", { + method: "POST", + body: JSON.stringify({ client_key: clientKey.trim(), client_secret: clientSecret.trim() }), + }); + toast.success("凭证已保存"); + setClientSecret(""); + void load(); + } catch (e: any) { + toast.error(e?.message || "保存失败"); + } finally { + setSavingCreds(false); + } + }; + + const addChannel = async () => { + await fetchJson("/api/tiktok/channels", { + method: "POST", + body: JSON.stringify({ + name: formName, + privacy_level: formPrivacy, + title_template: formTitle, + description_template: formDesc, + }), + }); + toast.success("账号已添加,请点击「授权」"); + setShowForm(false); + void load(); + }; + + const saveChannel = async () => { + if (!editId) return; + await fetchJson(`/api/tiktok/channels/${editId}`, { + method: "PATCH", + body: JSON.stringify({ + name: formName, + privacy_level: formPrivacy, + title_template: formTitle, + description_template: formDesc, + }), + }); + toast.success("已保存"); + setShowForm(false); + setEditId(""); + void load(); + }; + + const removeChannel = async (id: string) => { + if (!(await confirm("确定删除此 TikTok 账号?"))) return; + await fetchJson(`/api/tiktok/channels/${id}`, { method: "DELETE" }); + toast.success("已删除"); + void load(); + }; + + const authorize = (id: string) => { + window.location.href = `/api/tiktok/oauth/start?channel_pk=${encodeURIComponent(id)}`; + }; + + const sampleNow = async () => { + const r = await fetchJson("/api/tiktok/sample-now", { method: "POST" }); + toast.success(`已取样 ${r.enqueued || 0} 条`); + void load(); + }; + + const uploadNow = async (jobId: string) => { + setUploadingId(jobId); + try { + await fetchJson(`/api/tiktok/jobs/${jobId}/upload-now`, { method: "POST" }); + toast.success("上传成功"); + void load(); + } catch (e: any) { + toast.error(e?.message || "上传失败"); + } finally { + setUploadingId(""); + } + }; + + const retryJob = async (jobId: string) => { + await fetchJson(`/api/tiktok/jobs/${jobId}/retry`, { method: "POST" }); + toast.success("已重新排队"); + void load(); + }; + + const startEdit = (ch: Channel) => { + setEditId(ch.id); + setFormName(ch.name || "TikTok 账号"); + setFormPrivacy(ch.privacy_level || "SELF_ONLY"); + setFormTitle(ch.title_template || "{anchor} #fyp"); + setFormDesc(ch.description_template || "{anchor}\n{url}"); + setShowForm(true); + }; + + const statusLabel = useMemo( + () => ({ + pending: "待录制", + recording: "录制中", + recorded: "成片就绪", + scheduled: "已排程", + uploading: "上传中", + uploaded: "已上传", + failed: "失败", + }), + [], + ); + + if (loading && !status) { + return ( + + + + ); + } + + return ( + +
+ {/* Header */} +
+
+

+ + TikTok 自动上传 +

+

独立模块 · 不影响 Shorts · 抖音直播录屏 → TikTok

+
+
+ + {setupDone && ( + <> + + + + )} +
+
+ + {/* Setup wizard */} + {!setupDone && ( +
+

🚀 三步完成配置(约 5 分钟)

+

按顺序完成下面步骤,即可自动上传。未审核应用只能发「仅自己可见」。

+ +
+ {(setup?.steps || []).map((step: SetupStep, i: number) => ( +
+ {step.done ? ( + + ) : ( + + )} +
+
+ {i + 1}. {step.title} +
+ {step.url && !step.done && ( + + 打开官方文档 + + )} +
+
+ ))} +
+ + {!oauthConfigured && ( +
+

填写 TikTok 应用凭证

+

+ Redirect URI 填:{redirectUri} +

+
+ + +
+ +
+ )} + + {oauthConfigured && channels.length === 0 && ( + + )} + + {setup?.note_unaudited && ( +

⚠️ {setup.note_unaudited}

+ )} +
+ )} + + {/* Summary cards */} + {setupDone && ( +
+
+
今日剩余配额
+
{status?.quota_gap ?? "—"}
+
{beijingWindow}
+
+
+
抖音直播中
+
{status?.douyin_live_count ?? 0}
+
可取样来源
+
+
+
即将上传
+
{upcoming.length}
+
已排程素材
+
+
+
运行状态
+
+ + {status?.enabled ? "自动上传中" : "已暂停"} +
+
+
+ )} + + {/* Control bar */} + {oauthConfigured && ( +
+ + + + 开发者后台 + +
+ )} + + {/* Channel form */} + {showForm && ( +
+

{editId ? "编辑账号" : "新增 TikTok 账号"}

+
+ + + +
+
+ + +
+
+ )} + + {/* Two-column board */} + {channels.length > 0 && ( +
+
+
+

账号配额({channels.length})

+ 北京日 {beijingWindow || "—"} · 每账号 9 条/日 +
+
+ {(boardChannels.length ? boardChannels : channels).map((ch) => { + const full = channels.find((x) => x.id === ch.id); + const pct = Math.min(100, Math.round(((ch.used || 0) / Math.max(1, ch.daily_max || 9)) * 100)); + return ( +
+
+
+
{ch.name || "未命名"}
+
{ch.tiktok_username || "—"}
+
+ + {full?.authorized ? "已授权" : "未授权"} + +
+
+
+
+
+ 已传 {ch.uploaded ?? 0} + 排程 {ch.scheduled ?? 0} + 待录 {ch.pending ?? 0} + + {ch.max_met ? "已满" : `余 ${ch.gap ?? 0}`} + +
+
+ + {full && ( + + )} + +
+
+ ); + })} +
+
+ +
+
+
+ +

即将上传

+
+ + 素材 {upcoming.length} + +
+
+ {upcoming.length === 0 ? ( +
+ 暂无排程。启动自动上传后,系统会从抖音直播中取样。 +
+ ) : ( + upcoming.map((u) => ( +
+
+
{u.anchor_name || "—"}
+
+ {u.channel_name} · {u.upload_at ? fmtTs(u.upload_at) : "—"} +
+
+ {u.can_upload_now && ( + + )} +
+ )) + )} +
+
+
+ )} + + {/* Jobs table */} + {setupDone && ( +
+
+

任务流水(今日 {jobTotal})

+
+
+ + + + + + + + + + + + {jobs.length === 0 ? ( + + + + ) : ( + jobs.map((j) => ( + + + + + + + + )) + )} + +
主播账号状态时间操作
+ 暂无任务 +
{j.anchor_name || "—"}{j.channel_name || "—"} + + {statusLabel[j.status as keyof typeof statusLabel] || j.status} + + {j.error && ( +
+ {j.error} +
+ )} +
+ {j.finished_at ? fmtTs(j.finished_at) : j.created_at ? fmtTs(j.created_at) : "—"} + +
+ {j.clip_ready && j.status !== "uploaded" && ( + + )} + {j.status === "failed" && ( + + )} +
+
+
+
+ )} + + {/* Quick help */} +
+
+ + 使用说明 +
+
    +
  1. 在 TikTok 开发者后台创建应用,申请 video.publish 权限
  2. +
  3. Redirect URI 填:{redirectUri}
  4. +
  5. 保存 Client Key / Secret → 添加账号 → 点击「授权」
  6. +
  7. 点击「启动自动上传」,系统会自动从抖音直播取样、录屏、错峰上传
  8. +
+
+
+
+ ); +} diff --git a/frontend/src/components/Shell.tsx b/frontend/src/components/Shell.tsx index 509c127..1295e40 100644 --- a/frontend/src/components/Shell.tsx +++ b/frontend/src/components/Shell.tsx @@ -20,6 +20,7 @@ const NAV = [ { href: "/groups", label: "分组", emoji: "📺" }, { href: "/youtube", label: "YouTube", emoji: "▶️" }, { href: "/shorts", label: "Shorts", emoji: "📱" }, + { href: "/tiktok", label: "TikTok", emoji: "🎵" }, { href: "/blacklist", label: "黑名单", emoji: "🚫" }, { href: "/settings", label: "设置", emoji: "⚙️" }, ];