refactor: 重构执行机架构为 Electron 壳内置 Python 运行时子集
将原 webhost 底座的后端、前端、工具等代码迁移至 electron-shell 目录,构建自包含的 Python 环境包,移除冗余的前端代码、旧的后端模块及相关依赖,更新版本号至 1.0.6,优化平台登录态预检逻辑,统一代码结构为单一真源,避免多副本维护问题。
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
// 37du Electron 壳:配置固化(.env 加载 + 路径 + 常量)
|
||||
// 对齐 Python webhost backend/core/config.py 的语义与路径约定。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
@@ -17,9 +16,8 @@ const IS_FROZEN =
|
||||
// 本模块目录:desktop/electron-shell/electron → parents
|
||||
const SHELL_ROOT = path.resolve(__dirname, "..");
|
||||
|
||||
// 仓库根:electron/../.. = 37duAutomation(dev 模式定位 plugins/ 与 webhost 参考实现)
|
||||
// 仓库根:electron/../.. = 37duAutomation(dev 模式定位 plugins/)
|
||||
const REPO_ROOT = path.resolve(SHELL_ROOT, "..", "..");
|
||||
const DESKTOP_ROOT = path.resolve(SHELL_ROOT, "..");
|
||||
|
||||
// ==================== 轻量 .env 加载(仅本模块目录,变量已存在则不覆盖) ====================
|
||||
function loadDotEnv() {
|
||||
@@ -129,14 +127,14 @@ function pythonExe() {
|
||||
return "python";
|
||||
}
|
||||
|
||||
// 运行时根(webhost 包所在目录):环境包模式 = 环境包根;否则 = desktop/(dev,webhost 在仓库内)
|
||||
// 运行时根(webhost 包所在目录):环境包模式 = 环境包根;否则 = 壳内置 python/(vendor 子集)
|
||||
function runtimeRoot() {
|
||||
const envRoot = pythonEnvRoot();
|
||||
if (envRoot) return envRoot;
|
||||
return DESKTOP_ROOT;
|
||||
return path.join(SHELL_ROOT, "python");
|
||||
}
|
||||
|
||||
// 插件执行入口:环境包模式 = 环境包内 plugin_runner.py;打包态 = exe 同级;dev = 仓库 webhost
|
||||
// 插件执行入口:环境包模式 = 环境包内 plugin_runner.py;打包态 = exe 同级;dev = 壳内置 python/
|
||||
function runnerScript() {
|
||||
if (process.env.SHELL_RUNNER_SCRIPT) return process.env.SHELL_RUNNER_SCRIPT;
|
||||
const envRoot = pythonEnvRoot();
|
||||
@@ -144,7 +142,7 @@ function runnerScript() {
|
||||
if (IS_FROZEN) {
|
||||
return path.join(path.dirname(process.execPath), "plugin_runner.py");
|
||||
}
|
||||
return path.join(DESKTOP_ROOT, "webhost", "backend", "core", "plugin_runner.py");
|
||||
return path.join(SHELL_ROOT, "python", "webhost", "backend", "core", "plugin_runner.py");
|
||||
}
|
||||
|
||||
// Job Object 守护(环境包模式启用内存上限 + 整树托管):无环境包返回 ""
|
||||
@@ -154,18 +152,9 @@ function jobGuardScript() {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 前端静态资源:壳自带 renderer/dist(可单独拷贝);dev 兜底复用 webhost 构建产物
|
||||
// 前端静态资源:壳自带 renderer/dist(自包含;缺失时先跑 scripts/copy-renderer.ps1 构建)
|
||||
function frontendDist() {
|
||||
const own = path.join(SHELL_ROOT, "renderer", "dist");
|
||||
if (fs.existsSync(path.join(own, "index.html"))) return own;
|
||||
const legacy = path.join(DESKTOP_ROOT, "webhost", "frontend", "dist");
|
||||
if (fs.existsSync(path.join(legacy, "index.html"))) return legacy;
|
||||
return own;
|
||||
}
|
||||
|
||||
// 平台登录子进程:spawn python <shared 模块>(webhost.backend.shared.hr_login/oa_login)
|
||||
function sharedModule(moduleName) {
|
||||
return path.join(DESKTOP_ROOT, "webhost", "backend", "shared", `${moduleName}.py`);
|
||||
return path.join(SHELL_ROOT, "renderer", "dist");
|
||||
}
|
||||
|
||||
// 敏感凭证中心化下发:进程级覆盖存储(唯一来源:中心机下发 / 本地加密缓存)
|
||||
@@ -185,7 +174,6 @@ function getCred(name) {
|
||||
module.exports = {
|
||||
SHELL_ROOT,
|
||||
REPO_ROOT,
|
||||
DESKTOP_ROOT,
|
||||
PORT,
|
||||
APP_DATA,
|
||||
PLUGIN_CONFIG_DIR,
|
||||
@@ -199,7 +187,6 @@ module.exports = {
|
||||
pluginRoot,
|
||||
runnerScript,
|
||||
frontendDist,
|
||||
sharedModule,
|
||||
runtimeVersion,
|
||||
applyCreds,
|
||||
getCred,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// 平台登录态(HR/OA):真实登录/登出/在线校验。
|
||||
// 保持 Python 子进程执行登录自动化(shared/hr_login、oa_login,DrissionPage 滑块),
|
||||
// 保持 Python 子进程执行登录自动化(壳内置 python/webhost/backend/shared 下的
|
||||
// hr_login、oa_login,DrissionPage 滑块;自包含 vendor,不依赖老 webhost 底座),
|
||||
// Node 壳只负责拉起子进程与解析结果。
|
||||
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
|
||||
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
|
||||
|
||||
@@ -13,6 +13,7 @@ const state = require("./state");
|
||||
const scheduler = require("./scheduler");
|
||||
const licensing = require("./licensing");
|
||||
const runHistory = require("./run-history");
|
||||
const platformAuth = require("./platform-auth");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
@@ -66,6 +67,28 @@ function nsKey(account, platform) {
|
||||
return `${account || "anon"}:${platform || "local"}`;
|
||||
}
|
||||
|
||||
// 平台登录态预检(HR/OA):插件执行前检测该账号的平台登录态,
|
||||
// 失效时自动拉起自动登录(platform-auth.login,Python 子进程滑块自动化;
|
||||
// cookies 实际有效时不会弹浏览器)。登录成功继续执行,失败则本次运行报错,
|
||||
// 提示用户去个人中心手动登录(手动登录入口保留,不冲突)。
|
||||
// 在(账号, 平台)命名空间锁内调用,天然避免并发双开登录浏览器。
|
||||
const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" };
|
||||
async function ensurePlatformSession(plugin, runId, account) {
|
||||
const pid = plugin.platform;
|
||||
if (!pid || !PLATFORM_LABELS[pid]) return; // 无平台要求(或未知平台)直接执行
|
||||
if (await platformAuth.isOnline(pid, account)) return; // 登录态有效,直接执行
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
|
||||
const label = PLATFORM_LABELS[pid];
|
||||
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…(如需人工介入请观察弹出的浏览器窗口)`);
|
||||
const r = await platformAuth.login(pid, account);
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
|
||||
if (!r || !r.online) {
|
||||
const msg = (r && r.message) || "登录未生效";
|
||||
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」手动登录后重试`);
|
||||
}
|
||||
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
|
||||
}
|
||||
|
||||
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
|
||||
function emitLog(runId, pluginId, level, msg) {
|
||||
const text = String(msg === undefined || msg === null ? "" : msg);
|
||||
@@ -206,6 +229,8 @@ async function runQueued(plugin, fields, runId, account) {
|
||||
// 排队期间用户已点停止:不真正拉起插件
|
||||
throw new Error("用户已取消该排队任务");
|
||||
}
|
||||
// 平台登录态预检:HR/OA 失效时自动登录(手动登录入口保留)
|
||||
await ensurePlatformSession(plugin, runId, account);
|
||||
await startChild(plugin, fields, runId, account);
|
||||
return runId;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "37du-electron-shell",
|
||||
"productName": "37du 自动化工作台",
|
||||
"version": "1.0.5",
|
||||
"version": "1.0.6",
|
||||
"description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)",
|
||||
"main": "electron/main.js",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""37du 执行机壳内置 Python 运行时(自包含,vendor 自老 webhost 底座)。
|
||||
|
||||
包名保持 webhost 不变:这是插件 ABI(webhost.backend.plugins.base /
|
||||
webhost.backend.shared.hr_login)的兼容约束,已发插件与平台登录子进程都按
|
||||
该包名 import,改名意味着全部插件重新发版。本目录是壳子运行时子集的
|
||||
单一真源,环境包构建(scripts/build-python-env.ps1)从这里拷贝。
|
||||
"""
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""壳子运行时子集(webhost.backend)。
|
||||
|
||||
只包含插件执行与平台登录所需的最小模块集:
|
||||
plugin_runner + plugins + shared + core.auth(+ winjob/job_guard)。
|
||||
刻意不引入完整 core(调度/HTTP 等由 Node 壳承担)。
|
||||
"""
|
||||
+2
-1
@@ -37,7 +37,8 @@ if _env_plugins_root:
|
||||
elif getattr(sys, "frozen", False):
|
||||
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
|
||||
else:
|
||||
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
|
||||
# __file__ = <壳>/python/webhost/backend/plugins/__init__.py → parents[4] = 壳内置 python/
|
||||
# (vendor 布局回退仅兜底;壳子拉起插件子进程时始终注入 PLUGINS_ROOT,不依赖此回退)
|
||||
_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parents[4] / "plugins"
|
||||
if _PLUGINS_ROOT.is_dir() and str(_PLUGINS_ROOT) not in __path__:
|
||||
__path__.append(str(_PLUGINS_ROOT))
|
||||
+2
-2
@@ -12,7 +12,7 @@
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
约定(数据根与影刀版 / 各执行端统一):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
@@ -47,7 +47,7 @@ import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
# ================== 共享路径(各执行端统一的数据根) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
+2
-2
@@ -12,7 +12,7 @@
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
约定(数据根与影刀版 / 各执行端统一):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
@@ -43,7 +43,7 @@ from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
# ================== 共享路径(各执行端统一的数据根) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
+1
-1
@@ -133,7 +133,7 @@ if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
# ---------- 组织维护查询接口 ----------
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
+1
-1
@@ -143,7 +143,7 @@ if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
# ---------- 员工花名册查询/导出接口 ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
@@ -1,11 +1,11 @@
|
||||
# Build portable Python + environment package (python-env-<version>.zip)
|
||||
# Build portable Python + environment package (python-env-<version>.zip)
|
||||
# ============================================================================
|
||||
# Purpose: give the packaged Electron client a self-contained Python runtime so
|
||||
# plugins and platform-login no longer depend on an external Python install.
|
||||
# - Portable interpreter: python.org embeddable (self-contained) [default]
|
||||
# - Dependencies: pinned to the versions validated in the project .venv
|
||||
# - Runtime subset: webhost/backend/{plugins,core,shared} (minimal for
|
||||
# plugin_runner protocol + platform login)
|
||||
# - Runtime subset: electron-shell/python/webhost/backend/{plugins,core,shared}
|
||||
# (minimal for plugin_runner protocol + platform login; vendored, no webhost dep)
|
||||
# - Output: dist-env/python-env-<version>.zip + .sha256; by default also
|
||||
# installs into electron-shell/python-env/ for local dev (client probes it).
|
||||
# Usage (ASCII-safe, works on Windows PowerShell 5.1 with GBK codepage):
|
||||
@@ -161,23 +161,14 @@ if ($VcCount -lt 3) {
|
||||
throw "VC++ runtime DLLs incomplete ($VcCount): install VC++ 2015-2022 Redistributable x64 on this build machine first"
|
||||
}
|
||||
|
||||
# ---------- 3. webhost runtime subset ----------
|
||||
$Wb = Join-Path $Repo "desktop\webhost\backend"
|
||||
# ---------- 3. webhost runtime subset(单一真源 = electron-shell/python/webhost) ----------
|
||||
$Wb = Join-Path $Shell "python\webhost\backend"
|
||||
$EnvWb = Join-Path $PyDir "webhost\backend"
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $EnvWb "plugins"), (Join-Path $EnvWb "core"), (Join-Path $EnvWb "shared") | Out-Null
|
||||
|
||||
# top-level __init__ files: minimal (do NOT import the full core, avoids fastapi etc.)
|
||||
Set-Content -Path (Join-Path $PyDir "webhost\__init__.py") -Encoding utf8 -Value @(
|
||||
"# -*- coding: utf-8 -*-"
|
||||
'"""37du env-package runtime (self-contained)."""'
|
||||
)
|
||||
Set-Content -Path (Join-Path $EnvWb "__init__.py") -Encoding utf8 -Value @(
|
||||
"# -*- coding: utf-8 -*-"
|
||||
'"""37du env-package runtime subset (webhost.backend).'
|
||||
'Carries only the minimal modules needed for plugin execution and platform login:'
|
||||
'plugin_runner + plugins + shared + core.auth (+ winjob/job_guard).'
|
||||
'Deliberately does NOT import the full core (scheduler/http/etc. live in Node)."""'
|
||||
)
|
||||
# top-level __init__ files from source(minimal,不 import 完整 core)
|
||||
Copy-Item (Join-Path $Wb "__init__.py") (Join-Path $EnvWb "__init__.py") -Force
|
||||
Copy-Item (Join-Path (Join-Path $Shell "python\webhost") "__init__.py") (Join-Path $PyDir "webhost\__init__.py") -Force
|
||||
|
||||
# core: plugin_runner + auth + winjob + job_guard (no scheduler/http modules)
|
||||
$CoreFiles = @("__init__.py", "plugin_runner.py", "auth.py", "winjob.py", "job_guard.py")
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端(执行机底座):场景插件宿主。
|
||||
|
||||
组装层 main.py 之外的领域逻辑已归入 core 子包。本 `__init__` 作为 facade 再导出
|
||||
core 内各模块,以兼容 `from webhost.backend import X` 的既有用法(含插件 `auth` 引用)。
|
||||
"""
|
||||
from webhost.backend.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
cpapi,
|
||||
hub,
|
||||
licensing,
|
||||
meta,
|
||||
runner,
|
||||
scheduler,
|
||||
session,
|
||||
state,
|
||||
winjob,
|
||||
)
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -1,166 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览 / 头像代理。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, Request, Response, UploadFile
|
||||
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, _ACCT_CLOUD_TOKEN)
|
||||
|
||||
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": "", "avatar": ""}
|
||||
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": "", "avatar": ""}
|
||||
|
||||
|
||||
@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")
|
||||
# 沿用中心机登录时签发的用户云令牌,后续 /api/admin/me 等调用凭它定位账号(无需机器 TOKEN)
|
||||
_cloud_tok = (r or {}).get("cloud_token") or ""
|
||||
if _cloud_tok:
|
||||
_ACCT_CLOUD_TOKEN[b.account.strip()] = _cloud_tok
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
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)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(b.account.strip())
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
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": []}
|
||||
|
||||
|
||||
@router.get("/api/avatar/{account}")
|
||||
def avatar_get(account: str) -> Response:
|
||||
"""代理中心机头像读取(webhost 前端 img 直接引用;未设置头像返回 404)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/avatar/{quote(account)}", timeout=10)
|
||||
if r.status_code != 200:
|
||||
raise HTTPException(r.status_code, "头像不存在")
|
||||
return Response(content=r.content,
|
||||
media_type=r.headers.get("content-type", "application/octet-stream"))
|
||||
|
||||
|
||||
@router.post("/api/avatar")
|
||||
def avatar_upload(file: UploadFile = File(...), request: Request = None) -> dict:
|
||||
"""上传当前登录账号的头像(自服务,账号取本机会话),代理到中心机。"""
|
||||
if request is None:
|
||||
raise HTTPException(500, "missing request")
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests as _rq
|
||||
|
||||
data = file.file.read()
|
||||
if not data:
|
||||
raise HTTPException(400, "头像文件为空")
|
||||
resp = _rq.post(
|
||||
f"{config.CONTROLPLANE_URL}/api/admin/avatar?account={quote(account)}",
|
||||
headers=_cp_headers(request),
|
||||
files={"file": (file.filename or f"{account}.png", data,
|
||||
file.content_type or "application/octet-stream")},
|
||||
timeout=30)
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
body = {"detail": resp.text[:300]}
|
||||
if resp.status_code >= 400:
|
||||
raise HTTPException(resp.status_code, body.get("detail", f"中心机 {resp.status_code}"))
|
||||
return body
|
||||
@@ -1,230 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
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)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(acct)
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
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 由控制面代理构造。
|
||||
|
||||
执行机无需任何钉钉应用凭证(凭证只在控制面);前端「钉钉登录」当前窗口跳转该 URL,
|
||||
扫码后浏览器自动回跳本机 /auth/done。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
r = _cp_call(
|
||||
"GET", "/api/dingtalk/login-url",
|
||||
params={"back": redirect_uri, "state": state},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
return {"url": r.get("url") or "", "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)
|
||||
@@ -1,172 +0,0 @@
|
||||
# -*- 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, _cloud_plugin_manifest
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import chrome_manager as _chrome
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件可见性 = 本地授权票据快照(统一真源,与运行门禁一致):仅展示票据内被授权插件;
|
||||
# 票据不可用(缺失/过期且刷新失败)→ 空列表 + authExpired,前端提示联网刷新(超时不能使用)。
|
||||
auth_expired = False
|
||||
if account:
|
||||
ok, lic = licensing.ensure_license(account)
|
||||
if ok:
|
||||
allowed = {p.get("pluginId") for p in (lic or {}).get("plugins", [])}
|
||||
plugins = [_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
else:
|
||||
plugins = []
|
||||
auth_expired = True
|
||||
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 {
|
||||
"appName": "37du 自动化工作台",
|
||||
# 钉钉扫码 URL 由控制面代理构造,客户端零钉钉凭证;控制面配置了即可用扫码入口
|
||||
"dingtalkScan": bool(config.CONTROLPLANE_URL),
|
||||
"authExpired": auth_expired,
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/plugins/sync")
|
||||
def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
全程持 SYNC_LOCK:与启动后台同步串行,避免旧账号白名单覆盖本次同步结果。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
try:
|
||||
# 以「登录账号的授权插件集」作为加载白名单(替代启动时 CONTROLPLANE_ACCOUNT 的固定白名单),
|
||||
# 保证给员工账号授权插件后登录即可见/可运行;控制面不可达(manifest=None)时保持原白名单。
|
||||
from webhost.backend.core.plugin_sync import SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
result = sync_plugins(account)
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
# 授权票据一并刷新:管理台新授的插件在「F5 同步」后立即可运行,
|
||||
# 否则本地许可票据停留在上次登录时的快照,点执行会被 403 拒绝(须重登才恢复)。
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 票据刷新失败不阻断同步结果
|
||||
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/check")
|
||||
def shell_check(request: Request) -> dict:
|
||||
"""手动检查壳子更新:只比对版本(秒级),不下载;有新版由前端提示用户确认下载。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_check()
|
||||
return {"ok": True, "checking": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/download")
|
||||
def shell_download(request: Request) -> dict:
|
||||
"""开始下载新版安装包(后台流式下载,进度经 update-status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.apply_update()
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
# ===================== 浏览器(Chrome)检测/下载/安装 =====================
|
||||
|
||||
@router.get("/api/chrome/status")
|
||||
def chrome_status(request: Request) -> dict:
|
||||
"""浏览器状态:是否已装、版本、需否下载、下载进度。前端据此显示"安装 Chrome"图标提示。"""
|
||||
_require_login(request)
|
||||
return _chrome.status()
|
||||
|
||||
|
||||
@router.post("/api/chrome/check")
|
||||
def chrome_check(request: Request) -> dict:
|
||||
"""手动检测浏览器:刷新本机安装状态 + 中心机有无登记内网安装包。"""
|
||||
_require_login(request)
|
||||
_chrome.refresh()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/download")
|
||||
def chrome_download(request: Request) -> dict:
|
||||
"""开始后台下载 Chrome 安装包(进度经 /api/chrome/status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_chrome.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/install")
|
||||
def chrome_install(request: Request) -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包(后台进行,前端轮询 status.installed 感知成功)。"""
|
||||
_require_login(request)
|
||||
return _chrome.install()
|
||||
|
||||
|
||||
@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, "平台不存在")
|
||||
ok, _lic = licensing.ensure_license(account)
|
||||
if not ok:
|
||||
raise HTTPException(403, "授权已过期(最长离线 7 天),请联网刷新后重试")
|
||||
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)
|
||||
@@ -1,122 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「插件配置 + 插件 UI」路由:带 UI 插件的底座通用约定。
|
||||
|
||||
两块能力(插件包内 ui/ 目录 + 本地配置存取):
|
||||
- GET/POST /api/plugin-config/{pid} per-plugin JSON 配置存取(落执行机本机
|
||||
%LOCALAPPDATA%\\37duAutomation\\plugin_configs\\,账号密码等个性化配置改一次永久生效)
|
||||
- GET /pui/{pid}[/path] 插件自带前端静态托管(源码态与打包态都从
|
||||
plugins/<pid>/ui/ 现读,插件 UI 更新只发插件包、不随壳子发版)
|
||||
鉴权与其他 API 一致:统一账户 cookie 会话(壳子内嵌 iframe 同源自动携带)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS, _PLUGINS_ROOT # noqa: SLF001 插件根单一真源
|
||||
|
||||
router = APIRouter()
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_UI_DIRNAME = "ui" # 插件包内前端目录名(与 plugin.json 的 "ui": true 声明配套)
|
||||
_MIME = {".html": "text/html", ".js": "application/javascript",
|
||||
".mjs": "application/javascript", ".css": "text/css",
|
||||
".json": "application/json", ".map": "application/json",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg",
|
||||
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
|
||||
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain"}
|
||||
|
||||
|
||||
def _check_ui_allowed(plugin_id: str) -> None:
|
||||
"""托管/配置读写的前置校验:插件已加载且在账号白名单内,否则 404(不泄露存在性)。"""
|
||||
try:
|
||||
PLUGINS.find(plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
if _st.ALLOWED is not None and plugin_id not in _st.ALLOWED:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
|
||||
|
||||
# ==================== per-plugin 本地配置存取 ====================
|
||||
def _config_path(plugin_id: str):
|
||||
return config.PLUGIN_CONFIG_DIR / f"{plugin_id}.json"
|
||||
|
||||
|
||||
@router.get("/api/plugin-config/{plugin_id}")
|
||||
def get_plugin_config(plugin_id: str, request: Request):
|
||||
"""读取插件本地配置;从未保存过返回空对象(前端用默认值兜底)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
path = _config_path(plugin_id)
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
@router.post("/api/plugin-config/{plugin_id}")
|
||||
async def save_plugin_config(plugin_id: str, request: Request):
|
||||
"""整体保存插件配置(前端提交完整表单对象,本地原子落盘)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
path = _config_path(plugin_id)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
tmp.replace(path) # 原子替换,避免写一半被读到
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("插件 %s 配置保存失败:%s", plugin_id, exc)
|
||||
raise HTTPException(500, "配置保存失败")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ==================== 插件 UI 静态托管 ====================
|
||||
def _serve_ui(plugin_id: str, rel: str, request: Request) -> FileResponse:
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
ui_root = (_PLUGINS_ROOT / plugin_id / _UI_DIRNAME).resolve()
|
||||
if not ui_root.is_dir():
|
||||
raise HTTPException(404, "该插件未提供前端界面")
|
||||
target = (ui_root / rel).resolve() if rel.strip() else ui_root / "index.html"
|
||||
if not target.is_relative_to(ui_root): # 防路径穿越(..、绝对路径拼接等)
|
||||
raise HTTPException(404, "not found")
|
||||
if target.is_dir():
|
||||
target = target / "index.html"
|
||||
if not target.is_file():
|
||||
# SPA 兜底:未知路径回 index.html(history 路由可用)
|
||||
target = ui_root / "index.html"
|
||||
if not target.is_file():
|
||||
raise HTTPException(404, "not found")
|
||||
media_type = (_MIME.get(target.suffix.lower())
|
||||
or mimetypes.guess_type(str(target))[0] or "application/octet-stream")
|
||||
# index.html 不缓存(插件更新后刷新即生效);带 hash 的静态资源可长缓存
|
||||
headers = {"Cache-Control": "no-cache" if target.name == "index.html"
|
||||
else "public, max-age=86400"}
|
||||
return FileResponse(str(target), media_type=media_type, headers=headers)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}")
|
||||
def plugin_ui_root(plugin_id: str, request: Request):
|
||||
return _serve_ui(plugin_id, "", request)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}/{path:path}")
|
||||
def plugin_ui_file(plugin_id: str, path: str, request: Request):
|
||||
return _serve_ui(plugin_id, path, request)
|
||||
@@ -1,72 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。
|
||||
|
||||
手动启动入口复用 runner.submit_run(与定时任务共用同一执行链路);
|
||||
本文件只承担:登录门槛 + 插件查找 + 授权校验(403 前置门禁)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, submit_run, terminate_run
|
||||
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 = submit_run(account, plugin, req.fields or {})
|
||||
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.post("/api/runs/{run_id}/stop")
|
||||
def stop_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, "运行不存在")
|
||||
if run.get("status") != "running":
|
||||
raise HTTPException(409, "运行已结束,无需停止")
|
||||
if not terminate_run(run_id):
|
||||
raise HTTPException(409, "任务尚未真正启动(排队中或刚结束),请稍候再试")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
@@ -1,105 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「定时任务」路由:增删改查 + 启停;变更后自动备份到中心机(防丢失)。
|
||||
|
||||
- 任务归属创建者账号(配置时登录账号),仅创建者可修改/删除/启停。
|
||||
- cron 为 5 段标准表达式(分 时 日 月 周),由 core.tasks 解析与触发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import tasks as _tasks
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _SchedIn(BaseModel):
|
||||
name: str = ""
|
||||
plugin_id: str = ""
|
||||
fields: dict = {}
|
||||
cron: str = ""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class _ToggleIn(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
def _find_owned(sid: str, account: str) -> dict:
|
||||
"""按 id 取任务并校验归属;不存在/非本人抛 HTTP 异常。"""
|
||||
s = _tasks.get_schedule(sid)
|
||||
if s is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
if s.get("account") != account:
|
||||
raise HTTPException(403, "仅创建者可管理该任务")
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/api/schedules")
|
||||
def sched_list(request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
return {"schedules": _tasks.list_schedules(account)}
|
||||
|
||||
|
||||
@router.post("/api/schedules", status_code=201)
|
||||
def sched_create(b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
if not b.plugin_id:
|
||||
raise HTTPException(400, "请选择插件")
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.create_schedule(account, b.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.put("/api/schedules/{sid}")
|
||||
def sched_update(sid: str, b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if b.plugin_id:
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.update_schedule(sid, b.model_dump(exclude_unset=True))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.delete("/api/schedules/{sid}")
|
||||
def sched_delete(sid: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if not _tasks.delete_schedule(sid):
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/schedules/{sid}/toggle")
|
||||
def sched_toggle(sid: str, b: _ToggleIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
rec = _tasks.toggle_schedule(sid, b.enabled)
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
@@ -1,323 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -1,66 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主配置固化:加载本模块 env(webhost/.env) 并输出全部环境常量与路径。
|
||||
|
||||
依赖方向:config ← 所有领域逻辑与路由模块(只读,不含业务逻辑)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/core/config.py,parents[2]=webhost)
|
||||
# 打包运行(frozen)时:底座根 = exe 所在目录(.env、plugins/ 与 exe 同级部署);
|
||||
# 前端静态资源打包进 exe 内部,运行时从解压目录(_MEIPASS)读取
|
||||
if getattr(sys, "frozen", False):
|
||||
_HOST_ROOT = Path(sys.executable).resolve().parent
|
||||
DIST = Path(getattr(sys, "_MEIPASS", _HOST_ROOT)) / "frontend" / "dist"
|
||||
else:
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[2]
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
PORT = 8799
|
||||
|
||||
# 插件本地配置目录:per-plugin JSON 持久化(账号密码/仓库编码等个性化配置)。
|
||||
# 放 %LOCALAPPDATA% 下:按 Windows 用户隔离、清浏览器缓存不丢、壳子升级不丢。
|
||||
PLUGIN_CONFIG_DIR = (Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_configs")
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = _HOST_ROOT / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
_k, _v = _k.strip(), _v.strip()
|
||||
if _k and _k not in os.environ:
|
||||
os.environ[_k] = _v
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(控制面拉取 + 本地缓存,见 cpapi._resolve_allowed) ====================
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# ==================== 敏感凭证中心化下发(唯一来源:中心机下发/本地加密缓存) ====================
|
||||
# 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉凭证值;
|
||||
# apply_creds 仅保留进程级覆盖存储,供未来每账号敏感值下发能力使用(当前无消费点)。
|
||||
# 启动时由 main.py 调 creds_sync.load() 从中心机拉取(RSA 解密)后经 apply_creds() 注入。
|
||||
_CREDS_OVERRIDE: dict = {}
|
||||
|
||||
|
||||
def apply_creds(values: dict) -> None:
|
||||
"""把中心机下发的敏感凭证写入进程级覆盖 dict(敏感值唯一来源,不做本地 .env 回退)。"""
|
||||
_CREDS_OVERRIDE.update(values or {})
|
||||
@@ -1,147 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。
|
||||
|
||||
底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_ALLOW_CACHE = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_allow.json")
|
||||
|
||||
|
||||
def _save_allowed_cache(ids: set) -> None:
|
||||
"""权限清单落盘缓存(登录拉取时写入,离线/中心机不可达时直接复用)。"""
|
||||
try:
|
||||
_ALLOW_CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_ALLOW_CACHE.write_text(json.dumps(sorted(ids), ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("插件权限清单缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_allowed_cache() -> set | None:
|
||||
"""读权限清单缓存;无缓存/损坏返回 None。"""
|
||||
if not _ALLOW_CACHE.is_file():
|
||||
return None
|
||||
try:
|
||||
raw = json.loads(_ALLOW_CACHE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return {str(x) for x in (raw or [])}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set:
|
||||
"""插件权限白名单(fail-closed,绝不回退全量):控制面拉取 + 本地缓存。
|
||||
|
||||
语义:
|
||||
- 未登录(无恢复会话账号)→ 无权限,返回空集(零权限,不加载任何插件);
|
||||
- 登录过 → 拉取账号插件清单并落盘缓存;后续离线直接复用缓存清单;
|
||||
- 有账号但离线且无缓存 → 空集(无权限依据,fail-closed 防越权)。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return set()
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if not account:
|
||||
_LOGGER.info("未登录(无会话账号),插件零权限加载")
|
||||
return set()
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", account, sorted(allowed) or "(空)")
|
||||
_save_allowed_cache(allowed)
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001 不可达/失败:缓存兜底,无缓存零权限
|
||||
cached = _load_allowed_cache()
|
||||
if cached is not None:
|
||||
_LOGGER.info("权限清单拉取失败,用本地缓存(%s):%s", account, _exc)
|
||||
return cached
|
||||
_LOGGER.warning("权限清单拉取失败且无缓存,插件零权限加载:%s", _exc)
|
||||
return set()
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
"""构造到中心机的调用头:优先带「当前登录账号的云令牌」(登录时中心机签发,中心机
|
||||
_cloud_account 据此定位用户),不再依赖 CONTROLPLANE_TOKEN;X-Admin-User 仅作兜底。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
h = {}
|
||||
account = _sess_account(request)
|
||||
if account:
|
||||
_cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if _cloud_tok:
|
||||
h["Authorization"] = f"Bearer {_cloud_tok}"
|
||||
h["X-Admin-User"] = account
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
逐资源容错:公钥/授权票据/管控清单各自 try,单个接口失败不阻断其余(成功部分照常落盘
|
||||
+ touch_sync),保证一次刷新尽量完整;全部失败也静默,调用方按本地缓存兜底。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
got_any = False
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 公钥拉取失败不阻断授权/管控刷新
|
||||
_LOGGER.warning("中心机公钥拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 授权票据拉取失败不阻断公钥/管控刷新
|
||||
_LOGGER.warning("离线授权票据拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 管控清单拉取失败不阻断公钥/授权刷新
|
||||
_LOGGER.warning("管控清单拉取失败:%s", _exc)
|
||||
if got_any:
|
||||
licensing.flush_offline_reports()
|
||||
@@ -1,61 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证:RSA 密钥对管理(私钥本机持久化,公钥上报中心机用于加密下发)。
|
||||
|
||||
- 首启生成 RSA-2048 密钥对,私钥 PKCS8(PEM) 落盘
|
||||
%LOCALAPPDATA%\\37duAutomation\\creds\\id_rsa.pem(公钥由私钥导出)。
|
||||
- 私钥必须在执行机本机可解(解密中心机下发的敏感凭证),故本机明文存私钥是必要权衡
|
||||
(与现有 %LOCALAPPDATA%\\37duAutomation\\.env 同级保护;如需更高级别可后续加 DPAPI,本期不做)。
|
||||
- 公钥上报中心机后,中心机用它 OAEP-SHA256 逐个加密敏感值下发,本机私钥解密。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_CREDS_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_PRIV_PATH = _CREDS_DIR / "id_rsa.pem"
|
||||
|
||||
|
||||
def _load_or_create() -> rsa.RSAPrivateKey:
|
||||
"""加载本机 RSA 私钥;不存在则生成 RSA-2048 并持久化(重启复用)。"""
|
||||
if _PRIV_PATH.is_file():
|
||||
try:
|
||||
_key = serialization.load_pem_private_key(_PRIV_PATH.read_bytes(), password=None)
|
||||
if isinstance(_key, rsa.RSAPrivateKey):
|
||||
return _key
|
||||
except (ValueError, TypeError, OSError) as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 RSA 私钥失败,重新生成: %s", _exc)
|
||||
_CREDS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
_PRIV_PATH.write_bytes(_key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return _key
|
||||
|
||||
|
||||
_priv = _load_or_create() # 进程内复用同一私钥
|
||||
|
||||
|
||||
def public_key_pem() -> str:
|
||||
"""本机 RSA 公钥 PEM(上报中心机用)。"""
|
||||
return _priv.public_key().public_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
|
||||
|
||||
def decrypt(cipher_b64: str) -> str:
|
||||
"""用本机私钥 OAEP-SHA256 解密密文 base64 → 明文(与服务端 rsa_encrypt 对称)。"""
|
||||
_ct = base64.b64decode(cipher_b64)
|
||||
_pt = _priv.decrypt(_ct, padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(), label=None))
|
||||
return _pt.decode("utf-8")
|
||||
@@ -1,133 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
|
||||
|
||||
流程:
|
||||
sync(): 有登录云令牌且中心机可达 →
|
||||
1. POST /api/admin/creds/register 上报本机 RSA 公钥(幂等 upsert,本人云令牌可登记)
|
||||
2. GET /api/admin/creds (Bearer) 拉取 {key: base64(RSA 密文)}——服务端仅管理员可拉,
|
||||
员工账号 403 会走缓存(本地无密文则为空,不影响业务)
|
||||
3. 本机私钥逐个解密 → 返回明文 dict
|
||||
4. 拉到的密文 JSON 原样写缓存 %LOCALAPPDATA%\\37duAutomation\\creds\\cache.json
|
||||
(落盘的是密文,叠加中心机加密层)
|
||||
load(): 中心机可达走 sync();不可达/无云令牌则读缓存密文用私钥解密(离线可用)。
|
||||
|
||||
敏感键白名单与服务端 config_push._ALLOWED_KEYS 保持一致(仅钉钉开放平台凭证;
|
||||
HR/OA 平台登录账号由本地加密存储 platform_accounts,不经中心机)。
|
||||
钉钉扫码 URL 已由控制面代理构造(/api/dingtalk/login-url),本模块下发的值当前无消费点,
|
||||
链路保留供未来每账号敏感值下发能力使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.creds_store import decrypt, public_key_pem
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 与服务端 apis/config_push.py _ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
|
||||
_ALLOWED_KEYS = (
|
||||
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||
)
|
||||
|
||||
_CACHE_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_CACHE_FILE = _CACHE_DIR / "cache.json"
|
||||
|
||||
|
||||
def _cloud_token(account: str) -> str:
|
||||
"""当前账号的云端会话 token(登录时中心机签发,进程内存态;重启后需重新登录才有)。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
return (_ACCT_CLOUD_TOKEN or {}).get(account) or ""
|
||||
|
||||
|
||||
def _headers(account: str) -> dict:
|
||||
h = {"Authorization": f"Bearer {_cloud_token(account)}"}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _save_cache(encrypted: dict) -> None:
|
||||
"""密文 JSON 原样落盘(落盘的是密文,叠加中心机加密层;离线用私钥解密)。"""
|
||||
try:
|
||||
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_CACHE_FILE.write_text(json.dumps(encrypted, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("敏感凭证缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
"""读缓存密文并用本机私钥解密为明文 dict;缺失/解密失败返回空 dict(不阻断)。"""
|
||||
if not _CACHE_FILE.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(_CACHE_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
out = {}
|
||||
for _k, _b64 in (raw or {}).items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception: # noqa: BLE001 单值解密失败跳过(如密钥更换后旧缓存)
|
||||
_LOGGER.warning("敏感凭证缓存解密失败: %s", _k)
|
||||
return out
|
||||
|
||||
|
||||
def sync(account: str) -> dict | None:
|
||||
"""中心机在线拉取并解密敏感凭证,返回明文 dict;不可用返回 None(走缓存兜底)。"""
|
||||
if not config.CONTROLPLANE_URL or not account or not _cloud_token(account):
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
# 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
|
||||
r = requests.post(f"{config.CONTROLPLANE_URL}/api/admin/creds/register",
|
||||
json={"account": account, "pubkey_pem": public_key_pem()},
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
# 2. 拉取加密后的敏感凭证
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/admin/creds",
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
encrypted = r.json().get("creds") or {}
|
||||
except Exception as _exc: # noqa: BLE001 中心机不可达/鉴权失败 → 走缓存
|
||||
_LOGGER.warning("中心机敏感凭证拉取失败(用本地缓存): %s", _exc)
|
||||
return None
|
||||
if not encrypted:
|
||||
return {}
|
||||
# 3. 本机私钥逐个解密
|
||||
out = {}
|
||||
for _k, _b64 in encrypted.items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception as _exc: # noqa: BLE001 单值解密失败跳过
|
||||
_LOGGER.warning("敏感凭证解密失败: %s", _k)
|
||||
# 4. 密文原样落盘缓存(离线复用)
|
||||
_save_cache(encrypted)
|
||||
return out
|
||||
|
||||
|
||||
def load(account: str = "") -> dict:
|
||||
"""获取当前账号敏感凭证明文:中心机可达走 sync();否则读缓存密文解密(离线可用)。
|
||||
|
||||
返回 dict[key]=明文,仅含成功解密项;空 dict 表示无可用的下发值(不阻断启动)。
|
||||
"""
|
||||
account = account or config.CONTROLPLANE_ACCOUNT
|
||||
if not account:
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = _sess_active_account()
|
||||
synced = sync(account)
|
||||
if synced is not None:
|
||||
return synced
|
||||
cached = _load_cache()
|
||||
if cached:
|
||||
_LOGGER.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)")
|
||||
return cached
|
||||
@@ -1,47 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。
|
||||
run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._clients: list = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def bind(self, loop: asyncio.AbstractEventLoop):
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, websocket) -> None:
|
||||
await websocket.accept()
|
||||
with self._lock:
|
||||
self._clients.append(websocket)
|
||||
try:
|
||||
await websocket.receive_text() # 挂起直到客户端断开
|
||||
finally:
|
||||
with self._lock:
|
||||
self._clients.remove(websocket)
|
||||
|
||||
def publish(self, event: Dict) -> None:
|
||||
if self._loop is None:
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(self._send(event), self._loop)
|
||||
|
||||
async def _send(self, event: Dict) -> None:
|
||||
with self._lock:
|
||||
clients = list(self._clients)
|
||||
for ws in clients:
|
||||
try:
|
||||
await ws.send_json(event)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._clients.remove(ws)
|
||||
|
||||
|
||||
HUB = Hub()
|
||||
@@ -1,329 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
|
||||
|
||||
职责(对应架构设计七、八节):
|
||||
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
|
||||
license.json (离线授权票据,Ed25519 签名,离线一直有效)
|
||||
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
|
||||
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
|
||||
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
|
||||
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
|
||||
- verify_license() / verify_control() —— 用缓存公钥离线验签。
|
||||
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
KEYS_DIR = _APP_DATA / "keys"
|
||||
license_path = _APP_DATA / "license.json"
|
||||
control_path = _APP_DATA / "control.json"
|
||||
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
|
||||
|
||||
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
|
||||
_ONLINE_TTL = 180
|
||||
_last_sync = 0.0
|
||||
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
|
||||
|
||||
_CONTROLPLANE_URL = "" # 由 main.py 注入
|
||||
|
||||
|
||||
def init(controlplane_url: str, sync_lock) -> None:
|
||||
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
|
||||
global _CONTROLPLANE_URL, _sync_lock
|
||||
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
|
||||
_sync_lock = sync_lock
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
KEYS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
# ==================== 联网判定 ====================
|
||||
def touch_sync() -> None:
|
||||
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
|
||||
global _last_sync
|
||||
with _sync_lock:
|
||||
_last_sync = time.time()
|
||||
|
||||
|
||||
def is_online() -> bool:
|
||||
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
|
||||
with _sync_lock:
|
||||
return (time.time() - _last_sync) <= _ONLINE_TTL
|
||||
|
||||
|
||||
# ==================== 公钥缓存与验签 ====================
|
||||
def _pub_pem_path() -> Path:
|
||||
return KEYS_DIR / "pub.pem"
|
||||
|
||||
|
||||
def cache_public_key(pem_text: str) -> None:
|
||||
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
|
||||
pem_text = (pem_text or "").strip()
|
||||
if not pem_text:
|
||||
return
|
||||
_pub_pem_path().write_text(pem_text, encoding="ascii")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def _load_public_key() -> Ed25519PublicKey | None:
|
||||
try:
|
||||
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
|
||||
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
|
||||
return None
|
||||
|
||||
|
||||
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
"""验签返回 payload;签名非法抛 ValueError。"""
|
||||
if "." not in blob:
|
||||
raise ValueError("bad blob")
|
||||
b64, sig64 = blob.rsplit(".", 1)
|
||||
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
|
||||
|
||||
def verify_license() -> dict:
|
||||
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
|
||||
if not license_path.is_file():
|
||||
raise ValueError("无本地授权票据(license.json)")
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
raise ValueError("缺少中心机公钥,无法验签授权票据")
|
||||
data = json.loads(license_path.read_text(encoding="utf-8"))
|
||||
return _verify_blob(data["ticket"], pub)
|
||||
|
||||
|
||||
def verify_control() -> dict:
|
||||
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
|
||||
if not control_path.is_file():
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
try:
|
||||
data = json.loads(control_path.read_text(encoding="utf-8"))
|
||||
payload = _verify_blob(data["ticket"], pub)
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
|
||||
|
||||
# ==================== 授权周期(离线最多 LICENSE_TTL_DAYS 天) ====================
|
||||
def license_status() -> tuple[str, dict | None]:
|
||||
"""本地授权票据状态:("ok", payload) / ("missing", None) / ("invalid", None) / ("expired", payload)。
|
||||
|
||||
过期判定以票据内 expiresAt(控制面签发,issuedAt + 7 天)为基准;缺该字段一律视为过期
|
||||
(fail-safe,触发联网刷新,不因旧票据而永久放行)。
|
||||
"""
|
||||
if not license_path.is_file():
|
||||
return ("missing", None)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except ValueError:
|
||||
return ("invalid", None)
|
||||
exp = lic.get("expiresAt")
|
||||
if not exp or time.time() > int(exp):
|
||||
return ("expired", lic)
|
||||
return ("ok", lic)
|
||||
|
||||
|
||||
def ensure_license(account: str) -> tuple[bool, dict | None]:
|
||||
"""确保本地授权票据可用且属于当前账号:ok → (True, payload);否则联网刷新一次后复查。
|
||||
|
||||
票据必须与登录账号一致:票据只按 expiresAt 判过期,换账号登录后旧票仍在有效期内,
|
||||
沿用旧票会让「个人中心可见插件」与「运行门禁」停留在上一账号的授权快照
|
||||
(表现为换账号后显示"暂无可用插件"),故账号不匹配一律视为不可用并强制刷新。
|
||||
刷新失败(离线/控制面不可达)→ (False, None)。这是「可见性/运行/平台登录」的统一授权门禁,
|
||||
过期且实际在线时会自动刷新恢复(用户无感),离线则拒绝并提示联网刷新。
|
||||
"""
|
||||
status, payload = license_status()
|
||||
if status == "ok" and (payload or {}).get("userId") == account:
|
||||
return True, payload
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing # 延迟导入,避免模块环
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 联网刷新失败(离线/控制面不可达)
|
||||
_LOGGER.warning("授权票据联网刷新失败(离线或控制面不可达):%s", _exc)
|
||||
status, payload = license_status()
|
||||
return (status == "ok" and (payload or {}).get("userId") == account), payload
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
def save_license(ticket_json: dict | str) -> None:
|
||||
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
license_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def save_control(ticket_json: dict | str) -> None:
|
||||
"""持久化管控清单缓存。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
control_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
|
||||
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
|
||||
|
||||
- 授权周期:本地票据须有效(7 天窗口,见 ensure_license);缺失/过期先联网刷新一次,
|
||||
仍不可用则拒绝(离线超期必须联网更新票据)。
|
||||
- 验签授权票据,校验该插件 canRun。
|
||||
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
|
||||
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
|
||||
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
|
||||
"""
|
||||
ok, lic = ensure_license(account)
|
||||
if not ok:
|
||||
return "授权已过期(最长离线 7 天),请联网刷新后重试"
|
||||
|
||||
control = verify_control()
|
||||
if plugin_id in control.get("revokedPlugins", []):
|
||||
return "插件已被下架(revoked),禁止运行"
|
||||
if plugin_id in control.get("disabledPlugins", []):
|
||||
return "插件已被禁用(disabled),禁止运行"
|
||||
|
||||
lic_plugins = {p.get("pluginId"): p for p in (lic or {}).get("plugins", [])}
|
||||
grant = lic_plugins.get(plugin_id)
|
||||
if not grant:
|
||||
return f"账号 {account} 无插件「{plugin_id}」的授权"
|
||||
if not grant.get("canRun"):
|
||||
return f"账号 {account} 无「{plugin_id}」的运行授权"
|
||||
|
||||
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
|
||||
if online:
|
||||
forced = next((f for f in control.get("forcedUpdates", [])
|
||||
if f.get("pluginId") == plugin_id), None)
|
||||
if forced:
|
||||
min_ver = forced.get("minVersion", "")
|
||||
deadline = forced.get("deadline", "")
|
||||
if min_ver and deadline and _deadline_passed(deadline):
|
||||
installed = _installed_version(plugin_id)
|
||||
if installed and _version_lt(installed, min_ver):
|
||||
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
|
||||
f"当前 v{installed} 已禁止启动,请先更新")
|
||||
return None
|
||||
|
||||
|
||||
def _installed_version(plugin_id: str) -> str:
|
||||
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
|
||||
act = _APP_DATA / "active.json"
|
||||
try:
|
||||
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
|
||||
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _deadline_passed(deadline: str) -> bool:
|
||||
try:
|
||||
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
|
||||
return datetime.now(dt.tzinfo) > dt
|
||||
except Exception: # noqa: BLE001
|
||||
# 解析失败时按未过期兜底(不误伤在线用户)
|
||||
return False
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""版本比较:数字段按 int,非数字段按 str 小写。"""
|
||||
def _k(s):
|
||||
try:
|
||||
return (1, int(s))
|
||||
except ValueError:
|
||||
return (0, str(s).lower())
|
||||
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
|
||||
|
||||
|
||||
# ==================== 运行上报 ====================
|
||||
def report(account: str, device_id: str, plugin_id: str, version: str,
|
||||
status: str, msg: str = "", duration_sec: int = 0) -> None:
|
||||
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
|
||||
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
|
||||
"version": version, "status": status, "msg": msg,
|
||||
"duration_sec": int(duration_sec),
|
||||
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
||||
if not _CONTROLPLANE_URL:
|
||||
return
|
||||
if _push_report(rec):
|
||||
touch_sync()
|
||||
return
|
||||
# 离线:暂存待补报
|
||||
try:
|
||||
with open(reports_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _push_report(rec: dict) -> bool:
|
||||
"""同步上报一条到中心机;成功返回 True。"""
|
||||
try:
|
||||
_push_via_tempfile(rec) # 用 go-offset 方式直连
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _push_via_tempfile(rec: dict) -> None:
|
||||
"""向 /api/runtime/report 的同步 POST(requests)。
|
||||
必须带 X-API-Token 内部凭证:中心机 CONTROLPLANE_TOKEN 非空时该接口强制校验,
|
||||
无头 POST 一律 401(此前运行上报全部静默失败落离线暂存、补报同样无头永远补不上),
|
||||
与 cpapi.py 各接口的头注入保持一致。"""
|
||||
import requests
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
|
||||
json=rec, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
|
||||
|
||||
def flush_offline_reports() -> int:
|
||||
"""重连后补报此前暂存的离线记录;返回补报条数。"""
|
||||
if not reports_path.is_file():
|
||||
return 0
|
||||
sent = 0
|
||||
pending = []
|
||||
try:
|
||||
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
|
||||
for ln in lines:
|
||||
try:
|
||||
rec = json.loads(ln)
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
_push_via_tempfile(rec)
|
||||
sent += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pending.append(ln) # 仍失败则保留下次再补
|
||||
if not pending:
|
||||
reports_path.unlink(missing_ok=True) # 全部成功则清空
|
||||
else:
|
||||
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return sent
|
||||
@@ -1,98 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主插件元数据 / 平台权限解析。
|
||||
|
||||
- 插件元数据由 plugin.json(manifest) 驱动,离线与旧插件兼容
|
||||
- 平台/插件白名单来自中心机,按账号过滤(三态降级:授权集 / 空集防越权 / None 离线兜底全量)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
"""组装插件元数据(manifest 驱动)。
|
||||
|
||||
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
|
||||
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
|
||||
"""
|
||||
manifest = _read_own_manifest(p)
|
||||
name = (manifest or {}).get("name") or p.name
|
||||
description = (manifest or {}).get("description")
|
||||
if description is None:
|
||||
description = p.description
|
||||
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
|
||||
if fields is None:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name,
|
||||
# 版本优先取 plugin.json 的 version(与发布包一致),缺 manifest 时回退类的默认值
|
||||
"version": (manifest or {}).get("version") or p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"ui": bool((manifest or {}).get("ui")),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
def _read_own_manifest(p) -> dict | None:
|
||||
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
|
||||
try:
|
||||
mod = sys.modules.get(type(p).__module__)
|
||||
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
|
||||
if not jar or not jar.is_file():
|
||||
return None
|
||||
return json.loads(jar.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _fields_from_schema(schema: dict) -> list | None:
|
||||
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
|
||||
if not schema or schema.get("type") != "object" or not schema.get("properties"):
|
||||
return None
|
||||
out = []
|
||||
for key, prop in schema["properties"].items():
|
||||
item = {"key": key, "label": prop.get("title", key),
|
||||
"default": prop.get("default", "")}
|
||||
t = prop.get("type", "string")
|
||||
if t == "integer" or t == "number":
|
||||
item["type"] = "int"
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
elif t == "string" and prop.get("format") == "password":
|
||||
item["type"] = "password"
|
||||
elif t == "array":
|
||||
# 多选:items.enum 为预设选项;无 enum 则纯自由输入(前端 tags 可自建条目)
|
||||
item["type"] = "multiselect"
|
||||
if isinstance(prop.get("items"), dict) and "enum" in prop["items"]:
|
||||
item["options"] = prop["items"]["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
if d:
|
||||
item["description"] = d
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
@@ -1,242 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
# utf-8-sig:防 plugin.json 带 UTF-8 BOM(json.loads 遇 BOM 会抛 JSONDecodeError → 误判为新装重下)
|
||||
return str(json.loads(mf.read_text(encoding="utf-8-sig")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
@@ -1,273 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||||
|
||||
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
|
||||
由 Windows Job Object 整树托管(含浏览器孙进程)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import scheduler as _scheduler
|
||||
from webhost.backend.core import winjob as _winjob
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import state as _st
|
||||
from webhost.backend.core.hub import HUB
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
"""启动一次插件运行(手动 POST /api/runs 与定时任务共用入口)。
|
||||
|
||||
- 登记运行记录 + 广播 run_start + 上报 start;
|
||||
- 后台线程执行:命名空间并发闸(同平台串行)→ 设备级单活(排队等待当前插件结束)
|
||||
→ 拉起执行子进程;启动失败回滚单活槽位并广播 run_done(error)。
|
||||
返回 run_id。
|
||||
"""
|
||||
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():
|
||||
if _is_user_stopped(run_id):
|
||||
# 排队期间用户已点停止:不真正拉起插件,抛异常让 request_start 回滚单活槽位,
|
||||
# 由下方 !ok 分支把 run 落为"用户手动强制停止",避免"看似取消实际还在跑"。
|
||||
raise RuntimeError("用户已取消该排队任务")
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
err = r.get("error") or "启动失败"
|
||||
if _is_user_stopped(run_id):
|
||||
err = "用户手动强制停止"
|
||||
with _STOP_LOCK:
|
||||
_USER_STOPPED.discard(run_id)
|
||||
_st._set_run(run_id, status="error", result=None, error=err)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": err})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
|
||||
# ==================== 手动强制停止 ====================
|
||||
# run_id → 执行中 Job 句柄(供 POST /api/runs/{id}/stop 整树强杀,含浏览器孙进程)
|
||||
_ACTIVE: dict = {}
|
||||
_ACTIVE_LOCK = threading.Lock()
|
||||
_USER_STOPPED: set = set()
|
||||
_STOP_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def terminate_run(run_id: str) -> bool:
|
||||
"""手动终止运行:登记停止标记并整树强杀 Job。返回是否已找到并触发终止。"""
|
||||
with _ACTIVE_LOCK:
|
||||
job = _ACTIVE.get(run_id)
|
||||
with _STOP_LOCK:
|
||||
_USER_STOPPED.add(run_id)
|
||||
if job is None:
|
||||
return False # 尚未真正拉起执行子进程(排队中)或已结束
|
||||
try:
|
||||
job.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _is_user_stopped(run_id: str) -> bool:
|
||||
with _STOP_LOCK:
|
||||
return run_id in _USER_STOPPED
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
# 打包运行(frozen):拉起同级 37du-host-runner.exe(console 壳,内置同一套执行代码)
|
||||
if getattr(sys, "frozen", False):
|
||||
runner_exe = Path(sys.executable).with_name("37du-host-runner.exe")
|
||||
cmd = [str(runner_exe), "--plugin", plugin.id, "--run", run_id]
|
||||
root = Path(sys.executable).resolve().parent
|
||||
else:
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
# 子进程 stdio 编码统一 UTF-8:默认跟随 Windows locale(GBK) 会导致
|
||||
# stderr 中文 traceback 变 mojibake、stdin JSON 中文解出孤立代理字符
|
||||
_child_env = dict(os.environ)
|
||||
_child_env["PYTHONIOENCODING"] = "utf-8"
|
||||
_child_env["PYTHONUTF8"] = "1"
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace", env=_child_env,
|
||||
# 抑制宿主进程的控制台窗口(runner.exe 为 console 子系统),
|
||||
# 同时 stdout/stderr 走 PIPE 捕获不受影响
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
)
|
||||
job.assign(proc)
|
||||
with _ACTIVE_LOCK:
|
||||
_ACTIVE[run_id] = job # 登记句柄,供手动强制停止整树强杀
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_st._set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif _is_user_stopped(run_id):
|
||||
msg = "用户手动强制停止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
with _ACTIVE_LOCK:
|
||||
_ACTIVE.pop(run_id, None)
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||||
try:
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id) or {}
|
||||
account = run.get("account", "")
|
||||
status = "done" if run.get("status") == "done" else \
|
||||
("running" if run.get("status") == "running" else "error")
|
||||
msg = run.get("error") or ""
|
||||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||||
licensing.report(account=account, device_id="",
|
||||
plugin_id=plugin_id, version=run.get("version", ""),
|
||||
status=status, msg=msg, duration_sec=duration)
|
||||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||||
_LOGGER.warning("运行上报失败:%s", _exc)
|
||||
@@ -1,120 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""设备级单活调度器:整机同一时刻只运行一个插件进程。
|
||||
|
||||
- active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。
|
||||
- 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。
|
||||
- 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活;
|
||||
启动失败回滚到"空闲",不让半激活状态阻塞后续启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
ACTIVE_PATH = _APP_DATA / "active.json"
|
||||
|
||||
# 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。
|
||||
_SCHED_COND = threading.Condition()
|
||||
|
||||
|
||||
def init_active() -> None:
|
||||
"""初始化 active.json(无则写入空闲态),并确保数据目录可写。
|
||||
进程启动时若残留 running/switching(上次异常退出/断电),复位为空闲,
|
||||
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
if not ACTIVE_PATH.is_file():
|
||||
write_active(userId="", pluginId="", version="", status="idle")
|
||||
elif read_active().get("status") in ("running", "switching"):
|
||||
_LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲")
|
||||
write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="")
|
||||
|
||||
|
||||
def read_active() -> dict:
|
||||
try:
|
||||
d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {}
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def _is_busy() -> bool:
|
||||
return read_active().get("status") in ("running", "switching")
|
||||
|
||||
|
||||
def write_active(**kw) -> None:
|
||||
"""写回 active.json(保留既有键,仅更新传入字段)。"""
|
||||
d = read_active()
|
||||
d.update(kw)
|
||||
d.setdefault("userId", "")
|
||||
d.setdefault("pluginId", "")
|
||||
d.setdefault("version", "")
|
||||
d.setdefault("status", "idle")
|
||||
d.setdefault("startedAt", "")
|
||||
d.setdefault("runId", "")
|
||||
try:
|
||||
# 原子写:先写临时文件再 os.replace,避免写入中断留下半截 JSON 被误读
|
||||
tmp = ACTIVE_PATH.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
|
||||
os.replace(tmp, ACTIVE_PATH)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("写 active.json 失败:%s", _exc)
|
||||
|
||||
|
||||
def current() -> dict:
|
||||
"""当前活动插件(空闲则返回空映射)。"""
|
||||
return read_active()
|
||||
|
||||
|
||||
def is_active(plugin_id: str) -> bool:
|
||||
"""当前设备是否正在跑该插件。"""
|
||||
a = read_active()
|
||||
return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id)
|
||||
|
||||
|
||||
def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict:
|
||||
"""设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。
|
||||
|
||||
- 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。
|
||||
- `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。
|
||||
- 启动失败回滚到"空闲"并唤醒等待者。
|
||||
"""
|
||||
with _SCHED_COND:
|
||||
while _is_busy():
|
||||
_SCHED_COND.wait()
|
||||
write_active(status="switching", startedAt=_now())
|
||||
try:
|
||||
run_id = start_fn()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
return {"ok": False, "error": f"启动失败:{_exc}"}
|
||||
write_active(userId=user, pluginId=plugin_id, version=version,
|
||||
status="running", runId=run_id, startedAt=_now())
|
||||
return {"ok": True, "run_id": run_id}
|
||||
|
||||
|
||||
def mark_done(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。"""
|
||||
with _SCHED_COND:
|
||||
a = read_active()
|
||||
if a.get("pluginId") == plugin_id and a.get("runId") == run_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
elif a.get("pluginId") == plugin_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
@@ -1,97 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
|
||||
|
||||
会话状态(token->account 活跃ts)只在此模块定义;admin/dingtalk/meta 等路由经本模块访问。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
|
||||
_SESS_TTL = 7 * 24 * 3600
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
|
||||
# 打包运行(frozen)时落盘到 exe 同级目录
|
||||
_SESS_FILE = (Path(sys.executable).resolve().parent if getattr(sys, "frozen", False)
|
||||
else Path(__file__).resolve().parents[1]) / "_cp_sessions.json"
|
||||
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _sess_persist():
|
||||
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
|
||||
try:
|
||||
with _SESS_LOCK:
|
||||
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
|
||||
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("本机会话持久化失败: %s", _exc)
|
||||
|
||||
|
||||
def _sess_load():
|
||||
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
|
||||
if not _SESS_FILE.is_file():
|
||||
return
|
||||
try:
|
||||
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
_now = time.time()
|
||||
with _SESS_LOCK:
|
||||
for _t, _it in (_raw or {}).items():
|
||||
try:
|
||||
_a, _ts = _it[0], float(_it[1])
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
continue
|
||||
if _now - _ts <= _SESS_TTL:
|
||||
_SESS[_t] = (_a, _ts)
|
||||
|
||||
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
account = ""
|
||||
with _SESS_LOCK:
|
||||
item = _SESS.get(token)
|
||||
if item:
|
||||
_account, _ts = item
|
||||
if time.time() - _ts <= _SESS_TTL:
|
||||
_SESS[token] = (_account, time.time()) # 滑动续期
|
||||
account = _account
|
||||
else:
|
||||
_SESS.pop(token, None)
|
||||
if account:
|
||||
_sess_persist() # 滑动续期也落盘,重启后仍有效
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
def _sess_active_account() -> str:
|
||||
"""取最近活跃的本机会话账号(重启恢复的会话;CONTROLPLANE_ACCOUNT 不再配置时的兜底)。"""
|
||||
with _SESS_LOCK:
|
||||
items = sorted(_SESS.values(), key=lambda _it: _it[1], reverse=True)
|
||||
return items[0][0] if items else ""
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -1,338 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检查:启动时/每 30 分钟/手动"检查更新",只比对控制面 /api/shell/version,
|
||||
秒级返回"有新版/已是最新/不可达",不下载大包。发现新版后由前端提示用户,
|
||||
由用户决定是否下载(不默默后台拉包)。
|
||||
2. 下载:用户点击"立即下载" → 后台流式下载到
|
||||
%LOCALAPPDATA%\\37duAutomation\\shell\\(先写 .part 临时文件,完成校验后改名),
|
||||
进度(已下载/总量/百分比)写入状态供前端轮询展示。
|
||||
3. 应用:下载完成后前端提示"重启更新",用户点击 → apply_update() 运行安装包
|
||||
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
|
||||
安装完成由 [Run] 自动重启新版本主程序。
|
||||
4. 离线/控制面不可达/校验失败:状态记录错误原因,前端提示,不影响使用。
|
||||
|
||||
并发控制:检查与下载各持独立锁(检查是 5s 的版本接口,下载是数百 MB 大包,
|
||||
两者互不阻塞)。下载内部再防重入,避免重复拉包。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
|
||||
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
|
||||
|
||||
# 检查互斥锁:启动/周期/手动三入口共用,检查期间视为"检查中"(pending_status.checking)
|
||||
_CHECK_LOCK = threading.Lock()
|
||||
# 下载互斥锁:防止并发重复下载同一大包
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
|
||||
# 运行态(供前端轮询 update-status)
|
||||
_STATE: dict = {
|
||||
# 版本检查
|
||||
"checking": False, # 版本检查进行中(秒级,很快结束)
|
||||
"check_at": 0.0, # 最近一次检查完成时间
|
||||
"latest": "", # 云端最新版本
|
||||
"notes": "", # 云端最新版本更新说明
|
||||
"available": False, # 检测到可用新版本(当前 < 云端 且 尚未下载完成)
|
||||
"check_error": "", # 检查失败原因(控制面不可达/源码模式等)
|
||||
# 下载(流式,带进度)
|
||||
"dl_version": "", # 正在下载/刚下载完成的版本
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0, # 已下载字节
|
||||
"dl_total": 0, # 总字节(0 = 未知,无法算百分比)
|
||||
"dl_pct": 0, # 0-100
|
||||
"dl_error": "", # 下载失败原因
|
||||
"applying": False, # 正在静默安装升级
|
||||
}
|
||||
|
||||
_PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。
|
||||
用 utf-8-sig 读取:防文件带 UTF-8 BOM(记事本另存 UTF-8 时常见),否则会读到
|
||||
"\\ufeff1.2.0" 导致版本比对永远判为"不大于"(P1 修复:壳子升级失效根因)。"""
|
||||
if not getattr(sys, "frozen", False):
|
||||
return ""
|
||||
vf = Path(sys.executable).resolve().parent / "shell.version"
|
||||
try:
|
||||
return vf.read_text(encoding="utf-8-sig").strip() if vf.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def fetch_cloud_version() -> dict | None:
|
||||
"""拉取控制面壳子版本信息;非打包运行/未配置/不可达返回 None(失败原因记入 _STATE)。"""
|
||||
if not local_shell_version() or not config.CONTROLPLANE_URL:
|
||||
_STATE["check_error"] = "源码开发模式,不参与自更新" if not local_shell_version() else "未配置中心机地址"
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
|
||||
headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001 离线/不可达
|
||||
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
|
||||
_STATE["check_error"] = f"控制面不可达({_exc.__class__.__name__})"
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 检查(只比对版本,不下载) =====================
|
||||
|
||||
def check_update() -> None:
|
||||
"""只检查版本:比对控制面最新版,写入 _STATE。秒级完成,不下载大包。"""
|
||||
if not _CHECK_LOCK.acquire(blocking=False):
|
||||
return # 已有检查在进行,沿用其状态
|
||||
try:
|
||||
_STATE["checking"] = True
|
||||
cur = local_shell_version()
|
||||
info = fetch_cloud_version()
|
||||
_STATE["check_at"] = time.time()
|
||||
if not cur:
|
||||
_STATE["latest"] = ""
|
||||
_STATE["notes"] = ""
|
||||
_STATE["available"] = False
|
||||
return
|
||||
if not info:
|
||||
_STATE["available"] = False
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
notes = str(info.get("notes") or "")
|
||||
_STATE["latest"] = cloud
|
||||
_STATE["notes"] = notes
|
||||
_STATE["check_error"] = ""
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
# 已是最新:清掉"待下载"占位(若之前处于 failed,供用户重试的 available 也置 False)
|
||||
_STATE["available"] = False
|
||||
return
|
||||
_STATE["available"] = True
|
||||
# 缓存中已有该版本安装包 → 恢复为"已下载待应用",提示重启更新
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, notes)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
_CHECK_LOCK.release()
|
||||
|
||||
|
||||
def _restore_pending(cloud: str, notes: str) -> None:
|
||||
"""把已落盘的安装包恢复为待应用状态(重启后/下载完成后沿用)。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
_PENDING_VERSION = cloud
|
||||
_PENDING_NOTES = notes
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_LOGGER.info("壳子新版本 %s 已在缓存中,等待用户重启更新", cloud)
|
||||
|
||||
|
||||
def start_check() -> None:
|
||||
"""后台线程触发一次检查(启动/手动入口):立即返回,结果经 pending_status 轮询获取。"""
|
||||
threading.Thread(target=check_update, daemon=True, name="shell-check").start()
|
||||
|
||||
|
||||
def start_periodic_check(interval: int = _PERIODIC_INTERVAL) -> None:
|
||||
"""常驻周期检查:壳子长开时也能自动发现新版本(只比对版本,不自动下载)。"""
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
check_update()
|
||||
except Exception as _exc: # noqa: BLE001 周期失败不中断循环
|
||||
_LOGGER.warning("周期检查壳子更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_loop, daemon=True, name="shell-check-loop").start()
|
||||
|
||||
|
||||
# ===================== 下载(流式 + 进度) =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载新版本安装包(后台线程)。已有下载/已完成则直接沿用,不重复拉包。"""
|
||||
cur = local_shell_version()
|
||||
if not cur:
|
||||
return
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_VERSION:
|
||||
return
|
||||
info = fetch_cloud_version()
|
||||
if not info:
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
return
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
return
|
||||
# 占位防重入,随后后台流式下载
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(cloud, info), daemon=True,
|
||||
name="shell-download").start()
|
||||
_LOGGER.info("开始下载壳子新版本 %s", cloud)
|
||||
|
||||
|
||||
def _download(cloud: str, info: dict) -> None:
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(cloud, info)
|
||||
except Exception as _exc: # noqa: BLE001 下载异常兜底
|
||||
_LOGGER.exception("下载壳子安装包异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
|
||||
|
||||
def _download_locked(cloud: str, info: dict) -> None:
|
||||
import requests
|
||||
|
||||
# 中心机 version 接口新增 url 字段:有则直连内网文件服务器下载大包(无鉴权);
|
||||
# 为空回退中心机 /api/shell/pkg(该路径带 X-API-Token)。
|
||||
inner_url = (info.get("url") or "").strip()
|
||||
if inner_url:
|
||||
url = inner_url
|
||||
dl_headers = {}
|
||||
else:
|
||||
url = f"{config.CONTROLPLANE_URL}/api/shell/pkg"
|
||||
dl_headers = _headers()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
tmp = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part"
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
try:
|
||||
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, headers=dl_headers, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
|
||||
|
||||
def _cleanup_part(cloud: str) -> None:
|
||||
try:
|
||||
(_SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part").unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def cached_pkg(version: str) -> Path | None:
|
||||
"""本地缓存的指定版本安装包路径;不存在返回 None。"""
|
||||
p = _SHELL_CACHE / f"setup-37du-host-{version}.exe"
|
||||
return p if p.is_file() else None
|
||||
|
||||
|
||||
def pending_status() -> dict:
|
||||
"""当前更新状态(供前端展示与轮询):兼容旧字段,并补充下载进度/可用版本。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
cur = local_shell_version()
|
||||
downloaded = bool(_PENDING_VERSION) and cached_pkg(_PENDING_VERSION) is not None
|
||||
if not downloaded:
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
return {
|
||||
"current": cur,
|
||||
"new": _PENDING_VERSION if downloaded else "",
|
||||
"notes": _PENDING_NOTES if downloaded else "",
|
||||
"downloaded": downloaded,
|
||||
"available": bool(_STATE["available"]),
|
||||
"latest": _STATE.get("latest", ""),
|
||||
"checked_at": _STATE.get("check_at", 0),
|
||||
"checking": bool(_STATE.get("checking", False)),
|
||||
"error": _STATE.get("check_error", ""),
|
||||
"applying": bool(_STATE.get("applying", False)),
|
||||
"dl": {
|
||||
"version": _STATE.get("dl_version", ""),
|
||||
"status": _STATE.get("dl_status", "idle"),
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def apply_update() -> None:
|
||||
"""运行新版安装包静默覆盖安装并退出本进程(升级完成后由 Inno 重启新版本)。
|
||||
|
||||
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
|
||||
"""
|
||||
version = _PENDING_VERSION
|
||||
pkg = cached_pkg(version)
|
||||
if not pkg:
|
||||
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
|
||||
_STATE["applying"] = True
|
||||
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
time.sleep(1) # 给安装器接管进程,随后退出让 Inno CloseApplications 收尾
|
||||
os._exit(0)
|
||||
@@ -1,52 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。
|
||||
|
||||
- ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写
|
||||
(`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`),
|
||||
避免 from-import 复制绑定读不到最新值。
|
||||
- RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。
|
||||
依赖方向:state ← 领域逻辑与路由模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
|
||||
def set_allowed(v: set | None) -> None:
|
||||
global ALLOWED
|
||||
ALLOWED = v
|
||||
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
@@ -1,427 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主定时任务(壳子内置定时):按 cron 触发插件运行。
|
||||
|
||||
- 配置真源:%LOCALAPPDATA%\\37duAutomation\\schedules.json(按账号隔离,任务归属创建者账号)。
|
||||
- 触发链路与手动 POST /api/runs 完全一致(runner.submit_run):
|
||||
命名空间并发闸 + 设备级单活排队 + 授权/下架/禁用/强制更新校验(licensing.run_check_allowed)。
|
||||
- 变更即备份:增删改/启停后把该账号全量配置推送到中心机(/api/schedules/backup);
|
||||
本地缺失时启动按账号从服务端合并恢复(见 restore_from_cloud),配置不丢失。
|
||||
- 后台线程每 30s 检查一次,到点触发;last_run_at 记忆上次触发时刻,
|
||||
壳子重启后错过的触发点会立即补跑(last_run_at 之前的值保留,不重复触发同一时刻)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
_SCHED_FILE = _APP_DATA / "schedules.json"
|
||||
|
||||
_TICK_SECS = 30 # 后台检查周期(秒)
|
||||
_DENY_LOG_CD = 300 # 同一任务触发被拒后,拒绝日志的最小间隔(秒),避免离线时刷屏
|
||||
_STARTED = False
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE
|
||||
_SCHEDULES: list = []
|
||||
# 任务 id → 上次打印"触发被拒"日志的时间戳(节流用)
|
||||
_deny_log_ts: dict = {}
|
||||
|
||||
|
||||
# ==================== 标准 5 段 cron 解析 ====================
|
||||
# 字段顺序:分 时 日 月 周(minute hour day-of-month month day-of-week)
|
||||
def _parse_field(spec: str, lo: int, hi: int) -> set:
|
||||
"""解析单个 cron 字段为命中集合;支持 * ? */n a-b a-b/n 与逗号列表。非法抛 ValueError。"""
|
||||
if spec in ("*", "?"):
|
||||
return set(range(lo, hi + 1))
|
||||
out: set = set()
|
||||
for part in str(spec).split(","):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
step = 1
|
||||
if "/" in part:
|
||||
part, _, step_s = part.partition("/")
|
||||
try:
|
||||
step = int(step_s)
|
||||
except ValueError:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if step < 1:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if part in ("*", "?"):
|
||||
rng = (lo, hi)
|
||||
elif "-" in part:
|
||||
a, _, b = part.partition("-")
|
||||
rng = (int(a), int(b))
|
||||
else:
|
||||
v = int(part)
|
||||
rng = (v, v)
|
||||
a, b = rng
|
||||
if not (lo <= a <= hi and lo <= b <= hi) or a > b:
|
||||
raise ValueError(f"字段越界:{part}")
|
||||
out.update(range(a, b + 1, step))
|
||||
if not out:
|
||||
raise ValueError("空字段")
|
||||
return out
|
||||
|
||||
|
||||
def parse_cron(expr: str) -> dict:
|
||||
"""解析 5 段 cron 表达式;非法抛 ValueError。返回 {minute,hour,dom,month,dow} 集合。"""
|
||||
parts = str(expr or "").strip().split()
|
||||
if len(parts) != 5:
|
||||
raise ValueError("cron 需为 5 段:分 时 日 月 周")
|
||||
minute = _parse_field(parts[0], 0, 59)
|
||||
hour = _parse_field(parts[1], 0, 23)
|
||||
dom = _parse_field(parts[2], 1, 31)
|
||||
month = _parse_field(parts[3], 1, 12)
|
||||
dow = _parse_field(parts[4], 0, 7)
|
||||
has7 = 7 in dow # 标准 cron 中 0 与 7 均表示周日
|
||||
dow.discard(7)
|
||||
if has7:
|
||||
dow.add(0)
|
||||
return {"minute": minute, "hour": hour, "dom": dom, "month": month, "dow": dow}
|
||||
|
||||
|
||||
def _cron_dow(dt: datetime) -> int:
|
||||
"""cron 周日编号:0=周日,1=周一 … 6=周六。"""
|
||||
return (dt.weekday() + 1) % 7
|
||||
|
||||
|
||||
def next_match(cron: dict, after: datetime) -> datetime | None:
|
||||
"""返回严格晚于 after 的最近一个匹配时刻;一年内无匹配返回 None(如 2 月 30 日)。"""
|
||||
minute, hour, dom, month, dow = (cron["minute"], cron["hour"], cron["dom"],
|
||||
cron["month"], cron["dow"])
|
||||
dom_any = dom == set(range(1, 32))
|
||||
dow_any = dow == set(range(0, 7))
|
||||
t = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
|
||||
for _ in range(10000):
|
||||
if t.month not in month:
|
||||
y, m = (t.year + 1, 1) if t.month == 12 else (t.year, t.month + 1)
|
||||
t = datetime(y, m, 1)
|
||||
continue
|
||||
# 标准语义:dom 与 dow 均有限制时,命中其一即可;仅一方限制则只按该方
|
||||
if not dom_any and not dow_any:
|
||||
day_ok = (t.day in dom) or (_cron_dow(t) in dow)
|
||||
elif not dow_any:
|
||||
day_ok = _cron_dow(t) in dow
|
||||
elif not dom_any:
|
||||
day_ok = t.day in dom
|
||||
else:
|
||||
day_ok = True
|
||||
if not day_ok:
|
||||
t = (t + timedelta(days=1)).replace(hour=0, minute=0)
|
||||
continue
|
||||
if t.hour not in hour:
|
||||
t = (t + timedelta(hours=1)).replace(minute=0)
|
||||
continue
|
||||
if t.minute not in minute:
|
||||
t += timedelta(minutes=1)
|
||||
continue
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 本地存储与 CRUD ====================
|
||||
def _load() -> None:
|
||||
global _SCHEDULES
|
||||
with _LOCK:
|
||||
if _SCHED_FILE.is_file():
|
||||
try:
|
||||
data = json.loads(_SCHED_FILE.read_text(encoding="utf-8"))
|
||||
_SCHEDULES = [s for s in (data or {}).get("schedules", [])
|
||||
if isinstance(s, dict)]
|
||||
except (OSError, ValueError):
|
||||
_LOGGER.warning("定时任务配置损坏,已忽略:%s", _SCHED_FILE)
|
||||
_SCHEDULES = []
|
||||
else:
|
||||
_SCHEDULES = []
|
||||
|
||||
|
||||
def _persist() -> None:
|
||||
with _LOCK:
|
||||
_SCHED_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_SCHED_FILE.write_text(
|
||||
json.dumps({"schedules": _SCHEDULES}, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _new_id() -> str:
|
||||
return f"{int(time.time() * 1000):x}{os.urandom(4).hex()}"
|
||||
|
||||
|
||||
def get_schedule(sid: str) -> dict | None:
|
||||
"""按 id 取原始记录(调用方须持锁前读取,路由层只读不持有引用长期使用)。"""
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def list_schedules(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [_public(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
def create_schedule(account: str, payload: dict) -> dict:
|
||||
"""新增定时任务(cron 非法抛 ValueError)。"""
|
||||
cron = (payload.get("cron") or "").strip()
|
||||
parse_cron(cron)
|
||||
rec = {
|
||||
"id": _new_id(),
|
||||
"name": (payload.get("name") or "").strip() or "定时任务",
|
||||
"account": account,
|
||||
"plugin_id": payload.get("plugin_id", ""),
|
||||
"fields": payload.get("fields") or {},
|
||||
"cron": cron,
|
||||
"enabled": bool(payload.get("enabled", True)),
|
||||
"last_run_at": "",
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
with _LOCK:
|
||||
_SCHEDULES.append(rec)
|
||||
_persist()
|
||||
return dict(rec)
|
||||
|
||||
|
||||
def update_schedule(sid: str, payload: dict) -> dict | None:
|
||||
"""更新任务(仅覆盖 payload 中出现的字段;cron 非法抛 ValueError)。"""
|
||||
if payload.get("cron"):
|
||||
parse_cron(payload["cron"])
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") != sid:
|
||||
continue
|
||||
if "name" in payload:
|
||||
s["name"] = (payload["name"] or "").strip() or "定时任务"
|
||||
if "plugin_id" in payload:
|
||||
s["plugin_id"] = payload["plugin_id"]
|
||||
if "fields" in payload:
|
||||
s["fields"] = payload["fields"] or {}
|
||||
if payload.get("cron"):
|
||||
s["cron"] = payload["cron"].strip()
|
||||
if "enabled" in payload:
|
||||
s["enabled"] = bool(payload["enabled"])
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def delete_schedule(sid: str) -> bool:
|
||||
with _LOCK:
|
||||
for i, s in enumerate(_SCHEDULES):
|
||||
if s.get("id") == sid:
|
||||
_SCHEDULES.pop(i)
|
||||
_persist()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def toggle_schedule(sid: str, enabled: bool) -> dict | None:
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
s["enabled"] = bool(enabled)
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def next_run_at(s: dict) -> datetime | None:
|
||||
"""该任务最近一次触发后的下一次触发时刻(未跑过则取首次未来触发)。"""
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
return None
|
||||
try:
|
||||
last = datetime.fromisoformat(s.get("last_run_at")) if s.get("last_run_at") else None
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
return next_match(cron, last if last else datetime.now())
|
||||
|
||||
|
||||
def _public(s: dict) -> dict:
|
||||
out = dict(s)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
out["last_run_at"] = out.get("last_run_at") or ""
|
||||
# 已停用任务不再推算/展示下次执行,避免误导
|
||||
nxt = next_run_at(s) if out["enabled"] else None
|
||||
out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else ""
|
||||
return out
|
||||
|
||||
|
||||
def _export(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [dict(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
# ==================== 后台触发 ====================
|
||||
def start() -> None:
|
||||
"""启动后台定时检查线程(幂等)。"""
|
||||
global _STARTED
|
||||
with _LOCK:
|
||||
if _STARTED:
|
||||
return
|
||||
_STARTED = True
|
||||
threading.Thread(target=_loop, daemon=True, name="sched-tick").start()
|
||||
_LOGGER.info("定时任务后台检查已启动(每 %ds 一次)", _TICK_SECS)
|
||||
|
||||
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
_tick()
|
||||
except Exception as _exc: # noqa: BLE001 单轮异常不影响后续检查
|
||||
_LOGGER.warning("定时任务检查异常:%s", _exc)
|
||||
time.sleep(_TICK_SECS)
|
||||
|
||||
|
||||
def _tick() -> None:
|
||||
now = datetime.now()
|
||||
due = []
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if not s.get("enabled"):
|
||||
continue
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
last = (datetime.fromisoformat(s.get("last_run_at"))
|
||||
if s.get("last_run_at") else None)
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
nxt = next_match(cron, last if last else now)
|
||||
if nxt and nxt <= now:
|
||||
due.append((s, nxt))
|
||||
fired = False
|
||||
for s, nxt in due:
|
||||
if _fire(s):
|
||||
with _LOCK:
|
||||
s["last_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
fired = True
|
||||
if fired:
|
||||
_persist()
|
||||
|
||||
|
||||
def _fire(s: dict) -> bool:
|
||||
"""触发一次定时任务:授权校验通过后走 submit_run 启动;返回是否已启动。"""
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core.runner import submit_run
|
||||
|
||||
try:
|
||||
plugin = PLUGINS.find(s.get("plugin_id", ""))
|
||||
except KeyError:
|
||||
_LOGGER.warning("定时任务「%s」的插件 %s 不存在,跳过触发",
|
||||
s.get("name"), s.get("plugin_id"))
|
||||
return False
|
||||
account = s.get("account", "")
|
||||
deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online())
|
||||
if deny:
|
||||
# 拒绝日志节流:同一任务至少间隔 _DENY_LOG_CD 秒才再记一条,避免授权失效时每 tick 刷屏
|
||||
_ts = time.time()
|
||||
with _LOCK:
|
||||
_last = _deny_log_ts.get(s.get("id"))
|
||||
_deny_log_ts[s.get("id")] = _ts
|
||||
if _last is None or _ts - _last >= _DENY_LOG_CD:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
return False
|
||||
try:
|
||||
submit_run(account, plugin, s.get("fields") or {})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("定时任务「%s」启动失败:%s", s.get("name"), _exc)
|
||||
return False
|
||||
_LOGGER.info("定时任务触发:「%s」(插件 %s,账号 %s)",
|
||||
s.get("name"), plugin.id, account)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 中心机备份(防丢失) ====================
|
||||
def push_backup_async(request, account: str) -> None:
|
||||
"""变更后把该账号全量配置异步备份到中心机;失败静默(不阻断用户操作)。"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
|
||||
def _run():
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _cp_headers, _cp_call
|
||||
headers = {**_cp_headers(request), "Content-Type": "application/json"}
|
||||
_cp_call("POST", "/api/schedules/backup",
|
||||
headers=headers,
|
||||
json={"data": {"schedules": _export(account)}})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("定时任务备份失败(账号 %s):%s", account, _exc)
|
||||
|
||||
threading.Thread(target=_run, daemon=True, name="sched-backup").start()
|
||||
|
||||
|
||||
def restore_from_cloud() -> None:
|
||||
"""启动时按当前活跃账号从中心机合并恢复缺失的任务(本地已有 id 不覆盖)。
|
||||
|
||||
仅作「防丢失」兜底:本地配置为真源,服务端备份只在本地缺失对应任务时补充。
|
||||
"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
from webhost.backend.core.session import _sess_active_account, _ACCT_CLOUD_TOKEN
|
||||
account = _sess_active_account()
|
||||
if not account:
|
||||
return
|
||||
headers = {"X-Admin-User": account}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if cloud_tok:
|
||||
headers["Authorization"] = f"Bearer {cloud_tok}"
|
||||
import requests
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/schedules/backup",
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
remote = (r.json().get("data") or {}).get("schedules") or []
|
||||
except Exception as _exc: # noqa: BLE001 恢复失败不影响启动
|
||||
_LOGGER.warning("定时任务云端恢复失败(跳过):%s", _exc)
|
||||
return
|
||||
added = 0
|
||||
with _LOCK:
|
||||
local_ids = {s.get("id") for s in _SCHEDULES}
|
||||
for s in remote:
|
||||
if (not isinstance(s, dict) or s.get("id") in local_ids
|
||||
or s.get("account") != account):
|
||||
continue
|
||||
try:
|
||||
parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
_SCHEDULES.append(s)
|
||||
added += 1
|
||||
if added:
|
||||
_persist()
|
||||
if added:
|
||||
_LOGGER.info("定时任务云端恢复 %d 条(账号 %s)", added, account)
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""启动初始化:加载本地配置 + 启动后台检查线程 + 云端补恢复。"""
|
||||
_load()
|
||||
start()
|
||||
restore_from_cloud()
|
||||
@@ -1,139 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
|
||||
|
||||
业务逻辑已按领域拆到 sibling 模块:
|
||||
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
|
||||
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
|
||||
- apis/ 路由子包(admin / dingtalk / meta / runs)
|
||||
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import plugin_ui as api_plugin_ui
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
from webhost.backend.apis import schedules as api_schedules
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
try:
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
# 敏感凭证中心化下发:优先服务端在线拉取(RSA 解密),否则用本地缓存密文解密;
|
||||
# 失败不阻断启动(.env 回退 / 等待下次登录后刷新)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load()
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
_LOGGER.info("中心机敏感凭证下发完成(%s 个键)", len(_creds))
|
||||
except Exception as _exc: # noqa: BLE001 下发失败不影响启动
|
||||
_LOGGER.warning("加载中心机敏感凭证失败:%s", _exc)
|
||||
# 账号:.env 不再配置 CONTROLPLANE_ACCOUNT,取最近活跃的本机会话账号(重启恢复)
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
_acct = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if _acct:
|
||||
try:
|
||||
_sync_licensing(_acct)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级;
|
||||
# 并常驻周期检查(默认 30 分钟),壳子长开时也能自动发现新版本
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
_shell_updater.start_check()
|
||||
_shell_updater.start_periodic_check()
|
||||
# 壳子内置定时任务:加载本地配置 + 启动后台触发线程 + 从中心机合并恢复(防丢失)
|
||||
from webhost.backend.core import tasks as _boot_tasks
|
||||
_boot_tasks.init()
|
||||
yield
|
||||
except BaseException:
|
||||
# lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull,
|
||||
# 报错无处可看:崩溃现场记入 webhost.log,frozen 时并追加到 exe 同级 crash.log
|
||||
import traceback
|
||||
_tb = traceback.format_exc()
|
||||
_LOGGER.error("启动初始化失败:\n%s", _tb)
|
||||
if getattr(sys, "frozen", False):
|
||||
try:
|
||||
with open(Path(sys.executable).parent / "crash.log", "a", encoding="utf-8") as _f:
|
||||
_f.write("\n[lifespan]\n" + _tb)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
app.include_router(api_schedules.router)
|
||||
app.include_router(api_plugin_ui.router)
|
||||
|
||||
|
||||
if config.DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(config.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 {config.PORT} free = {_port_free(config.PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")
|
||||
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 自动化工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
-1576
File diff suppressed because it is too large
Load Diff
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"name": "37du-webhost-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -1,798 +0,0 @@
|
||||
<template>
|
||||
<div v-if="booting" class="boot">
|
||||
<span class="boot-logo">37</span>
|
||||
<span class="boot-txt">{{ syncing ? '正在同步插件,请稍候…' : (store.appName || '自动化工作台') }}</span>
|
||||
<span class="boot-dots"><i></i><i></i><i></i></span>
|
||||
</div>
|
||||
<LoginPage v-else-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<!-- 壳子更新提示:已就绪重启更新 / 下载失败重试 / 发现新版本可下载(下载进度改用弹窗) -->
|
||||
<div v-if="updBarVisible" class="update-bar">
|
||||
<template v-if="shellUpdate.downloaded">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
|
||||
</template>
|
||||
<template v-else-if="updDl.status === 'failed'">
|
||||
<span class="upd-txt">新版本下载失败<em>{{ updDl.error }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="downloading" @click="onShellDownload">重试</el-button>
|
||||
</template>
|
||||
<template v-else-if="shellUpdate.available">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.latest }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<div class="upd-actions">
|
||||
<el-button size="small" type="primary" round :loading="downloading" @click="onShellDownload">立即下载</el-button>
|
||||
<el-button size="small" round @click="shellDismissed = true">暂不</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<!-- 授权已过期:离线超 7 天须联网刷新票据后才能继续使用 -->
|
||||
<div v-if="store.authExpired" class="auth-expired-bar">
|
||||
<span class="ae-txt">授权已过期(最长离线 7 天),需联网刷新授权后才能继续使用</span>
|
||||
<el-button size="small" type="primary" round :loading="syncingPlugins" @click="onPluginSync">立即刷新</el-button>
|
||||
</div>
|
||||
<!-- 顶部:品牌 + 平台登录态 + 当前账号/登出 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>{{ wsText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-divider direction="vertical" class="vdiv" />
|
||||
|
||||
<div class="band">
|
||||
<span class="band-label">平台登录态</span>
|
||||
<el-tooltip
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
:content="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
|
||||
placement="bottom"
|
||||
:disabled="p.online && p.allowed !== false"
|
||||
>
|
||||
<el-button
|
||||
class="chip"
|
||||
:class="{ online: p.online, locked: p.allowed === false }"
|
||||
:disabled="busyLogin === p.id || p.allowed === false"
|
||||
:loading="busyLogin === p.id"
|
||||
round
|
||||
@click="login(p.id)"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<!-- 浏览器(Chrome)状态图标:已安装显示版本(绿),未安装高亮可点击进入下载/安装 -->
|
||||
<div class="band chrome-band" v-if="chromeVis">
|
||||
<el-tooltip
|
||||
:content="chromeTip"
|
||||
placement="bottom"
|
||||
>
|
||||
<el-button
|
||||
class="chip chrome-chip"
|
||||
:class="{ ok: chromeInstalled, warn: !chromeInstalled && chromeCloud, loading: chromeBusy }"
|
||||
round
|
||||
:loading="chromeBusy"
|
||||
@click="onChromeClick"
|
||||
>
|
||||
<i class="chrome-icon" :class="{ blink: !chromeInstalled }"></i>
|
||||
<span>{{ chromeLabel }}</span>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<div class="spacer"></div>
|
||||
|
||||
<div class="run-state">
|
||||
<template v-if="store.running">
|
||||
<span class="run-pct">{{ store.progress }}%</span>
|
||||
<el-progress
|
||||
:percentage="store.progress"
|
||||
:show-text="false"
|
||||
:stroke-width="8"
|
||||
color="#3b6cff"
|
||||
class="run-bar"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
|
||||
<el-avatar :size="26" class="acct-avatar" :src="accountAvatar()" :key="accountAvatar()" @error="onAvatarError">
|
||||
<span class="acct-avatar-fb">{{ (store.nickname || store.current).slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
</button>
|
||||
<el-button class="chip" round @click="logout">登出</el-button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 主体:左场景 | 右插件页 + 日志 -->
|
||||
<div class="body">
|
||||
<aside class="panel side">
|
||||
<div class="side-head">
|
||||
<span class="sec-title">场景</span>
|
||||
<div class="side-head-r">
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
<el-tooltip content="插件同步" placement="top">
|
||||
<el-button class="sync-btn" text :icon="Refresh" :loading="syncingPlugins"
|
||||
:disabled="store.running" @click="onPluginSync" />
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="scene-list">
|
||||
<li
|
||||
v-for="(p, i) in store.plugins"
|
||||
:key="p.id"
|
||||
:class="{ active: p.id === store.selectedId && store.view === 'plugin' }"
|
||||
@click="openPlugin(p.id)"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: PALETTE[i % PALETTE.length] }">
|
||||
{{ p.name.slice(0, 1) }}
|
||||
</span>
|
||||
<span class="scene-name">{{ p.name }}</span>
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员进行授权</span></div>
|
||||
<div class="side-nav" @click="openSchedules">
|
||||
<span class="nav-item" :class="{ active: store.view === 'schedules' }">
|
||||
<el-icon><Clock /></el-icon>
|
||||
<span>定时任务</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="side-foot">
|
||||
<div class="foot-ver">
|
||||
<span class="ver-num">壳子 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }}</span>
|
||||
<el-link type="primary" :underline="false" class="check-link"
|
||||
:disabled="shellChecking" @click="onShellCheck">
|
||||
{{ shellChecking ? '检查中…' : '检查更新' }}</el-link>
|
||||
</div>
|
||||
<div>场景以插件方式接入</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
<SchedulePage v-else-if="store.view === 'schedules'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
|
||||
<!-- 壳子更新下载进度弹窗:点击「立即下载」后弹出,可最小化到后台继续下载 -->
|
||||
<el-dialog v-model="updDlg" :title="`下载更新 v${updDl.version || ''}`" width="420px"
|
||||
:close-on-click-modal="false" align-center class="upd-dl-dialog">
|
||||
<template v-if="updDl.status === 'downloading'">
|
||||
<div class="dl-dlg-body">
|
||||
<el-progress :percentage="updDl.pct || 0" :stroke-width="10" />
|
||||
<span class="dl-dlg-bytes">{{ fmtBytes(updDl.received) }}{{ updDl.total ? ' / ' + fmtBytes(updDl.total) : '' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="updDl.status === 'failed'">
|
||||
<div class="dl-dlg-body">
|
||||
<span class="dl-dlg-err">下载失败:{{ updDl.error || '未知错误' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="dl-dlg-body"><span>已下载完成</span></div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button v-if="updDl.status === 'failed'" size="small" type="primary" round
|
||||
:loading="downloading" @click="onShellDownload">重试</el-button>
|
||||
<el-button size="small" round @click="updDlg = false">后台下载</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock, Refresh } from '@element-plus/icons-vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import SchedulePage from './components/SchedulePage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache, accountAvatar } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate, checkShellUpdate, downloadShellUpdate, getChromeStatus, checkChrome, downloadChrome, installChrome } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
// 顶栏头像加载失败:清除缓存返回首字符兜底
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const wsText = computed(() =>
|
||||
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
|
||||
|
||||
function openPlugin(id) {
|
||||
store.selectedId = id
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
function openSchedules() {
|
||||
store.view = 'schedules'
|
||||
}
|
||||
|
||||
function openWS() {
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => {
|
||||
store.wsOn = false
|
||||
// 仅登录态下自动重连刷新;未登录被拒(1008)时静默,避免 reload 死循环
|
||||
if (store.current) setTimeout(() => (location.reload()), 2500)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.authExpired = !!meta.authExpired
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
await checkSession()
|
||||
booting.value = false // 会话判定完成(登录/未登录/后端不可达均已定),再渲染首屏
|
||||
loadAvatar()
|
||||
loadShellStatus()
|
||||
loadChromeStatus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (shellPollTimer) { clearTimeout(shellPollTimer); shellPollTimer = null }
|
||||
if (chromePollTimer) { clearTimeout(chromePollTimer); chromePollTimer = null }
|
||||
})
|
||||
|
||||
// ===== 浏览器(Chrome)检测/下载/安装 =====
|
||||
const chrome = ref({})
|
||||
let chromePollTimer = null
|
||||
const chromeBusy = ref(false) // 正在轮询/下载/安装(按钮 loading)
|
||||
|
||||
const chromeInstalled = computed(() => !!chrome.value.installed)
|
||||
const chromeVisible = computed(() => {
|
||||
// 下载中/已下载待安装/未安装但中心机有登记 → 显示;已装则不显示(已可用不占用空间)
|
||||
return chrome.value.installed || chrome.value.downloaded || chrome.value.cloud_available
|
||||
})
|
||||
// 与模板 v-if 共用(template 里用的是字符串写法,这里保持简单)
|
||||
const chromeVis = computed(() =>
|
||||
!chrome.value.installed || chrome.value.downloaded || chrome.value.dl?.status === 'downloading')
|
||||
|
||||
const chromeLabel = computed(() => {
|
||||
const c = chrome.value
|
||||
if (c.installing) return '安装中…'
|
||||
if (!c.installed) {
|
||||
if (c.dl?.status === 'downloading') return c.dl?.pct + '%'
|
||||
if (c.downloaded) return '点击安装'
|
||||
if (c.cloud_available) return '装浏览器'
|
||||
return '浏览器'
|
||||
}
|
||||
return c.version ? 'Chrome ' + c.version : 'Chrome'
|
||||
})
|
||||
|
||||
const chromeTip = computed(() => {
|
||||
const c = chrome.value
|
||||
if (c.installed) return `本机已安装 Chrome ${c.version},点击重新检测`
|
||||
if (c.installing) return '正在安装 Chrome,请稍候…'
|
||||
if (c.downloaded) return 'Chrome 安装包已下载,点击安装'
|
||||
if (c.dl?.status === 'downloading') return '正在下载 Chrome 安装包 ' + c.dl?.pct + '%'
|
||||
if (!c.cloud_available) return '中心机暂未登记浏览器安装包,点击重新检测'
|
||||
return '本机未安装 Chrome,点击下载安装'
|
||||
})
|
||||
|
||||
async function loadChromeStatus() {
|
||||
try { chrome.value = await getChromeStatus() } catch (_) {}
|
||||
// 未安装或操作中才轮询;已安装无需常驻
|
||||
if (!chrome.value.installed || chrome.value.installing || chrome.value.dl?.status === 'downloading') {
|
||||
startChromePoll()
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshChromeStatus() {
|
||||
try {
|
||||
const s = await getChromeStatus()
|
||||
chrome.value = s
|
||||
if (chrome.value.installed && chrome.value.dl?.status !== 'downloading' && !chrome.value.installing) {
|
||||
if (chromePollTimer) { clearTimeout(chromePollTimer); chromePollTimer = null }
|
||||
return // 已装好,停止轮询
|
||||
}
|
||||
} catch (_) {}
|
||||
chromePollTimer = setTimeout(refreshChromeStatus, 1500)
|
||||
}
|
||||
function startChromePoll() {
|
||||
if (chromePollTimer) return
|
||||
refreshChromeStatus()
|
||||
}
|
||||
|
||||
async function onChromeClick() {
|
||||
if (chromeBusy.value) return
|
||||
const c = chrome.value
|
||||
// 安装中:仅刷新状态
|
||||
if (c.installing) { return }
|
||||
// 已下载:直接安装
|
||||
if (c.downloaded) {
|
||||
chromeBusy.value = true
|
||||
try { await installChrome(); chrome.value.installing = true; startChromePoll() }
|
||||
catch (e) { ElMessage.error('安装失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
return
|
||||
}
|
||||
// 未装且中心机有登记:下载
|
||||
if (!c.installed && c.cloud_available) {
|
||||
chromeBusy.value = true
|
||||
try { await downloadChrome(); loadChromeStatus() }
|
||||
catch (e) { ElMessage.error('开始下载失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
return
|
||||
}
|
||||
// 其余:重新检测
|
||||
chromeBusy.value = true
|
||||
try { await checkChrome(); loadChromeStatus() }
|
||||
catch (e) { ElMessage.error('检测失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
}
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
const booting = ref(true) // 鉴权判定中:未确定会话前先显示加载骨架,避免「闪一下登录页再进首页」
|
||||
const syncing = ref(false) // 首次启动/启动时:按账号权限自下载/更新插件(等待下载界面)
|
||||
|
||||
// ===== 壳子自动更新:检查 → 用户确认下载(带进度)→ 重启更新 =====
|
||||
const shellUpdate = ref({})
|
||||
const updating = ref(false)
|
||||
const downloading = ref(false)
|
||||
const shellChecking = ref(false) // 手动检查请求进行中(秒级)
|
||||
const shellDismissed = ref(false) // 用户点了"暂不",本会话内隐藏"立即下载"提示
|
||||
let shellPollTimer = null // 状态轮询(setTimeout 递归,下载中 1.2s / 常态 15s)
|
||||
let lastDlStatus = '' // 上一轮下载状态,用于下载完成/失败时的一次性提示
|
||||
|
||||
const updDl = computed(() => shellUpdate.value.dl || {})
|
||||
const updDlg = ref(false) // 下载进度弹窗(点击「立即下载」后弹出)
|
||||
const updBarVisible = computed(() =>
|
||||
shellUpdate.value.downloaded ||
|
||||
(updDl.value.status === 'failed' && !updDlg.value) ||
|
||||
(shellUpdate.value.available && !shellDismissed.value)
|
||||
)
|
||||
|
||||
function fmtBytes(n) {
|
||||
if (!n) return '0 B'
|
||||
const u = ['B', 'KB', 'MB', 'GB']
|
||||
let i = 0
|
||||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++ }
|
||||
return (n >= 100 || i === 0 ? n.toFixed(0) : n.toFixed(1)) + ' ' + u[i]
|
||||
}
|
||||
|
||||
async function loadShellStatus() {
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {}
|
||||
startShellPoll()
|
||||
}
|
||||
|
||||
// 常驻状态轮询:驱动下载进度条与 available/downloaded 提示;下载完成/失败各提示一次
|
||||
async function refreshShellStatus() {
|
||||
try {
|
||||
const s = await getShellStatus()
|
||||
shellUpdate.value = s
|
||||
const st = s.dl?.status || ''
|
||||
if (lastDlStatus === 'downloading' && st === 'downloaded') {
|
||||
updDlg.value = false // 弹窗开着时自动收起,顶部提示条转为「重启更新」
|
||||
ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`)
|
||||
log('INFO', `壳子新版本 v${s.new} 已就绪,可重启更新`)
|
||||
} else if (lastDlStatus === 'downloading' && st === 'failed') {
|
||||
ElMessage.warning('新版本下载失败:' + (s.dl?.error || ''))
|
||||
}
|
||||
lastDlStatus = st
|
||||
} catch (_) {}
|
||||
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 1200 : 15000)
|
||||
}
|
||||
function startShellPoll() {
|
||||
if (shellPollTimer) return
|
||||
refreshShellStatus()
|
||||
}
|
||||
|
||||
async function doShellUpdate() {
|
||||
updating.value = true
|
||||
try {
|
||||
await applyShellUpdate() // 后端运行静默安装并退出进程,升级后自动重启
|
||||
} catch (e) {
|
||||
updating.value = false
|
||||
ElMessage.error('更新失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
async function onShellDownload() {
|
||||
if (downloading.value) return
|
||||
downloading.value = true
|
||||
shellDismissed.value = false
|
||||
updDlg.value = true // 点击下载即弹出进度弹窗,不再用页头条展示进度
|
||||
// 点击即进入"下载中"反馈(不等轮询):内网直连下载很快,若靠 15s 轮询拉状态,
|
||||
// 进度条可能还没显示就已经下载完,用户会以为点了没反应
|
||||
const v = shellUpdate.value.latest || ''
|
||||
shellUpdate.value = { ...shellUpdate.value,
|
||||
dl: { status: 'downloading', version: v, received: 0, total: 0, pct: 0, error: '' } }
|
||||
lastDlStatus = 'downloading' // 兜底:即使立即下载完成,也能触发"已就绪"一次性提示
|
||||
try {
|
||||
await downloadShellUpdate() // 后端后台流式下载,进度经轮询展示
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {} // 抢拉真实进度,避免卡在 0%
|
||||
} catch (e) {
|
||||
shellUpdate.value = { ...shellUpdate.value,
|
||||
dl: { status: 'failed', version: v, received: 0, total: 0, pct: 0, error: (e.message || e) } }
|
||||
ElMessage.error('开始下载失败:' + (e.message || e))
|
||||
}
|
||||
downloading.value = false
|
||||
}
|
||||
|
||||
// 手动"检查更新":触发秒级版本比对 → 轮询检查结束后按结果提示
|
||||
async function onShellCheck() {
|
||||
if (shellChecking.value) return
|
||||
try { await checkShellUpdate() } catch (e) {
|
||||
ElMessage.error('检查更新失败:' + (e.message || e))
|
||||
return
|
||||
}
|
||||
shellChecking.value = true
|
||||
const timer = setInterval(async () => {
|
||||
try {
|
||||
const s = await getShellStatus()
|
||||
shellUpdate.value = s
|
||||
if (s.checking) return
|
||||
clearInterval(timer)
|
||||
shellChecking.value = false
|
||||
handleCheckResult(s)
|
||||
} catch (_) {}
|
||||
}, 800)
|
||||
// 兜底:30s 仍未结束则停止轮询,避免无限等待
|
||||
setTimeout(() => {
|
||||
if (shellChecking.value) {
|
||||
clearInterval(timer)
|
||||
shellChecking.value = false
|
||||
}
|
||||
}, 30000)
|
||||
}
|
||||
|
||||
function handleCheckResult(s) {
|
||||
if (!s.current) {
|
||||
ElMessage.info('当前为源码开发模式,不参与壳子自更新')
|
||||
return
|
||||
}
|
||||
if (s.downloaded) {
|
||||
ElMessage.info(`新版本 v${s.new} 已就绪,点击顶部「重启更新」完成升级`)
|
||||
return
|
||||
}
|
||||
if (updDl.value.status === 'downloading') return // 正在下载,进度条展示中
|
||||
if (s.error) {
|
||||
ElMessage.warning('检查更新失败:' + s.error)
|
||||
log('WARN', `检查壳子更新失败:${s.error}`)
|
||||
return
|
||||
}
|
||||
if (s.available) {
|
||||
ElMessageBox.confirm(
|
||||
`发现新版本 v${s.latest},是否立即下载?${s.notes ? '\n\n更新说明:' + s.notes : ''}`,
|
||||
'发现新版本',
|
||||
{ confirmButtonText: '立即下载', cancelButtonText: '稍后再说', type: 'info' }
|
||||
).then(() => onShellDownload()).catch(() => {})
|
||||
} else {
|
||||
ElMessage.info(`已是最新版本 v${s.current}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 插件同步:按当前账号权限重新同步(新装/更新/清理已删除),完成后刷新清单 =====
|
||||
// 登录成功与手动刷新共用;同步失败也补拉清单,保证离线时沿用本地已装插件
|
||||
const syncingPlugins = ref(false)
|
||||
async function onPluginSync() {
|
||||
if (syncingPlugins.value || store.running) return
|
||||
syncingPlugins.value = true
|
||||
try {
|
||||
const r = await syncPlugins()
|
||||
const parts = []
|
||||
if (r.downloaded?.length) parts.push(`新装 ${r.downloaded.length} 个`)
|
||||
if (r.updated?.length) parts.push(`更新 ${r.updated.length} 个`)
|
||||
if (r.removed?.length) parts.push(`清理 ${r.removed.length} 个`)
|
||||
if (r.failed?.length) parts.push(`失败 ${r.failed.length} 个`)
|
||||
if (parts.length) {
|
||||
ElMessage.success('插件同步完成:' + parts.join(','))
|
||||
const detail = [...(r.downloaded || []), ...(r.updated || []), ...(r.removed || [])].join('、')
|
||||
if (detail) log('INFO', `插件同步完成:${parts.join(',')}(${detail})`)
|
||||
} else {
|
||||
ElMessage.info('插件已是最新')
|
||||
}
|
||||
if (r.failed?.length) log('ERROR', `插件同步失败:${r.failed.join('、')}`)
|
||||
} catch (e) {
|
||||
ElMessage.error('插件同步失败:' + (e.message || e))
|
||||
} finally {
|
||||
await refreshMeta()
|
||||
syncingPlugins.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 平台登录等轻量操作反馈:统一走 element-plus 全局消息
|
||||
function showToast(msg, type = 'info') {
|
||||
ElMessage({ message: msg, type, duration: 2200 })
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
// 登录态一律以**后端会话 cookie** 为准(钉钉扫码/账号登录/后端重启后均从 admin/me 判定),
|
||||
// 不再以 localStorage 的 cp_account 早退——否则全新扫码流程(未写过 cp_account)回跳后无法进入插件页。
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account) {
|
||||
store.current = ''; store.dept = ''; store.nickname = ''; store.avatar = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
return
|
||||
}
|
||||
store.current = me.account
|
||||
store.dept = me.dept || ''
|
||||
store.nickname = me.nickname || ''
|
||||
store.avatar = me.avatar || ''
|
||||
try { localStorage.setItem('cp_account', me.account) } catch (_) {}
|
||||
// 会话确认后:按账号权限自下载/更新插件(首次启动等待下载完成;离线/失败直接跳过)
|
||||
syncing.value = true
|
||||
try { await syncPlugins() } catch (_) {}
|
||||
syncing.value = false
|
||||
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
|
||||
await refreshMeta()
|
||||
} catch (_) { /* 后端 down:无法校验,保持现状(可能为登录页或本地态) */ }
|
||||
}
|
||||
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.authExpired = !!meta.authExpired
|
||||
// 选中场景不存在(被同步清理/授权收回)时回落到第一个可用场景
|
||||
if (!store.plugins.find((p) => p.id === store.selectedId)) {
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.dept = ok.dept || ''
|
||||
store.nickname = ok.nickname || ''
|
||||
store.avatar = ok.avatar || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录成功后立即按该账号权限同步插件(新装机首次登录即下载授权插件),再刷新平台/清单
|
||||
await onPluginSync()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
loadShellStatus() // 挂载时未登录拉不到更新状态,登录后补拉(版本显示/更新提示)
|
||||
loadChromeStatus() // 浏览器状态同此
|
||||
// 首次登录/钉钉自动建号的默认密码:提示立即改密
|
||||
if (ok.must_change_pwd) { promptChangePwd(ok.account) }
|
||||
}
|
||||
|
||||
async function promptChangePwd(account) {
|
||||
try {
|
||||
// 旧密码 = 钉钉通知下发的初始密码,必须输入校验(与个人中心改密一致)
|
||||
let op = ''
|
||||
try {
|
||||
const { value } = await ElMessageBox.prompt(
|
||||
'当前账号正使用默认密码,请输入钉钉通知中的初始密码',
|
||||
'首次登录 · 身份验证',
|
||||
{ inputType: 'password', inputPlaceholder: '请输入初始密码',
|
||||
confirmButtonText: '下一步', cancelButtonText: '稍后再说' })
|
||||
op = value
|
||||
} catch (_) { return /* 用户取消 */ }
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'请设置新密码(至少 6 位),避免他人误登录',
|
||||
'首次登录 · 设置新密码',
|
||||
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
|
||||
try {
|
||||
await adminPassword({ account, old_password: op, new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e) {
|
||||
ElMessage.warning('改密失败:' + (e.message || e))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.nickname = ''
|
||||
store.avatar = ''
|
||||
store.avatarUrl = ''
|
||||
store.authExpired = false
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
const label = p?.label || id
|
||||
if (p?.online) {
|
||||
showToast(`${label} 已登录`, 'success')
|
||||
return
|
||||
}
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const ok = !!(r && r.online)
|
||||
if (p) p.online = ok
|
||||
log(ok ? 'INFO' : 'ERROR',
|
||||
ok ? `平台 ${label} 登录成功` : `平台 ${label} 登录未生效:${(r && r.message) || ''}`)
|
||||
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`, ok ? 'success' : 'error')
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
|
||||
showToast(`登录失败:${e.message || e}`, 'error')
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.boot {
|
||||
min-height: 100vh;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 14px; background: var(--bg);
|
||||
}
|
||||
.boot-logo {
|
||||
width: 54px; height: 54px; border-radius: 16px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 20px; font-weight: 800;
|
||||
box-shadow: 0 10px 26px -8px rgba(59,108,255,.65);
|
||||
animation: bootpop .4s ease;
|
||||
}
|
||||
.boot-txt { font-size: 13px; color: var(--text-faint); letter-spacing: .06em; }
|
||||
.boot-dots { display: flex; gap: 5px; }
|
||||
.boot-dots i {
|
||||
width: 6px; height: 6px; border-radius: 50%; background: var(--primary);
|
||||
animation: bootblink 1s infinite ease-in-out;
|
||||
}
|
||||
.boot-dots i:nth-child(2) { animation-delay: .15s; }
|
||||
.boot-dots i:nth-child(3) { animation-delay: .3s; }
|
||||
@keyframes bootpop { from { transform: scale(.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes bootblink { 0%,80%,100% { opacity: .25; } 40% { opacity: 1; transform: translateY(-2px); } }
|
||||
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 12px 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.update-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: var(--primary-weak);
|
||||
border: 1px solid rgba(59, 108, 255, .35);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: var(--text-sub);
|
||||
}
|
||||
.update-bar b { color: var(--primary); }
|
||||
.update-bar em { font-style: normal; color: var(--text-faint); margin-left: 6px; }
|
||||
.update-bar .upd-actions { display: flex; align-items: center; gap: 8px; }
|
||||
|
||||
/* 壳子更新下载进度弹窗 */
|
||||
.dl-dlg-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 2px; }
|
||||
.dl-dlg-bytes { font-size: 12px; color: var(--text-faint); text-align: right; }
|
||||
.dl-dlg-err { color: var(--danger, #e5484d); font-size: 13px; line-height: 1.6; }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo {
|
||||
width: 36px; height: 36px; border-radius: 10px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 14px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(59,108,255,.6);
|
||||
}
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
|
||||
.vdiv { height: 26px; margin: 0 2px; }
|
||||
|
||||
.band { display: flex; align-items: center; gap: 8px; }
|
||||
.band-label { font-size: 12px; color: var(--text-faint); margin-right: 4px; }
|
||||
|
||||
.chip { padding: 5px 14px; border-radius: 999px; }
|
||||
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; margin-right: 6px; display: inline-block; }
|
||||
.chip.online { border-color: transparent; background: var(--ok-weak); color: #1a8f63; }
|
||||
.chip.online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(34,176,122,.18); }
|
||||
.chip.locked { border-style: dashed; opacity: .5; }
|
||||
|
||||
/* 浏览器(Chrome)状态图标 */
|
||||
.chrome-band { margin-left: 2px; }
|
||||
.chrome-chip { border-color: transparent; background: var(--surface-2); color: var(--text-sub); }
|
||||
.chrome-chip.ok { background: var(--ok-weak); color: #1a8f63; }
|
||||
.chrome-chip.warn { background: #FFF4E5; color: #9A5B14; border-color: rgba(224,122,40,.4); }
|
||||
.chrome-icon {
|
||||
width: 14px; height: 14px; border-radius: 50%;
|
||||
margin-right: 6px; display: inline-block; flex-shrink: 0;
|
||||
background: radial-gradient(circle at 30% 30%, #e6f2ff, #4a8cf7 55%, #2b6be0);
|
||||
box-shadow: 0 0 0 3px rgba(74, 140, 247, .18);
|
||||
}
|
||||
.chrome-chip.warn .chrome-icon { background: radial-gradient(circle at 30% 30%, #fff6e6, #f7a23a 55%, #e07324); box-shadow: 0 0 0 3px rgba(247,162,58,.2); }
|
||||
.chrome-chip.loading .chrome-icon { opacity: .4; }
|
||||
.chrome-icon.blink { animation: chromeblink 1s infinite ease-in-out; }
|
||||
@keyframes chromeblink { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
|
||||
|
||||
.auth-expired-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: #FFF4E5;
|
||||
border: 1px solid rgba(224, 122, 40, .45);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: #9A5B14;
|
||||
}
|
||||
.auth-expired-bar .ae-txt { flex: 1; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-bar { width: 180px; flex-shrink: 0; }
|
||||
.run-pct { font-size: 12px; font-weight: 700; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
|
||||
.acct-btn {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
padding: 4px 8px; margin: -4px -8px; border-radius: 8px;
|
||||
font: inherit; transition: background .13s;
|
||||
}
|
||||
.acct-btn:hover { background: var(--surface-2); }
|
||||
.acct-avatar { flex-shrink: 0; }
|
||||
.acct-avatar-fb { font-size: 12px; font-weight: 700; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
.side { width: 232px; flex-shrink: 0; display: flex; flex-direction: column; padding: 14px 12px; }
|
||||
.side-head { display: flex; align-items: center; justify-content: space-between; padding: 0 6px 10px; }
|
||||
.side-head-r { display: flex; align-items: center; gap: 2px; }
|
||||
.sync-btn { padding: 5px 6px; font-size: 14px; color: var(--text-faint); }
|
||||
.sync-btn:hover { color: var(--primary); }
|
||||
.count { font-size: 11px; color: var(--text-faint); background: var(--surface-2); border: 1px solid var(--border); border-radius: 999px; padding: 1px 8px; }
|
||||
.scene-list { list-style: none; margin: 0; padding: 0; flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.scene-list li {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
position: relative;
|
||||
transition: background .13s, transform .13s ease;
|
||||
}
|
||||
.scene-list li:hover { background: var(--surface-2); transform: translateX(2px); }
|
||||
.scene-list li.active { background: var(--primary-weak); }
|
||||
.scene-list li.active::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 3px; background: var(--primary);
|
||||
}
|
||||
.scene-list li.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #fff; font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.scene-empty {
|
||||
flex: 1; display: grid; place-items: center; text-align: center;
|
||||
font-size: 12.5px; color: var(--text-sub); line-height: 1.9; padding: 20px 12px;
|
||||
}
|
||||
.scene-empty span { font-size: 11px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; display: flex; flex-direction: column; gap: 4px; }
|
||||
.side-nav { padding: 6px 4px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
color: var(--text-sub); font-size: 13px; position: relative;
|
||||
transition: background .13s;
|
||||
}
|
||||
.side-nav:hover .nav-item { background: var(--surface-2); }
|
||||
.nav-item.active { background: var(--primary-weak); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.active::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 3px; background: var(--primary);
|
||||
}
|
||||
.foot-ver { display: flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.ver-num { font-variant-numeric: tabular-nums; }
|
||||
.check-link { font-size: 10px; vertical-align: baseline; }
|
||||
|
||||
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
|
||||
</style>
|
||||
@@ -1,130 +0,0 @@
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function syncPlugins() {
|
||||
return j('/api/plugins/sync', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
// ===== 定时任务(壳子内置定时,配置自动备份中心机) =====
|
||||
export async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
// v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL
|
||||
export async function authDingtalk() {
|
||||
return j('/api/auth/dingtalk')
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
<template>
|
||||
<div class="panel log-wrap">
|
||||
<div class="log-head">
|
||||
<div class="log-title">
|
||||
<i class="status" :class="store.wsOn ? 'on' : 'off'" :title="store.wsOn ? '实时连接正常' : '连接已中断'"></i>
|
||||
<span>运行日志</span>
|
||||
<span v-if="store.running" class="live">● LIVE</span>
|
||||
<span v-else-if="store.logs.length" class="count">{{ visibleLogs.length }} 条</span>
|
||||
</div>
|
||||
|
||||
<div class="log-tools">
|
||||
<el-radio-group v-model="level" size="small">
|
||||
<el-radio-button v-for="l in LEVELS" :key="l" :value="l">{{ l }}</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-button size="small" :icon="CopyDocument" circle title="复制日志" :disabled="!visibleLogs.length"
|
||||
@click="copy" />
|
||||
<el-button size="small" :icon="pause ? VideoPlay : VideoPause" circle :title="pause ? '继续滚动' : '暂停滚动'"
|
||||
@click="pause = !pause" />
|
||||
<el-button size="small" plain :disabled="!store.logs.length" @click="confirmClear">清空</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div ref="box" class="log-box">
|
||||
<div v-if="!visibleLogs.length" class="log-empty">
|
||||
<template v-if="store.logs.length">当前级别无日志</template>
|
||||
<template v-else>暂无日志,点击「一键执行」开始</template>
|
||||
</div>
|
||||
<div v-for="(l, i) in visibleLogs" :key="i" class="log-line">
|
||||
<span class="t">{{ l.time }}</span>
|
||||
<span class="lv" :class="'s-' + (l.level || 'INFO')">[{{ l.level || 'INFO' }}]</span>
|
||||
<span>{{ l.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { nextTick, ref, watch, computed } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { CopyDocument, VideoPause, VideoPlay } from '@element-plus/icons-vue'
|
||||
import { store, clearLogs } from '../store'
|
||||
|
||||
const LEVELS = ['全部', 'INFO', 'WARN', 'ERROR']
|
||||
const level = ref('全部')
|
||||
const pause = ref(false)
|
||||
const box = ref(null)
|
||||
|
||||
const visibleLogs = computed(() => {
|
||||
if (level.value === '全部') return store.logs
|
||||
return store.logs.filter((l) => l.level === level.value)
|
||||
})
|
||||
|
||||
// 日志变化或过滤切换时,若未暂停则自动滚到最新
|
||||
watch(
|
||||
[() => store.logs.length, level],
|
||||
async () => {
|
||||
if (pause.value) return
|
||||
await nextTick()
|
||||
if (box.value) box.value.scrollTop = box.value.scrollHeight
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function confirmClear() {
|
||||
ElMessageBox.confirm('确认清空全部运行日志?', '清空日志', {
|
||||
confirmButtonText: '清空',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
.then(() => { clearLogs(); ElMessage.success('日志已清空') })
|
||||
.catch(() => { })
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
const text = visibleLogs.value.map((l) => `[${l.time}] [${l.level || 'INFO'}] ${l.msg}`).join('\n')
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
ElMessage.success(`已复制 ${visibleLogs.value.length} 条日志`)
|
||||
} catch (_) {
|
||||
ElMessage.error('复制失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.log-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 216px;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.log-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px 8px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.log-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.log-tools .el-button+.el-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status.on {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 3px var(--ok-weak);
|
||||
}
|
||||
|
||||
.status.off {
|
||||
background: #c6ccdc;
|
||||
}
|
||||
|
||||
.live {
|
||||
color: var(--ok);
|
||||
font-size: 10px;
|
||||
animation: blink 1s infinite;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
.count {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% {
|
||||
opacity: .2;
|
||||
}
|
||||
}
|
||||
|
||||
.log-empty {
|
||||
color: var(--text-faint);
|
||||
padding: 14px;
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,725 +0,0 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<!-- 巨大 37:节点阵列 -->
|
||||
<div class="ghost" aria-hidden="true">37</div>
|
||||
|
||||
<!-- 基线管道:流程节点 -->
|
||||
<div class="pipeline" aria-hidden="true">
|
||||
<i></i><i></i><i></i>
|
||||
</div>
|
||||
|
||||
<!-- 顶部:品牌 + 系统状态 -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="mark">37</span>
|
||||
<span class="name">{{ appName || '37du 自动化工作台' }}</span>
|
||||
</div>
|
||||
<div class="sys">
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
<span>引擎运行中</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 中央:接入终端 -->
|
||||
<main class="panel">
|
||||
<span class="core-mark">37 CORE · AUTOMATION</span>
|
||||
<h1>自动化工作台</h1>
|
||||
<p class="sub">使用统一账号或钉钉扫码,进入你的流程中心</p>
|
||||
|
||||
<el-form label-position="top" class="form" @submit.prevent="doLogin">
|
||||
<el-form-item label="员工账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" autocomplete="username" size="large" clearable
|
||||
@keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="password" type="password" placeholder="请输入密码" autocomplete="current-password" size="large"
|
||||
show-password @keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" size="large" class="primary" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '进 入 中 …' : '进 入 工 作 台' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="divider"><span>或</span></div>
|
||||
|
||||
<el-button size="large" class="dingtalk" :loading="dingBusy" :icon="ChatDotRound" @click="openDing">
|
||||
钉钉扫码接入
|
||||
</el-button>
|
||||
</main>
|
||||
|
||||
<!-- 底部:流程状态 -->
|
||||
<footer class="footbar">
|
||||
<div class="flows">
|
||||
<span>接入终端就绪</span>
|
||||
<span class="f-blocks" aria-hidden="true">
|
||||
<i></i><i></i><i></i><i></i><i></i>
|
||||
</span>
|
||||
</div>
|
||||
<span class="copyright">© 37du 自动化工作台</span>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ChatDotRound } from '@element-plus/icons-vue'
|
||||
import { adminLogin, authDingtalk } from '../api'
|
||||
|
||||
defineProps({ appName: { type: String, default: '' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const dingBusy = ref(false)
|
||||
|
||||
async function doLogin() {
|
||||
if (busy.value) return
|
||||
if (!account.value.trim() || !password.value) { ElMessage.warning('请输入账号和密码'); return }
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
ElMessage.success('登录成功')
|
||||
emit('ok', {
|
||||
account: account.value.trim(),
|
||||
dept: r.dept || '',
|
||||
must_change_pwd: !!r.must_change_pwd,
|
||||
nickname: r.nickname || '',
|
||||
avatar: r.avatar || ''
|
||||
})
|
||||
} catch (e) {
|
||||
ElMessage.error('登录失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 钉钉扫码登录:壳后端直接生成授权 URL,当前窗口跳转钉钉;扫码后浏览器自动跳回 /auth/done
|
||||
async function openDing() {
|
||||
if (dingBusy.value) return
|
||||
dingBusy.value = true
|
||||
try {
|
||||
const r = await authDingtalk()
|
||||
if (r && r.url) {
|
||||
window.location.href = r.url
|
||||
return
|
||||
}
|
||||
ElMessage.error('钉钉登录未配置,请联系管理员')
|
||||
} catch (e) {
|
||||
ElMessage.error('钉钉登录不可用:' + (e.message || e))
|
||||
}
|
||||
dingBusy.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ============================================================
|
||||
暖米画布 + 工程网格 + 点阵 37 + 接入终端
|
||||
- 精密感来自网格与节点,不来自阴影
|
||||
- 体温红只出现在:port 聚焦、主按钮、管线节点、状态点
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 画布 ---------- */
|
||||
.login {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 110px 24px 170px;
|
||||
overflow: hidden;
|
||||
background: #EDE7DB;
|
||||
color: #1C1712;
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
/* 工程网格:边缘径向淡出 */
|
||||
.login::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(28, 23, 18, .045) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(28, 23, 18, .045) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
-webkit-mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 顶部暖辉光 */
|
||||
.login::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background: radial-gradient(660px 480px at 50% 38%, rgba(209, 74, 43, .06), transparent 68%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 巨大 37:节点阵列 ---------- */
|
||||
.ghost {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: -0.12em;
|
||||
transform: translateX(-50%);
|
||||
font-family: 'Helvetica Neue', 'Arial Narrow', Arial, sans-serif;
|
||||
font-size: clamp(280px, 74vw, 640px);
|
||||
font-weight: 800;
|
||||
line-height: .72;
|
||||
letter-spacing: -.08em;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
color: rgba(28, 23, 18, .05);
|
||||
/* 兜底 */
|
||||
animation: breathe 7s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .8;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@supports ((-webkit-background-clip: text) or (background-clip: text)) {
|
||||
.ghost {
|
||||
color: transparent;
|
||||
background-image: radial-gradient(circle at 1px 1px,
|
||||
rgba(28, 23, 18, .16) 1px, transparent 1.9px);
|
||||
background-size: 9px 9px;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 基线管道 ---------- */
|
||||
.pipeline {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 0;
|
||||
transform: translateX(-50%);
|
||||
width: min(920px, 92vw);
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg,
|
||||
transparent, rgba(28, 23, 18, .14) 18%,
|
||||
rgba(28, 23, 18, .14) 82%, transparent);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pipeline i {
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .10);
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(1) {
|
||||
left: 22%;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(2) {
|
||||
left: 50%;
|
||||
animation: blip 3.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(3) {
|
||||
left: 78%;
|
||||
}
|
||||
|
||||
@keyframes blip {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .35;
|
||||
transform: scale(.85);
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 顶部栏 ---------- */
|
||||
.topbar {
|
||||
position: absolute;
|
||||
top: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mark {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #F7F2E8;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .01em;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .04em;
|
||||
color: #6B6155;
|
||||
}
|
||||
|
||||
.sys {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
animation: pulse 2.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, .4);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px rgba(209, 74, 43, 0);
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.sep {
|
||||
color: #C4BBA8;
|
||||
}
|
||||
|
||||
/* ---------- 中央:接入终端 ---------- */
|
||||
.panel {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
padding: 40px 36px 36px;
|
||||
background: #F8F4EC;
|
||||
border: 1px solid #DDD4C2;
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
0 1px 0 rgba(255, 255, 255, .9) inset,
|
||||
0 24px 48px -28px rgba(28, 23, 18, .30);
|
||||
animation: rise .45s cubic-bezier(.22, 1, .36, 1) both;
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* 卡片内元素依次点亮:终端端口逐个上电 */
|
||||
@keyframes seq {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
animation: seq .5s .05s both;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
animation: seq .5s .10s both;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
animation: seq .5s .15s both;
|
||||
}
|
||||
|
||||
.form {
|
||||
animation: seq .55s .20s both;
|
||||
}
|
||||
|
||||
.divider {
|
||||
animation: seq .5s .26s both;
|
||||
}
|
||||
|
||||
.dingtalk {
|
||||
animation: seq .5s .32s both;
|
||||
}
|
||||
|
||||
/* 底部金手指纹理 */
|
||||
.panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 36px;
|
||||
right: 36px;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background-image: repeating-linear-gradient(to right,
|
||||
rgba(201, 191, 171, .65) 0 8px,
|
||||
transparent 8px 12px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
display: block;
|
||||
margin-bottom: 20px;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .18em;
|
||||
color: #D14A2B;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
letter-spacing: -.01em;
|
||||
color: #1C1712;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
margin: 0 0 34px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 表单:接口式输入 ---------- */
|
||||
.form :deep(.el-form-item) {
|
||||
position: relative;
|
||||
padding-left: 16px;
|
||||
margin-bottom: 26px;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__content) {
|
||||
position: relative;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
/* 左侧接口指示灯 */
|
||||
.form :deep(.el-form-item__content)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -16px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: #C9BFAB;
|
||||
transition: background .2s, box-shadow .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item:focus-within .el-form-item__content)::before {
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .12);
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
line-height: 1.4;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* 底线式输入 */
|
||||
.form :deep(.el-input__wrapper) {
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
box-shadow: none !important;
|
||||
border-bottom: 1px solid #D8D0BC;
|
||||
transition: border-color .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper:hover) {
|
||||
border-bottom-color: #BCB29A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper.is-focus) {
|
||||
border-bottom-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner) {
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
color: #1C1712;
|
||||
caret-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner::placeholder) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix),
|
||||
.form :deep(.el-input__prefix),
|
||||
.form :deep(.el-input__suffix-inner) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix-inner .el-input__icon:hover) {
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 主按钮 ---------- */
|
||||
.primary.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
margin-top: 6px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #FFF8F2;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .12em;
|
||||
box-shadow: 0 12px 28px -14px rgba(209, 74, 43, .7);
|
||||
transition: background-color .15s, opacity .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.primary.el-button:hover,
|
||||
.primary.el-button:focus {
|
||||
background: #BB3F21;
|
||||
color: #FFF8F2;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 15px 30px -14px rgba(209, 74, 43, .78);
|
||||
}
|
||||
|
||||
.primary.el-button:active {
|
||||
background: #A53517;
|
||||
transform: translateY(1px) scale(.99);
|
||||
box-shadow: 0 6px 16px -12px rgba(209, 74, 43, .8);
|
||||
}
|
||||
|
||||
.primary.el-button.is-disabled,
|
||||
.primary.el-button.is-loading {
|
||||
background: #D14A2B;
|
||||
opacity: .55;
|
||||
}
|
||||
|
||||
/* ---------- 分隔线 ---------- */
|
||||
.divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin: 28px 0 16px;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: .04em;
|
||||
color: #8D8476;
|
||||
}
|
||||
|
||||
.divider::before,
|
||||
.divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: #E0D9C6;
|
||||
}
|
||||
|
||||
/* ---------- 钉钉按钮 ---------- */
|
||||
.dingtalk.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #DED6C2;
|
||||
background: #FDFBF6;
|
||||
color: #1C1712;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
transition: border-color .15s, background-color .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.dingtalk.el-button:hover,
|
||||
.dingtalk.el-button:focus {
|
||||
border-color: #C4BBA8;
|
||||
background: #FFFFFF;
|
||||
color: #1C1712;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 8px 20px -14px rgba(28, 23, 18, .28);
|
||||
}
|
||||
|
||||
.dingtalk.el-button:active {
|
||||
transform: translateY(0) scale(.99);
|
||||
}
|
||||
|
||||
.dingtalk.el-button :deep(.el-icon) {
|
||||
color: #1491F0;
|
||||
}
|
||||
|
||||
/* ---------- 键盘可达 ---------- */
|
||||
.primary.el-button:focus-visible,
|
||||
.dingtalk.el-button:focus-visible {
|
||||
outline: 2px solid #D14A2B;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
/* ---------- 底部:流程状态 ---------- */
|
||||
.footbar {
|
||||
position: absolute;
|
||||
bottom: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.flows {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.f-blocks {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.f-blocks i {
|
||||
width: 12px;
|
||||
height: 4px;
|
||||
border-radius: 1px;
|
||||
background: #C9BEAA;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .1em;
|
||||
color: #9A8F7C;
|
||||
}
|
||||
|
||||
/* ---------- 自适应 ---------- */
|
||||
@media (max-width: 720px) {
|
||||
.login {
|
||||
padding: 96px 20px 140px;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
top: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
bottom: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
padding: 32px 24px 30px;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
font-size: 23px;
|
||||
}
|
||||
|
||||
.panel::after {
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 680px) {
|
||||
.login {
|
||||
align-items: flex-start;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 80px 24px 120px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
.dot,
|
||||
.pipeline i,
|
||||
.ghost {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.panel {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.core-mark,
|
||||
.panel h1,
|
||||
.panel .sub,
|
||||
.form,
|
||||
.divider,
|
||||
.dingtalk {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
* {
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,330 +0,0 @@
|
||||
<template>
|
||||
<div v-if="plugin" class="plugin-page">
|
||||
<!-- 页头 -->
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
|
||||
<div class="ident-meta">
|
||||
<h2>{{ plugin.name }} <span class="ver-tag">v{{ plugin.version }}</span></h2>
|
||||
<p>{{ plugin.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="plugin?.uses_month" class="month">
|
||||
<span class="field-label">执行月份</span>
|
||||
<el-select v-model="month" class="month-sel" :disabled="store.running">
|
||||
<el-option v-for="m in months" :key="m" :value="m" :label="m" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果横幅 -->
|
||||
<el-alert v-if="store.lastResult" :type="store.lastResult.ok ? 'success' : 'error'" :closable="true"
|
||||
:close-text="null" class="banner" @close="closeBanner" show-icon>
|
||||
<template #title>
|
||||
<span>
|
||||
{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败:' + store.lastResult.error }}
|
||||
</span>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 专属界面插件:插件 UI 直接内嵌在页面主体(同源共享会话 cookie,不再弹窗/外跳),日志保持在其下方可见 -->
|
||||
<div v-if="plugin.ui" class="ui-inline">
|
||||
<div class="ui-tip">个性化配置项在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<iframe :key="plugin.id" :src="uiSrc" class="pui-frame" title="插件界面"></iframe>
|
||||
</div>
|
||||
|
||||
<!-- 参数 -->
|
||||
<template v-else>
|
||||
<div class="sec-head">
|
||||
<span class="sec-title">参数配置</span>
|
||||
<el-button v-if="Object.keys(form).length" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
</div>
|
||||
<el-form label-width="auto" class="form-card">
|
||||
<div class="fields">
|
||||
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
|
||||
<template v-if="f.type === 'int'">
|
||||
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
|
||||
</template>
|
||||
<el-input v-else-if="f.type === 'password'" v-model="form[f.key]" type="password" show-password
|
||||
:placeholder="String(f.default ?? '')" :disabled="store.running">
|
||||
<template v-if="f.help || f.description" #suffix>
|
||||
<el-tooltip :content="f.help || f.description" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form[f.key]" :placeholder="String(f.default ?? '')"
|
||||
:disabled="store.running">
|
||||
<template v-if="f.help || f.description" #suffix>
|
||||
<el-tooltip :content="f.help || f.description" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select v-else-if="f.type === 'multiselect'" v-model="form[f.key]" multiple filterable allow-create
|
||||
default-first-option placeholder="选择或输入后回车" :disabled="store.running">
|
||||
<el-option v-for="opt in (f.options || [])" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
<el-select v-else v-model="form[f.key]" :disabled="store.running">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span v-if="store.running" class="run-ind">
|
||||
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
|
||||
</span>
|
||||
<el-button type="primary" size="large" :loading="store.running" @click="run">
|
||||
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<p v-if="!plugin.ui" class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
</div>
|
||||
|
||||
<el-empty v-else-if="!store.plugins.length" description="当前账号暂无可用场景" />
|
||||
<el-empty v-else description="未选择场景" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { QuestionFilled, RefreshLeft } from '@element-plus/icons-vue'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
const now = new Date()
|
||||
const list = []
|
||||
for (let off = 1; off <= 6; off++) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - off, 1)
|
||||
list.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
|
||||
}
|
||||
return list
|
||||
})
|
||||
const month = ref(months.value[0])
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
const idx = computed(() => Math.max(0, store.plugins.findIndex((p) => p.id === store.selectedId)))
|
||||
const avatarBg = computed(() => PALETTE[idx.value % PALETTE.length])
|
||||
|
||||
const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null)
|
||||
|
||||
const form = ref({})
|
||||
|
||||
function buildFormDefaults(p) {
|
||||
const f = {}
|
||||
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
|
||||
return f
|
||||
}
|
||||
|
||||
watch(
|
||||
() => plugin.value?.id,
|
||||
(id) => {
|
||||
form.value = buildFormDefaults(store.plugins.find((x) => x.id === id))
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function resetForm() {
|
||||
form.value = buildFormDefaults(plugin.value)
|
||||
}
|
||||
|
||||
// 专属界面插件:插件 UI 直接内嵌在页面主体(同源自动携带会话 cookie,不再弹窗/外跳)。
|
||||
// 不能用 window.open 外跳:壳子是 PyWebView 窗口,系统浏览器里没有会话 cookie,会 401。
|
||||
const uiSrc = computed(() => (plugin.value?.ui ? `/pui/${plugin.value.id}/` : ''))
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
if (plugin.value.platform && !(store.platforms.find((p) => p.id === plugin.value.platform)?.online)) {
|
||||
log('WARN', `插件「${plugin.value.name}」需要先登录平台「${store.platforms.find((p) => p.id === plugin.value.platform)?.label || plugin.value.platform}」才能正确执行`)
|
||||
}
|
||||
store.running = true
|
||||
store.progress = 0
|
||||
store.currentRun = ''
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
try {
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
} catch (e) {
|
||||
store.running = false
|
||||
store.lastResult = { ok: false, error: e.message || String(e) }
|
||||
log('ERROR', `启动执行失败:${e.message || e}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
watch(
|
||||
() => store.lastResult,
|
||||
async (res) => {
|
||||
if (res && res.ok && store.lastRunId) {
|
||||
try {
|
||||
const run = await getRun(store.lastRunId)
|
||||
store.lastSummary = run.result?.summary || ''
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function closeBanner() {
|
||||
store.lastResult = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.plugin-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ident {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 13px;
|
||||
flex-shrink: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.ident-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ident-meta h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ident-meta p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.ver-tag {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--text-faint);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.month {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.month-sel {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.ui-inline {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ui-tip {
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
background: var(--surface-2, #f7f8fa);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.pui-frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
min-height: 420px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: #f6f7fb;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-card .el-form-item {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.help-ic {
|
||||
color: var(--text-faint);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 14px;
|
||||
border-top: 1px dashed var(--border);
|
||||
padding-top: 14px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.run-ind {
|
||||
flex: 1;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
margin: 0;
|
||||
padding-left: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,353 +0,0 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>已授权插件</span>
|
||||
<span class="mono">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>平台在线</span>
|
||||
<span class="mono">{{ store.platforms.filter(p => p.online).length }}/{{ store.platforms.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 折叠面板:平台登录态 / 我的插件 / 修改密码 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<span>平台登录态</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-for="(p, i) in store.platforms" :key="p.id" class="prow">
|
||||
<span class="ridx mono">P0{{ i + 1 }}</span>
|
||||
<span class="dot" :class="{ on: p.online }"></span>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<el-button size="small" :disabled="busy === p.id || p.online" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : p.online ? '正常' : '重新登录' }}
|
||||
</el-button>
|
||||
<el-button v-if="p.online" size="small" plain type="danger" :disabled="busy === p.id" @click="logout(p.id)">登出</el-button>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Box /></el-icon>
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
<span class="iname">{{ p.name }}</span>
|
||||
<span class="mono iver">v{{ p.version }}</span>
|
||||
<span class="i-dot"></span>
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先昵称(真实姓名),无昵称时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins']) // 修改密码默认折叠,点击展开
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
ElMessage.success(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
ElMessage.success(`平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
ElMessage.error(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
ElMessage.success(`平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const formRef = ref()
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v && v === form.oldPwd
|
||||
? cb(new Error('新密码不能与原密码相同')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v !== form.newPwd
|
||||
? cb(new Error('两次输入的密码不一致')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
}
|
||||
const pwdBusy = ref(false)
|
||||
async function changePwd() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: form.oldPwd,
|
||||
new_password: form.newPwd,
|
||||
})
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mono { font-family: var(--font-mono); letter-spacing: .04em; }
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 11px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: var(--text); font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.prow:last-child { border-bottom: none; }
|
||||
.ridx { flex: none; width: 26px; font-size: 11px; color: var(--text-faint); }
|
||||
.dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: #c6ccdc;
|
||||
}
|
||||
.dot.on { background: #22b07a; box-shadow: 0 0 0 3px rgba(34, 176, 122, .16); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.prow :deep(.el-button--primary) { border-color: transparent; }
|
||||
.prow :deep(.el-button--danger.is-plain) { border-color: rgba(214, 69, 69, .35); color: #d64545; }
|
||||
|
||||
/* ---------- 我的插件:台账式列表 ---------- */
|
||||
.ilist { display: flex; flex-direction: column; }
|
||||
.irow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
</style>
|
||||
@@ -1,583 +0,0 @@
|
||||
<template>
|
||||
<div class="sched-page">
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar"><el-icon><Clock /></el-icon></span>
|
||||
<div class="ident-meta">
|
||||
<h2>定时任务</h2>
|
||||
<p>壳子内置定时:按 cron 到点自动执行插件,配置自动备份到中心机防丢失</p>
|
||||
</div>
|
||||
</div>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建任务</el-button>
|
||||
</div>
|
||||
|
||||
<el-empty v-if="!list.length" description="暂无定时任务,点击右上角「新建任务」创建" />
|
||||
|
||||
<el-table v-else :data="list" class="sched-table" row-key="id">
|
||||
<el-table-column label="任务" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">
|
||||
<span class="t-name">{{ row.name }}</span>
|
||||
<span class="t-plugin">{{ pluginName(row.plugin_id) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="cron 表达式" width="140">
|
||||
<template #default="{ row }">
|
||||
<code class="cron">{{ row.cron }}</code>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="下次执行" width="158">
|
||||
<template #default="{ row }">{{ row.next_run_at || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近执行" width="158">
|
||||
<template #default="{ row }">{{ row.last_run_at || '从未' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="启用" width="80" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-switch :model-value="row.enabled" @change="(v) => onToggle(row, v)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" @click="onDelete(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="min(780px, 94vw)" align-center
|
||||
class="sched-dlg">
|
||||
<el-form label-width="86px" class="dlg-form">
|
||||
<el-form-item label="任务名称">
|
||||
<el-input v-model="form.name" placeholder="如:每日考勤封存检查" maxlength="32" />
|
||||
</el-form-item>
|
||||
<el-form-item label="执行插件">
|
||||
<el-select v-model="form.plugin_id" placeholder="选择要定时执行的插件" class="w-full" @change="onPluginChange">
|
||||
<el-option v-for="p in store.plugins" :key="p.id" :value="p.id"
|
||||
:label="`${p.name}(${p.id})`" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="触发时间">
|
||||
<div class="freq-zone">
|
||||
<el-radio-group v-model="freq" class="freq-tabs" size="small">
|
||||
<el-radio-button value="daily">每天</el-radio-button>
|
||||
<el-radio-button value="weekdays">工作日</el-radio-button>
|
||||
<el-radio-button value="weekly">每周</el-radio-button>
|
||||
<el-radio-button value="monthly">每月</el-radio-button>
|
||||
<el-radio-button value="hourly">每隔 N 小时</el-radio-button>
|
||||
<el-radio-button value="advanced">高级</el-radio-button>
|
||||
</el-radio-group>
|
||||
|
||||
<!-- 每天 / 工作日 -->
|
||||
<div v-if="freq === 'daily' || freq === 'weekdays'" class="freq-row">
|
||||
<span class="freq-desc">{{ freq === 'daily' ? '每天' : '周一至周五' }}</span>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每周:选周几 + 时间 -->
|
||||
<div v-else-if="freq === 'weekly'" class="freq-row">
|
||||
<span class="freq-desc">每周</span>
|
||||
<el-checkbox-group v-model="weekdays" class="week-days">
|
||||
<el-checkbox-button v-for="d in weekDayOpts" :key="d.v" :value="d.v">{{ d.label }}</el-checkbox-button>
|
||||
</el-checkbox-group>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每月:选几号 + 时间 -->
|
||||
<div v-else-if="freq === 'monthly'" class="freq-row">
|
||||
<span class="freq-desc">每月</span>
|
||||
<el-select v-model="monthDay" class="day-sel">
|
||||
<el-option v-for="d in 31" :key="d" :value="d" :label="`${d} 日`" />
|
||||
</el-select>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每隔 N 小时 -->
|
||||
<div v-else-if="freq === 'hourly'" class="freq-row">
|
||||
<span class="freq-desc">每隔</span>
|
||||
<el-input-number v-model="hourlyStep" :min="1" :max="24" :controls="false" class="step-num" />
|
||||
<span class="freq-desc">小时执行一次(整点)</span>
|
||||
</div>
|
||||
|
||||
<!-- 高级:直接写 cron -->
|
||||
<div v-else class="freq-row col">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="advancedCron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</div>
|
||||
|
||||
<!-- 非高级模式下实时预览生成的 cron -->
|
||||
<div v-if="freq !== 'advanced'" class="cron-preview">
|
||||
表达式 <code>{{ form.cron }}</code>
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="pluginFields.length" label="执行参数">
|
||||
<div class="fields">
|
||||
<div v-for="f in pluginFields" :key="f.key" class="field">
|
||||
<span class="field-label">{{ f.label }}</span>
|
||||
<el-input-number v-if="f.type === 'int'" v-model="form.fields[f.key]" :controls="false"
|
||||
placeholder="0" class="field-ctl" />
|
||||
<el-input v-else-if="f.type === 'password'" v-model="form.fields[f.key]" type="password"
|
||||
show-password :placeholder="String(f.default ?? '')" class="field-ctl" />
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form.fields[f.key]"
|
||||
:placeholder="String(f.default ?? '')" class="field-ctl" />
|
||||
<el-select v-else-if="f.type === 'multiselect'" v-model="form.fields[f.key]" multiple
|
||||
filterable allow-create default-first-option placeholder="选择或输入后回车" class="field-ctl">
|
||||
<el-option v-for="opt in (f.options || [])" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
<el-select v-else v-model="form.fields[f.key]" class="field-ctl">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="启用">
|
||||
<el-switch v-model="form.enabled" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="onSave">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock, Plus } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
import { listSchedules, createSchedule, updateSchedule, deleteSchedule, toggleSchedule } from '../api'
|
||||
|
||||
const list = ref([])
|
||||
const dlg = ref(false)
|
||||
const editing = ref(null)
|
||||
const saving = ref(false)
|
||||
const preset = ref('')
|
||||
|
||||
// ---- 闹钟式触发时间选择状态 ----
|
||||
// freq: daily=每天 weekdays=工作日 weekly=每周 monthly=每月 hourly=每隔N小时 advanced=高级cron
|
||||
const freq = ref('daily')
|
||||
const timeStr = ref('08:00')
|
||||
const weekdays = ref([1])
|
||||
const monthDay = ref(1)
|
||||
const hourlyStep = ref(1)
|
||||
const advancedCron = ref('')
|
||||
const weekDayOpts = [
|
||||
{ v: 1, label: '周一' }, { v: 2, label: '周二' }, { v: 3, label: '周三' },
|
||||
{ v: 4, label: '周四' }, { v: 5, label: '周五' }, { v: 6, label: '周六' }, { v: 7, label: '周日' },
|
||||
]
|
||||
|
||||
function pad2(n) { return String(n).padStart(2, '0') }
|
||||
|
||||
// 由可视化选择状态生成 cron 表达式(分钟/小时补齐 2 位,兼容解析)
|
||||
function buildCron() {
|
||||
const [h, m] = timeStr.value.split(':').map(Number)
|
||||
switch (freq.value) {
|
||||
case 'daily': return `${pad2(m)} ${pad2(h)} * * *`
|
||||
case 'weekdays': return `${pad2(m)} ${pad2(h)} * * 1-5`
|
||||
case 'weekly': {
|
||||
const ds = (weekdays.value.length ? weekdays.value : [1]).slice().sort((a, b) => a - b)
|
||||
return `${pad2(m)} ${pad2(h)} * * ${ds.join(',')}`
|
||||
}
|
||||
case 'monthly': return `${pad2(m)} ${pad2(h)} ${monthDay.value} * *`
|
||||
case 'hourly': return `0 */${hourlyStep.value || 1} * * *`
|
||||
default: return advancedCron.value.trim()
|
||||
}
|
||||
}
|
||||
|
||||
// 把已有 cron 反向解析为可视化选择状态;无法识别的回退到高级模式原样展示
|
||||
function cronToState(cron) {
|
||||
const s = String(cron || '').trim()
|
||||
const parts = s.split(/\s+/)
|
||||
const st = { freq: 'advanced', timeStr: '08:00', weekdays: [1], monthDay: 1, hourlyStep: 1, advancedCron: s }
|
||||
if (parts.length !== 5) return st
|
||||
const [m, h, dom, mon, dow] = parts
|
||||
// 每隔 N 小时:0 */N * * *
|
||||
if (m === '0' && /^\*\/\d+$/.test(h) && dom === '*' && mon === '*' && dow === '*') {
|
||||
const step = parseInt(h.split('/')[1], 10)
|
||||
if (step >= 1 && step <= 24) return { ...st, freq: 'hourly', hourlyStep: step }
|
||||
}
|
||||
const num = (x) => (/^\d+$/.test(x) ? parseInt(x, 10) : null)
|
||||
const mn = num(m), hr = num(h)
|
||||
if (mn == null || hr == null || mn < 0 || mn > 59 || hr < 0 || hr > 23) return st
|
||||
const hhmm = pad2(hr) + ':' + pad2(mn)
|
||||
if (dom === '*' && mon === '*') {
|
||||
if (dow === '*') return { ...st, freq: 'daily', timeStr: hhmm }
|
||||
if (dow === '1-5') return { ...st, freq: 'weekdays', timeStr: hhmm }
|
||||
if (/^[0-7](,[0-7])*$/.test(dow)) {
|
||||
const ds = [...new Set(dow.split(',').map(Number).map((x) => (x === 0 ? 7 : x)))].sort((a, b) => a - b)
|
||||
return { ...st, freq: 'weekly', timeStr: hhmm, weekdays: ds }
|
||||
}
|
||||
return st
|
||||
}
|
||||
if (dow === '*' && mon === '*') {
|
||||
const dd = num(dom)
|
||||
if (dd != null && dd >= 1 && dd <= 31) return { ...st, freq: 'monthly', timeStr: hhmm, monthDay: dd }
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// 同步状态 → form.cron(打开弹窗时立即生成一次)
|
||||
function syncCron() {
|
||||
if (freq.value !== 'advanced') form.value.cron = buildCron()
|
||||
}
|
||||
|
||||
// 选择状态变化时自动重写 form.cron
|
||||
watch([freq, timeStr, weekdays, monthDay, hourlyStep], syncCron)
|
||||
watch(advancedCron, (v) => {
|
||||
if (freq.value === 'advanced') form.value.cron = v.trim()
|
||||
})
|
||||
|
||||
const presets = [
|
||||
{ label: '每天 08:00', cron: '0 8 * * *' },
|
||||
{ label: '每天 12:00', cron: '0 12 * * *' },
|
||||
{ label: '每天 18:00', cron: '0 18 * * *' },
|
||||
{ label: '每小时整点', cron: '0 * * * *' },
|
||||
{ label: '每周一 09:00', cron: '0 9 * * 1' },
|
||||
{ label: '每月 1 日 09:00', cron: '0 9 1 * *' },
|
||||
]
|
||||
|
||||
const form = ref({ name: '', plugin_id: '', cron: '', enabled: true, fields: {} })
|
||||
|
||||
const pluginFields = computed(() => {
|
||||
const p = store.plugins.find((x) => x.id === form.value.plugin_id)
|
||||
return (p && p.fields) || []
|
||||
})
|
||||
|
||||
function pluginName(id) {
|
||||
return store.plugins.find((p) => p.id === id)?.name || id
|
||||
}
|
||||
|
||||
function buildFields(p) {
|
||||
const f = {}
|
||||
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
|
||||
return f
|
||||
}
|
||||
|
||||
function onPluginChange(id) {
|
||||
form.value.fields = buildFields(store.plugins.find((x) => x.id === id))
|
||||
}
|
||||
|
||||
function onPreset(cron) {
|
||||
advancedCron.value = cron
|
||||
preset.value = ''
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const r = await listSchedules()
|
||||
list.value = r.schedules || []
|
||||
} catch (e) {
|
||||
ElMessage.error('加载定时任务失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editing.value = null
|
||||
form.value = { name: '', plugin_id: '', cron: '', enabled: true, fields: {} }
|
||||
// 默认:每天 08:00
|
||||
freq.value = 'daily'
|
||||
timeStr.value = '08:00'
|
||||
weekdays.value = [1]
|
||||
monthDay.value = 1
|
||||
hourlyStep.value = 1
|
||||
advancedCron.value = ''
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {
|
||||
name: row.name || '',
|
||||
plugin_id: row.plugin_id || '',
|
||||
cron: row.cron || '',
|
||||
enabled: !!row.enabled,
|
||||
fields: buildFields(store.plugins.find((x) => x.id === row.plugin_id)),
|
||||
}
|
||||
Object.assign(form.value.fields, row.fields || {})
|
||||
// 把已有 cron 解析回可视化选择状态
|
||||
const st = cronToState(row.cron || '')
|
||||
freq.value = st.freq
|
||||
timeStr.value = st.timeStr
|
||||
weekdays.value = st.weekdays
|
||||
monthDay.value = st.monthDay
|
||||
hourlyStep.value = st.hourlyStep
|
||||
advancedCron.value = st.advancedCron
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function onSave() {
|
||||
if (!form.value.plugin_id) { ElMessage.warning('请选择执行插件'); return }
|
||||
if (!form.value.cron.trim()) { ElMessage.warning('请填写 cron 表达式'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
if (editing.value) {
|
||||
await updateSchedule(editing.value.id, { ...form.value })
|
||||
ElMessage.success('已保存')
|
||||
} else {
|
||||
await createSchedule({ ...form.value })
|
||||
ElMessage.success('已创建,配置已备份到中心机')
|
||||
}
|
||||
dlg.value = false
|
||||
await load()
|
||||
} catch (e) {
|
||||
ElMessage.error(e.message || String(e))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onToggle(row, v) {
|
||||
try {
|
||||
await toggleSchedule(row.id, v)
|
||||
row.enabled = v
|
||||
ElMessage.success(v ? '已启用' : '已停用')
|
||||
} catch (e) {
|
||||
ElMessage.error('操作失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(row) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除定时任务「${row.name}」?删除后其配置备份会一并移除。`, '删除确认', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
})
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await deleteSchedule(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
} catch (e) {
|
||||
ElMessage.error('删除失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
load()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sched-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ident {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 13px;
|
||||
flex-shrink: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
background: var(--primary-grad, linear-gradient(135deg, #3b6cff, #7c5cff));
|
||||
box-shadow: var(--shadow-md);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.ident-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ident-meta h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.ident-meta p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
.sched-table {
|
||||
--el-table-border-color: var(--border);
|
||||
--el-table-header-bg-color: var(--surface-2, #f7f8fa);
|
||||
}
|
||||
|
||||
.cell-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.t-name {
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.t-plugin {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.cron {
|
||||
font-family: Consolas, Monaco, monospace;
|
||||
font-size: 12px;
|
||||
color: var(--primary);
|
||||
background: var(--primary-weak, #eef2ff);
|
||||
border-radius: 6px;
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.cron-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cron-input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.preset-sel {
|
||||
width: 128px;
|
||||
}
|
||||
|
||||
.cron-tip {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
margin-top: 6px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---- 闹钟式触发时间选择 ---- */
|
||||
.freq-zone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.freq-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-row.col {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.freq-desc {
|
||||
font-size: 13px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.time-sel {
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.day-sel {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
.step-num {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.week-days {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cron-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.cron-preview code {
|
||||
padding: 1px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--surface-2, #f7f8fa);
|
||||
border: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px 14px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
width: 96px;
|
||||
flex-shrink: 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
.field-ctl {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.w-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 定时任务弹窗:内容超高时弹窗内滚动,避免配置多的插件把弹窗顶出屏幕 */
|
||||
:deep(.sched-dlg .el-dialog) {
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
:deep(.sched-dlg .el-dialog__body) {
|
||||
max-height: 62vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,14 +0,0 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import 'element-plus/dist/index.css'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
const app = createApp(App)
|
||||
// 全量注册图标,模板中可直接 <component :is="XxxIcon"> 使用
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -1,101 +0,0 @@
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '',
|
||||
platforms: [],
|
||||
plugins: [],
|
||||
selectedId: '',
|
||||
logs: [], // {time, level, msg}
|
||||
progress: 0,
|
||||
running: false,
|
||||
currentRun: '', // 当前接收日志/进度的 run_id
|
||||
lastRunId: '', // 最近一次执行的 run_id
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 个人身份信息(中心机 accounts,登录/会话校验回填)
|
||||
dept: '',
|
||||
nickname: '', // 真实姓名(中心机 accounts.nickname,钉钉登录时自动带入)
|
||||
avatar: '', // 账号头像文件名(中心机 accounts.avatar,用户上传)
|
||||
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 当前主视图(插件页)
|
||||
authExpired: false, // 授权票据已过期(最长离线 7 天),须联网刷新才能继续使用
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
// 缓存按账号隔离(cp_avatar_url_<账号>),切换账号不会串用上一个人的头像
|
||||
const AVATAR_API = 'https://v2.xxapi.cn/api/head'
|
||||
|
||||
function avatarCacheKey() {
|
||||
return `cp_avatar_url_${store.current || 'anon'}`
|
||||
}
|
||||
|
||||
export function loadAvatar() {
|
||||
const key = avatarCacheKey()
|
||||
try {
|
||||
const cached = localStorage.getItem(key)
|
||||
if (cached) { store.avatarUrl = cached; return }
|
||||
} catch (_) {}
|
||||
store.avatarUrl = ''
|
||||
fetch(AVATAR_API, { signal: AbortSignal.timeout(4000) })
|
||||
.then((r) => r.json())
|
||||
.then((j) => {
|
||||
if (j && j.code === 200 && j.data) {
|
||||
store.avatarUrl = j.data
|
||||
try { localStorage.setItem(avatarCacheKey(), j.data) } catch (_) {}
|
||||
}
|
||||
})
|
||||
.catch(() => { /* 网络不可达/超时:保持首字符色块兜底 */ })
|
||||
}
|
||||
|
||||
export function clearAvatarCache() {
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem(avatarCacheKey()) } catch (_) {}
|
||||
loadAvatar()
|
||||
}
|
||||
|
||||
// 头像优先级:账号上传头像(中心机) > 外部随机头像 > 首字符兜底
|
||||
export function accountAvatar() {
|
||||
if (store.avatar) {
|
||||
return `/api/avatar/${store.current}?v=${encodeURIComponent(store.avatar)}`
|
||||
}
|
||||
return store.avatarUrl
|
||||
}
|
||||
|
||||
export function clearLogs() {
|
||||
store.logs = []
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
}
|
||||
|
||||
export function log(level, msg) {
|
||||
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
store.logs.push({ time, level, msg })
|
||||
if (store.logs.length > 500) store.logs.splice(0, store.logs.length - 500)
|
||||
}
|
||||
|
||||
export function handleEvent(ev) {
|
||||
switch (ev.t) {
|
||||
case 'run_start':
|
||||
store.currentRun = ev.run_id
|
||||
if (!store.running) { clearLogs() }
|
||||
break
|
||||
case 'log':
|
||||
if (ev.run_id === store.currentRun || !store.currentRun) {
|
||||
log(ev.level || 'INFO', ev.msg)
|
||||
}
|
||||
break
|
||||
case 'progress':
|
||||
if (ev.run_id === store.currentRun) store.progress = ev.pct
|
||||
break
|
||||
case 'run_done':
|
||||
store.running = false
|
||||
store.progress = 100
|
||||
store.lastResult = { ok: ev.ok, error: ev.error || '' }
|
||||
if (ev.ok) log('INFO', '===== 执行完成 =====')
|
||||
else log('ERROR', `执行失败:${ev.error}`)
|
||||
store.currentRun = ''
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
|
||||
/* element-plus 主题与品牌蓝统一 */
|
||||
--el-color-primary: #3b6cff;
|
||||
--el-color-primary-light-3: #6f8dff;
|
||||
--el-color-primary-light-5: #a3b7ff;
|
||||
--el-color-primary-light-7: #d0dcff;
|
||||
--el-color-primary-light-8: #e2e9ff;
|
||||
--el-color-primary-light-9: #eef2ff;
|
||||
--el-color-primary-dark-2: #2f56d6;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-border-radius-small: 6px;
|
||||
--el-border-radius-round: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
@@ -1,19 +0,0 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// dev 时把 /api 与 /ws 代理到 FastAPI 后端,实现前后端分离开发
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
@@ -1,249 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
FROZEN = getattr(sys, "frozen", False)
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn", "37du-host")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _wait_ready(proc: subprocess.Popen | None) -> None:
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return
|
||||
if proc is not None and proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _start_server():
|
||||
"""拉起 uvicorn 服务:源码运行=子进程;打包运行=进程内后台线程。"""
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
if FROZEN:
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
def _serve() -> None:
|
||||
try:
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")
|
||||
except BaseException:
|
||||
import traceback
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
|
||||
t = threading.Thread(target=_serve, daemon=True, name="uvicorn")
|
||||
t.start()
|
||||
_wait_ready(None)
|
||||
return t
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
_wait_ready(proc)
|
||||
return proc
|
||||
|
||||
|
||||
def _apply_win11_corners(window) -> None:
|
||||
"""Win11 窗口圆角:去掉老式方角观感(DWM 设置圆角偏好,失败静默忽略)。"""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||
DWMWCP_ROUND = 2
|
||||
|
||||
def _on_shown():
|
||||
try:
|
||||
hwnd = int(window.native.Handle)
|
||||
ctypes.windll.dwmapi.DwmSetWindowAttribute(
|
||||
ctypes.c_int(hwnd),
|
||||
ctypes.c_int(DWMWA_WINDOW_CORNER_PREFERENCE),
|
||||
ctypes.byref(ctypes.c_int(DWMWCP_ROUND)),
|
||||
ctypes.c_int(4),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window.events.shown += _on_shown
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
window = webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
_apply_win11_corners(window)
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(server) -> None:
|
||||
if isinstance(server, threading.Thread):
|
||||
# 打包运行:uvicorn 为进程内线程,进程退出即随之结束,无需也无法 terminate
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
server.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("37du.Host")
|
||||
except Exception:
|
||||
pass
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
def _fatal_log(msg: str) -> None:
|
||||
"""窗口模式无控制台:崩溃现场落盘到 exe 同级 crash.log,便于诊断。"""
|
||||
try:
|
||||
(HERE / "crash.log").write_text(msg, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
import traceback
|
||||
if FROZEN:
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.6 KiB |
@@ -1,52 +0,0 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + .env 默认配置
|
||||
; .env 与 webhost/.env 同源(控制面/平台共享配置):仅首次安装写入(onlyifdoesntexist),
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.2.1"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
AppId={{8F3D5C7A-2B41-4E9A-9D6C-37DUE5A1B0F0}
|
||||
AppName={#MyAppName}
|
||||
AppVersion={#MyAppVersion}
|
||||
AppPublisher=37du
|
||||
DefaultDirName={localappdata}\Programs\37duHost
|
||||
PrivilegesRequired=lowest
|
||||
OutputDir=..\installer
|
||||
OutputBaseFilename=setup-37du-host-{#MyAppVersion}
|
||||
Compression=lzma2
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
UninstallDisplayName={#MyAppName}
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; 主程序 onedir 目录(exe + _internal 依赖)
|
||||
Source: "..\dist-exe\37du-host\*"; DestDir: "{app}"; Flags: recursesubdirs ignoreversion
|
||||
; 插件执行壳(onefile 单文件,需与主程序 exe 同级)
|
||||
Source: "..\dist-exe\37du-host-runner.exe"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 壳子版本标记:执行端据此比对控制面版本判断是否需要自动升级
|
||||
Source: "..\tools\shell.version"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; .env 默认配置:仅首次安装写入,升级/重装不覆盖机器已有配置
|
||||
Source: "..\.env"; DestDir: "{app}"; Flags: onlyifdoesntexist uninsneveruninstall
|
||||
; 插件不由安装包分发:执行机首次启动/登录后按账号权限从控制面自下载(见 backend/core/plugin_sync.py)
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"
|
||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
; 交互安装:向导结束自动启动;静默升级(/VERYSILENT)后也自动启动新版本,实现"重启自动更新"
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "立即启动 {#MyAppName}"; Flags: nowait postinstall
|
||||
|
||||
[UninstallDelete]
|
||||
; 卸载时清理整个安装目录(含运行期生成的 .webhost.pid / _cp_sessions.json 等)
|
||||
Type: filesandordirs; Name: "{app}"
|
||||
@@ -1 +0,0 @@
|
||||
1.2.1
|
||||
Reference in New Issue
Block a user