douyinWEB/backend/app/x2_db.py
eric b0706b351b feat(test1): X 按账号隔离展示任务与切片数据
切换顶部账号后,任务流/结果/统计与切片列表按该账号过滤;新建任务写入 account。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 08:29:17 -05:00

721 lines
26 KiB
Python

# -*- coding: utf-8 -*-
"""X2 (Twitter/X ops) ingest store — isolated from Douyin/Shorts/TikTok."""
from __future__ import annotations
import json
import secrets
import time
import uuid
from typing import Any, Optional
from .db import _connect, _lock, _row_to_dict
def ensure_x2_tables(conn) -> None:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS x2_agents (
id TEXT PRIMARY KEY,
label TEXT NOT NULL DEFAULT '',
last_seen_at REAL NOT NULL DEFAULT 0,
extension_connected INTEGER NOT NULL DEFAULT 0,
meta_json TEXT NOT NULL DEFAULT '{}',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS x2_accounts (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
display_name TEXT NOT NULL DEFAULT '',
avatar_url TEXT NOT NULL DEFAULT '',
bound_at TEXT NOT NULL DEFAULT '',
last_seen_at TEXT NOT NULL DEFAULT '',
raw_json TEXT NOT NULL DEFAULT '{}',
updated_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_x2_accounts_agent ON x2_accounts(agent_id, username);
CREATE TABLE IF NOT EXISTS x2_jobs (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL DEFAULT '',
kind TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT '',
account_id TEXT NOT NULL DEFAULT '',
account_username TEXT NOT NULL DEFAULT '',
progress_current INTEGER NOT NULL DEFAULT 0,
progress_total INTEGER NOT NULL DEFAULT 0,
progress_message TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
result_json TEXT NOT NULL DEFAULT '{}',
params_json TEXT NOT NULL DEFAULT '{}',
job_created_at TEXT NOT NULL DEFAULT '',
job_updated_at TEXT NOT NULL DEFAULT '',
received_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_x2_jobs_received ON x2_jobs(received_at DESC);
CREATE INDEX IF NOT EXISTS idx_x2_jobs_agent ON x2_jobs(agent_id, received_at DESC);
CREATE TABLE IF NOT EXISTS x2_events (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL DEFAULT '',
event TEXT NOT NULL DEFAULT '',
message TEXT NOT NULL DEFAULT '',
payload_json TEXT NOT NULL DEFAULT '{}',
created_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_x2_events_created ON x2_events(created_at DESC);
"""
)
def ensure_ingest_token() -> str:
from . import db
cfg = db.get_settings_map()
token = str(cfg.get("x2_ingest_token") or "").strip()
if token:
return token
token = secrets.token_urlsafe(24)
db.update_settings_map({"x2_ingest_token": token})
return token
def verify_ingest_token(provided: str) -> bool:
expected = ensure_ingest_token()
got = str(provided or "").strip()
if not got or not expected:
return False
return secrets.compare_digest(got, expected)
def _json_dumps(obj: Any) -> str:
try:
return json.dumps(obj if obj is not None else {}, ensure_ascii=False, default=str)
except Exception:
return "{}"
def upsert_agent(
agent_id: str,
*,
label: str = "",
extension_connected: bool | None = None,
meta: dict[str, Any] | None = None,
) -> dict[str, Any]:
aid = str(agent_id or "").strip() or "default"
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
row = conn.execute("SELECT * FROM x2_agents WHERE id = ?", (aid,)).fetchone()
if row:
sets = ["last_seen_at = ?", "updated_at = ?"]
params: list[Any] = [now, now]
if label:
sets.append("label = ?")
params.append(label)
if extension_connected is not None:
sets.append("extension_connected = ?")
params.append(1 if extension_connected else 0)
if meta is not None:
sets.append("meta_json = ?")
params.append(_json_dumps(meta))
params.append(aid)
conn.execute(f"UPDATE x2_agents SET {', '.join(sets)} WHERE id = ?", params)
else:
conn.execute(
"""
INSERT INTO x2_agents(id, label, last_seen_at, extension_connected, meta_json, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
aid,
label or aid,
now,
1 if extension_connected else 0,
_json_dumps(meta or {}),
now,
now,
),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM x2_agents WHERE id = ?", (aid,)).fetchone()) # type: ignore
finally:
conn.close()
def sync_accounts(agent_id: str, accounts: list[dict[str, Any]]) -> int:
aid = str(agent_id or "").strip() or "default"
now = time.time()
n = 0
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
for acc in accounts or []:
if not isinstance(acc, dict):
continue
username = str(acc.get("username") or "").strip().lstrip("@")
if not username:
continue
pk = str(acc.get("id") or "").strip() or f"{aid}:{username}"
conn.execute(
"""
INSERT INTO x2_accounts(id, agent_id, username, display_name, avatar_url, bound_at, last_seen_at, raw_json, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
agent_id=excluded.agent_id,
username=excluded.username,
display_name=excluded.display_name,
avatar_url=excluded.avatar_url,
bound_at=excluded.bound_at,
last_seen_at=excluded.last_seen_at,
raw_json=excluded.raw_json,
updated_at=excluded.updated_at
""",
(
pk,
aid,
username,
str(acc.get("displayName") or acc.get("display_name") or ""),
str(acc.get("avatarUrl") or acc.get("avatar_url") or ""),
str(acc.get("boundAt") or acc.get("bound_at") or ""),
str(acc.get("lastSeenAt") or acc.get("last_seen_at") or ""),
_json_dumps(acc),
now,
),
)
n += 1
conn.commit()
finally:
conn.close()
return n
def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
if not isinstance(job, dict):
return None
jid = str(job.get("id") or "").strip()
if not jid:
return None
aid = str(agent_id or "").strip() or "default"
progress = job.get("progress") if isinstance(job.get("progress"), dict) else {}
result = job.get("result")
account_username = ""
if isinstance(result, dict):
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, account_username, account_id FROM x2_jobs WHERE id = ?",
(jid,),
).fetchone()
params_to_store = incoming_params
if not params_to_store and existing:
try:
params_to_store = json.loads(str(existing["params_json"] or "{}"))
except Exception:
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(
id, agent_id, kind, status, account_id, account_username,
progress_current, progress_total, progress_message, error,
result_json, params_json, job_created_at, job_updated_at, received_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
agent_id=excluded.agent_id,
kind=excluded.kind,
status=excluded.status,
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,
error=excluded.error,
result_json=excluded.result_json,
params_json=excluded.params_json,
job_created_at=excluded.job_created_at,
job_updated_at=excluded.job_updated_at,
received_at=excluded.received_at
""",
(
jid,
aid,
str(job.get("kind") or ""),
str(job.get("status") or ""),
account_id,
account_username,
int(progress.get("current") or 0),
int(progress.get("total") or 0),
str(progress.get("message") or ""),
str(job.get("error") or "")[:800],
_json_dumps(result if result is not None else {}),
_json_dumps(params_to_store),
str(job.get("createdAt") or job.get("created_at") or ""),
str(job.get("updatedAt") or job.get("updated_at") or ""),
now,
),
)
# keep last 500 jobs
conn.execute(
"""
DELETE FROM x2_jobs WHERE id IN (
SELECT id FROM x2_jobs ORDER BY received_at DESC LIMIT -1 OFFSET 500
)
"""
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
def add_event(agent_id: str, event: str, message: str = "", payload: Any = None) -> None:
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
conn.execute(
"""
INSERT INTO x2_events(id, agent_id, event, message, payload_json, created_at)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
str(uuid.uuid4()),
str(agent_id or "").strip() or "default",
str(event or "")[:80],
str(message or "")[:400],
_json_dumps(payload or {}),
now,
),
)
conn.execute(
"""
DELETE FROM x2_events WHERE id IN (
SELECT id FROM x2_events ORDER BY created_at DESC LIMIT -1 OFFSET 300
)
"""
)
conn.commit()
finally:
conn.close()
def ingest_payload(body: dict[str, Any]) -> dict[str, Any]:
agent_id = str(body.get("agent_id") or body.get("agentId") or "default").strip() or "default"
label = str(body.get("label") or body.get("agent_label") or "").strip()
event = str(body.get("event") or "heartbeat").strip() or "heartbeat"
ext = body.get("extension_connected")
if ext is None:
ext = body.get("extensionConnected")
meta = body.get("meta") if isinstance(body.get("meta"), dict) else {}
if body.get("source"):
meta = {**meta, "source": body.get("source")}
agent = upsert_agent(
agent_id,
label=label,
extension_connected=bool(ext) if ext is not None else None,
meta=meta,
)
accounts = body.get("accounts")
accounts_n = 0
if isinstance(accounts, list):
accounts_n = sync_accounts(agent_id, accounts)
job_row = None
job = body.get("job")
if isinstance(job, dict):
job_row = upsert_job(agent_id, job)
st = str(job.get("status") or "")
if st in {"completed", "failed", "cancelled"}:
add_event(
agent_id,
event or "job.updated",
f"{job.get('kind') or 'job'} → {st}",
{"job_id": job.get("id"), "status": st, "error": job.get("error")},
)
# Only drop S3 staging after success/cancel. Keep media on failed so retry can re-fetch.
if st in {"completed", "cancelled"}:
try:
from . import x2_media
params = job.get("params") if isinstance(job.get("params"), dict) else {}
if not params and job_row:
raw = job_row.get("params") if isinstance(job_row.get("params"), dict) else None
if raw:
params = raw
else:
try:
params = json.loads(str(job_row.get("params_json") or "{}"))
except Exception:
params = {}
x2_media.cleanup_job_media(params)
except Exception:
pass
elif event not in {"heartbeat", "accounts.sync"}:
add_event(agent_id, event, str(body.get("message") or ""), body)
return {
"ok": True,
"agent_id": agent_id,
"event": event,
"accounts_synced": accounts_n,
"job_id": (job_row or {}).get("id") if job_row else "",
"agent_last_seen_at": float((agent or {}).get("last_seen_at") or 0),
}
def list_agents() -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
rows = conn.execute("SELECT * FROM x2_agents ORDER BY last_seen_at DESC").fetchall()
out = []
now = time.time()
for r in rows:
d = _row_to_dict(r) or {}
last = float(d.get("last_seen_at") or 0)
d["online"] = (now - last) < 120
d["extension_connected"] = bool(int(d.get("extension_connected") or 0))
try:
d["meta"] = json.loads(str(d.get("meta_json") or "{}"))
except Exception:
d["meta"] = {}
out.append(d)
return out
finally:
conn.close()
def list_accounts(*, limit: int = 50) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
rows = conn.execute(
"SELECT * FROM x2_accounts ORDER BY updated_at DESC LIMIT ?",
(max(1, min(int(limit), 200)),),
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()
def list_jobs(*, limit: int = 40, agent_id: str = "") -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
lim = max(1, min(int(limit), 200))
if agent_id:
rows = conn.execute(
"SELECT * FROM x2_jobs WHERE agent_id = ? ORDER BY received_at DESC LIMIT ?",
(agent_id, lim),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM x2_jobs ORDER BY received_at DESC LIMIT ?",
(lim,),
).fetchall()
out = []
for r in rows:
d = _row_to_dict(r) or {}
for key in ("result_json", "params_json"):
try:
d[key.replace("_json", "")] = json.loads(str(d.get(key) or "{}"))
except Exception:
d[key.replace("_json", "")] = {}
out.append(d)
return out
finally:
conn.close()
def list_events(*, limit: int = 30) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
rows = conn.execute(
"SELECT * FROM x2_events ORDER BY created_at DESC LIMIT ?",
(max(1, min(int(limit), 100)),),
).fetchall()
out = []
for r in rows:
d = _row_to_dict(r) or {}
try:
d["payload"] = json.loads(str(d.get("payload_json") or "{}"))
except Exception:
d["payload"] = {}
out.append(d)
return out
finally:
conn.close()
def status_snapshot() -> dict[str, Any]:
agents = list_agents()
online = [a for a in agents if a.get("online")]
jobs = list_jobs(limit=30)
accounts = list_accounts(limit=30)
events = list_events(limit=20)
running = sum(1 for j in jobs if str(j.get("status") or "") == "running")
failed = sum(1 for j in jobs if str(j.get("status") or "") == "failed")
completed = sum(1 for j in jobs if str(j.get("status") or "") == "completed")
queued = sum(1 for j in jobs if str(j.get("status") or "") == "queued")
token = ensure_ingest_token()
hint = (token[:4] + "…" + token[-4:]) if len(token) > 8 else ("***" if token else "")
ext_online = any(
a.get("online") and a.get("extension_connected") for a in agents
)
return {
"agents": agents,
"online_count": len(online),
"extension_online": ext_online,
"accounts": accounts,
"jobs": jobs,
"events": events,
"stats": {
"agents": len(agents),
"accounts": len(accounts),
"jobs_shown": len(jobs),
"running": running,
"queued": queued,
"failed": failed,
"completed": completed,
},
"ingest_token_hint": hint,
}
def _job_to_client(d: dict[str, Any]) -> dict[str, Any]:
"""Normalize DB row to extension/web job shape."""
params = d.get("params") if isinstance(d.get("params"), dict) else {}
if not params:
try:
params = json.loads(str(d.get("params_json") or "{}"))
except Exception:
params = {}
result = d.get("result") if isinstance(d.get("result"), dict) else {}
if not result:
try:
result = json.loads(str(d.get("result_json") or "{}"))
except Exception:
result = {}
return {
"id": str(d.get("id") or ""),
"kind": str(d.get("kind") or ""),
"status": str(d.get("status") or ""),
"params": params,
"result": result,
"error": str(d.get("error") or ""),
"progress": {
"current": int(d.get("progress_current") or 0),
"total": int(d.get("progress_total") or 0),
"message": str(d.get("progress_message") or ""),
},
"accountId": str(d.get("account_id") or ""),
"account_username": str(d.get("account_username") or ""),
"agent_id": str(d.get("agent_id") or ""),
"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,
*,
agent_id: str = "",
) -> dict[str, Any]:
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": 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, "account": account_username})
return _job_to_client(row or job)
def claim_next_job(agent_id: str) -> dict[str, Any] | None:
aid = str(agent_id or "").strip() or "dylive-helper"
now = time.time()
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
row = conn.execute(
"""
SELECT * FROM x2_jobs
WHERE status = 'queued'
ORDER BY received_at ASC
LIMIT 1
"""
).fetchone()
if not row:
return None
d = _row_to_dict(row) or {}
jid = str(d.get("id") or "")
conn.execute(
"""
UPDATE x2_jobs
SET status = 'running',
agent_id = ?,
progress_message = ?,
job_updated_at = ?,
received_at = ?
WHERE id = ? AND status = 'queued'
""",
(aid, "插件执行中", now_iso, now, jid),
)
if conn.total_changes == 0:
conn.commit()
return None
conn.commit()
refreshed = _row_to_dict(
conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
)
return _job_to_client(refreshed or d)
finally:
conn.close()
def cancel_job(job_id: str) -> dict[str, Any] | None:
jid = str(job_id or "").strip()
if not jid:
return None
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
out: dict[str, Any] | None = None
should_cleanup = False
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
d = _row_to_dict(row) or {}
st = str(d.get("status") or "")
if st in {"completed", "failed", "cancelled"}:
return _job_to_client(d)
conn.execute(
"""
UPDATE x2_jobs
SET status = 'cancelled',
error = ?,
progress_message = ?,
job_updated_at = ?
WHERE id = ?
""",
("用户取消", "已取消", now_iso, jid),
)
conn.commit()
refreshed = _row_to_dict(
conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
)
out = _job_to_client(refreshed or d)
should_cleanup = True
finally:
conn.close()
if should_cleanup and out:
try:
from . import x2_media
x2_media.cleanup_job_media(out.get("params"))
except Exception:
pass
return out
def list_cancel_requested(agent_id: str = "") -> list[str]:
"""Jobs cancelled while possibly still running on extension."""
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
# recent cancelled in last 10 min
cutoff = time.time() - 600
if agent_id:
rows = conn.execute(
"""
SELECT id FROM x2_jobs
WHERE status = 'cancelled' AND agent_id = ? AND received_at >= ?
ORDER BY received_at DESC LIMIT 20
""",
(agent_id, cutoff),
).fetchall()
else:
rows = conn.execute(
"""
SELECT id FROM x2_jobs
WHERE status = 'cancelled' AND received_at >= ?
ORDER BY received_at DESC LIMIT 20
""",
(cutoff,),
).fetchall()
return [str(r[0]) for r in rows]
finally:
conn.close()