diff --git a/AGENTS.md b/AGENTS.md index b8f9fb4..2a73457 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,13 +54,28 @@ python scripts/_deploy.py ## 开发约定 +### 平台业务隔离(强制) + +**Shorts(YouTube)/ TikTok / X 三大分发业务必须相互独立,禁止串扰。** + +| 原则 | 要求 | +|------|------| +| 代码边界 | 各自独立模块与命名前缀:`shorts_*`、`tiktok_*`、`x2_*` / `x_clips_*`;禁止在 A 平台流水线里直接调用 B 平台的业务函数(可共享的仅限无副作用工具,如 `record_clip`、S3、时间工具) | +| 数据边界 | 独立表 / 独立 settings 键 / 独立配额与任务状态;禁止共用「今日已传」计数或互相改对方 job 状态 | +| 采样边界 | 房间标签与采样开关分平台(如 `shorts` / `tiktok` / `x` 或 `shorts_only` 等);一边取样失败不得拖垮另一边 | +| 运行边界 | 独立 worker / pipeline 实例与异常域;A 的异常、限流、OAuth/Cookie 失效不得阻塞 B、C | +| 前端边界 | 独立页面与 API(`/shorts`、`/tiktok`、`/x`);接口与状态面板不混展示对方任务 | +| 监控主路径 | 抖音开停播监控(`monitor.py`)不得因 Shorts/TikTok/X 上传逻辑失败而中断 | + +实现新平台能力时:**复制模式、不耦合实现**——可对照 Shorts 流程设计,但落库、配置、调度、上传出口必须是本平台自己的一套。 + ### 后端(Python / FastAPI) -- 数据库操作统一在 `backend/app/db.py`,加锁用 `with _lock:` +- 数据库操作统一在 `backend/app/db.py`(或平台专属 `*_db.py`),加锁用 `with _lock:` - 新增 API 路由放 `backend/app/main.py`,遵循已有命名风格 - 平台过滤用 `_platform_clause(platform, room_col=..., meta_col=...)`,勿自行拼 SQL -- YouTube 相关:`shorts_*.py`、`shorts_yt_quota.py`;抖音监控:`monitor.py`、`douyin.py` -- 不要在监控主路径里引入 Shorts 相关异常(隔离原则) +- YouTube Shorts:`shorts_*.py`、`shorts_yt_quota.py`;TikTok:`tiktok_*.py`;X 运维:`x2_*.py`;X 直播切片:`x_clips_*.py`;抖音监控:`monitor.py`、`douyin.py` +- 不要在监控主路径里引入任一上传分发平台的异常 ### 前端(Next.js / TypeScript) diff --git a/backend/app/db.py b/backend/app/db.py index 5892488..5fb94f7 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -319,8 +319,10 @@ def init_db() -> None: if col not in tt_cols: conn.execute(f"ALTER TABLE tiktok_channels ADD COLUMN {col} {decl}") from . import x2_db as _x2_db + from . import x_clips_db as _x_clips_db _x2_db.ensure_x2_tables(conn) + _x_clips_db.ensure_x_clips_tables(conn) 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"), @@ -475,6 +477,23 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: # X2 (Twitter/X ops agent) ingest "x2_ingest_token": "", "x2_default_agent_label": "PVE-X2", + # X live-clip auto post (isolated from Shorts / TikTok) + "x_clips_enabled": False, + "x_clips_clip_sec": 12, + "x_clips_trigger": "tagged", + "x_clips_tag": "x", + "x_clips_dedupe_room_day": True, + "x_clips_max_concurrent": 1, + "x_clips_auto_post": True, + "x_clips_live_sample": True, + "x_clips_live_sample_interval_sec": 180, + "x_clips_live_sample_batch": 1, + "x_clips_sample_any_live": True, + "x_clips_upload_spread": True, + "x_clips_upload_min_gap_sec": 600, + "x_clips_delete_clip_after_post": True, + "x_clips_daily_max": 20, + "x_clips_caption_template": "{anchor}", "tiktok_auto_retry_failed": False, "tiktok_auto_retry_max_attempts": 3, "tiktok_auto_retry_interval_sec": 300, diff --git a/backend/app/main.py b/backend/app/main.py index 64300c9..afcf115 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -72,6 +72,7 @@ from .session_auth import ( from .youtube_monitor import yt_monitor from .shorts_pipeline import shorts_pipeline from .tiktok_pipeline import tiktok_pipeline +from .x_clips_pipeline import x_clips_pipeline from . import tiktok_session from .timeutil import stamp_beijing @@ -135,9 +136,17 @@ async def lifespan(_: FastAPI): await tiktok_pipeline.start() except Exception: pass + try: + await x_clips_pipeline.start() + except Exception: + pass asyncio.create_task(_start_workers()) yield + try: + await x_clips_pipeline.stop() + except Exception: + pass try: await tiktok_pipeline.stop() except Exception: @@ -956,6 +965,206 @@ async def x2_media_cleanup(body: dict[str, Any] | None = None) -> dict[str, Any] return x2_media.cleanup_media_keys([str(k) for k in keys]) +# ---------- X live clips (isolated auto text+video from Douyin live) ---------- + + +@app.get("/api/x-clips/status") +async def x_clips_status() -> dict[str, Any]: + return await asyncio.to_thread(x_clips_pipeline.status) + + +@app.post("/api/x-clips/start") +async def x_clips_start() -> dict[str, Any]: + db.update_settings_map({"x_clips_enabled": True}) + try: + await x_clips_pipeline.start() + except Exception: + pass + return x_clips_pipeline.status() + + +@app.post("/api/x-clips/stop") +async def x_clips_stop() -> dict[str, Any]: + db.update_settings_map({"x_clips_enabled": False}) + return x_clips_pipeline.status() + + +@app.post("/api/x-clips/settings") +async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[str, Any]: + patch: dict[str, Any] = {} + raw = body or {} + if "x_clips_clip_sec" in raw: + try: + patch["x_clips_clip_sec"] = max(10, min(15, int(raw["x_clips_clip_sec"]))) + except Exception: + raise HTTPException(400, "clip_sec 无效") from None + if "x_clips_daily_max" in raw: + try: + patch["x_clips_daily_max"] = max(1, min(100, int(raw["x_clips_daily_max"]))) + except Exception: + raise HTTPException(400, "daily_max 无效") from None + if "x_clips_caption_template" in raw: + patch["x_clips_caption_template"] = str(raw.get("x_clips_caption_template") or "{anchor}")[:200] + if "x_clips_trigger" in raw: + t = str(raw.get("x_clips_trigger") or "tagged").strip().lower() + if t not in {"tagged", "all", "favorite"}: + raise HTTPException(400, "trigger 无效") + patch["x_clips_trigger"] = t + if "x_clips_tag" in raw: + patch["x_clips_tag"] = str(raw.get("x_clips_tag") or "x").strip()[:40] or "x" + for k in ( + "x_clips_live_sample", + "x_clips_sample_any_live", + "x_clips_auto_post", + "x_clips_upload_spread", + "x_clips_delete_clip_after_post", + "x_clips_dedupe_room_day", + ): + if k in raw: + patch[k] = bool(raw[k]) + if "x_clips_live_sample_interval_sec" in raw: + try: + patch["x_clips_live_sample_interval_sec"] = max( + 60, min(3600, int(raw["x_clips_live_sample_interval_sec"])) + ) + except Exception: + raise HTTPException(400, "sample_interval 无效") from None + if "x_clips_live_sample_batch" in raw: + try: + patch["x_clips_live_sample_batch"] = max(1, min(5, int(raw["x_clips_live_sample_batch"]))) + except Exception: + raise HTTPException(400, "sample_batch 无效") from None + if "x_clips_upload_min_gap_sec" in raw: + try: + patch["x_clips_upload_min_gap_sec"] = max(120, min(7200, int(raw["x_clips_upload_min_gap_sec"]))) + except Exception: + raise HTTPException(400, "upload_min_gap 无效") from None + if patch: + db.update_settings_map(patch) + return x_clips_pipeline.status() + + +@app.post("/api/x-clips/sample-now") +async def x_clips_sample_now() -> dict[str, Any]: + from .x_clips_pipeline import sample_live_now + + result = await asyncio.to_thread(sample_live_now) + recording = await x_clips_pipeline.kick_pending_records(list(result.get("job_ids") or [])) + return { + "ok": True, + "enqueued": int(result.get("enqueued") or 0), + "live_count": int(result.get("live_count") or 0), + "skipped_dedupe": int(result.get("skipped_dedupe") or 0), + "recording": recording, + "reason": str(result.get("reason") or ""), + "status": x_clips_pipeline.status(), + } + + +@app.post("/api/x-clips/fill-quota") +async def x_clips_fill_quota() -> dict[str, Any]: + from . import x_clips_db + from .x_clips_pipeline import try_fill_daily_quota + + result = await asyncio.to_thread(try_fill_daily_quota) + pending = await _db(x_clips_db.list_pending_x_clip_jobs, limit=20) + recording = await x_clips_pipeline.kick_pending_records([str(j.get("id")) for j in pending]) + return { + "ok": True, + **result, + "recording": recording, + "status": x_clips_pipeline.status(), + } + + +@app.get("/api/x-clips/jobs") +async def x_clips_jobs_list( + status: str = "", + push_date: str = "", + session_id: str = "", + room_id: str = "", + limit: int = Query(50, ge=1, le=500), + offset: int = Query(0, ge=0), +) -> dict[str, Any]: + from . import x_clips_db + + return await _db( + x_clips_db.list_x_clip_jobs, + status=status, + push_date=push_date, + session_id=session_id, + room_id=room_id, + limit=limit, + offset=offset, + ) + + +@app.get("/api/x-clips/jobs/{job_id}") +async def x_clips_job_detail(job_id: str) -> dict[str, Any]: + from . import x_clips_db + + job = await _db(x_clips_db.get_x_clip_job, job_id) + if not job: + raise HTTPException(404, "任务不存在") + return {"job": job} + + +@app.post("/api/x-clips/jobs/{job_id}/post-now") +async def x_clips_job_post_now(job_id: str) -> dict[str, Any]: + from .x2_ws import hub + + try: + job = await x_clips_pipeline.post_job_now(job_id) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + try: + await hub.dispatch_queued() + except Exception: + pass + return {"ok": True, "job": job} + + +@app.post("/api/x-clips/jobs/{job_id}/retry") +async def x_clips_job_retry(job_id: str) -> dict[str, Any]: + from pathlib import Path + + from . import x_clips_db + from .x_clips_schedule import pick_upload_at + + job = await _db(x_clips_db.get_x_clip_job, job_id) + if not job: + raise HTTPException(404, "任务不存在") + st = str(job.get("status") or "") + if st not in {"failed", "skipped"}: + raise HTTPException(400, "仅失败/跳过任务可重试") + clip = str(job.get("clip_path") or "").strip() + if clip and Path(clip).is_file(): + cfg = db.get_settings_map() + upload_at = pick_upload_at(push_date=str(job.get("push_date") or ""), cfg=cfg) + updated = x_clips_db.update_x_clip_job( + job_id, + status="scheduled", + upload_at=upload_at, + error="", + finished_at=0, + x2_job_id="", + ) + else: + updated = x_clips_db.update_x_clip_job( + job_id, + status="pending", + error="", + finished_at=0, + started_at=0, + x2_job_id="", + media_key="", + media_url="", + ) + if updated: + await x_clips_pipeline.kick_pending_records([job_id]) + return {"ok": True, "job": updated or job} + + @app.post("/api/x2/jobs/{job_id}/cancel") async def x2_jobs_cancel(job_id: str) -> dict[str, Any]: from . import x2_db diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 9c6b434..bb8b68e 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -46,7 +46,7 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: return True if trigger == "favorite": return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts"} for t in tags) - if "tiktok_only" in tags: + if "tiktok_only" in tags or "x_only" in tags: return False tag = str(cfg.get("shorts_tag") or "shorts").strip() or "shorts" return tag in tags or "shorts" in tags or "both" in tags diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index c76202d..72fadb0 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -32,7 +32,7 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: return True if trigger == "favorite": return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts", "tiktok"} for t in tags) - if "shorts_only" in tags: + if "shorts_only" in tags or "x_only" in tags: return False tag = str(cfg.get("tiktok_tag") or "shorts").strip() or "shorts" return tag in tags or "tiktok" in tags or "shorts" in tags or "both" in tags diff --git a/backend/app/x2_db.py b/backend/app/x2_db.py index b604d76..8a31796 100644 --- a/backend/app/x2_db.py +++ b/backend/app/x2_db.py @@ -525,9 +525,28 @@ def _job_to_client(d: dict[str, Any]) -> dict[str, Any]: "createdAt": str(d.get("job_created_at") or ""), "updatedAt": str(d.get("job_updated_at") or ""), "received_at": d.get("received_at"), + # raw fields for internal sync + "result_json": d.get("result_json"), + "params_json": d.get("params_json"), } +def get_job(job_id: str) -> dict[str, Any] | None: + jid = str(job_id or "").strip() + if not jid: + return None + with _lock: + conn = _connect() + try: + ensure_x2_tables(conn) + row = conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone() + if not row: + return None + return _job_to_client(_row_to_dict(row) or {}) + finally: + conn.close() + + def create_web_job( kind: str, params: dict[str, Any] | None = None, diff --git a/backend/app/x2_media.py b/backend/app/x2_media.py index 679d57a..4362a15 100644 --- a/backend/app/x2_media.py +++ b/backend/app/x2_media.py @@ -119,3 +119,38 @@ def upload_media_bytes( tmp_path.unlink(missing_ok=True) except Exception: pass + + +def upload_media_file(path: Path | str, *, filename: str = "", content_type: str = "") -> dict[str, Any]: + """Stage an existing local file to S3 (does not delete the source clip).""" + if not s3_storage.s3_enabled(): + raise ValueError("S3 未启用") + p = Path(path) + if not p.is_file(): + raise ValueError("文件不存在") + size = p.stat().st_size + if size <= 0: + raise ValueError("空文件") + if size > _MAX_BYTES: + raise ValueError(f"文件过大(上限 {_MAX_BYTES // (1024 * 1024)} MB)") + + name = _safe_filename(filename or p.name) + ctype = (content_type or mimetypes.guess_type(name)[0] or "application/octet-stream").strip() + if not any(ctype.startswith(pref) for pref in _ALLOWED_MIME_PREFIXES): + raise ValueError(f"不支持的文件类型: {ctype}(仅图片/视频)") + + day = time.strftime("%Y%m%d", time.gmtime()) + key = f"{_ALLOWED_PREFIX}{day}/{uuid.uuid4().hex[:12]}_{name}" + url = s3_storage.upload_file(p, key, content_type=ctype) + if not url: + raise ValueError("上传 S3 失败") + return { + "ok": True, + "key": key, + "url": url, + "filename": name, + "mime": ctype, + "size": size, + "public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"), + "bucket": settings.s3_bucket, + } diff --git a/backend/app/x_clips_db.py b/backend/app/x_clips_db.py new file mode 100644 index 0000000..ab70f35 --- /dev/null +++ b/backend/app/x_clips_db.py @@ -0,0 +1,481 @@ +# -*- 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 + +# Quota-consuming statuses (posting pipeline has claimed a daily slot) +_QUOTA_STATUSES = ("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 '', + 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 + ) + """ + ) + 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 = "", +) -> 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: + 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, 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, + 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", + "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 = "", + 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()) + 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) + rows = conn.execute( + """ + SELECT * FROM x_clip_jobs + WHERE status = 'pending' + ORDER BY 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) + row = conn.execute( + """ + SELECT * FROM x_clip_jobs + WHERE status = 'scheduled' + AND clip_path != '' + AND IFNULL(x2_job_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 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) -> int: + cutoff = time.time() - max(120.0, float(max_age_sec)) + with _lock: + conn = _connect() + try: + ensure_x_clips_tables(conn) + 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, '') = '' + """, + (time.time(), cutoff), + ) + 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() diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py new file mode 100644 index 0000000..9cd4730 --- /dev/null +++ b/backend/app/x_clips_pipeline.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +"""Isolated X live-clip pipeline — sample → record → S3 → extension engage.post. + +Never touches Shorts / TikTok uploaders or Douyin monitor control flow. +Shares only side-effect-free tools: record_clip, resolve_stream_candidates, S3 helpers. +""" +from __future__ import annotations + +import asyncio +import random +import time +from pathlib import Path +from typing import Any, Optional + +from . import db +from . import x2_db +from . import x2_media +from . import x_clips_db +from .shorts_clip import record_clip, resolve_stream_candidates +from .timeutil import push_date_from_ts +from .x_clips_schedule import pick_upload_at, schedule_board + + +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("x_clips_trigger") or "tagged").strip().lower() + tags = _room_tags(room) + if "shorts_only" in tags or "tiktok_only" in tags: + return False + if trigger == "all": + return True + if trigger == "favorite": + return any(t in {"收藏", "重点", "priority", "vip", "高优", "x", "shorts"} for t in tags) + tag = str(cfg.get("x_clips_tag") or "x").strip() or "x" + return tag in tags or "x" in tags or "both" in tags or "x_only" in tags + + +def _clip_sec(cfg: dict[str, Any], room: dict[str, Any] | None = None) -> int: + try: + base = int(cfg.get("x_clips_clip_sec") or 12) + except Exception: + base = 12 + base = max(10, min(15, base)) + try: + override = db.room_clip_seconds(room, default=0, platform="x") if room else 0 + if override > 0: + return max(10, min(15, override)) + except Exception: + pass + return base + + +def build_caption(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> str: + settings = cfg or db.get_settings_map() + tpl = str(settings.get("x_clips_caption_template") or "{anchor}").strip() or "{anchor}" + anchor = str(job.get("anchor_name") or "").strip() or "Live" + room = str(job.get("room_id") or "").strip() + text = ( + tpl.replace("{anchor}", anchor) + .replace("{room}", room) + .replace("{title}", anchor) + ).strip() + # X hard limit ~280; leave headroom for media + return text[:270] + + +def _enqueue_job( + *, + session: dict[str, Any] | None, + room: dict[str, Any], + stream_url: str = "", + cfg: dict[str, Any] | None = None, + push_date: str = "", +) -> Optional[dict[str, Any]]: + try: + settings = cfg or db.get_settings_map() + if not settings.get("x_clips_enabled"): + return None + if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0: + return None + room_id = str(room.get("room_id") or (session or {}).get("room_id") or "") + if room_id.startswith("yt:"): + return None + day = str(push_date or "").strip() or push_date_from_ts(time.time()) + if settings.get("x_clips_dedupe_room_day", True) and room_id: + if x_clips_db.has_x_clip_job_for_room_day(room_id, day): + return None + sid = str((session or {}).get("id") or room.get("active_session_id") or "") + job = x_clips_db.create_x_clip_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 ""), + push_date=day, + ) + if not job: + return None + try: + db.add_event( + kind="ops", + level="info", + message=f"X 切片任务已入队:{job.get('anchor_name') or room_id}", + room_id=room_id, + room_pk=str(room.get("id") or ""), + session_id=sid, + anchor_name=str(job.get("anchor_name") or ""), + meta={"x_clip_job_id": job.get("id")}, + ) + except Exception: + pass + return job + except Exception: + return None + + +def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: + """Pick live Douyin rooms and enqueue X clip jobs. Never raises.""" + try: + settings = cfg or db.get_settings_map() + if not settings.get("x_clips_enabled"): + return 0 + if not settings.get("x_clips_live_sample", True): + return 0 + if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0: + return 0 + batch = max(1, min(5, int(settings.get("x_clips_live_sample_batch") or 1))) + any_live = bool(settings.get("x_clips_sample_any_live", True)) + day = push_date_from_ts(time.time()) + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + candidates: list[dict[str, Any]] = [] + for room in rooms: + rid = str(room.get("room_id") or "") + if not rid: + continue + if settings.get("x_clips_dedupe_room_day", True) and x_clips_db.has_x_clip_job_for_room_day(rid, day): + continue + if any_live or _room_eligible(room, settings): + candidates.append(room) + if not candidates: + return 0 + random.shuffle(candidates) + enqueued = 0 + for room in candidates: + if enqueued >= batch: + break + if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0: + 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, push_date=day): + enqueued += 1 + return enqueued + except Exception: + return 0 + + +def sample_live_now() -> dict[str, Any]: + """Manual sample entry — returns summary for API.""" + settings = db.get_settings_map() + if not settings.get("x_clips_enabled"): + return {"enqueued": 0, "live_count": 0, "skipped_dedupe": 0, "job_ids": [], "reason": "x_clips_disabled"} + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + day = push_date_from_ts(time.time()) + skipped = 0 + for room in rooms: + rid = str(room.get("room_id") or "") + if rid and x_clips_db.has_x_clip_job_for_room_day(rid, day): + skipped += 1 + n = try_sample_live_rooms(settings) + jobs = x_clips_db.list_pending_x_clip_jobs(limit=20) + return { + "enqueued": n, + "live_count": len(rooms), + "skipped_dedupe": skipped, + "job_ids": [str(j.get("id")) for j in jobs], + "reason": "" if n else ("no_quota" if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0 else "no_candidates"), + } + + +def try_fill_daily_quota() -> dict[str, Any]: + settings = db.get_settings_map() + if not settings.get("x_clips_enabled"): + return {"enqueued": 0, "gap": 0, "reason": "disabled"} + gap = x_clips_db.x_clips_quota_gap(cfg=settings) + if gap <= 0: + return {"enqueued": 0, "gap": 0, "reason": "quota_full"} + # Temporarily bump batch to fill gap (capped) + patched = {**settings, "x_clips_live_sample_batch": min(gap, 5), "x_clips_live_sample": True} + total = 0 + rounds = 0 + while total < gap and rounds < 8: + rounds += 1 + n = try_sample_live_rooms(patched) + if n <= 0: + break + total += n + patched = {**patched, "x_clips_live_sample_batch": min(gap - total, 5)} + return {"enqueued": total, "gap": gap, "reason": ""} + + +class XClipsPipeline: + def __init__(self) -> None: + self._task: asyncio.Task | None = None + self._stop = asyncio.Event() + self._active_records = 0 + self._active_posts = 0 + self.processed = 0 + self.sampled = 0 + self.last_error = "" + self._last_sample_at = 0.0 + + def status(self) -> dict[str, Any]: + cfg = db.get_settings_map() + try: + board = schedule_board(limit=30) + except Exception: + board = {} + day = push_date_from_ts(time.time()) + return { + "running": bool(self._task and not self._task.done()), + "busy": self._active_records > 0 or self._active_posts > 0, + "enabled": bool(cfg.get("x_clips_enabled")), + "processed": self.processed, + "sampled": self.sampled, + "quota_gap": x_clips_db.x_clips_quota_gap(day, cfg), + "quota_used": x_clips_db.x_clips_quota_used(day), + "daily_max": x_clips_db.x_clips_daily_max(cfg), + "last_error": self.last_error, + "clip_sec": _clip_sec(cfg), + "douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)), + "board": board, + "stats": x_clips_db.x_clips_stats(day), + "settings": { + "x_clips_enabled": bool(cfg.get("x_clips_enabled")), + "x_clips_clip_sec": _clip_sec(cfg), + "x_clips_trigger": cfg.get("x_clips_trigger") or "tagged", + "x_clips_tag": cfg.get("x_clips_tag") or "x", + "x_clips_daily_max": x_clips_db.x_clips_daily_max(cfg), + "x_clips_caption_template": cfg.get("x_clips_caption_template") or "{anchor}", + "x_clips_live_sample": bool(cfg.get("x_clips_live_sample", True)), + "x_clips_live_sample_interval_sec": int(cfg.get("x_clips_live_sample_interval_sec") or 180), + "x_clips_live_sample_batch": int(cfg.get("x_clips_live_sample_batch") or 1), + "x_clips_sample_any_live": bool(cfg.get("x_clips_sample_any_live", True)), + "x_clips_auto_post": bool(cfg.get("x_clips_auto_post", True)), + "x_clips_upload_spread": bool(cfg.get("x_clips_upload_spread", True)), + "x_clips_upload_min_gap_sec": int(cfg.get("x_clips_upload_min_gap_sec") or 600), + "x_clips_delete_clip_after_post": bool(cfg.get("x_clips_delete_clip_after_post", True)), + }, + } + + 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="x-clips-pipeline") + + async def stop(self) -> None: + self._stop.set() + if self._task: + try: + await asyncio.wait_for(self._task, timeout=5) + except Exception: + self._task.cancel() + self._task = None + + async def kick_pending_records(self, job_ids: list[str]) -> int: + ids = [str(j) for j in job_ids if str(j).strip()] + if not ids: + return 0 + cfg = db.get_settings_map() + max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1)) + + async def _drain() -> None: + leftover = list(ids) + while leftover: + while self._active_records >= max_rec: + await asyncio.sleep(0.25) + jid = leftover.pop(0) + job = x_clips_db.claim_x_clip_job_record(jid) + if not job: + continue + self._active_records += 1 + asyncio.create_task(self._run_record(job)) + + asyncio.create_task(_drain()) + return min(len(ids), max_rec) + + async def post_job_now(self, job_id: str) -> dict[str, Any]: + job = x_clips_db.claim_x_clip_job_manual_post(job_id) + if not job: + raise ValueError("任务不可立即发帖(需要成片且未发布)") + try: + await self._do_post(job, manual=True) + except Exception as exc: + x_clips_db.update_x_clip_job( + job_id, + status="failed", + error=str(exc)[:500], + finished_at=time.time(), + ) + raise + fresh = x_clips_db.get_x_clip_job(job_id) + if not fresh: + raise ValueError("任务不存在") + if str(fresh.get("status") or "") not in {"posted", "posting"}: + 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("x_clips_enabled"): + await asyncio.sleep(5) + continue + interval = max(60.0, float(cfg.get("x_clips_live_sample_interval_sec") or 180)) + if cfg.get("x_clips_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 + try: + x_clips_db.reclaim_stale_x_clip_recordings(max_age_sec=240) + except Exception: + pass + try: + x_clips_db.reclaim_stale_x_clip_posts(max_age_sec=900) + except Exception: + pass + + # Sync extension job outcomes + try: + await asyncio.to_thread(self._sync_posting_jobs) + except Exception as exc: + self.last_error = str(exc)[:240] + + max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1)) + while self._active_records < max_rec: + pending = x_clips_db.list_pending_x_clip_jobs(limit=1) + if not pending: + break + job = x_clips_db.claim_x_clip_job_record(str(pending[0].get("id") or "")) + if not job: + break + self._active_records += 1 + asyncio.create_task(self._run_record(job)) + + if cfg.get("x_clips_auto_post", True): + max_post = max(1, int(cfg.get("x_clips_max_concurrent") or 1)) + while self._active_posts < max_post: + job = x_clips_db.claim_due_x_clip_post() + if not job: + break + self._active_posts += 1 + asyncio.create_task(self._run_post(job)) + except Exception as exc: + self.last_error = str(exc)[:240] + await asyncio.sleep(2.5) + + 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] + x_clips_db.update_x_clip_job( + str(job.get("id") or ""), + status="failed", + error=str(exc)[:500], + finished_at=time.time(), + ) + finally: + self._active_records = max(0, self._active_records - 1) + + async def _do_record(self, job: dict[str, Any]) -> None: + cfg = db.get_settings_map() + jid = str(job.get("id") or "") + cookie = str(cfg.get("dy_cookie") or "") + source = str(job.get("source_url") or "") + candidates = await resolve_stream_candidates( + source_url=source, + stream_url=str(job.get("stream_url") or ""), + cookie=cookie, + prefer_fresh=True, + max_candidates=8, + ) + if not candidates: + err = str(job.get("error") or "") + if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900: + x_clips_db.update_x_clip_job( + jid, + status="pending", + error="stream_retry:1", + stream_url="", + started_at=0, + ) + return + x_clips_db.update_x_clip_job( + jid, + status="failed", + error="无法获取直播流(可能已停播)", + finished_at=time.time(), + ) + return + + room_pk = str(job.get("room_pk") or "") + room = db.get_room(room_pk) if room_pk else None + sec = _clip_sec(cfg, room) + outcome = await record_clip( + job_id=f"xclip_{jid[:8]}", + stream_urls=candidates, + seconds=sec, + ) + stream = str(outcome.get("stream_url") or (candidates[0] if candidates else "")) + if not outcome.get("ok"): + err = str(outcome.get("error") or "录制失败") + x_clips_db.update_x_clip_job( + jid, + status="failed", + error=err[:500], + stream_url=stream, + finished_at=time.time(), + ) + return + + clip_path = str(outcome.get("path") or "") + try: + from .clip_quality import assert_clip_quality + + assert_clip_quality(clip_path) + except ValueError as qerr: + x_clips_db.update_x_clip_job( + jid, + status="failed", + clip_path=clip_path, + clip_seconds=float(outcome.get("seconds") or sec), + stream_url=stream, + error=str(qerr)[:500], + finished_at=time.time(), + ) + return + except Exception: + pass + + caption = build_caption({**job, "id": jid}, cfg) + day = str(job.get("push_date") or "") or push_date_from_ts(time.time()) + upload_at = pick_upload_at(push_date=day, cfg=cfg) + x_clips_db.update_x_clip_job( + jid, + status="scheduled", + clip_path=clip_path, + clip_seconds=float(outcome.get("seconds") or sec), + stream_url=stream, + caption=caption, + upload_at=upload_at, + error="", + ) + self.processed += 1 + + async def _run_post(self, job: dict[str, Any]) -> None: + try: + await self._do_post(job, manual=False) + except Exception as exc: + self.last_error = str(exc)[:240] + x_clips_db.update_x_clip_job( + str(job.get("id") or ""), + status="failed", + error=str(exc)[:500], + finished_at=time.time(), + ) + finally: + self._active_posts = max(0, self._active_posts - 1) + + async def _do_post(self, job: dict[str, Any], *, manual: bool = False) -> None: + jid = str(job.get("id") or "") + cfg = db.get_settings_map() + caption = str(job.get("caption") or "").strip() or build_caption(job, cfg) + media_url = str(job.get("media_url") or "").strip() + media_key = str(job.get("media_key") or "").strip() + clip = str(job.get("clip_path") or "").strip() + + # Stage to S3 if needed + if not media_url or not media_key: + if not clip or not Path(clip).is_file(): + raise ValueError("成片文件不存在") + staged = await asyncio.to_thread(x2_media.upload_media_file, Path(clip), filename=Path(clip).name) + media_url = str(staged.get("url") or "") + media_key = str(staged.get("key") or "") + if not media_url or not media_key: + raise ValueError("S3 暂存失败") + x_clips_db.update_x_clip_job(jid, media_url=media_url, media_key=media_key, caption=caption) + + # Already dispatched? + existing_x2 = str(job.get("x2_job_id") or "").strip() + if existing_x2 and not manual: + return + + media_item = { + "url": media_url, + "key": media_key, + "mime": "video/mp4", + "name": Path(clip).name if clip else "clip.mp4", + "size": Path(clip).stat().st_size if clip and Path(clip).is_file() else 0, + } + x2_job = await asyncio.to_thread( + x2_db.create_web_job, + "engage.post", + {"text": caption, "mediaUrls": [media_item], "xClipJobId": jid}, + ) + x2_id = str(x2_job.get("id") or "") + if not x2_id: + raise ValueError("创建插件发帖任务失败") + x_clips_db.update_x_clip_job( + jid, + status="posting", + caption=caption, + media_url=media_url, + media_key=media_key, + x2_job_id=x2_id, + error="", + ) + # Best-effort push to connected extension (poll fallback remains) + try: + from .x2_ws import hub + + asyncio.create_task(hub.dispatch_queued()) + except Exception: + pass + + def _sync_posting_jobs(self) -> None: + cfg = db.get_settings_map() + for job in x_clips_db.list_posting_x_clip_jobs(limit=40): + jid = str(job.get("id") or "") + x2_id = str(job.get("x2_job_id") or "").strip() + if not jid or not x2_id: + continue + row = x2_db.get_job(x2_id) + if not row: + continue + st = str(row.get("status") or "") + if st == "completed": + tweet_id = "" + result = row.get("result") if isinstance(row.get("result"), dict) else {} + if not result: + try: + import json + + result = json.loads(str(row.get("result_json") or "{}")) + except Exception: + result = {} + if isinstance(result, dict): + tweet_id = str( + result.get("tweetId") + or result.get("tweet_id") + or result.get("id") + or "" + ).strip() + x_clips_db.update_x_clip_job( + jid, + status="posted", + tweet_id=tweet_id, + error="", + finished_at=time.time(), + ) + if cfg.get("x_clips_delete_clip_after_post", True): + self._delete_clip(str(job.get("clip_path") or "")) + elif st in {"failed", "cancelled"}: + err = str(row.get("error") or st)[:500] + x_clips_db.update_x_clip_job( + jid, + status="failed", + error=err, + finished_at=time.time(), + ) + + @staticmethod + def _delete_clip(path: str) -> None: + try: + Path(path).unlink(missing_ok=True) + except Exception: + pass + + +x_clips_pipeline = XClipsPipeline() diff --git a/backend/app/x_clips_schedule.py b/backend/app/x_clips_schedule.py new file mode 100644 index 0000000..59a6755 --- /dev/null +++ b/backend/app/x_clips_schedule.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""X clip post scheduling — staggered within Beijing day (isolated).""" +from __future__ import annotations + +import random +import time +from pathlib import Path +from typing import Any + +from . import db +from . import x_clips_db +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[float]: + data = x_clips_db.list_x_clip_jobs(push_date=push_date, limit=500, offset=0) + slots: list[float] = [] + for j in data.get("jobs") or []: + st = str(j.get("status") or "") + if st in {"scheduled", "recorded", "posting"}: + ts = float(j.get("upload_at") or 0) or float(j.get("updated_at") or 0) + if ts > 0: + slots.append(ts) + elif st == "posted": + ts = float(j.get("finished_at") or j.get("updated_at") or 0) + if ts > 0: + slots.append(ts) + return slots + + +def pick_upload_at(*, 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("x_clips_upload_spread", True): + return min(now + random.uniform(20, 90), latest) + global_min = max(180.0, float(settings.get("x_clips_upload_min_gap_sec") or 600)) + earliest = now + random.uniform(60, 900) + if earliest >= latest: + earliest = now + random.uniform(20, max(60.0, global_min * 0.35)) + slots = _occupied_slots(day) + + def conflicts(ts: float) -> bool: + for other_ts in slots: + if abs(ts - other_ts) < global_min * 0.9: + return True + return False + + window_end = max(earliest + 60, latest) + for _ in range(40): + cand = random.uniform(earliest, window_end) + if not conflicts(cand): + return float(min(cand, latest)) + last_ts = max(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 = x_clips_db.list_x_clip_jobs(push_date=day, limit=500, offset=0) + upcoming: list[dict[str, Any]] = [] + by_status: dict[str, int] = {} + for j in data.get("jobs") or []: + st = str(j.get("status") or "") + by_status[st] = by_status.get(st, 0) + 1 + clip = str(j.get("clip_path") or "").strip() + clip_ready = bool(clip) and Path(clip).is_file() + media_ready = bool(str(j.get("media_url") or "").strip()) + if st in {"scheduled", "recorded"} and (clip_ready or media_ready): + upcoming.append(j) + upcoming.sort(key=lambda x: float(x.get("upload_at") or x.get("updated_at") or 0)) + enriched = [] + for j in upcoming[: max(1, min(int(limit), 80))]: + 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"), + "status": j.get("status"), + "caption": j.get("caption") or "", + "clip_ready": bool(clip) and Path(clip).is_file(), + "clip_seconds": float(j.get("clip_seconds") or 0), + "can_post_now": str(j.get("status") or "") in {"scheduled", "recorded", "failed"} + and (bool(clip) or bool(str(j.get("media_url") or "").strip())), + } + ) + bj = beijing_from_ts(now) + return { + "push_date": day, + "now": now, + "day_start": day_start, + "day_end": day_end, + "beijing_hour": bj.hour if bj else None, + "by_status": by_status, + "used": x_clips_db.x_clips_quota_used(day), + "daily_max": x_clips_db.x_clips_daily_max(), + "upcoming": enriched, + } diff --git a/frontend/src/app/x/ClipsPanel.tsx b/frontend/src/app/x/ClipsPanel.tsx new file mode 100644 index 0000000..8e45346 --- /dev/null +++ b/frontend/src/app/x/ClipsPanel.tsx @@ -0,0 +1,338 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Film, RefreshCw, Zap } from "lucide-react"; + +import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; + +const panel = + "rounded-2xl border border-white/10 bg-gradient-to-b from-white/[0.07] to-black/30 p-4 shadow-[0_8px_32px_rgba(0,0,0,0.25)]"; +const title = "text-sm font-semibold text-white"; +const sub = "mt-0.5 text-[11px] text-slate-400"; +const field = + "mt-1 w-full rounded-xl border border-white/10 bg-black/45 px-3 py-2 text-sm text-slate-100 outline-none focus:border-orange-400/50"; +const label = "block text-[11px] text-slate-400"; +const btn = + "inline-flex items-center justify-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold transition hover:-translate-y-0.5"; +const primary = `${btn} bg-gradient-to-br from-orange-400 to-rose-500 text-[#1a1210] shadow-lg shadow-orange-500/20`; +const ghost = `${btn} border border-white/10 bg-white/5 text-slate-200 hover:bg-white/10`; + +type XClipJob = { + id: string; + status?: string; + anchor_name?: string; + room_id?: string; + caption?: string; + clip_seconds?: number; + upload_at?: number; + finished_at?: number; + error?: string; + x2_job_id?: string; + tweet_id?: string; + push_date?: string; + created_at?: number; +}; + +type Status = { + enabled?: boolean; + running?: boolean; + busy?: boolean; + quota_used?: number; + quota_gap?: number; + daily_max?: number; + clip_sec?: number; + douyin_live_count?: number; + last_error?: string; + settings?: Record; + board?: { upcoming?: Array>; by_status?: Record }; + stats?: { by_status?: Record }; +}; + +const STATUS_ZH: Record = { + pending: "待录制", + recording: "录制中", + recorded: "已成片", + scheduled: "已排程", + posting: "发帖中", + posted: "已发布", + failed: "失败", + skipped: "已跳过", +}; + +export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err") => void }) { + const [st, setSt] = useState(null); + const [jobs, setJobs] = useState([]); + const [busy, setBusy] = useState(false); + const [clipSec, setClipSec] = useState(12); + const [dailyMax, setDailyMax] = useState(20); + const [captionTpl, setCaptionTpl] = useState("{anchor}"); + const [trigger, setTrigger] = useState("tagged"); + const [sampleAny, setSampleAny] = useState(true); + const [autoPost, setAutoPost] = useState(true); + + const load = useCallback(async () => { + try { + const iso = todayBeijingISO(); + const [status, jobData] = await Promise.all([ + fetchJson("/api/x-clips/status"), + fetchJson(`/api/x-clips/jobs?push_date=${iso}&limit=40`), + ]); + setSt(status || null); + const s = status?.settings || {}; + setClipSec(Number(s.x_clips_clip_sec || status?.clip_sec || 12)); + setDailyMax(Number(s.x_clips_daily_max || status?.daily_max || 20)); + setCaptionTpl(String(s.x_clips_caption_template || "{anchor}")); + setTrigger(String(s.x_clips_trigger || "tagged")); + setSampleAny(Boolean(s.x_clips_sample_any_live ?? true)); + setAutoPost(Boolean(s.x_clips_auto_post ?? true)); + setJobs(jobData?.jobs || []); + } catch (e) { + toast((e as Error).message || "加载失败", "err"); + } + }, [toast]); + + useEffect(() => { + void load(); + const t = setInterval(() => void load(), 8000); + return () => clearInterval(t); + }, [load]); + + const run = async (fn: () => Promise, okMsg: string) => { + setBusy(true); + try { + await fn(); + toast(okMsg, "ok"); + await load(); + } catch (e) { + toast((e as Error).message || "操作失败", "err"); + } finally { + setBusy(false); + } + }; + + const enabled = Boolean(st?.enabled); + + return ( +
+
+
+
+

