2026-10-17 10:46:29 +08:00

348 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import asyncio
import base64
import json
import re
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, field_validator
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
RUNS_DIR = STATIC_DIR / "runs"
RUNS_DIR.mkdir(parents=True, exist_ok=True)
app = FastAPI(title="Web 群控工作台")
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
class RunRequest(BaseModel):
url: str
instances: int = Field(default=3, ge=1, le=12)
action_text: str = Field(default="", max_length=120)
@field_validator("url")
@classmethod
def validate_url(cls, value: str) -> str:
value = value.strip()
parsed = urlparse(value)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("请输入完整的网址,例如 https://example.com")
return value
@dataclass
class InstanceState:
id: int
status: str = "等待中"
message: str = ""
title: str = ""
frame: bytes | None = field(default=None, repr=False)
frame_version: int = field(default=0, repr=False)
page: Any | None = field(default=None, repr=False)
control_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
@dataclass
class RunState:
id: str
url: str
instances: list[InstanceState]
status: str = "运行中"
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
error: str = ""
stop_event: asyncio.Event = field(default_factory=asyncio.Event, repr=False)
task: asyncio.Task[Any] | None = field(default=None, repr=False)
subscribers: set[asyncio.Queue[dict[str, Any]]] = field(default_factory=set, repr=False)
runs: dict[str, RunState] = {}
def publish_run(run: RunState) -> None:
snapshot = public_run(run)
for queue in tuple(run.subscribers):
if queue.full():
try:
queue.get_nowait()
except asyncio.QueueEmpty:
pass
queue.put_nowait(snapshot)
def public_run(run: RunState) -> dict[str, Any]:
return {
"id": run.id,
"url": run.url,
"status": run.status,
"created_at": run.created_at,
"error": run.error,
"instances": [
{
"id": instance.id,
"status": instance.status,
"message": instance.message,
"title": instance.title,
"stream": f"/api/runs/{run.id}/instances/{instance.id}/stream",
"control": f"/ws/runs/{run.id}/instances/{instance.id}",
}
for instance in run.instances
],
}
async def control_instance(browser: Any, run: RunState, state: InstanceState, action_text: str) -> None:
context = await browser.new_context(viewport={"width": 1365, "height": 860})
page = await context.new_page()
state.page = page
cdp = None
try:
cdp = await context.new_cdp_session(page)
def receive_frame(payload: dict[str, Any]) -> None:
state.frame = base64.b64decode(payload["data"])
state.frame_version += 1
asyncio.create_task(
cdp.send("Page.screencastFrameAck", {"sessionId": payload["sessionId"]})
)
cdp.on("Page.screencastFrame", receive_frame)
await cdp.send(
"Page.startScreencast",
{"format": "jpeg", "quality": 72, "maxWidth": 1365, "maxHeight": 860},
)
state.status = "打开页面"
publish_run(run)
await page.goto(run.url, wait_until="domcontentloaded", timeout=30_000)
state.title = await page.title()
publish_run(run)
if run.stop_event.is_set():
state.status = "已停止"
publish_run(run)
return
if action_text:
state.status = "识别文字"
publish_run(run)
locator = page.get_by_text(re.compile(re.escape(action_text), re.IGNORECASE)).first
try:
await locator.wait_for(state="visible", timeout=5_000)
await locator.click(timeout=5_000)
state.message = f"已点击“{action_text}”"
except Exception:
state.message = f"未找到“{action_text}”,已保留页面"
else:
state.message = "页面已打开"
publish_run(run)
state.status = "实时监控"
publish_run(run)
await run.stop_event.wait()
state.status = "已停止"
state.message = "实时画面已停止"
publish_run(run)
except Exception as exc:
state.status = "失败"
state.message = str(exc)[:180]
publish_run(run)
finally:
if cdp is not None:
try:
await cdp.send("Page.stopScreencast")
except Exception:
pass
await context.close()
state.page = None
async def execute_run(run: RunState, action_text: str) -> None:
try:
from playwright.async_api import async_playwright
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=True)
try:
await asyncio.gather(
*(control_instance(browser, run, state, action_text) for state in run.instances)
)
finally:
await browser.close()
if run.stop_event.is_set():
run.status = "已停止"
elif any(item.status == "失败" for item in run.instances):
run.status = "部分失败"
else:
run.status = "已完成"
publish_run(run)
except Exception as exc:
run.status = "失败"
run.error = "浏览器启动失败,请先执行:playwright install chromium"
for state in run.instances:
if state.status == "等待中":
state.status = "失败"
state.message = str(exc)[:180]
publish_run(run)
@app.get("/")
async def index() -> FileResponse:
return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-store, max-age=0"})
@app.get("/api/health")
async def health() -> dict[str, str]:
return {"status": "ok"}
@app.post("/api/runs")
async def create_run(request: RunRequest) -> dict[str, Any]:
run_id = uuid.uuid4().hex[:10]
run = RunState(
id=run_id,
url=request.url,
instances=[InstanceState(id=index + 1) for index in range(request.instances)],
)
runs[run_id] = run
run.task = asyncio.create_task(execute_run(run, request.action_text.strip()))
return public_run(run)
@app.get("/api/runs/{run_id}")
async def get_run(run_id: str) -> dict[str, Any]:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
return public_run(run)
@app.get("/api/runs/{run_id}/events")
async def run_events(run_id: str) -> StreamingResponse:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=3)
run.subscribers.add(queue)
queue.put_nowait(public_run(run))
async def event_stream():
try:
while True:
snapshot = await queue.get()
yield f"data: {json.dumps(snapshot, ensure_ascii=False)}\n\n"
if snapshot["status"] not in {"运行中", "停止中"}:
break
finally:
run.subscribers.discard(queue)
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
)
@app.get("/api/runs/{run_id}/instances/{instance_id}/stream")
async def instance_stream(run_id: str, instance_id: int) -> StreamingResponse:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
state = next((item for item in run.instances if item.id == instance_id), None)
if state is None:
raise HTTPException(status_code=404, detail="实例不存在")
async def frame_stream():
last_version = -1
while True:
if state.frame is not None and state.frame_version != last_version:
last_version = state.frame_version
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n"
b"Cache-Control: no-cache\r\n\r\n"
+ state.frame
+ b"\r\n"
)
if run.status not in {"运行中", "停止中"} and last_version == state.frame_version:
break
await asyncio.sleep(0.08)
return StreamingResponse(
frame_stream(),
media_type="multipart/x-mixed-replace; boundary=frame",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
)
@app.websocket("/ws/runs/{run_id}/instances/{instance_id}")
async def instance_control(websocket: WebSocket, run_id: str, instance_id: int) -> None:
run = runs.get(run_id)
state = next((item for item in run.instances if item.id == instance_id), None) if run else None
if run is None or state is None:
await websocket.close(code=1008, reason="任务或实例不存在")
return
await websocket.accept()
try:
while True:
message = await websocket.receive_json()
page = state.page
if page is None:
await websocket.send_json({"type": "error", "message": "实例尚未准备好"})
continue
async with state.control_lock:
event_type = message.get("type")
if event_type == "click":
await page.mouse.click(
float(message["x"]),
float(message["y"]),
button=message.get("button", "left"),
click_count=int(message.get("clickCount", 1)),
)
elif event_type == "wheel":
await page.mouse.wheel(float(message.get("deltaX", 0)), float(message.get("deltaY", 0)))
elif event_type == "key":
key = str(message["key"])
modifiers = [str(item) for item in message.get("modifiers", [])]
if len(key) == 1 and not modifiers:
await page.keyboard.insert_text(key)
else:
combo = "+".join([*modifiers, key]) if modifiers else key
await page.keyboard.press(combo)
elif event_type == "text":
await page.keyboard.insert_text(str(message.get("value", "")))
else:
await websocket.send_json({"type": "error", "message": "不支持的操作"})
continue
await websocket.send_json({"type": "ack", "event": event_type})
except WebSocketDisconnect:
return
except Exception as exc:
try:
await websocket.send_json({"type": "error", "message": str(exc)[:180]})
except Exception:
return
@app.post("/api/runs/{run_id}/stop")
async def stop_run(run_id: str) -> dict[str, Any]:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
run.stop_event.set()
if run.status == "运行中":
run.status = "停止中"
publish_run(run)
return public_run(run)