# -*- coding: utf-8 -*- """webhost 宿主:FastAPI 后端。 - 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验) - 场景插件注册表 + 表单 schema - 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成 - 挂载前端构建产物(frontend/dist)实现单产物 """ from __future__ import annotations import asyncio import socket import threading import uuid from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path from fastapi import FastAPI, HTTPException, WebSocket from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from webhost.backend import auth as platform_auth from webhost.backend.hub import HUB from webhost.backend.plugins import PLUGINS # noqa: F401 触发注册 from webhost.backend.plugins.base import RunContext PORT = 8799 DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist" # 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态) PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]} for p in platform_auth.platforms()} # 运行会话:run_id -> {status, result, error} RUNS: dict = {} RUN_LOCK = threading.Lock() MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长 class RunReq(BaseModel): plugin_id: str fields: dict = {} @asynccontextmanager async def lifespan(app: FastAPI): HUB.bind(asyncio.get_running_loop()) yield app = FastAPI(title="37du Web Host", lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) def _plugin_schema(p) -> dict: return {"id": p.id, "name": p.name, "version": p.version, "description": p.description, "uses_month": getattr(p, "uses_month", False), "fields": p.fields} @app.get("/api/meta") def meta() -> dict: plugins = [_plugin_schema(p) for p in PLUGINS] platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)} for pid, m in PLATFORMS.items()] return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins} @app.post("/api/platforms/{pid}/login") def login(pid: str) -> dict: """真实登录:复用有效 cookies 或浏览器自动化登录(滑块),秒级~分钟级阻塞。""" plat = PLATFORMS.get(pid) if not plat: raise HTTPException(404, "平台不存在") return platform_auth.login(pid) def _run_target(plugin, fields: dict, run_id: str) -> None: ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth) try: result = plugin.run(fields, ctx) with RUN_LOCK: RUNS[run_id] = {"status": "done", "result": result, "error": None} HUB.publish({"t": "run_done", "run_id": run_id, "ok": True}) except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端 with RUN_LOCK: RUNS[run_id] = {"status": "error", "result": None, "error": str(e)} HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)}) @app.post("/api/runs", status_code=202) def start_run(req: RunReq) -> dict: try: plugin = PLUGINS.find(req.plugin_id) except KeyError: raise HTTPException(404, "插件不存在") run_id = uuid.uuid4().hex with RUN_LOCK: if len(RUNS) >= MAX_RUNS: RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录 RUNS[run_id] = {"status": "running", "result": None, "error": None} HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id, "at": datetime.now().strftime("%H:%M:%S")}) threading.Thread(target=_run_target, args=(plugin, req.fields, run_id), daemon=True, name=f"run-{plugin.id}").start() return {"run_id": run_id} @app.get("/api/runs/{run_id}") def get_run(run_id: str) -> dict: with RUN_LOCK: run = RUNS.get(run_id) if not run: raise HTTPException(404, "运行不存在") return run @app.websocket("/ws") async def ws(websocket: WebSocket): await HUB.connect(websocket) if DIST.exists(): app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web") def _port_free(port: int) -> bool: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(("127.0.0.1", port)) != 0 if __name__ == "__main__": import uvicorn print(f"[webhost] port {PORT} free = {_port_free(PORT)}") uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")