From b0706b351bb701fc81a732e733ab892b8b9de756 Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 08:29:17 -0500 Subject: [PATCH] =?UTF-8?q?feat(test1):=20X=20=E6=8C=89=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E9=9A=94=E7=A6=BB=E5=B1=95=E7=A4=BA=E4=BB=BB=E5=8A=A1=E4=B8=8E?= =?UTF-8?q?=E5=88=87=E7=89=87=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 切换顶部账号后,任务流/结果/统计与切片列表按该账号过滤;新建任务写入 account。 Co-authored-by: Cursor --- backend/app/db.py | 1 + backend/app/main.py | 4 ++ backend/app/x2_db.py | 39 ++++++++++--- backend/app/x_clips_db.py | 17 +++++- backend/app/x_clips_pipeline.py | 16 +++++- frontend/src/app/x/ClipsPanel.tsx | 30 ++++++++-- frontend/src/app/x/page.tsx | 92 +++++++++++++++++++++++++------ frontend/src/lib/xOps.ts | 26 +++++++++ 8 files changed, 192 insertions(+), 33 deletions(-) diff --git a/backend/app/db.py b/backend/app/db.py index 5fb94f7..da9d00a 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -494,6 +494,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "x_clips_delete_clip_after_post": True, "x_clips_daily_max": 20, "x_clips_caption_template": "{anchor}", + "x_clips_account_username": "", "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 2fd677b..681b59f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1005,6 +1005,8 @@ async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[st 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 "").strip()[:200] or "{anchor}" + if "x_clips_account_username" in raw: + patch["x_clips_account_username"] = str(raw.get("x_clips_account_username") or "").strip().lstrip("@")[:80] if "x_clips_trigger" in raw: t = str(raw.get("x_clips_trigger") or "tagged").strip().lower() if t not in {"tagged", "all", "favorite"}: @@ -1083,6 +1085,7 @@ async def x_clips_jobs_list( push_date: str = "", session_id: str = "", room_id: str = "", + account_username: str = "", limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0), ) -> dict[str, Any]: @@ -1094,6 +1097,7 @@ async def x_clips_jobs_list( push_date=push_date, session_id=session_id, room_id=room_id, + account_username=account_username, limit=limit, offset=offset, ) diff --git a/backend/app/x2_db.py b/backend/app/x2_db.py index bd6165e..9298745 100644 --- a/backend/app/x2_db.py +++ b/backend/app/x2_db.py @@ -203,16 +203,24 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None: result = job.get("result") account_username = "" if isinstance(result, dict): - account_username = str(result.get("account") or "").strip() + account_username = str(result.get("account") or result.get("username") or "").strip().lstrip("@") incoming_params = job.get("params") if isinstance(job.get("params"), dict) else {} if not account_username: account_username = str(incoming_params.get("username") or "").strip().lstrip("@") + if not account_username: + account_username = str(job.get("account_username") or job.get("accountUsername") or "").strip().lstrip("@") + account_id = str(job.get("accountId") or job.get("account_id") or "").strip() + if not account_id and account_username: + account_id = f"x:{account_username}" now = time.time() with _lock: conn = _connect() try: ensure_x2_tables(conn) - existing = conn.execute("SELECT params_json FROM x2_jobs WHERE id = ?", (jid,)).fetchone() + existing = conn.execute( + "SELECT params_json, account_username, account_id FROM x2_jobs WHERE id = ?", + (jid,), + ).fetchone() params_to_store = incoming_params if not params_to_store and existing: try: @@ -221,6 +229,13 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None: params_to_store = {} if not isinstance(params_to_store, dict): params_to_store = {} + # Never wipe account attribution on partial updates from extension + if existing and not account_username: + account_username = str(existing["account_username"] or "").strip().lstrip("@") + if existing and not account_id: + account_id = str(existing["account_id"] or "").strip() + if not account_id and account_username: + account_id = f"x:{account_username}" conn.execute( """ INSERT INTO x2_jobs( @@ -232,8 +247,14 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None: agent_id=excluded.agent_id, kind=excluded.kind, status=excluded.status, - account_id=excluded.account_id, - account_username=excluded.account_username, + account_id=CASE + WHEN excluded.account_id != '' THEN excluded.account_id + ELSE x2_jobs.account_id + END, + account_username=CASE + WHEN excluded.account_username != '' THEN excluded.account_username + ELSE x2_jobs.account_username + END, progress_current=excluded.progress_current, progress_total=excluded.progress_total, progress_message=excluded.progress_message, @@ -249,7 +270,7 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None: aid, str(job.get("kind") or ""), str(job.get("status") or ""), - str(job.get("accountId") or job.get("account_id") or ""), + account_id, account_username, int(progress.get("current") or 0), int(progress.get("total") or 0), @@ -557,19 +578,23 @@ def create_web_job( k = str(kind or "").strip() if not k: raise ValueError("缺少 kind") + p = dict(params or {}) + account_username = str(p.get("username") or "").strip().lstrip("@") jid = f"web_{uuid.uuid4().hex[:16]}" now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) job = { "id": jid, "kind": k, "status": "queued", - "params": params or {}, + "params": p, + "account_username": account_username, + "accountId": f"x:{account_username}" if account_username else "", "progress": {"current": 0, "total": 1, "message": "排队等待插件领取"}, "createdAt": now_iso, "updatedAt": now_iso, } row = upsert_job(str(agent_id or "").strip() or "web", job) - add_event(str(agent_id or "web"), "job.queued", f"{k} 已入队", {"job_id": jid}) + add_event(str(agent_id or "web"), "job.queued", f"{k} 已入队", {"job_id": jid, "account": account_username}) return _job_to_client(row or job) diff --git a/backend/app/x_clips_db.py b/backend/app/x_clips_db.py index ab70f35..326c100 100644 --- a/backend/app/x_clips_db.py +++ b/backend/app/x_clips_db.py @@ -35,6 +35,7 @@ def ensure_x_clips_tables(conn: sqlite3.Connection) -> None: media_url TEXT NOT NULL DEFAULT '', x2_job_id TEXT NOT NULL DEFAULT '', tweet_id TEXT NOT NULL DEFAULT '', + account_username TEXT NOT NULL DEFAULT '', error TEXT NOT NULL DEFAULT '', push_date TEXT NOT NULL DEFAULT '', upload_at REAL NOT NULL DEFAULT 0, @@ -46,6 +47,9 @@ def ensure_x_clips_tables(conn: sqlite3.Connection) -> None: ) """ ) + cols = {r[1] for r in conn.execute("PRAGMA table_info(x_clip_jobs)").fetchall()} + if "account_username" not in cols: + conn.execute("ALTER TABLE x_clip_jobs ADD COLUMN account_username TEXT NOT NULL DEFAULT ''") conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_status ON x_clip_jobs(status, created_at)") conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_date ON x_clip_jobs(push_date, status)") conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_room_day ON x_clip_jobs(room_id, push_date, status)") @@ -118,11 +122,13 @@ def create_x_clip_job( anchor_name: str = "", stream_url: str = "", push_date: str = "", + account_username: str = "", ) -> dict[str, Any] | None: now = time.time() jid = str(uuid.uuid4()) day = push_date or push_date_from_ts(now) rid = str(room_id or "").strip() + acct = str(account_username or "").strip().lstrip("@") with _lock: conn = _connect() try: @@ -144,9 +150,9 @@ def create_x_clip_job( 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, + tweet_id, account_username, error, push_date, upload_at, attempts, created_at, updated_at, started_at, finished_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', '', '', '', ?, 0, 0, ?, ?, 0, 0) + ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', '', '', ?, '', ?, 0, 0, ?, ?, 0, 0) """, ( jid, @@ -156,6 +162,7 @@ def create_x_clip_job( source_url, anchor_name, stream_url, + acct, day, now, now, @@ -177,6 +184,7 @@ def update_x_clip_job(job_id: str, **fields: Any) -> dict[str, Any] | None: "media_url", "x2_job_id", "tweet_id", + "account_username", "error", "stream_url", "attempts", @@ -226,6 +234,7 @@ def list_x_clip_jobs( push_date: str = "", session_id: str = "", room_id: str = "", + account_username: str = "", limit: int = 100, offset: int = 0, ) -> dict[str, Any]: @@ -247,6 +256,10 @@ def list_x_clip_jobs( if room_id.strip(): clauses.append("room_id = ?") params.append(room_id.strip()) + acct = account_username.strip().lstrip("@") + if acct: + clauses.append("LOWER(account_username) = LOWER(?)") + params.append(acct) where = (" WHERE " + " AND ".join(clauses)) if clauses else "" total = int( conn.execute(f"SELECT COUNT(*) AS c FROM x_clip_jobs{where}", params).fetchone()["c"] or 0 diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py index c8979b3..297cdda 100644 --- a/backend/app/x_clips_pipeline.py +++ b/backend/app/x_clips_pipeline.py @@ -95,6 +95,7 @@ def _enqueue_job( 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 "") + acct = str(settings.get("x_clips_account_username") or "").strip().lstrip("@") job = x_clips_db.create_x_clip_job( session_id=sid, room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""), @@ -105,6 +106,7 @@ def _enqueue_job( ), stream_url=str(stream_url or ""), push_date=day, + account_username=acct, ) if not job: return None @@ -250,6 +252,7 @@ class XClipsPipeline: "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_account_username": str(cfg.get("x_clips_account_username") or "").strip().lstrip("@"), "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), @@ -490,6 +493,12 @@ class XClipsPipeline: caption = build_caption(job, cfg) if not caption: raise ValueError("文案模板结果为空") + acct = ( + str(job.get("account_username") or "").strip().lstrip("@") + or str(cfg.get("x_clips_account_username") or "").strip().lstrip("@") + ) + if acct and str(job.get("account_username") or "").strip().lstrip("@") != acct: + x_clips_db.update_x_clip_job(jid, account_username=acct) 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() @@ -520,7 +529,12 @@ class XClipsPipeline: x2_job = await asyncio.to_thread( x2_db.create_web_job, "engage.post", - {"text": caption, "mediaUrls": [media_item], "xClipJobId": jid}, + { + "text": caption, + "mediaUrls": [media_item], + "xClipJobId": jid, + **({"username": acct} if acct else {}), + }, ) x2_id = str(x2_job.get("id") or "") if not x2_id: diff --git a/frontend/src/app/x/ClipsPanel.tsx b/frontend/src/app/x/ClipsPanel.tsx index 1f8cb16..3be2a14 100644 --- a/frontend/src/app/x/ClipsPanel.tsx +++ b/frontend/src/app/x/ClipsPanel.tsx @@ -59,7 +59,13 @@ const STATUS_ZH: Record = { skipped: "已跳过", }; -export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err") => void }) { +export function ClipsPanel({ + toast, + accountUsername = "", +}: { + toast: (msg: string, kind?: "ok" | "err") => void; + accountUsername?: string; +}) { const [st, setSt] = useState(null); const [jobs, setJobs] = useState([]); const [busy, setBusy] = useState(false); @@ -73,9 +79,11 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err" const load = useCallback(async () => { try { const iso = todayBeijingISO(); + const acct = (accountUsername || "").trim().replace(/^@/, ""); + const q = acct ? `&account_username=${encodeURIComponent(acct)}` : ""; const [status, jobData] = await Promise.all([ fetchJson("/api/x-clips/status"), - fetchJson(`/api/x-clips/jobs?push_date=${iso}&limit=40`), + fetchJson(`/api/x-clips/jobs?push_date=${iso}&limit=40${q}`), ]); setSt(status || null); const s = status?.settings || {}; @@ -89,7 +97,16 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err" } catch (e) { toast((e as Error).message || "加载失败", "err"); } - }, [toast]); + }, [toast, accountUsername]); + + // Bind clip pipeline to the account selected in the X header + useEffect(() => { + const acct = (accountUsername || "").trim().replace(/^@/, ""); + void fetchJson("/api/x-clips/settings", { + method: "POST", + body: JSON.stringify({ x_clips_account_username: acct }), + }).catch(() => {}); + }, [accountUsername]); useEffect(() => { void load(); @@ -122,7 +139,10 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err" 直播切片发帖

