diff --git a/backend/app/auth.py b/backend/app/auth.py index c5ab13b..44499de 100644 --- a/backend/app/auth.py +++ b/backend/app/auth.py @@ -16,6 +16,7 @@ _PUBLIC_PATHS = { "/api/events/stream", "/api/x2/ingest", "/api/x2/extension/poll", + "/api/x2/extension/ws", } diff --git a/backend/app/main.py b/backend/app/main.py index 26034e9..fc27af4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio import csv import io +import json import os import sys import time @@ -17,7 +18,7 @@ if sys.platform == "win32": except Exception: pass -from fastapi import FastAPI, HTTPException, Query, Request +from fastapi import FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, StreamingResponse from fastapi.staticfiles import StaticFiles @@ -882,6 +883,7 @@ async def x2_accounts_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, An async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]: """Web console creates a job; Chrome extension claims & executes it.""" from . import x2_db + from .x2_ws import hub kind = str(body.get("kind") or "").strip() params = body.get("params") if isinstance(body.get("params"), dict) else {} @@ -889,22 +891,32 @@ async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]: job = await _db(x2_db.create_web_job, kind, params) except ValueError as exc: raise HTTPException(400, str(exc)) from exc + # Push to idle WebSocket helpers immediately (poll fallback still works) + try: + await hub.dispatch_queued() + except Exception: + pass return {"ok": True, "job": job} @app.post("/api/x2/jobs/{job_id}/cancel") async def x2_jobs_cancel(job_id: str) -> dict[str, Any]: from . import x2_db + from .x2_ws import hub job = await _db(x2_db.cancel_job, job_id) if not job: raise HTTPException(404, "任务不存在") + try: + await hub.notify_cancel(job_id, agent_id=str(job.get("agent_id") or "")) + except Exception: + pass return {"ok": True, "job": job} @app.post("/api/x2/extension/poll") async def x2_extension_poll(request: Request, body: dict[str, Any] | None = None) -> dict[str, Any]: - """Extension heartbeat + claim next queued job. Auth: X-X2-Token (auto-synced from /x).""" + """Legacy fallback: heartbeat + claim. Prefer /api/x2/extension/ws.""" from . import x2_db token = ( @@ -928,6 +940,7 @@ async def x2_extension_poll(request: Request, body: dict[str, Any] | None = None "source": "dylive-helper", "accounts": accounts, "message": "poll", + "meta": {"transport": "poll"}, }, ) cancel_ids = await _db(x2_db.list_cancel_requested, agent_id) @@ -938,6 +951,106 @@ async def x2_extension_poll(request: Request, body: dict[str, Any] | None = None return {"ok": True, "job": job, "cancel_ids": cancel_ids} +@app.websocket("/api/x2/extension/ws") +async def x2_extension_ws(websocket: WebSocket) -> None: + """Chrome extension realtime channel. Auth: ?token= or header Sec not available — query token.""" + import time as _time + + from . import x2_db + from .x2_ws import ExtClient, hub + + token = (websocket.query_params.get("token") or "").strip() + if not token or not x2_db.verify_ingest_token(token): + await websocket.close(code=4401) + return + + agent_id = (websocket.query_params.get("agent_id") or "dylive-helper").strip() or "dylive-helper" + label = (websocket.query_params.get("label") or "dylive Helper").strip() or "dylive Helper" + + await websocket.accept() + client = ExtClient( + ws=websocket, + agent_id=agent_id, + label=label, + busy=False, + connected_at=_time.time(), + ) + await hub.register(client) + + async def _heartbeat(accounts: list | None = None, message: str = "ws") -> None: + await _db( + x2_db.ingest_payload, + { + "agent_id": agent_id, + "label": label, + "event": "heartbeat", + "extension_connected": True, + "source": "dylive-helper", + "accounts": accounts, + "message": message, + "meta": {"transport": "ws"}, + }, + ) + + try: + await _heartbeat(message="ws.connected") + await hub.send_json(client, {"type": "hello.ok", "agent_id": agent_id}) + # Offer any queued work right away + await hub.dispatch_queued() + + while True: + raw = await websocket.receive_text() + try: + msg = json.loads(raw) + except Exception: + continue + if not isinstance(msg, dict): + continue + mtype = str(msg.get("type") or "") + if mtype in {"ping", "heartbeat", "hello"}: + accounts = msg.get("accounts") if isinstance(msg.get("accounts"), list) else None + if "busy" in msg: + await hub.set_busy(client, bool(msg.get("busy"))) + await _heartbeat(accounts, message=mtype) + await hub.send_json(client, {"type": "pong", "t": _time.time()}) + cancel_ids = await _db(x2_db.list_cancel_requested, agent_id) + if cancel_ids: + await hub.send_json(client, {"type": "job.cancel", "ids": cancel_ids}) + if not client.busy: + await hub.dispatch_queued() + elif mtype == "busy": + await hub.set_busy(client, bool(msg.get("busy"))) + if not client.busy: + await hub.dispatch_queued() + elif mtype == "ready": + await hub.set_busy(client, False) + await hub.dispatch_queued() + elif mtype == "job.ack": + # client accepted job.exec + await hub.set_busy(client, True) + except WebSocketDisconnect: + pass + except Exception: + pass + finally: + await hub.unregister(client) + try: + await _db( + x2_db.ingest_payload, + { + "agent_id": agent_id, + "label": label, + "event": "heartbeat", + "extension_connected": False, + "source": "dylive-helper", + "message": "ws.disconnected", + "meta": {"transport": "ws"}, + }, + ) + except Exception: + pass + + # ---------- TikTok (fully isolated from Shorts) ---------- def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: diff --git a/backend/app/session_auth.py b/backend/app/session_auth.py index d21ed3c..b128ecb 100644 --- a/backend/app/session_auth.py +++ b/backend/app/session_auth.py @@ -33,6 +33,7 @@ _PUBLIC_API_EXACT = { "/api/events/stream", "/api/x2/ingest", "/api/x2/extension/poll", + "/api/x2/extension/ws", } diff --git a/backend/app/x2_ws.py b/backend/app/x2_ws.py new file mode 100644 index 0000000..357ed30 --- /dev/null +++ b/backend/app/x2_ws.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +"""X2 extension WebSocket hub — push jobs to online Chrome helpers.""" +from __future__ import annotations + +import asyncio +import json +import logging +from dataclasses import dataclass +from typing import Any, Optional + +from fastapi import WebSocket + +log = logging.getLogger("x2_ws") + + +@dataclass +class ExtClient: + ws: WebSocket + agent_id: str + label: str = "dylive Helper" + busy: bool = False + connected_at: float = 0.0 + + +class ExtensionHub: + def __init__(self) -> None: + self._clients: list[ExtClient] = [] + self._lock = asyncio.Lock() + + @property + def online_count(self) -> int: + return len(self._clients) + + async def register(self, client: ExtClient) -> None: + async with self._lock: + # drop dead duplicates for same agent (single helper expected) + stale = [c for c in self._clients if c.agent_id == client.agent_id] + self._clients = [c for c in self._clients if c.agent_id != client.agent_id] + self._clients.append(client) + for old in stale: + try: + await old.ws.close(code=4000) + except Exception: + pass + log.info("x2 ws register agent=%s total=%s", client.agent_id, len(self._clients)) + + async def unregister(self, client: ExtClient) -> None: + async with self._lock: + self._clients = [c for c in self._clients if c is not client] + log.info("x2 ws unregister agent=%s total=%s", client.agent_id, len(self._clients)) + + async def set_busy(self, client: ExtClient, busy: bool) -> None: + client.busy = bool(busy) + + async def send_json(self, client: ExtClient, payload: dict[str, Any]) -> bool: + try: + await client.ws.send_text(json.dumps(payload, ensure_ascii=False, default=str)) + return True + except Exception as exc: + log.warning("x2 ws send fail agent=%s: %s", client.agent_id, exc) + return False + + async def broadcast(self, payload: dict[str, Any], *, agent_id: str = "") -> int: + async with self._lock: + targets = list(self._clients) + if agent_id: + targets = [c for c in targets if c.agent_id == agent_id] + n = 0 + for c in targets: + if await self.send_json(c, payload): + n += 1 + return n + + async def notify_cancel(self, job_id: str, *, agent_id: str = "") -> None: + jid = str(job_id or "").strip() + if not jid: + return + await self.broadcast({"type": "job.cancel", "ids": [jid]}, agent_id=agent_id) + + async def dispatch_queued(self) -> int: + """Claim queued jobs and push to idle websocket clients. Returns jobs sent.""" + from . import x2_db + + sent = 0 + async with self._lock: + idle = [c for c in self._clients if not c.busy] + for client in idle: + # claim in threadpool via sync db + loop = asyncio.get_running_loop() + job = await loop.run_in_executor(None, x2_db.claim_next_job, client.agent_id) + if not job: + break + client.busy = True + ok = await self.send_json(client, {"type": "job.exec", "job": job}) + if ok: + sent += 1 + else: + client.busy = False + # best-effort: leave job running in DB; extension reconnect may not re-claim + return sent + + +hub = ExtensionHub() diff --git a/extensions/dylive-helper/src/background.ts b/extensions/dylive-helper/src/background.ts index 8b96d62..ccfb078 100644 --- a/extensions/dylive-helper/src/background.ts +++ b/extensions/dylive-helper/src/background.ts @@ -175,79 +175,206 @@ async function pushHeartbeatToDouyin() { } } -/** Web /x → extension job queue (does not affect solo popup jobs). */ +/** Web /x → extension via WSS (poll kept only as rare fallback). */ let webJobBusy = false; +let dyliveWs: WebSocket | null = null; +let dyliveWsOpening = false; +let dyliveWsBackoffMs = 1500; +let dyliveWsTimer: ReturnType | null = null; + +function accountsPayload() { + if (!cachedAccount?.username) return undefined; + return [ + { + id: `x:${cachedAccount.username}`, + username: cachedAccount.username, + displayName: cachedAccount.displayName || "", + avatarUrl: cachedAccount.avatarUrl || "", + lastSeenAt: nowIso(), + }, + ]; +} async function applyDyliveAutoPair(msg: { origin?: string; token?: string; ingestUrl?: string; pollUrl?: string; + wsUrl?: string; }) { const origin = String(msg.origin || "https://dylive.nomadro.com").replace(/\/$/, ""); const token = String(msg.token || "").trim(); if (!token) return; + const wsBase = origin.replace(/^http/i, "ws"); await chrome.storage.local.set({ douyinWebhookEnabled: true, douyinWebhookUrl: String(msg.ingestUrl || `${origin}/api/x2/ingest`), douyinWebhookToken: token, douyinPollUrl: String(msg.pollUrl || `${origin}/api/x2/extension/poll`), + douyinWsUrl: String(msg.wsUrl || `${wsBase}/api/x2/extension/ws`), douyinOrigin: origin, douyinAgentId: "dylive-helper", douyinAgentLabel: "dylive Helper", douyinAutoPaired: true, douyinAutoPairedAt: nowIso(), }); + dyliveWsBackoffMs = 1500; + void ensureDyliveWs(true); } -async function pollWebQueue() { - if (webJobBusy) { - // still heartbeat so /x shows online +async function runWebJob(job: { + id: string; + kind: JobKind; + params?: Record; +}) { + if (!job?.id || !job.kind) return; + webJobBusy = true; + wsSend({ type: "busy", busy: true }); + const local: LocalJob = { + id: String(job.id), + kind: job.kind, + status: "queued", + params: (job.params || {}) as Record, + progress: { current: 0, total: 1, message: "Web 任务领取" }, + createdAt: nowIso(), + updatedAt: nowIso(), + source: "local", + }; + upsertLocalJob(local); + try { + await runLocalJob(local); + } finally { + webJobBusy = false; + wsSend({ type: "ready" }); + } +} + +function wsSend(payload: Record) { + if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) { try { - const cfg = await chrome.storage.local.get([ - "douyinWebhookEnabled", - "douyinWebhookToken", - "douyinPollUrl", - "douyinOrigin", - "douyinAgentId", - "douyinAgentLabel", - ]); - if (cfg.douyinWebhookEnabled === false) return; - const token = String(cfg.douyinWebhookToken || "").trim(); - if (!token) return; - const pollUrl = String( - cfg.douyinPollUrl || - `${cfg.douyinOrigin || "https://dylive.nomadro.com"}/api/x2/extension/poll`, - ); - await fetch(pollUrl, { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-X2-Token": token, - }, - body: JSON.stringify({ - agent_id: String(cfg.douyinAgentId || "dylive-helper"), - label: String(cfg.douyinAgentLabel || "dylive Helper"), - busy: true, - accounts: cachedAccount?.username - ? [ - { - id: `x:${cachedAccount.username}`, - username: cachedAccount.username, - displayName: cachedAccount.displayName || "", - avatarUrl: cachedAccount.avatarUrl || "", - lastSeenAt: nowIso(), - }, - ] - : undefined, - }), - }); + dyliveWs.send(JSON.stringify(payload)); } catch { /* ignore */ } + } +} + +function scheduleDyliveWsReconnect() { + if (dyliveWsTimer) return; + const wait = dyliveWsBackoffMs; + dyliveWsBackoffMs = Math.min(30000, Math.floor(dyliveWsBackoffMs * 1.6)); + dyliveWsTimer = setTimeout(() => { + dyliveWsTimer = null; + void ensureDyliveWs(false); + }, wait); +} + +async function ensureDyliveWs(force = false) { + if (dyliveWsOpening) return; + if (!force && dyliveWs && (dyliveWs.readyState === WebSocket.OPEN || dyliveWs.readyState === WebSocket.CONNECTING)) { return; } + const cfg = await chrome.storage.local.get([ + "douyinWebhookEnabled", + "douyinWebhookToken", + "douyinWsUrl", + "douyinOrigin", + "douyinAgentId", + "douyinAgentLabel", + ]); + if (cfg.douyinWebhookEnabled === false) return; + const token = String(cfg.douyinWebhookToken || "").trim(); + if (!token) return; + const origin = String(cfg.douyinOrigin || "https://dylive.nomadro.com").replace(/\/$/, ""); + const wsBase = String(cfg.douyinWsUrl || `${origin.replace(/^http/i, "ws")}/api/x2/extension/ws`).trim(); + const agentId = encodeURIComponent(String(cfg.douyinAgentId || "dylive-helper")); + const label = encodeURIComponent(String(cfg.douyinAgentLabel || "dylive Helper")); + const url = `${wsBase}${wsBase.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}&agent_id=${agentId}&label=${label}`; + try { + if (dyliveWs) { + try { + dyliveWs.close(); + } catch { + /* ignore */ + } + dyliveWs = null; + } + dyliveWsOpening = true; + const ws = new WebSocket(url); + dyliveWs = ws; + ws.onopen = () => { + dyliveWsOpening = false; + dyliveWsBackoffMs = 1500; + wsSend({ + type: "hello", + busy: webJobBusy, + accounts: accountsPayload(), + }); + }; + ws.onmessage = (ev) => { + void (async () => { + let msg: { + type?: string; + job?: { id: string; kind: JobKind; params?: Record }; + ids?: string[]; + }; + try { + msg = JSON.parse(String(ev.data)); + } catch { + return; + } + const t = String(msg?.type || ""); + if (t === "job.cancel" && Array.isArray(msg.ids)) { + for (const cid of msg.ids) { + cancelledLocal.add(String(cid)); + patchLocalJob(String(cid), { status: "cancelled", error: "用户取消" }); + } + return; + } + if (t === "job.exec" && msg.job?.id && msg.job.kind) { + if (webJobBusy) { + wsSend({ type: "busy", busy: true }); + return; + } + wsSend({ type: "job.ack", jobId: msg.job.id }); + await runWebJob(msg.job); + } + })(); + }; + ws.onclose = () => { + dyliveWsOpening = false; + if (dyliveWs === ws) dyliveWs = null; + scheduleDyliveWsReconnect(); + }; + ws.onerror = () => { + try { + ws.close(); + } catch { + /* ignore */ + } + }; + } catch { + dyliveWsOpening = false; + scheduleDyliveWsReconnect(); + } +} + +function wsHeartbeatTick() { + void ensureDyliveWs(false); + if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) { + wsSend({ + type: "heartbeat", + busy: webJobBusy, + accounts: accountsPayload(), + }); + } +} + +/** Rare HTTP fallback if WS down for a while (should almost never run jobs this way). */ +async function pollWebQueueFallback() { + if (webJobBusy) return; + if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) return; try { const cfg = await chrome.storage.local.get([ "douyinWebhookEnabled", @@ -274,55 +401,21 @@ async function pollWebQueue() { agent_id: String(cfg.douyinAgentId || "dylive-helper"), label: String(cfg.douyinAgentLabel || "dylive Helper"), busy: false, - accounts: cachedAccount?.username - ? [ - { - id: `x:${cachedAccount.username}`, - username: cachedAccount.username, - displayName: cachedAccount.displayName || "", - avatarUrl: cachedAccount.avatarUrl || "", - lastSeenAt: nowIso(), - }, - ] - : undefined, + accounts: accountsPayload(), }), }); if (!res.ok) return; const data = (await res.json()) as { - job?: { - id: string; - kind: JobKind; - params?: Record; - status?: string; - }; + job?: { id: string; kind: JobKind; params?: Record }; cancel_ids?: string[]; }; for (const cid of data.cancel_ids || []) { cancelledLocal.add(String(cid)); patchLocalJob(String(cid), { status: "cancelled", error: "用户取消" }); } - const job = data.job; - if (!job?.id || !job.kind) return; - - webJobBusy = true; - const local: LocalJob = { - id: String(job.id), - kind: job.kind, - status: "queued", - params: (job.params || {}) as Record, - progress: { current: 0, total: 1, message: "Web 任务领取" }, - createdAt: nowIso(), - updatedAt: nowIso(), - source: "local", - }; - upsertLocalJob(local); - try { - await runLocalJob(local); - } finally { - webJobBusy = false; - } + if (data.job?.id && data.job.kind) await runWebJob(data.job); } catch { - webJobBusy = false; + /* ignore */ } } @@ -1352,19 +1445,23 @@ chrome.alarms.onAlarm.addListener((a) => { } if (a.name === "dylive.heartbeat") { void pushHeartbeatToDouyin(); + wsHeartbeatTick(); } - if (a.name === "dylive.webPoll") { - void pollWebQueue(); + if (a.name === "dylive.ws") { + wsHeartbeatTick(); + void pollWebQueueFallback(); } }); chrome.alarms.create("dylive.heartbeat", { periodInMinutes: 2 }); -chrome.alarms.create("dylive.webPoll", { periodInMinutes: 0.05 }); // ~3s (Chrome min is 1 min in MV3 actually!) +chrome.alarms.create("dylive.ws", { periodInMinutes: 1 }); -// MV3 alarms minimum is often 1 minute — also use setInterval in SW when alive +// Keep WS alive while SW is awake setInterval(() => { - void pollWebQueue(); -}, 3500); + wsHeartbeatTick(); +}, 12000); + +void ensureDyliveWs(false); chrome.tabs.onUpdated.addListener((_tabId, info, tab) => { if (info.status !== "complete") return; diff --git a/extensions/dylive-helper/src/content-dylive-bridge.js b/extensions/dylive-helper/src/content-dylive-bridge.js index 9db41df..6fc39ec 100644 --- a/extensions/dylive-helper/src/content-dylive-bridge.js +++ b/extensions/dylive-helper/src/content-dylive-bridge.js @@ -19,6 +19,7 @@ token, ingestUrl: `${origin}/api/x2/ingest`, pollUrl: `${origin}/api/x2/extension/poll`, + wsUrl: `${origin.replace(/^http/i, "ws")}/api/x2/extension/ws`, }); } catch { /* not logged in / offline */