refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
# 登录成功即按账号权限自下载/更新插件并重载(离线/失败不影响登录)
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.plugins import load_plugins
|
||||
sync_plugins(b.account.strip())
|
||||
load_plugins(None, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@router.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
|
||||
_SESS_LOCK, _sess_persist)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
|
||||
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
|
||||
|
||||
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
|
||||
"""
|
||||
r = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/auth",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
|
||||
acct = r.get("account") or account
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (acct, time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/login")
|
||||
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
|
||||
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
|
||||
if not d.account:
|
||||
raise HTTPException(400, "工号不能为空")
|
||||
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/inline")
|
||||
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
|
||||
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
|
||||
|
||||
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
|
||||
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"code": d.code.strip()})
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return _cp_call(
|
||||
"GET", "/api/admin/dingtalk/inline_qr",
|
||||
params={"back": back},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
|
||||
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
|
||||
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
|
||||
<script>
|
||||
(async function(){
|
||||
var q = new URLSearchParams(location.search);
|
||||
var account = q.get('account') || '';
|
||||
var nickname = q.get('nickname') || '';
|
||||
if (account) {
|
||||
try {
|
||||
await fetch('/api/admin/dingtalk/login', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ account: account, nickname: nickname })
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
try { window.opener && window.opener.location.reload(); } catch (e) {}
|
||||
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
|
||||
})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「业务元数据与平台登录」路由:/api/meta 聚合 + 平台真实登录/登出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/plugins/sync")
|
||||
def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/shell/update-status")
|
||||
def shell_update_status(request: Request) -> dict:
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示。"""
|
||||
_require_login(request)
|
||||
return _shell_updater.pending_status()
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.apply_update()
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
|
||||
online = licensing.is_online()
|
||||
deny = licensing.run_check_allowed(plugin.id, account, online)
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
Reference in New Issue
Block a user