- 独立流水线:抖音在播取样 → 录 10–15 秒 → S3 → 插件文字+视频发帖。与 Shorts / TikTok 完全隔离。 + 独立流水线:抖音在播取样 → 录 10–15 秒 → S3 → 插件文字+视频发帖。 + {accountUsername + ? ` 当前账号 @${accountUsername.replace(/^@/, "")}(任务/发帖按账号隔离)` + : " 请先在顶部选择账号,否则任务不按账号隔离"}

@@ -279,7 +299,7 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err"
-

今日任务

+

今日任务{accountUsername ? ` · @${accountUsername.replace(/^@/, "")}` : ""}

{jobs.length} 条
{jobs.length === 0 ? ( diff --git a/frontend/src/app/x/page.tsx b/frontend/src/app/x/page.tsx index 799d833..4bc1522 100644 --- a/frontend/src/app/x/page.tsx +++ b/frontend/src/app/x/page.tsx @@ -16,6 +16,7 @@ import { nonFollowersFromJob, STATUS_ZH, summarizeJob, + jobMatchesAccount, type XJob, } from "@/lib/xOps"; import { @@ -66,6 +67,24 @@ export default function XPage() { const [extOnline, setExtOnline] = useState(false); const [username, setUsername] = useState(""); + + // Persist selected account across reloads + useEffect(() => { + try { + const saved = window.localStorage.getItem("x2_selected_account") || ""; + if (saved) setUsername(saved); + } catch { + /* ignore */ + } + }, []); + useEffect(() => { + try { + if (username) window.localStorage.setItem("x2_selected_account", username); + else window.localStorage.removeItem("x2_selected_account"); + } catch { + /* ignore */ + } + }, [username]); const [limit, setLimit] = useState(80); const [minD, setMinD] = useState(2000); const [maxD, setMaxD] = useState(5000); @@ -90,8 +109,14 @@ export default function XPage() { setExtOnline(Boolean(st?.extension_online)); const accs: X2Account[] = st?.accounts || []; setUsername((cur) => { - if (cur) return cur; - return accs[0]?.username ? String(accs[0].username) : ""; + if (cur && accs.some((a) => String(a.username || "") === cur)) return cur; + try { + const saved = window.localStorage.getItem("x2_selected_account") || ""; + if (saved && accs.some((a) => String(a.username || "") === saved)) return saved; + } catch { + /* ignore */ + } + return accs[0]?.username ? String(accs[0].username) : cur || ""; }); } catch (e: unknown) { toast.push((e as Error)?.message || "加载失败", "err"); @@ -111,8 +136,13 @@ export default function XPage() { if (!extOnline) { toast.push("插件未在线:请加载扩展并打开本页完成自动配对", "err"); } + const handle = username.trim().replace(/^@/, ""); + if (!handle && accounts.length > 0) { + toast.push("请先在顶部选择要操作的账号", "err"); + return; + } const merged = { - ...(username.trim() ? { username: username.trim().replace(/^@/, "") } : {}), + ...(handle ? { username: handle } : {}), export: "none", ...params, }; @@ -134,7 +164,7 @@ export default function XPage() { toast.push((e as Error)?.message || "创建失败", "err"); } }, - [extOnline, toast, username], + [extOnline, toast, username, accounts.length], ); const cancelJob = async (id: string) => { @@ -149,32 +179,49 @@ export default function XPage() { } }; + const accountJobs = useMemo( + () => jobs.filter((j) => jobMatchesAccount(j, username)), + [jobs, username], + ); + const selected = useMemo( - () => jobs.find((j) => j.id === selectedId) || jobs[0] || null, - [jobs, selectedId], + () => accountJobs.find((j) => j.id === selectedId) || accountJobs[0] || null, + [accountJobs, selectedId], ); const filteredJobs = useMemo(() => { - return jobs.filter((j) => { + return accountJobs.filter((j) => { const s = j.status || ""; if (feedFilter === "active") return s === "running" || s === "queued"; if (feedFilter === "completed") return s === "completed"; if (feedFilter === "failed") return s === "failed" || s === "cancelled"; return true; }); - }, [jobs, feedFilter]); + }, [accountJobs, feedFilter]); + + const accountStats = useMemo(() => { + const out = { completed: 0, running: 0, queued: 0, failed: 0 }; + for (const j of accountJobs) { + const s = j.status || ""; + if (s === "completed") out.completed += 1; + else if (s === "running") out.running += 1; + else if (s === "queued") out.queued += 1; + else if (s === "failed" || s === "cancelled") out.failed += 1; + } + return out; + }, [accountJobs]); const lastNonFollowers = useMemo(() => { - for (const j of jobs) { + for (const j of accountJobs) { const list = nonFollowersFromJob(j); if (list.length) return list; } return [] as string[]; - }, [jobs]); + }, [accountJobs]); const recentResults = useMemo( () => - jobs + accountJobs .filter((j) => j.status === "completed" || j.status === "failed" || j.status === "cancelled") .slice(0, 5) .map((j) => ({ @@ -183,10 +230,10 @@ export default function XPage() { status: j.status, summary: summarizeJob(j), })), - [jobs], + [accountJobs], ); - const active = jobs.find((j) => j.status === "running" || j.status === "queued"); + const active = accountJobs.find((j) => j.status === "running" || j.status === "queued"); const pct = active ? Math.min( 100, @@ -252,9 +299,12 @@ export default function XPage() {