+ + 直播切片发帖 +

+

+ 独立流水线:抖音在播取样 → 录 10–15 秒 → S3 → 插件文字+视频发帖。与 Shorts / TikTok 完全隔离。 +

+
+
+ + +
+
+
+ {[ + ["今日配额", `${st?.quota_used ?? 0}/${st?.daily_max ?? 20}`], + ["剩余", String(st?.quota_gap ?? "—")], + ["在播", String(st?.douyin_live_count ?? "—")], + ["切片秒数", `${st?.clip_sec ?? clipSec}s`], + ].map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+ {st?.last_error ? ( +
+ {st.last_error} +
+ ) : null} +
+ +
+
+

参数

+
+ + + + + + +
+ +
+ +
+

操作

+

插件需保持连接;发帖走 engage.post + S3 视频。

+
+ + +
+
+
房间标签:`x` / `both` / `x_only`(`shorts_only`/`tiktok_only` 不取样)
+
状态:{enabled ? (st?.running ? "流水线运行中" : "已启用(等待 worker)") : "未启用"}
+
+
+
+ +
+
+

今日任务

+ {jobs.length} 条 +
+ {jobs.length === 0 ? ( +
暂无切片任务
+ ) : ( +
+ {jobs.map((j) => ( +
+
+
+ {j.anchor_name || j.room_id || j.id.slice(0, 8)} +
+
+ {STATUS_ZH[j.status || ""] || j.status} + {j.clip_seconds ? ` · ${Math.round(j.clip_seconds)}s` : ""} + {j.upload_at ? ` · 排程 ${fmtTs(j.upload_at)}` : ""} + {j.error ? ` · ${j.error}` : ""} +
+ {j.caption ?
{j.caption}
: null} +
+
+ {["scheduled", "recorded", "failed"].includes(j.status || "") ? ( + + ) : null} + {["failed", "skipped"].includes(j.status || "") ? ( + + ) : null} +
+
+ ))} +
+ )} +
+
+ ); +} diff --git a/frontend/src/app/x/XOpsPanels.tsx b/frontend/src/app/x/XOpsPanels.tsx index 694f6f7..e8d2c99 100644 --- a/frontend/src/app/x/XOpsPanels.tsx +++ b/frontend/src/app/x/XOpsPanels.tsx @@ -146,6 +146,7 @@ export function WorkbenchPanel({
{( [ + ["clips", "🎬", "切片发帖", "直播切片文字+视频"], ["cleanup", "🧹", "扫描不互关", "找出没回关的人"], ["scrape", "📥", "采集数据", "画像 / 搜索 / 书签"], ["engage", "⚡", "互动增长", "赞 · 关 · 回 · 转推"], diff --git a/frontend/src/app/x/page.tsx b/frontend/src/app/x/page.tsx index 32fd3a8..799d833 100644 --- a/frontend/src/app/x/page.tsx +++ b/frontend/src/app/x/page.tsx @@ -25,8 +25,9 @@ import { ScrapePanel, WorkbenchPanel, } from "./XOpsPanels"; +import { ClipsPanel } from "./ClipsPanel"; -type TabId = "workbench" | "cleanup" | "scrape" | "engage" | "monitor" | "jobs"; +type TabId = "workbench" | "clips" | "cleanup" | "scrape" | "engage" | "monitor" | "jobs"; type X2Agent = { id: string; @@ -46,6 +47,7 @@ type X2Account = { const NAV: { id: TabId; emoji: string; label: string }[] = [ { id: "workbench", emoji: "🏠", label: "工作台" }, + { id: "clips", emoji: "🎬", label: "切片发帖" }, { id: "cleanup", emoji: "🧹", label: "清理" }, { id: "scrape", emoji: "📥", label: "采集" }, { id: "engage", emoji: "⚡", label: "互动" }, @@ -348,6 +350,7 @@ export default function XPage() { }} /> ) : null} + {tab === "clips" ? toast.push(m, k)} /> : null} {tab === "cleanup" ? (