# -*- 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 "").strip() if not account_username: params = job.get("params") if isinstance(job.get("params"), dict) else {} account_username = str(params.get("username") or "").strip().lstrip("@") now = time.time() with _lock: conn = _connect() try: ensure_x2_tables(conn) 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=excluded.account_id, account_username=excluded.account_username, 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 ""), str(job.get("accountId") or job.get("account_id") or ""), 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(job.get("params") or {}), 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")}, ) 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") token = ensure_ingest_token() hint = (token[:4] + "…" + token[-4:]) if len(token) > 8 else ("***" if token else "") return { "agents": agents, "online_count": len(online), "accounts": accounts, "jobs": jobs, "events": events, "stats": { "agents": len(agents), "accounts": len(accounts), "jobs_shown": len(jobs), "running": running, "failed": failed, "completed": completed, }, "ingest_token_hint": hint, }