feat(electron-shell): 补录壳子源码(排除运行环境与构建产物)
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
# 37du Electron 壳:开发环境配置(拷贝为 .env 并修改)
|
||||
# =============================================================
|
||||
# 服务端地址(中心机控制面)
|
||||
CONTROLPLANE_URL=http://117.72.191.188:8800
|
||||
|
||||
# 内部凭证(与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 保持一致;非空时发 X-API-Token)
|
||||
CONTROLPLANE_TOKEN=
|
||||
|
||||
# 插件执行子进程的 Python 解释器(解析优先级:本变量 > 环境包 python-env/current.json > 系统 python)
|
||||
# 开发推荐显式指定项目 .venv;正式打包后不设即可自动使用随包/下发的环境包
|
||||
# PYTHON_EXE=D:\work\code\37duAutomation\.venv\Scripts\python.exe
|
||||
|
||||
# 环境包目录的显式覆盖(默认:打包态 exe 同级 python-env/;dev electron-shell/python-env/)
|
||||
# SHELL_PYTHON_ENV_ROOT=D:\work\code\37duAutomation\desktop\electron-shell\python-env
|
||||
|
||||
# 插件执行超时(秒,浏览器类默认 30min)
|
||||
RUN_TIMEOUT=1800
|
||||
|
||||
# 插件进程作业级内存上限(MB,环境包模式经 job_guard/Job Object 生效,默认 2048)
|
||||
# RUN_MAX_MEM_MB=2048
|
||||
|
||||
# 调试:1 开启完整 JSON 调试日志
|
||||
# DEBUG=1
|
||||
@@ -0,0 +1,11 @@
|
||||
node_modules/
|
||||
dist-app/
|
||||
renderer/dist/
|
||||
*.log
|
||||
_cp_sessions.json
|
||||
.env
|
||||
|
||||
# 便携 Python 环境包产物(体积大,构建/下载生成,不入库)
|
||||
build/
|
||||
dist-env/
|
||||
python-env/
|
||||
@@ -0,0 +1,256 @@
|
||||
# 37du 执行机客户端(Node/Electron 版)
|
||||
|
||||
替代旧 Python `desktop/webhost/` 底座的新一代执行机客户端。**换壳不换插件**:
|
||||
- 壳与底座:Electron + Node.js(主进程纯 Node,可无 Electron 运行)
|
||||
- 插件执行机制:**保持 Python**,Node 壳负责生命周期/调度/权限,以子进程跑 `plugin_runner.py`(协议逐字节兼容)
|
||||
- 服务端契约:以 [docs/桌面端/Node版客户端开发交接文档.md](../../docs/桌面端/Node版客户端开发交接文档.md) §5 为准,向后兼容,不改服务端公开接口
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
desktop/electron-shell/
|
||||
├── package.json # 依赖 ws(WS 服务) / adm-zip(插件包解压);devDeps electron
|
||||
├── .env # 本模块配置(CONTROLPLANE_URL/TOKEN、PYTHON_EXE、RUN_TIMEOUT)
|
||||
├── .env.example # 配置样例
|
||||
├── frontend/ # 壳自有的 Vue3 前端源码(从 webhost/frontend 复制独立演进,老版本不受影响)
|
||||
│ └── src/ # - style.css:设计令牌(token 层)+ [data-skin] 皮肤机制,默认 cream 奶油风
|
||||
│ # - main.js:皮肤应用(localStorage['37du.skin'])+ 涂鸦装饰层(localStorage['37du.doodles'])
|
||||
│ # - components/LoginPage.vue:登录页(浅天蓝强调 + 手写标题字体)
|
||||
├── renderer/dist/ # 前端构建产物(npm run copy-renderer 从 frontend/ 构建,自包含)
|
||||
├── scripts/
|
||||
│ ├── copy-renderer.ps1 # 构建 frontend/ → renderer/dist
|
||||
│ └── build-python-env.ps1 # 构建便携 Python 环境包(python-env-<ver>.zip + 本地安装)
|
||||
├── python-env/ # 便携 Python 环境包(build-python-env 产物;dev 联调用)
|
||||
│ └── current.json # 指向当前版本目录(客户端自动探测)
|
||||
└── electron/ # 主进程(CommonJS,纯 Node 可跑)
|
||||
├── main.js # 入口:--cli 无 Electron 运行 / electron . 窗口模式
|
||||
├── config.js # .env 加载 + 路径常量(对齐 Python config.py)
|
||||
├── logger.js # 日志(INFO 屏蔽大 JSON,DEBUG=1 全开)
|
||||
├── state.js # 运行会话/白名单/平台表(对齐 state.py)
|
||||
├── hub.js # 事件枢纽 → WS /ws 广播(对齐 hub.py)
|
||||
├── session.js # cp_session cookie 会话 + 落盘 + 云令牌(对齐 session.py)
|
||||
├── cpclient.js # 中心机 REST 客户端(_cp_call 等价)
|
||||
├── crypto.js # Ed25519 验签 / RSA-OAEP / sha256 / 版本比较
|
||||
├── licensing.js # 授权票据/管控清单/公钥缓存 + 验签 + 运行上报 + 设备上报
|
||||
├── registry.js # 插件元数据注册表(plugin.json 驱动)
|
||||
├── plugin-sync.js # 插件自下载/更新/清理(download-ticket + sha256 + 原子安装)
|
||||
├── runner.js # 插件执行:spawn python plugin_runner + 整树强杀 + 事件转发
|
||||
├── run-history.js # 运行历史:run_history.jsonl 索引 + run_history/<run_id>.jsonl 日志
|
||||
├── last-fields.js # 上次执行参数回填(按账号+插件,password 字段不落盘)
|
||||
├── scheduler.js # 设备级单活(active.json)+ 平台命名空间并发闸
|
||||
├── tasks.js # 5 段 cron 定时任务 + 中心机备份/恢复
|
||||
├── platform-auth.js # HR/OA 登录/登出/在线校验(登录走 Python 子进程)
|
||||
├── meta.js # /api/meta 聚合
|
||||
├── creds-sync.js # 敏感凭证下发(RSA 密钥对 + OAEP 解密 + 密文缓存)
|
||||
├── shell-updater.js # 壳子自更新(检查/下载/静默升级)
|
||||
├── chrome-manager.js # Chrome 检测/下载/静默安装
|
||||
├── server.js # 本地 HTTP/WS 兼容层(127.0.0.1:8799)
|
||||
├── app.js # 启动组装
|
||||
├── env-sync.js # 环境包(便携 Python)检查/下载/解压/切换/回滚
|
||||
├── electron-main.js # Electron 窗口/托盘/单实例/自启(已移除默认英文菜单)
|
||||
└── preload.js # contextBridge(渲染层主通道走 HTTP)
|
||||
```
|
||||
|
||||
## 运行
|
||||
|
||||
```powershell
|
||||
# 1. 安装依赖
|
||||
cd desktop/electron-shell
|
||||
npm install
|
||||
|
||||
# 2. 构建前端静态资源(源码在 frontend/,产物 → renderer/dist;旧 webhost 前端不受影响)
|
||||
npm run copy-renderer
|
||||
|
||||
# 3a. 无窗口 CLI 模式(调试/无人值守)
|
||||
node electron/main.js --cli
|
||||
|
||||
# 3b. Electron 窗口模式
|
||||
npm run electron
|
||||
```
|
||||
|
||||
## 配置(.env)
|
||||
|
||||
| 变量 | 说明 |
|
||||
|---|---|
|
||||
| `CONTROLPLANE_URL` | 中心机控制面地址(如 `http://117.72.191.188:8800`) |
|
||||
| `CONTROLPLANE_TOKEN` | 内部凭证(与 controlplane/.env 一致;非空时发 X-API-Token) |
|
||||
| `PYTHON_EXE` | 插件执行子进程的 Python 解释器。**解析优先级**:显式 `PYTHON_EXE` > 环境包 `python-env/current.json` 指向的 `python.exe` > 系统 `python`(不设即可用环境包) |
|
||||
| `SHELL_PYTHON_ENV_ROOT` | 环境包目录的显式覆盖(默认:打包态 exe 同级 `python-env/`,dev `electron-shell/python-env/`) |
|
||||
| `RUN_TIMEOUT` | 插件执行超时秒数(默认 1800) |
|
||||
| `RUN_MAX_MEM_MB` | 插件进程作业级内存上限(默认 2048,环境包模式经 job_guard 生效) |
|
||||
| `DEBUG=1` | 开启完整 JSON 调试日志 |
|
||||
|
||||
## 便携 Python 环境包(python-env)
|
||||
|
||||
正式打包的客户端**开箱即用**:不依赖用户机器上安装的任何 Python。环境包 = 便携解释器
|
||||
(embeddable 3.11.9)+ 全部插件依赖(与 .venv 验证版本钉死)+ webhost 运行时子集
|
||||
(`plugin_runner` / `plugins` / `shared` / `core.auth`)。
|
||||
|
||||
```powershell
|
||||
# 构建(本地联调会同时安装到 electron-shell/python-env/)
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 [-EnvVersion 1.0.0]
|
||||
# 产物:dist-env/python-env-<version>.zip + .sha256
|
||||
```
|
||||
|
||||
- **加载**:`config.pythonEnvRoot()` 读 `python-env/current.json` → 版本目录;插件执行走
|
||||
`python-exe -u webhost/backend/core/job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...`
|
||||
—— Job Object 整树托管 + 内存上限(对齐旧 Python 底座 winjob 能力);stdin/stdout/stderr
|
||||
逐字节透传,执行协议不变。
|
||||
- **下发**:中心机 `agent_cli file push <zip> --category python-env --version <ver>` 登记后,
|
||||
客户端启动/每 30 分钟检查 `/api/file-sources/python-env`,有新版自动下载 → sha256 →
|
||||
解压 `python-env/<version>/` → 切 `current.json` → 保留上一版供回滚。
|
||||
- **本地 API**:`GET /api/env/status`(版本/云端/进度)、`POST /api/env/sync`(手动检查更新)、
|
||||
`POST /api/env/rollback`(回滚上一版);`/api/meta` 增加 `env.version` 字段。
|
||||
|
||||
## 跨端共享数据(%LOCALAPPDATA%\37duAutomation)
|
||||
|
||||
与旧 Python 底座/影刀版**同路径同格式**(换壳不破坏数据):
|
||||
|
||||
| 文件/目录 | 用途 |
|
||||
|---|---|
|
||||
| `license.json` / `control.json` / `keys/pub.pem` | 离线授权票据/管控清单/公钥(Ed25519 验签) |
|
||||
| `active.json` | 设备级单活运行状态 |
|
||||
| `schedules.json` | 定时任务配置(按账号隔离);每条含 `last_status/last_duration/last_error` 最近一次结论。触发语义:**错过不补跑**(壳子停机/离线期间到点的任务直接跳过,要补就人工运行一次);触发失败(授权被拒/插件缺失)跳过本次到点,等下一个 cron 点再试 |
|
||||
| `run_history.jsonl` + `run_history/<run_id>.jsonl` | 运行历史:索引(结论,最近 300~350 条)+ 每次运行独立日志文件 |
|
||||
| `last_run_fields.json` | 上次执行参数(按账号+插件,用于表单回填;`password` 类型字段不写入) |
|
||||
| `plugin_configs/` | 插件个性化配置(账号密码等) |
|
||||
| `.sessions/` | HR/OA 平台登录 cookies(三方共享) |
|
||||
| `creds/id_rsa.pem` + `creds/cache.json` | RSA 私钥 + 加密凭证缓存 |
|
||||
| `offline_reports.jsonl` | 离线上报暂存(重连补报) |
|
||||
| `plugin_allow.json` | 插件权限清单缓存(离线兜底) |
|
||||
| `plugin_rollback/` | 插件回滚备份:升级前自动保留上一版(`<id>@<version>/`,每插件仅最新一版),坏包可在运行台一键回滚 |
|
||||
| `window-state.json` | 主窗口位置/尺寸(重启还原;显示器变更后自动避让屏幕外) |
|
||||
|
||||
## 插件安全基线
|
||||
|
||||
- **插件 UI 加固**:`/pui/<id>/` 响应带 Content-Security-Policy(仅同源资源,阻断外联脚本/图片与外域跳转);壳内嵌 iframe 带 `sandbox="allow-scripts allow-same-origin allow-forms"`(禁止 top 跳转与弹窗)
|
||||
- **版本兼容校验**:插件 `plugin.json` 可声明 `minRuntimeVersion`(要求的最小壳运行时版本);安装时校验,不满足拒绝安装并提示先升级客户端
|
||||
- **回滚**:升级前自动备份上一版到 `plugin_rollback/`,设备空闲时可在运行台回滚(回滚后再次同步可回到最新版)
|
||||
- WS 心跳:30s ping 巡检,僵尸/半开连接自动 terminate
|
||||
|
||||
## 插件执行协议(★ 与旧底座逐字节兼容)
|
||||
|
||||
```
|
||||
<PYTHON_EXE> -u <plugin_runner.py> --plugin <id> --run <run_id> [--allowed a,b]
|
||||
stdin : 单行 JSON fields(UTF-8)
|
||||
stdout : JSON 事件行 {ev: log|progress|result}
|
||||
stderr : 诊断通道(转发为 ERROR 日志)
|
||||
```
|
||||
|
||||
- 设备级单活:整机同时只跑一个插件(active.json 门闩)
|
||||
- 平台命名空间并发闸:同平台(hr/oa)任务串行,保护共享 cookies
|
||||
- 超时强杀:`taskkill /pid <pid> /T /F` 整树终止(含浏览器孙进程)
|
||||
- 授权门禁:启动前验签本地授权票据 + 下架/禁用/强制更新校验
|
||||
|
||||
## 本地 HTTP 兼容层(127.0.0.1:8799)
|
||||
|
||||
路由与返回结构与旧底座 `backend/apis/*` 一致:`/api/meta`、`/api/admin/*`、`/api/runs*`、
|
||||
`/api/schedules*`、`/api/plugins/sync`、`/api/plugin-config/{pid}`、`/pui/{pid}`、`/api/shell/*`、
|
||||
`/api/chrome/*`、`/api/platforms/*`、钉钉登录链路(`/api/auth/dingtalk`、`/auth/done`)、
|
||||
WS `/ws`(登录会话鉴权,广播 log/progress/run_done)。
|
||||
|
||||
新增(向后兼容,均为追加):
|
||||
- `GET /api/runs?limit=N` —— 运行历史列表(按当前账号,最新在前)。返回 `{runs:[{run_id, plugin_id, name,
|
||||
version, trigger, schedule_id, status, ok, error, summary, started, finished, duration_sec}]}`,
|
||||
**不含 logs**(列表页不解析历史日志,避免大文件拖慢);`trigger` 为 `manual` / `schedule`。
|
||||
- `GET /api/runs/{id}` —— 运行详情。内存中已结束的运行会回落 `run_history`,因此重启后仍可回看日志。
|
||||
- `GET /api/plugins/{id}/last-fields` —— 上次执行参数回填,返回 `{fields, at}`。
|
||||
写入时机为 `POST /api/runs`(发起执行时自动记忆);`fields` schema 中 `type/format` 为 `password`
|
||||
的键**永不落盘、永不下发**(插件字段可能含凭据)。
|
||||
|
||||
## 打包(electron-builder)
|
||||
|
||||
```powershell
|
||||
npm install # 含 electron + electron-builder(首次需放行 electron postinstall)
|
||||
npm run pack # → dist-app/setup-37du-shell-<version>.exe(NSIS 静默升级兼容)
|
||||
```
|
||||
|
||||
打包后:插件根目录 = exe 同级 `plugins/`;壳子版本文件 = exe 同级 `shell.version`
|
||||
(参与自更新的前提,与旧壳一致);`apply_update` 以 `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART`
|
||||
运行新安装包后退出,由 Inno `[Run]` 重启新版本。
|
||||
|
||||
## 验证记录(2026-09-23,线上控制面)
|
||||
|
||||
- 登录/登出/改密、`/api/admin/me` 昵称补齐 ✓
|
||||
- `/api/meta` 授权票据驱动插件可见性(2 个授权插件 + 字段/UI 元数据)✓
|
||||
- 授权票据 Ed25519 离线验签 ✓;运行门禁 404/403 路径 ✓
|
||||
- 插件同步(清单 diff → 已有最新,无下载)✓;Chrome 检测(本机已装 154.x)✓
|
||||
- 定时任务 CRUD + 非法 cron 拒绝 + 删除 ✓;WS 鉴权握手 ✓
|
||||
- 执行协议三态自测:成功回传 / 异常回传(含 stderr Traceback 转发)/ 超时强杀 ✓
|
||||
- 奶油极简治愈风前端(frontend/ 自持源码):登录页浅天蓝强调 + 手写标题字体 + 可开关涂鸦装饰层 ✓
|
||||
|
||||
## 前端主题(token 层 + 可换肤)
|
||||
|
||||
壳自带 `frontend/` 前端源码(从 webhost 复制后独立演进)。**样式与皮肤已分层**:
|
||||
|
||||
- **token 层**:`frontend/src/style.css` 的 `:root` 是唯一色值来源(111 个 token,含
|
||||
`--primary-rgb` / `--ok-rgb` / `--text-rgb` 这类分量变量,供 `rgba()` 拼装)。
|
||||
组件(`.vue`)里**不写任何字面色值**,只用 `var(--token)`;`password`/`#000` 掩码等
|
||||
非主题色与 SVG `data:` URI 内的色值除外(后者无法用 `var()`)。
|
||||
改动样式请先加 token 再引用,不要再写字面值。
|
||||
- **皮肤层**:`[data-skin="..."]` 块只重映射同名 token,组件代码零改动。
|
||||
- `cream`(默认):奶油极简治愈风,背景 `#F9F7F2` / 文本 `#222`·`#666` / 强调 `#7CC3E8`,
|
||||
卡片 16px、登录卡 22px、按钮输入 12–14px 大圆角,仅极柔和浅阴影。
|
||||
- `precision`:冷灰画布 + 压深天蓝(`#1E6FA8`)的"精密工作台"。**2026-09 已完成对比度审计**:
|
||||
正文/次级/弱化文字、按钮白字、磁贴图标、成功/警告/失败徽章等 19 组关键配对全部达到
|
||||
WCAG 阈值(正文 ≥4.5、徽章/图标 ≥3.0,实测 3.27~16.03);cream 的 5 处偏低(弱化文字、
|
||||
粉彩徽章、淡红失败图标)是奶油风**刻意保留的柔和粉彩设计**,非缺陷。
|
||||
- 切换:`localStorage['37du.skin'] = 'cream' | 'precision'`(`main.js` 挂载前写入
|
||||
`<html data-skin>`,避免首屏闪烁)。皮肤同时重映射 element-plus 的 `--el-color-primary*`,
|
||||
否则内置表单/表格会残留奶油浅蓝。
|
||||
- 磁贴类(场景图标/头像)前景色走 `--tile-fg`:cream 为白色(配深渐变),
|
||||
precision 为深蓝(配淡色底)——**换肤时若把 `--grad-*` 改成淡色,必须同步改 `--tile-fg`**;
|
||||
2026-09 已把左栏场景图标/统计图标/场景卡图标/运行台 hero 头像统一到 `--tile-fg`,
|
||||
修掉 precision 下"白字落在淡色底上"的不可读问题(cream 取值同为白色,观感不变)。
|
||||
- **涂鸦装饰层**:手绘涂鸦 SVG fixed 浮于页面顶层,`pointer-events:none` 不拦截交互;
|
||||
登录页右上角 ✿ 按钮或 `localStorage['37du.doodles']='off'` 可整体关闭;
|
||||
它是奶油皮肤专属装饰,`precision` 皮肤下由 CSS 整体隐藏。
|
||||
- 标题可用圆润手写装饰字体(`--font-doodle`:Segoe Script → Comic Sans → 楷体),正文固定无衬线 Inter。
|
||||
|
||||
产品化界面(2026-09 三栏版,对齐 design-preview-v2 的信息架构):
|
||||
- **三栏骨架**:左栏场景导轨 + 中栏内容区(总览/运行台/计划)+ 右栏活动流(<1240px 自动收起)
|
||||
+ 底部状态栏。三栏与状态栏为静态面板,不做悬停抬升;顶栏保留浏览器检测 CTA 与运行进度。
|
||||
- **左栏**:总览 / 计划 主导航 + 场景库(浅天蓝激活态,点击进运行台)
|
||||
- **右栏活动流**:当前运行(运行中显示场景名/进度条/最近日志,空闲显示"当前空闲")
|
||||
+ 最近运行(最近 8 次,点击直达该场景运行台);运行态由 WS 事件驱动,
|
||||
定时任务触发的运行同样点亮(`store.running` 在 `run_start` 置位,日志归属本次运行)
|
||||
- **状态栏**:授权状态(剩余天数/异常)/ 本地服务连接 / 本地地址 / 平台在线 N/M /
|
||||
壳子版本 + 检查更新;授权异常态标红提示
|
||||
- **运行台**:Hero 卡(大图标/版本徽章/平台登录态)+ 一键执行大按钮(执行中显示进度环)
|
||||
+ 结果横幅(成功/失败);下方标签页:有专属界面的插件默认「插件界面」内嵌 iframe,
|
||||
其余默认「参数配置」白卡,运行日志独立标签(LIVE 呼吸点 + 级别过滤,圆角交给卡片容器)
|
||||
- **运行台 · 历史运行**:第三标签页列出本场景最近 30 次运行(手动/定时、成功/失败、时间/耗时),
|
||||
点击任一条**回看该次运行**:结果徽章 + 触发方式 + 摘要 + 该次完整日志(`GET /api/runs/{id}`
|
||||
落回 `run_history/` 的逐次日志文件);右栏「最近运行」、总览「最近动态」点击直达对应回看
|
||||
- 视图切换:`store.view` 取值 `overview`(总览)/ `run`(运行台)/ `plans`(计划)
|
||||
|
||||
## 行为变更(2026-09,需知悉)
|
||||
|
||||
| 项 | 变更 | 影响 |
|
||||
|---|---|---|
|
||||
| cron 星期编号 | `tasks.js cronDow` 原为 `(getDay()+6)%7`(周一=0),与 Python 底座 `tasks.py _cron_dow`(`(weekday()+1)%7`,周日=0,标准 cron)**差一天** | 已修正为 `dt.getDay()`。**存量排程会平移**:`0 8 * * 1-5`(工作日)原先实际在**周二~周六**触发,修正后按界面标注的**周一~周五**触发;`0`/`7`(周日)原先落在周一,修正后落在周日;`* * * * 6`(周六)原先无法命中周六 |
|
||||
| 运行历史 | 新增 `run_history.jsonl` + `run_history/` | 首次运行自动创建,无需迁移;上限最近 300~350 条,超出按批裁剪并清理孤儿日志文件 |
|
||||
|
||||
## 平台登录(HR/OA)按账号隔离
|
||||
|
||||
- 每个人的 HR/OA 账号密码由本人在「个人中心 → 平台账号」填写(AES-256-GCM 本机加密,
|
||||
存 `%LOCALAPPDATA%\37duAutomation\platform-creds\creds.json`),顶栏不再显示设备级平台徽章
|
||||
- 平台会话 cookies 按账号隔离:`.sessions/<账号>/hr_cookies.json`、`oa_cookies.json`;
|
||||
Python 共享模块(hr_login / oa_login / seal_data_export / roster_export_api / org_export /
|
||||
core.auth)通过 `PLATFORM_ACCOUNT` 环境变量解析各自的会话目录,未设置时沿用共享目录(兼容旧逻辑)
|
||||
- 登录/登出:壳端 `platform-auth` 拉起 Python 登录子进程时注入 `PLATFORM_ACCOUNT`
|
||||
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env)
|
||||
- 插件执行:runner 子进程同样注入 `PLATFORM_ACCOUNT`,插件内数据导出按当前登录账号的身份执行;
|
||||
同平台并发闸键改为(账号, 平台)
|
||||
- 接口:`GET /api/meta` 平台在线按当前账号返回;`GET /api/platforms/status` 返回当前账号
|
||||
的平台在线/是否已配置个人账号/已存用户名;`PUT /api/platforms/creds` 保存个人账号密码
|
||||
|
||||
## 已知差异(相对旧 Python 底座)
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 进程内存上限 | 环境包模式已实现(job_guard + Job Object,`RUN_MAX_MEM_MB`);无环境包直拉 .venv 的 dev 链路未做(超时强杀已覆盖主要风险) |
|
||||
| 定时任务错过触发 | 旧底座重启后逐点补跑错过的触发点;Node 版**错过不补跑**(停机/离线期间到点直接跳过,要补就人工运行一次) |
|
||||
| 平台登录 | 登录自动化仍为 Python 子进程(DrissionPage 滑块);在线校验改为 Node 直接 HTTP 校验(复刻同逻辑,短缓存) |
|
||||
| 渲染层 | 复用 webhost Vue3 前端产物(本地 HTTP 主通道);IPC 通道为后续演进预留(preload 已就位) |
|
||||
| 云令牌持久化 | 旧底座仅内存;Node 版随 `_cp_sessions.json` 落盘,重启后 Bearer 仍可用 |
|
||||
@@ -0,0 +1,157 @@
|
||||
// 应用组装层:启动初始化(单活复位/权限/授权/插件同步/壳子检查/定时任务/设备上报)+ 本地服务。
|
||||
"use strict";
|
||||
|
||||
const os = require("os");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const state = require("./state");
|
||||
const session = require("./session");
|
||||
const scheduler = require("./scheduler");
|
||||
const licensing = require("./licensing");
|
||||
const registry = require("./registry");
|
||||
const pluginSync = require("./plugin-sync");
|
||||
const tasks = require("./tasks");
|
||||
const shellUpdater = require("./shell-updater");
|
||||
const chromeManager = require("./chrome-manager");
|
||||
const envSync = require("./env-sync");
|
||||
const { makeLogger, setLogFile } = require("./logger");
|
||||
|
||||
const logger = makeLogger("app");
|
||||
|
||||
// 设备 ID:持久化 uuid(跨重启稳定,供 device/report)
|
||||
function deviceId() {
|
||||
const f = path.join(config.APP_DATA, "device_id");
|
||||
try {
|
||||
if (fs.existsSync(f)) {
|
||||
const v = fs.readFileSync(f, "utf-8").trim();
|
||||
if (v) return v;
|
||||
}
|
||||
const id = crypto.randomUUID();
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(f, id, "utf-8");
|
||||
return id;
|
||||
} catch (e) {
|
||||
return "dev-" + crypto.randomBytes(8).toString("hex");
|
||||
}
|
||||
}
|
||||
|
||||
function localIp() {
|
||||
try {
|
||||
const ifs = os.networkInterfaces();
|
||||
for (const list of Object.values(ifs)) {
|
||||
for (const it of list || []) {
|
||||
if (it.family === "IPv4" && !it.internal) return it.address;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// 设备环境上报(心跳 + Chrome 环境):Node 版新增接入(旧 Python 底座无调用方)
|
||||
async function reportDevice(account) {
|
||||
const chrome = await chromeManager.detectLocal();
|
||||
await licensing.deviceReport(deviceId(), account, {
|
||||
hostname: os.hostname(),
|
||||
os: process.platform,
|
||||
ip: localIp(),
|
||||
chromeInstalled: chrome.installed,
|
||||
chromeVersion: chrome.version,
|
||||
chromeOk: chrome.installed,
|
||||
});
|
||||
}
|
||||
|
||||
async function init(options = {}) {
|
||||
// 崩溃现场落盘(窗口模式无控制台时排查唯一窗口):Electron 运行时都落盘(含打包版),
|
||||
// CLI 纯 Node 模式日志走 stdout 即可。不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。
|
||||
// ★ 日志放数据根 %LOCALAPPDATA%\37duAutomation\logs\(打包态 SHELL_ROOT 在 app.asar 内只读,不能写)
|
||||
if (process.versions && process.versions.electron) {
|
||||
setLogFile(path.join(config.APP_DATA, "logs", "shell.log"));
|
||||
}
|
||||
|
||||
scheduler.initActive();
|
||||
|
||||
// 账号:优先 .env,其次最近活跃本机会话
|
||||
const account = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount();
|
||||
if (config.CONTROLPLANE_URL) {
|
||||
// 权限白名单(fail-closed)
|
||||
try {
|
||||
const allowed = await pluginSync.resolveAllowed(account);
|
||||
state.setAllowed(allowed);
|
||||
} catch (e) {
|
||||
state.setAllowed(new Set());
|
||||
}
|
||||
|
||||
// 敏感凭证中心化下发(在线拉取 RSA 解密 / 本地缓存兜底;失败不阻断启动)
|
||||
try {
|
||||
const creds = await require("./creds-sync").load(account);
|
||||
if (creds && Object.keys(creds).length) {
|
||||
config.applyCreds(creds);
|
||||
logger.info(`中心机敏感凭证下发完成(${Object.keys(creds).length} 个键)`);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`加载中心机敏感凭证失败:${e.message}`);
|
||||
}
|
||||
|
||||
// 启动同步离线授权票据
|
||||
if (account) {
|
||||
try {
|
||||
await licensing.syncLicensing(account);
|
||||
logger.info(`启动同步离线授权票据成功(账号 ${account})`);
|
||||
} catch (e) {
|
||||
logger.warning(`启动同步离线授权票据失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 启动即检查插件更新(后台,不阻塞启动)
|
||||
const accts = session.accountSet();
|
||||
if (accts.size > 0) {
|
||||
const firstAcct = accts.values().next().value;
|
||||
void pluginSync
|
||||
.withSyncLock(async () => {
|
||||
await pluginSync.syncPlugins(firstAcct);
|
||||
const manifest = await pluginSync.cloudPluginManifest(firstAcct);
|
||||
if (manifest !== null) state.setAllowed(new Set(manifest.map((p) => p.id)));
|
||||
logger.info(`启动插件更新完成(账号 ${firstAcct})`);
|
||||
})
|
||||
.catch((e) => logger.warning(`启动插件更新失败:${e.message}`));
|
||||
}
|
||||
|
||||
// 环境包(便携 Python 运行时):启动即检查(异步不阻塞),缺失/有新版本自动下载;
|
||||
// 插件执行/平台登录在环境包就绪前会报"环境包未就绪",由设置页提供状态与手动更新
|
||||
void envSync
|
||||
.checkAndSync()
|
||||
.then((r) => logger.info(`环境包检查:${r.ok ? `就绪 v${r.version || ""}` : `未就绪(${r.reason})`}`))
|
||||
.catch((e) => logger.warning(`环境包启动检查异常:${e.message}`));
|
||||
// 常驻周期检查(30 分钟,与壳子更新同频)
|
||||
setInterval(() => {
|
||||
void envSync.checkAndSync().catch((e) => logger.warning(`环境包周期检查异常:${e.message}`));
|
||||
}, 30 * 60 * 1000);
|
||||
|
||||
// 壳子更新:启动检查 + 常驻周期检查
|
||||
shellUpdater.startCheck();
|
||||
shellUpdater.startPeriodicCheck();
|
||||
|
||||
// 定时任务:加载 + 后台触发 + 云端合并恢复
|
||||
tasks.init();
|
||||
|
||||
// 设备上报(Chrome 环境 + 心跳;失败静默)
|
||||
void reportDevice(account)
|
||||
.then(() => logger.info("设备环境上报完成"))
|
||||
.catch(() => {});
|
||||
} else {
|
||||
logger.info("未配置中心机地址(CONTROLPLANE_URL),进入离线本地模式");
|
||||
state.setAllowed(new Set());
|
||||
tasks.load();
|
||||
tasks.start();
|
||||
}
|
||||
|
||||
logger.info(`插件根目录:${registry.pluginRoot()}`);
|
||||
logger.info(`数据根目录:${config.APP_DATA}`);
|
||||
return { deviceId: deviceId(), account };
|
||||
}
|
||||
|
||||
module.exports = { init, deviceId };
|
||||
@@ -0,0 +1,279 @@
|
||||
// 浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
// 对齐 Python chrome_manager.py 的状态结构与流程。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { spawn, execFile } = require("child_process");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("chrome-manager");
|
||||
|
||||
const CHROME_CACHE = path.join(config.APP_DATA, "chrome");
|
||||
let _pendingPkg = null;
|
||||
|
||||
const _STATE = {
|
||||
installed: true,
|
||||
version: "",
|
||||
checking: false,
|
||||
check_error: "",
|
||||
cloud_available: true,
|
||||
dl_status: "idle",
|
||||
dl_received: 0,
|
||||
dl_total: 0,
|
||||
dl_pct: 0,
|
||||
dl_error: "",
|
||||
installing: false,
|
||||
};
|
||||
|
||||
const VERSION_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
||||
|
||||
// 本机检测缓存:前端轮询 status 时避免每 2s 反复 spawn reg/powershell
|
||||
let _localCache = { ts: 0, value: null };
|
||||
const LOCAL_CACHE_TTL = 30 * 1000;
|
||||
|
||||
async function detectLocal(force = false) {
|
||||
const now = Date.now();
|
||||
if (!force && _localCache.value && now - _localCache.ts < LOCAL_CACHE_TTL) {
|
||||
return _localCache.value;
|
||||
}
|
||||
const exe = await findChromeExe();
|
||||
let value;
|
||||
if (!exe) value = { installed: false, version: "" };
|
||||
else value = { installed: true, version: await readVersion(exe) };
|
||||
_localCache = { ts: now, value };
|
||||
return value;
|
||||
}
|
||||
|
||||
function execFileAsync(file, args, timeout = 8000) {
|
||||
return new Promise((resolve) => {
|
||||
execFile(file, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
|
||||
if (err) resolve({ err, stdout: stdout || "", stderr: stderr || "" });
|
||||
else resolve({ err: null, stdout: stdout || "", stderr: stderr || "" });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 注册表探测 Chrome.exe 路径(64/32 位)
|
||||
async function findChromeExe() {
|
||||
const roots = [
|
||||
["HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||
["HKLM", "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||
["HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||
];
|
||||
for (const [hive, key] of roots) {
|
||||
const r = await execFileAsync("reg", ["query", `${hive}\\${key}`, "/ve"]);
|
||||
if (!r.err) {
|
||||
// 输出形如: (默认) REG_SZ C:\...\chrome.exe
|
||||
const m = /REG_SZ\s+(.+)$/m.exec(r.stdout);
|
||||
if (m && fs.existsSync(m[1].trim())) return m[1].trim();
|
||||
}
|
||||
}
|
||||
// 目录扫描兜底
|
||||
const dirs = [
|
||||
path.join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application"),
|
||||
path.join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Google", "Chrome", "Application"),
|
||||
path.join(config.APP_DATA, "..", "Google", "Chrome", "Application"),
|
||||
];
|
||||
for (const d of dirs) {
|
||||
const p = path.join(d, "chrome.exe");
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function readVersion(exe) {
|
||||
const r = await execFileAsync(
|
||||
"powershell",
|
||||
["-NoProfile", "-NonInteractive", "-Command", `(Get-Item -LiteralPath '${exe}').VersionInfo.ProductVersion`],
|
||||
8000
|
||||
);
|
||||
if (r.err) return "";
|
||||
const v = r.stdout.trim();
|
||||
return VERSION_RE.test(v) ? v : "";
|
||||
}
|
||||
|
||||
async function cloudInfo() {
|
||||
if (!config.CONTROLPLANE_URL) return null;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/file-sources/chrome", { headers: cp.machineHeaders(), timeout: 5 });
|
||||
if (!r.available) {
|
||||
_STATE.cloud_available = false;
|
||||
return null;
|
||||
}
|
||||
_STATE.cloud_available = true;
|
||||
return r;
|
||||
} catch (e) {
|
||||
logger.info(`获取浏览器云端信息失败(离线跳过):${e.message}`);
|
||||
_STATE.cloud_available = false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function status() {
|
||||
const local = await detectLocal();
|
||||
if (local.installed) {
|
||||
_STATE.installed = true;
|
||||
_STATE.version = local.version;
|
||||
_STATE.check_error = "";
|
||||
} else {
|
||||
_STATE.installed = false;
|
||||
_STATE.version = "";
|
||||
}
|
||||
const pkgOk = !!_pendingPkg && fs.existsSync(_pendingPkg);
|
||||
return {
|
||||
installed: !!_STATE.installed,
|
||||
version: _STATE.version || "",
|
||||
downloaded: !!pkgOk,
|
||||
cloud_available: !!_STATE.cloud_available,
|
||||
error: _STATE.check_error || "",
|
||||
installing: !!_STATE.installing,
|
||||
dl: {
|
||||
status: _STATE.dl_status || "idle",
|
||||
received: _STATE.dl_received || 0,
|
||||
total: _STATE.dl_total || 0,
|
||||
pct: _STATE.dl_pct || 0,
|
||||
error: _STATE.dl_error || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
_STATE.checking = true;
|
||||
try {
|
||||
await detectLocal();
|
||||
await cloudInfo();
|
||||
} catch (e) {
|
||||
logger.warning(`浏览器检测异常:${e.message}`);
|
||||
} finally {
|
||||
_STATE.checking = false;
|
||||
}
|
||||
}
|
||||
|
||||
let _downloading = false;
|
||||
|
||||
async function startDownload() {
|
||||
if (_STATE.dl_status === "downloading") return;
|
||||
if (_STATE.dl_status === "downloaded" && _pendingPkg && fs.existsSync(_pendingPkg)) return;
|
||||
const info = await cloudInfo();
|
||||
if (!info || !info.url) return;
|
||||
const url = String(info.url).trim();
|
||||
const expect = String(info.sha256 || "").toLowerCase();
|
||||
const filename = String(info.filename || "ChromeStandaloneSetup64.exe").trim();
|
||||
if (_downloading) return;
|
||||
_downloading = true;
|
||||
_STATE.dl_status = "downloading";
|
||||
_STATE.dl_received = 0;
|
||||
_STATE.dl_total = 0;
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
try {
|
||||
await download(url, expect, filename);
|
||||
} catch (e) {
|
||||
logger.warning(`下载 Chrome 安装包失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||
cleanupPart();
|
||||
} finally {
|
||||
_downloading = false;
|
||||
}
|
||||
logger.info(`开始下载 Chrome 安装包:${url}`);
|
||||
}
|
||||
|
||||
async function download(url, expect, filename) {
|
||||
const crypto = require("crypto");
|
||||
const sha = crypto.createHash("sha256");
|
||||
const tmp = path.join(CHROME_CACHE, `${filename}.part`);
|
||||
const pkg = path.join(CHROME_CACHE, filename);
|
||||
fs.mkdirSync(CHROME_CACHE, { recursive: true });
|
||||
const out = fs.createWriteStream(tmp);
|
||||
let received = 0;
|
||||
let total = 0;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
|
||||
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
await new Promise((res2, rej2) => out.end((e) => (e ? rej2(e) : res2())));
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
logger.error("Chrome 安装包 sha256 校验失败");
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包校验失败,请重试";
|
||||
cleanupPart();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmp, pkg);
|
||||
} catch (e) {
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包保存失败";
|
||||
cleanupPart();
|
||||
return;
|
||||
}
|
||||
_pendingPkg = pkg;
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
logger.info(`Chrome 安装包下载完成:${pkg}`);
|
||||
}
|
||||
|
||||
function cleanupPart() {
|
||||
try {
|
||||
for (const f of fs.readdirSync(CHROME_CACHE)) {
|
||||
if (f.endsWith(".part")) fs.unlinkSync(path.join(CHROME_CACHE, f));
|
||||
}
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function install() {
|
||||
if (!_pendingPkg || !fs.existsSync(_pendingPkg)) {
|
||||
throw Object.assign(new Error("未找到已下载的 Chrome 安装包"), { status: 404 });
|
||||
}
|
||||
_STATE.installing = true;
|
||||
logger.info(`开始静默安装 Chrome:${_pendingPkg}`);
|
||||
const child = spawn(_pendingPkg, ["/silent", "/install"], {
|
||||
cwd: path.dirname(_pendingPkg),
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
child.unref();
|
||||
void pollInstall();
|
||||
return { ok: true, installing: true };
|
||||
}
|
||||
|
||||
async function pollInstall() {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
const local = await detectLocal();
|
||||
if (local.installed) {
|
||||
_STATE.installing = false;
|
||||
_STATE.installed = true;
|
||||
_STATE.version = local.version;
|
||||
logger.info(`Chrome 安装完成:${_STATE.version}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
_STATE.installing = false;
|
||||
logger.warning("等待 Chrome 安装完成超时");
|
||||
}
|
||||
|
||||
module.exports = { status, refresh, startDownload, install, detectLocal };
|
||||
@@ -0,0 +1,204 @@
|
||||
// 37du Electron 壳:配置固化(.env 加载 + 路径 + 常量)
|
||||
// 对齐 Python webhost backend/core/config.py 的语义与路径约定。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
// 打包态判定:Electron 运行时 + resources 下存在 app.asar(打包版独有,dev `electron .` 无 asar)。
|
||||
// 不能依赖 ELECTRON_RENDERER_URL(那是 electron-vite 等 dev-server 工具的变量,本工程从不设置)。
|
||||
const IS_FROZEN =
|
||||
!!process.versions &&
|
||||
!!process.versions.electron &&
|
||||
!!process.resourcesPath &&
|
||||
!process.env.ELECTRON_RUN_AS_NODE &&
|
||||
fs.existsSync(path.join(process.resourcesPath, "app.asar"));
|
||||
|
||||
// 本模块目录:desktop/electron-shell/electron → parents
|
||||
const SHELL_ROOT = path.resolve(__dirname, "..");
|
||||
|
||||
// 仓库根:electron/../.. = 37duAutomation(dev 模式定位 plugins/ 与 webhost 参考实现)
|
||||
const REPO_ROOT = path.resolve(SHELL_ROOT, "..", "..");
|
||||
const DESKTOP_ROOT = path.resolve(SHELL_ROOT, "..");
|
||||
|
||||
// ==================== 轻量 .env 加载(仅本模块目录,变量已存在则不覆盖) ====================
|
||||
function loadDotEnv() {
|
||||
const envPath = path.join(SHELL_ROOT, ".env");
|
||||
if (!fs.existsSync(envPath)) return;
|
||||
try {
|
||||
const text = fs.readFileSync(envPath, "utf-8");
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith("#") || !line.includes("=")) continue;
|
||||
const idx = line.indexOf("=");
|
||||
const key = line.slice(0, idx).trim();
|
||||
const value = line.slice(idx + 1).trim();
|
||||
if (key && process.env[key] === undefined) process.env[key] = value;
|
||||
}
|
||||
} catch (e) {
|
||||
// 读取失败静默(与 Python 实现一致)
|
||||
}
|
||||
}
|
||||
loadDotEnv();
|
||||
|
||||
// ==================== 基础常量 ====================
|
||||
const PORT = 8799;
|
||||
|
||||
// 数据根目录:与影刀版 / 旧 Python 底座共享 %LOCALAPPDATA%\37duAutomation(跨端契约)
|
||||
function localAppData() {
|
||||
return process.env.LOCALAPPDATA || process.env.APPDATA || require("os").homedir();
|
||||
}
|
||||
const APP_DATA = path.join(localAppData(), "37duAutomation");
|
||||
|
||||
// 插件本地配置目录:per-plugin JSON 持久化
|
||||
const PLUGIN_CONFIG_DIR = path.join(APP_DATA, "plugin_configs");
|
||||
|
||||
// 插件源码/安装根:dev = 仓库根 plugins/;打包 = exe 同级 plugins/
|
||||
function pluginRoot() {
|
||||
if (process.env.SHELL_PLUGIN_ROOT) return process.env.SHELL_PLUGIN_ROOT;
|
||||
if (IS_FROZEN) {
|
||||
return path.join(path.dirname(process.execPath), "plugins");
|
||||
}
|
||||
return path.join(REPO_ROOT, "plugins");
|
||||
}
|
||||
|
||||
// 运行时版本:打包态读 exe 同级 shell.version(发版文件);开发/CLI 回退 package.json 版本。
|
||||
// 插件 plugin.json 可声明 minRuntimeVersion 做版本兼容校验(不满足则拒绝安装)。
|
||||
function runtimeVersion() {
|
||||
try {
|
||||
if (!process.env.ELECTRON_RUN_AS_NODE && process.resourcesPath) {
|
||||
const vf = path.join(path.dirname(process.execPath), "shell.version");
|
||||
if (fs.existsSync(vf)) {
|
||||
const v = fs.readFileSync(vf, "utf-8").trim();
|
||||
if (v) return v;
|
||||
}
|
||||
}
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(SHELL_ROOT, "package.json"), "utf-8"));
|
||||
return String(pkg.version || "").trim();
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 控制面配置 ====================
|
||||
const CONTROLPLANE_URL = (process.env.CONTROLPLANE_URL || "").replace(/\/+$/, "");
|
||||
const CONTROLPLANE_ACCOUNT = process.env.CONTROLPLANE_ACCOUNT || "";
|
||||
const CONTROLPLANE_TOKEN = process.env.CONTROLPLANE_TOKEN || "";
|
||||
|
||||
// ==================== 插件执行子进程配置 ====================
|
||||
// Python 解释器:优先 env,默认 python(PATH 中的 venv/系统 Python)
|
||||
const PYTHON_EXE = process.env.PYTHON_EXE || "python";
|
||||
const RUN_TIMEOUT = parseInt(process.env.RUN_TIMEOUT || "1800", 10);
|
||||
const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10);
|
||||
|
||||
// ==================== 便携 Python 环境包(python-env) ====================
|
||||
// 版本化目录(python-env/<version>/)+ current.json 指向当前版本,保留上一版供回滚。
|
||||
// 目录位置:打包态 = exe 同级 python-env/;开发态 = electron-shell/python-env/(可本地构建联调)。
|
||||
function envRootDir() {
|
||||
if (process.env.SHELL_PYTHON_ENV_ROOT) return path.resolve(process.env.SHELL_PYTHON_ENV_ROOT);
|
||||
if (IS_FROZEN) return path.join(path.dirname(process.execPath), "python-env");
|
||||
return path.join(SHELL_ROOT, "python-env");
|
||||
}
|
||||
|
||||
// 当前环境包目录(current.json → 版本目录);无环境包返回 ""
|
||||
function pythonEnvRoot() {
|
||||
const dir = envRootDir();
|
||||
try {
|
||||
const raw = fs.readFileSync(path.join(dir, "current.json"), "utf-8").replace(/^\uFEFF/, "");
|
||||
const cur = JSON.parse(raw);
|
||||
const ver = String((cur || {}).version || "").trim();
|
||||
if (ver && fs.existsSync(path.join(dir, ver, "python.exe"))) return path.join(dir, ver);
|
||||
} catch (e) {
|
||||
/* 尚无环境包 */
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// 环境包解析的 Python 解释器:显式 PYTHON_EXE 优先,其次环境包,最后系统 python
|
||||
function pythonExe() {
|
||||
if (process.env.PYTHON_EXE) return process.env.PYTHON_EXE;
|
||||
const envRoot = pythonEnvRoot();
|
||||
if (envRoot) return path.join(envRoot, "python.exe");
|
||||
return "python";
|
||||
}
|
||||
|
||||
// 运行时根(webhost 包所在目录):环境包模式 = 环境包根;否则 = desktop/(dev,webhost 在仓库内)
|
||||
function runtimeRoot() {
|
||||
const envRoot = pythonEnvRoot();
|
||||
if (envRoot) return envRoot;
|
||||
return DESKTOP_ROOT;
|
||||
}
|
||||
|
||||
// 插件执行入口:环境包模式 = 环境包内 plugin_runner.py;打包态 = exe 同级;dev = 仓库 webhost
|
||||
function runnerScript() {
|
||||
if (process.env.SHELL_RUNNER_SCRIPT) return process.env.SHELL_RUNNER_SCRIPT;
|
||||
const envRoot = pythonEnvRoot();
|
||||
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "plugin_runner.py");
|
||||
if (IS_FROZEN) {
|
||||
return path.join(path.dirname(process.execPath), "plugin_runner.py");
|
||||
}
|
||||
return path.join(DESKTOP_ROOT, "webhost", "backend", "core", "plugin_runner.py");
|
||||
}
|
||||
|
||||
// Job Object 守护(环境包模式启用内存上限 + 整树托管):无环境包返回 ""
|
||||
function jobGuardScript() {
|
||||
const envRoot = pythonEnvRoot();
|
||||
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "job_guard.py");
|
||||
return "";
|
||||
}
|
||||
|
||||
// 前端静态资源:壳自带 renderer/dist(可单独拷贝);dev 兜底复用 webhost 构建产物
|
||||
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`);
|
||||
}
|
||||
|
||||
// 敏感凭证中心化下发:进程级覆盖存储(唯一来源:中心机下发 / 本地加密缓存)
|
||||
const _CREDS_OVERRIDE = {};
|
||||
|
||||
function applyCreds(values) {
|
||||
if (values && typeof values === "object") {
|
||||
Object.assign(_CREDS_OVERRIDE, values);
|
||||
}
|
||||
}
|
||||
|
||||
function getCred(name) {
|
||||
if (_CREDS_OVERRIDE[name] !== undefined) return _CREDS_OVERRIDE[name];
|
||||
return process.env[name] !== undefined ? process.env[name] : "";
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SHELL_ROOT,
|
||||
REPO_ROOT,
|
||||
DESKTOP_ROOT,
|
||||
PORT,
|
||||
APP_DATA,
|
||||
PLUGIN_CONFIG_DIR,
|
||||
CONTROLPLANE_URL,
|
||||
CONTROLPLANE_ACCOUNT,
|
||||
CONTROLPLANE_TOKEN,
|
||||
PYTHON_EXE,
|
||||
RUN_TIMEOUT,
|
||||
RUN_MAX_MEM_MB,
|
||||
IS_FROZEN,
|
||||
pluginRoot,
|
||||
runnerScript,
|
||||
frontendDist,
|
||||
sharedModule,
|
||||
runtimeVersion,
|
||||
applyCreds,
|
||||
getCred,
|
||||
envRootDir,
|
||||
pythonEnvRoot,
|
||||
pythonExe,
|
||||
runtimeRoot,
|
||||
jobGuardScript,
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
// 中心机 REST 客户端:_cp_call 等价(头规则一致、超时、错误透传 detail)。
|
||||
"use strict";
|
||||
|
||||
const { makeLogger } = require("./logger");
|
||||
const config = require("./config");
|
||||
|
||||
const logger = makeLogger("cpclient");
|
||||
|
||||
class HttpError extends Error {
|
||||
constructor(status, detail) {
|
||||
super(typeof detail === "string" && detail ? detail : `中心机 ${status}`);
|
||||
this.status = status;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
function baseUrl() {
|
||||
if (!config.CONTROLPLANE_URL) {
|
||||
const err = new Error("统一后端未配置(CONTROLPLANE_URL)");
|
||||
err.status = 503;
|
||||
throw err;
|
||||
}
|
||||
return config.CONTROLPLANE_URL;
|
||||
}
|
||||
|
||||
// 机器凭证头(X-API-Token)
|
||||
function machineHeaders() {
|
||||
const h = {};
|
||||
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||
return h;
|
||||
}
|
||||
|
||||
// params: {a: 1} → query string
|
||||
function qs(params) {
|
||||
if (!params) return "";
|
||||
const parts = Object.entries(params)
|
||||
.filter(([, v]) => v !== undefined && v !== null)
|
||||
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
|
||||
return parts.length ? `?${parts.join("&")}` : "";
|
||||
}
|
||||
|
||||
async function request(method, urlPath, opts = {}) {
|
||||
const { headers = {}, json, params, body, timeout = 30, raw = false } = opts;
|
||||
const url = `${baseUrl()}${urlPath}${qs(params)}`;
|
||||
const h = { ...headers };
|
||||
let payload;
|
||||
if (json !== undefined) {
|
||||
h["Content-Type"] = "application/json";
|
||||
payload = JSON.stringify(json);
|
||||
} else if (body !== undefined) {
|
||||
payload = body;
|
||||
}
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method,
|
||||
headers: h,
|
||||
body: payload,
|
||||
signal: ctrl.signal,
|
||||
redirect: "follow",
|
||||
});
|
||||
} catch (e) {
|
||||
const err = new Error(`中心机不可达: ${e.message}`);
|
||||
err.status = 502;
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
if (res.status >= 400) {
|
||||
let detail = buf.toString("utf-8").slice(0, 300);
|
||||
try {
|
||||
detail = JSON.parse(detail).detail || detail;
|
||||
} catch (e) {
|
||||
/* 非 JSON 错误体 */
|
||||
}
|
||||
throw new HttpError(res.status, detail);
|
||||
}
|
||||
if (raw) {
|
||||
return { status: res.status, headers: res.headers, body: buf };
|
||||
}
|
||||
// JSON(二进制接口用 raw)
|
||||
const text = buf.toString("utf-8");
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (e) {
|
||||
return { detail: text.slice(0, 300) };
|
||||
}
|
||||
}
|
||||
|
||||
// 流式下载(shell/chrome 大包,带进度回调):返回 {status, sha, contentLength}
|
||||
async function streamDownload(urlPath, opts = {}) {
|
||||
const { headers = {}, timeout = 600, onProgress, onData } = opts;
|
||||
const url = `${baseUrl()}${urlPath}`;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
|
||||
} catch (e) {
|
||||
clearTimeout(timer);
|
||||
const err = new Error(`下载失败: ${e.message}`);
|
||||
err.status = 502;
|
||||
throw err;
|
||||
}
|
||||
const crypto = require("crypto");
|
||||
const sha = crypto.createHash("sha256");
|
||||
const total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
let received = 0;
|
||||
const reader = res.body.getReader();
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
if (onData) onData(value);
|
||||
if (onProgress) onProgress(received, total);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`下载中断: ${e.message}`);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (res.status >= 400) {
|
||||
throw new HttpError(res.status, `下载失败 HTTP ${res.status}`);
|
||||
}
|
||||
return { status: res.status, sha256: sha.digest("hex"), contentLength: total, received };
|
||||
}
|
||||
|
||||
module.exports = { HttpError, request, machineHeaders, qs, streamDownload, baseUrl };
|
||||
@@ -0,0 +1,119 @@
|
||||
// 执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
|
||||
// 对齐 Python creds_sync.py:RSA-2048 密钥对 + OAEP-SHA256 解密 + cache.json 密文缓存。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const session = require("./session");
|
||||
const { loadOrCreateRsaKey, rsaDecrypt } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("creds-sync");
|
||||
|
||||
// 与服务端 config_push._ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
|
||||
const ALLOWED_KEYS = new Set([
|
||||
"DINGTALK_APPKEY",
|
||||
"DINGTALK_APPSECRET",
|
||||
"DINGTALK_AGENT_ID",
|
||||
"DINGTALK_CORP_ID",
|
||||
]);
|
||||
|
||||
const CREDS_DIR = path.join(config.APP_DATA, "creds");
|
||||
const PRIV_PATH = path.join(CREDS_DIR, "id_rsa.pem");
|
||||
const CACHE_FILE = path.join(CREDS_DIR, "cache.json");
|
||||
|
||||
let _priv = null;
|
||||
|
||||
function privateKey() {
|
||||
if (!_priv) _priv = loadOrCreateRsaKey(PRIV_PATH);
|
||||
return _priv;
|
||||
}
|
||||
|
||||
function publicKeyPem() {
|
||||
const key = privateKey();
|
||||
return crypto.createPublicKey(key).export({ type: "spki", format: "pem" }).toString();
|
||||
}
|
||||
|
||||
function decrypt(cipherB64) {
|
||||
return rsaDecrypt(privateKey(), cipherB64);
|
||||
}
|
||||
|
||||
function saveCache(encrypted) {
|
||||
try {
|
||||
fs.mkdirSync(CREDS_DIR, { recursive: true });
|
||||
fs.writeFileSync(CACHE_FILE, JSON.stringify(encrypted), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`敏感凭证缓存写入失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function loadCache() {
|
||||
if (!fs.existsSync(CACHE_FILE)) return {};
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
|
||||
const out = {};
|
||||
for (const [k, b64] of Object.entries(raw || {})) {
|
||||
if (!ALLOWED_KEYS.has(k)) continue;
|
||||
try {
|
||||
out[k] = decrypt(b64);
|
||||
} catch (e) {
|
||||
logger.warning(`敏感凭证缓存解密失败: ${k}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// 中心机在线拉取并解密敏感凭证;不可用返回 null(走缓存兜底)
|
||||
async function sync(account) {
|
||||
if (!config.CONTROLPLANE_URL || !account || !session.cloudToken(account)) return null;
|
||||
try {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${session.cloudToken(account)}`,
|
||||
};
|
||||
if (config.CONTROLPLANE_TOKEN) headers["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||
// 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
|
||||
await cp.request("POST", "/api/admin/creds/register", {
|
||||
headers,
|
||||
json: { account, pubkey_pem: publicKeyPem() },
|
||||
timeout: 10,
|
||||
});
|
||||
// 2. 拉取加密后的敏感凭证
|
||||
const r = await cp.request("GET", "/api/admin/creds", { headers, timeout: 10 });
|
||||
const encrypted = r.creds || {};
|
||||
if (Object.keys(encrypted).length === 0) return {};
|
||||
// 3. 本机私钥逐个解密
|
||||
const out = {};
|
||||
for (const [k, b64] of Object.entries(encrypted)) {
|
||||
if (!ALLOWED_KEYS.has(k)) continue;
|
||||
try {
|
||||
out[k] = decrypt(b64);
|
||||
} catch (e) {
|
||||
logger.warning(`敏感凭证解密失败: ${k}`);
|
||||
}
|
||||
}
|
||||
// 4. 密文原样落盘缓存(离线复用)
|
||||
saveCache(encrypted);
|
||||
return out;
|
||||
} catch (e) {
|
||||
logger.warning(`中心机敏感凭证拉取失败(用本地缓存): ${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function load(account = "") {
|
||||
account = account || config.CONTROLPLANE_ACCOUNT;
|
||||
if (!account) account = session.sessActiveAccount();
|
||||
const synced = await sync(account);
|
||||
if (synced !== null) return synced;
|
||||
const cached = loadCache();
|
||||
if (Object.keys(cached).length) logger.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)");
|
||||
return cached;
|
||||
}
|
||||
|
||||
module.exports = { load, sync, publicKeyPem, decrypt, ALLOWED_KEYS, PRIV_PATH };
|
||||
@@ -0,0 +1,120 @@
|
||||
// 密码学与通用工具:Ed25519 验签 / RSA-OAEP 解密 / sha256 / base64url / 版本比较。
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
// ==================== base64url(无填充解码,对齐 Python urlsafe_b64decode) ====================
|
||||
function b64urlDecode(s) {
|
||||
// JS 中 -len % 4 为负数(Python 为正补数),显式换算补位数
|
||||
const pad = (4 - (s.length % 4)) % 4;
|
||||
return Buffer.from(s + "=".repeat(pad), "base64url");
|
||||
}
|
||||
|
||||
// ==================== Ed25519 票据验签 ====================
|
||||
// 票据格式:base64url(canonical_json).base64url(64B 签名);验签返回 payload 对象。
|
||||
function verifyBlob(blob, publicKeyPem) {
|
||||
if (typeof blob !== "string" || !blob.includes(".")) throw new Error("bad blob");
|
||||
const idx = blob.lastIndexOf(".");
|
||||
const b64 = blob.slice(0, idx);
|
||||
const sig64 = blob.slice(idx + 1);
|
||||
const canon = b64urlDecode(b64);
|
||||
const sig = b64urlDecode(sig64);
|
||||
if (sig.length !== 64) throw new Error("bad signature len");
|
||||
const key = crypto.createPublicKey(publicKeyPem);
|
||||
const ok = crypto.verify(null, canon, key, sig);
|
||||
if (!ok) throw new Error("signature verification failed");
|
||||
return JSON.parse(canon.toString("utf-8"));
|
||||
}
|
||||
|
||||
// ==================== RSA-2048 密钥对(creds 下发) ====================
|
||||
// 私钥 PKCS8 PEM 落盘 %LOCALAPPDATA%\37duAutomation\creds\id_rsa.pem;公钥上报中心机。
|
||||
function loadOrCreateRsaKey(privPath) {
|
||||
if (fs.existsSync(privPath)) {
|
||||
try {
|
||||
const pem = fs.readFileSync(privPath, "utf-8");
|
||||
return crypto.createPrivateKey(pem);
|
||||
} catch (e) {
|
||||
// 损坏则重新生成
|
||||
}
|
||||
}
|
||||
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicExponent: 0x10001,
|
||||
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
||||
});
|
||||
fs.mkdirSync(path.dirname(privPath), { recursive: true });
|
||||
fs.writeFileSync(privPath, privateKey, { encoding: "utf-8", mode: 0o600 });
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
// OAEP-SHA256 解密 base64 密文 → 明文(与服务端 rsa_encrypt 对称)
|
||||
function rsaDecrypt(privateKey, cipherB64) {
|
||||
const ct = Buffer.from(cipherB64, "base64");
|
||||
const pt = crypto.privateDecrypt(
|
||||
{ key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
||||
ct
|
||||
);
|
||||
return pt.toString("utf-8");
|
||||
}
|
||||
|
||||
// ==================== 通用工具 ====================
|
||||
function sha256Hex(data) {
|
||||
return crypto.createHash("sha256").update(data).digest("hex");
|
||||
}
|
||||
|
||||
// 版本比较:数字段按 int,非数字段按 str 小写(对齐 Python licensing._version_lt)
|
||||
function versionKey(s) {
|
||||
return String(s)
|
||||
.split(".")
|
||||
.map((x) => (/^\d+$/.test(x) ? [1, parseInt(x, 10)] : [0, x.toLowerCase()]));
|
||||
}
|
||||
function versionLt(a, b) {
|
||||
const ka = versionKey(a);
|
||||
const kb = versionKey(b);
|
||||
for (let i = 0; i < Math.max(ka.length, kb.length); i++) {
|
||||
const x = ka[i] || [0, ""];
|
||||
const y = kb[i] || [0, ""];
|
||||
if (x[0] !== y[0]) return x[0] < y[0];
|
||||
if (x[0] === 1) {
|
||||
if (x[1] !== y[1]) return x[1] < y[1];
|
||||
} else if (x[1] !== y[1]) return x[1] < y[1];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function deadlinePassed(deadline) {
|
||||
if (!deadline) return false;
|
||||
const t = Date.parse(String(deadline).replace("Z", "+00:00"));
|
||||
if (Number.isNaN(t)) return false;
|
||||
return Date.now() > t;
|
||||
}
|
||||
|
||||
function nowStr() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function newId() {
|
||||
return Date.now().toString(16) + crypto.randomBytes(4).toString("hex");
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
b64urlDecode,
|
||||
verifyBlob,
|
||||
loadOrCreateRsaKey,
|
||||
rsaDecrypt,
|
||||
sha256Hex,
|
||||
versionLt,
|
||||
deadlinePassed,
|
||||
nowStr,
|
||||
newId,
|
||||
sleep,
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
// 壳子本地 SQLite(better-sqlite3):替代散落 JSON 承载新增数据。
|
||||
// 数据库:%LOCALAPPDATA%\37duAutomation\shell.db
|
||||
// 说明:
|
||||
// - 既有 JSON(license/active/schedules/run_history/creds 等)是和老客户端(Python webhost)
|
||||
// 共享的契约文件,保持原样不动;**新增数据一律入 SQLite**,避免再堆 JSON。
|
||||
// - better-sqlite3 为原生模块:CLI 模式用系统 Node 的二进制;打包(electron-builder)时
|
||||
// 自动 rebuild 为 Electron ABI,产物无需额外处理。
|
||||
"use strict";
|
||||
|
||||
const path = require("path");
|
||||
const Database = require("better-sqlite3");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("db");
|
||||
|
||||
const DB_PATH = path.join(config.APP_DATA, "shell.db");
|
||||
|
||||
// 打开即建库建表(幂等);WAL 提升并发读性能,写仍同步
|
||||
const db = new Database(DB_PATH);
|
||||
db.pragma("journal_mode = WAL");
|
||||
|
||||
function migrate() {
|
||||
db.exec(`
|
||||
-- 场景配置方案(多配置):同一场景多套命名参数,运行台/定时任务按需选用
|
||||
CREATE TABLE IF NOT EXISTS plugin_configs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
fields TEXT NOT NULL DEFAULT '{}',
|
||||
at TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE(account, plugin_id, name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_pcfg_owner ON plugin_configs(account, plugin_id);
|
||||
`);
|
||||
logger.info(`SQLite 就绪:${DB_PATH}`);
|
||||
}
|
||||
|
||||
migrate();
|
||||
|
||||
module.exports = { db, DB_PATH };
|
||||
@@ -0,0 +1,170 @@
|
||||
// Electron 壳:窗口 / 托盘 / 单实例 / 自启。渲染层加载本地 8799 兼容层(复用 webhost 前端)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen } = require("electron");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("electron-main");
|
||||
|
||||
// 移除 Electron 默认英文菜单栏(File Edit View Window Help):成品客户端菜单由页面自绘
|
||||
Menu.setApplicationMenu(null);
|
||||
|
||||
const PORT = config.PORT;
|
||||
const URL = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
// 窗口状态持久化:记住位置/尺寸,重启还原(防显示器变更后窗口跑到屏幕外)
|
||||
const WINDOW_STATE_FILE = path.join(config.APP_DATA, "window-state.json");
|
||||
|
||||
function loadWindowState() {
|
||||
try {
|
||||
if (!fs.existsSync(WINDOW_STATE_FILE)) return null;
|
||||
const s = JSON.parse(fs.readFileSync(WINDOW_STATE_FILE, "utf-8"));
|
||||
if (!s || typeof s !== "object") return null;
|
||||
const w = Math.max(1000, Math.min(4000, Number(s.width) || 1200));
|
||||
const h = Math.max(660, Math.min(4000, Number(s.height) || 780));
|
||||
const x = Number(s.x);
|
||||
const y = Number(s.y);
|
||||
if (
|
||||
!Number.isFinite(x) ||
|
||||
!Number.isFinite(y) ||
|
||||
!screen.getAllDisplays().some((d) => {
|
||||
const a = d.workArea;
|
||||
return x < a.x + a.width && x + w > a.x && y < a.y + a.height && y + h > a.y;
|
||||
})
|
||||
) {
|
||||
return { width: w, height: h }; // 位置失效:只恢复尺寸
|
||||
}
|
||||
return { width: w, height: h, x, y };
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveWindowState(win) {
|
||||
try {
|
||||
const b = win.getBounds();
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(WINDOW_STATE_FILE, JSON.stringify(b), "utf-8");
|
||||
} catch (e) {
|
||||
/* 忽略:状态保存失败不影响运行 */
|
||||
}
|
||||
}
|
||||
|
||||
let mainWindow = null;
|
||||
let tray = null;
|
||||
let server = null;
|
||||
|
||||
// 单实例锁:重复启动聚焦已有窗口
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on("second-instance", () => {
|
||||
if (mainWindow) {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.setAppUserModelId("37du.Host");
|
||||
|
||||
function createWindow() {
|
||||
const st = loadWindowState() || {};
|
||||
mainWindow = new BrowserWindow({
|
||||
width: st.width || 1200,
|
||||
height: st.height || 780,
|
||||
x: st.x,
|
||||
y: st.y,
|
||||
minWidth: 1000,
|
||||
minHeight: 660,
|
||||
backgroundColor: "#eef2f9",
|
||||
title: "37du 自动化工作台",
|
||||
icon: trayIconImage(),
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
},
|
||||
});
|
||||
mainWindow.loadURL(URL);
|
||||
// 关闭时保存窗口状态;resize/move 防抖保存(异常退出也不丢太多)
|
||||
let stateTimer = null;
|
||||
const save = () => {
|
||||
if (stateTimer) clearTimeout(stateTimer);
|
||||
stateTimer = setTimeout(() => {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
|
||||
}, 400);
|
||||
if (stateTimer.unref) stateTimer.unref();
|
||||
};
|
||||
mainWindow.on("resize", save);
|
||||
mainWindow.on("move", save);
|
||||
mainWindow.on("close", () => {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
|
||||
});
|
||||
mainWindow.on("closed", () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
function trayIconImage() {
|
||||
// 16x16 蓝色圆点占位图标(正式打包时替换为 tools/icon.ico 生成的 png)
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="4" fill="#3b6cf6"/><text x="8" y="12" font-size="10" text-anchor="middle" fill="#fff" font-family="sans-serif">37</text></svg>`;
|
||||
return nativeImage.createFromDataURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`);
|
||||
}
|
||||
|
||||
function createTray() {
|
||||
tray = new Tray(trayIconImage());
|
||||
const ctx = Menu.buildFromTemplate([
|
||||
{ label: "打开工作台", click: () => createWindow() },
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "开机自启",
|
||||
type: "checkbox",
|
||||
checked: app.getLoginItemSettings().openAtLogin,
|
||||
click: (item) => {
|
||||
app.setLoginItemSettings({ openAtLogin: item.checked });
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ label: "退出", click: () => app.quit() },
|
||||
]);
|
||||
tray.setToolTip("37du 自动化工作台");
|
||||
tray.setContextMenu(ctx);
|
||||
tray.on("click", () => {
|
||||
if (!mainWindow) createWindow();
|
||||
else mainWindow.show();
|
||||
});
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
try {
|
||||
const { init } = require("./app");
|
||||
const { listen } = require("./server");
|
||||
await init();
|
||||
server = listen(() => {
|
||||
createWindow();
|
||||
createTray();
|
||||
logger.info("Electron 壳就绪");
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error(`启动失败:${e.stack || e}`);
|
||||
dialog.showErrorBox("37du 自动化工作台", `启动失败:${e.message}`);
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
app.quit(); // Windows:关闭窗口即退出(服务随主进程结束)
|
||||
});
|
||||
|
||||
app.on("before-quit", () => {
|
||||
try {
|
||||
if (server) server.close();
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
// 环境包同步(python-env):检查中心机 /api/file-sources/python-env → 下载 → sha256 →
|
||||
// 解压到 python-env/<version>/ → 更新 current.json → 清理(保留上一版供回滚)。
|
||||
// 与插件/壳子更新同一套"版本单点 + 校验 + 原子切换"模式;中心机无需改接口(category 为
|
||||
// 任意字符串,`agent_cli file push --category python-env` 即可发布)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const AdmZip = require("adm-zip");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { versionLt } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("env-sync");
|
||||
|
||||
const _STATE = {
|
||||
installed: false,
|
||||
version: "",
|
||||
dir: "",
|
||||
cloud_available: false,
|
||||
cloud_version: "",
|
||||
dl_status: "idle", // idle | downloading | downloaded | failed
|
||||
dl_received: 0,
|
||||
dl_total: 0,
|
||||
dl_pct: 0,
|
||||
dl_error: "",
|
||||
checking: false,
|
||||
};
|
||||
|
||||
function envDir() {
|
||||
return config.envRootDir();
|
||||
}
|
||||
|
||||
// 当前环境包版本(读 current.json;兼容 UTF-8 BOM)
|
||||
function readCurrent() {
|
||||
try {
|
||||
const raw = fs.readFileSync(path.join(envDir(), "current.json"), "utf-8").replace(/^\uFEFF/, "");
|
||||
const cur = JSON.parse(raw);
|
||||
return String((cur || {}).version || "").trim();
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// 中心机登记的云端环境包信息
|
||||
async function cloudInfo() {
|
||||
if (!config.CONTROLPLANE_URL) return null;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/file-sources/python-env", {
|
||||
headers: cp.machineHeaders(),
|
||||
timeout: 8,
|
||||
});
|
||||
_STATE.cloud_available = !!(r && r.available);
|
||||
_STATE.cloud_version = r && r.available ? String(r.version || "") : "";
|
||||
return r && r.available ? r : null;
|
||||
} catch (e) {
|
||||
logger.warning(`获取环境包云端信息失败(离线跳过):${e.message}`);
|
||||
_STATE.cloud_available = false;
|
||||
_STATE.cloud_version = "";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 状态(每次从磁盘实时计算安装态;云端信息来自最近一次 cloudInfo)
|
||||
function status() {
|
||||
const ver = readCurrent();
|
||||
const dir = ver ? path.join(envDir(), ver) : "";
|
||||
const installed = !!dir && fs.existsSync(path.join(dir, "python.exe"));
|
||||
return {
|
||||
installed,
|
||||
version: installed ? ver : "",
|
||||
dir: installed ? dir : "",
|
||||
cloud_available: !!_STATE.cloud_available,
|
||||
cloud_version: _STATE.cloud_version || "",
|
||||
checking: !!_STATE.checking,
|
||||
dl: {
|
||||
status: _STATE.dl_status || "idle",
|
||||
received: _STATE.dl_received || 0,
|
||||
total: _STATE.dl_total || 0,
|
||||
pct: _STATE.dl_pct || 0,
|
||||
error: _STATE.dl_error || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 刷新状态(供启动后/同步后调用,等价于 status())
|
||||
function refreshStatus() {
|
||||
return status();
|
||||
}
|
||||
|
||||
function resetDl() {
|
||||
_STATE.dl_status = "idle";
|
||||
_STATE.dl_received = 0;
|
||||
_STATE.dl_total = 0;
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
}
|
||||
|
||||
// 下载 zip 到缓存目录(.part → sha256 → rename),返回落盘路径
|
||||
async function downloadZip(info) {
|
||||
const url = String(info.url || "").trim();
|
||||
if (!url) throw new Error("环境包下载地址为空");
|
||||
const expect = String(info.sha256 || "").toLowerCase();
|
||||
const filename = String(info.filename || `python-env-${info.version}.zip`).trim();
|
||||
const cache = path.join(envDir(), "_cache");
|
||||
fs.mkdirSync(cache, { recursive: true });
|
||||
const part = path.join(cache, `${filename}.part`);
|
||||
const zip = path.join(cache, filename);
|
||||
const sha = crypto.createHash("sha256");
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 900 * 1000); // 大包 15 分钟上限
|
||||
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
const out = fs.createWriteStream(part);
|
||||
let received = 0;
|
||||
try {
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
}
|
||||
await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve())));
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
try { fs.unlinkSync(part); } catch (e) { /* 忽略 */ }
|
||||
throw new Error("环境包 sha256 校验失败");
|
||||
}
|
||||
try {
|
||||
fs.renameSync(part, zip);
|
||||
} catch (e) {
|
||||
try { fs.unlinkSync(part); } catch (e2) { /* 忽略 */ }
|
||||
throw new Error("环境包保存失败");
|
||||
}
|
||||
return zip;
|
||||
}
|
||||
|
||||
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录
|
||||
async function extractZip(zip, version) {
|
||||
const target = path.join(envDir(), version);
|
||||
const tmp = path.join(envDir(), `.${version}.tmp`);
|
||||
const rm = (p) => {
|
||||
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
|
||||
};
|
||||
// 清理可能的残留临时目录
|
||||
rm(tmp);
|
||||
rm(target);
|
||||
fs.mkdirSync(tmp, { recursive: true });
|
||||
|
||||
const az = new AdmZip(zip);
|
||||
const entries = az.getEntries();
|
||||
for (const en of entries) {
|
||||
const name = en.entryName.replace(/\\/g, "/");
|
||||
if (name.startsWith("/") || name.split("/").includes("..")) {
|
||||
throw new Error(`环境包含非法路径: ${name}`);
|
||||
}
|
||||
}
|
||||
az.extractAllTo(tmp, true);
|
||||
|
||||
// 冒烟校验:必须含 python.exe + webhost/backend/core/plugin_runner.py
|
||||
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
|
||||
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
|
||||
throw new Error("环境包缺少 plugin_runner.py");
|
||||
}
|
||||
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
|
||||
let lastErr = null;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
try {
|
||||
fs.renameSync(tmp, target);
|
||||
return target;
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
await new Promise((r) => setTimeout(r, 500 * (i + 1)));
|
||||
}
|
||||
}
|
||||
throw lastErr || new Error("环境包切换失败");
|
||||
}
|
||||
|
||||
// 切换当前版本 + 清理旧版本(保留上一版供回滚)
|
||||
function switchCurrent(version) {
|
||||
const cur = readCurrent();
|
||||
fs.mkdirSync(envDir(), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(envDir(), "current.json"),
|
||||
JSON.stringify({ version, updated_at: new Date().toISOString() }, null, 2),
|
||||
"utf-8"
|
||||
);
|
||||
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)
|
||||
const keep = new Set([version, cur].filter(Boolean));
|
||||
try {
|
||||
for (const name of fs.readdirSync(envDir())) {
|
||||
if (name === "current.json" || name === "_cache") continue;
|
||||
if (keep.has(name)) continue;
|
||||
const p = path.join(envDir(), name);
|
||||
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
}
|
||||
|
||||
let _syncing = false;
|
||||
|
||||
// 手动/启动同步:有更新的环境包则下载并切换;无则保持现状
|
||||
async function checkAndSync(force = false) {
|
||||
if (_syncing) return { ok: false, reason: "busy" };
|
||||
_syncing = true;
|
||||
_STATE.checking = true;
|
||||
resetDl();
|
||||
try {
|
||||
const info = await cloudInfo();
|
||||
if (!info) return { ok: false, reason: "no-cloud" };
|
||||
const cur = readCurrent();
|
||||
if (!force && cur && !versionLt(cur, info.version) && fs.existsSync(path.join(envDir(), cur, "python.exe"))) {
|
||||
refreshStatus();
|
||||
return { ok: true, current: true, version: cur };
|
||||
}
|
||||
_STATE.dl_status = "downloading";
|
||||
logger.info(`开始下载环境包 ${info.version}:${info.url}`);
|
||||
const zip = await downloadZip(info);
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
const dir = await extractZip(zip, info.version);
|
||||
switchCurrent(info.version);
|
||||
_STATE.dl_status = "idle";
|
||||
logger.info(`环境包 ${info.version} 安装完成:${dir}`);
|
||||
refreshStatus();
|
||||
return { ok: true, current: false, version: info.version };
|
||||
} catch (e) {
|
||||
logger.warning(`环境包同步失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = e.message;
|
||||
return { ok: false, reason: "error", error: e.message };
|
||||
} finally {
|
||||
_syncing = false;
|
||||
_STATE.checking = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 回滚到上一版(current.json 前一个版本目录;无则报错)
|
||||
function rollback() {
|
||||
const cur = readCurrent();
|
||||
const versions = [];
|
||||
try {
|
||||
for (const name of fs.readdirSync(envDir())) {
|
||||
if (name === "current.json" || name === "_cache") continue;
|
||||
if (fs.existsSync(path.join(envDir(), name, "python.exe"))) versions.push(name);
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
const target = versions
|
||||
.filter((v) => v !== cur)
|
||||
.sort((a, b) => (versionLt(a, b) ? 1 : -1))[0];
|
||||
if (!target) return { ok: false, error: "无可回滚版本" };
|
||||
switchCurrent(target);
|
||||
refreshStatus();
|
||||
return { ok: true, version: target };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
status,
|
||||
refreshStatus,
|
||||
checkAndSync,
|
||||
rollback,
|
||||
readCurrent,
|
||||
envDir,
|
||||
extractZip,
|
||||
switchCurrent,
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
// 事件枢纽:插件运行线程产生的 日志/进度/完成 事件 → WS 广播给渲染层。
|
||||
// 对齐 Python webhost hub.py 语义(t/run_id/plugin_id/level/pct/ok/error)。
|
||||
"use strict";
|
||||
|
||||
const { EventEmitter } = require("events");
|
||||
|
||||
class Hub extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
this._clients = new Set(); // ws 连接
|
||||
}
|
||||
|
||||
// 由 server.js 在 WS 连接建立后注册
|
||||
addClient(ws) {
|
||||
this._clients.add(ws);
|
||||
ws.on("close", () => this._clients.delete(ws));
|
||||
ws.on("error", () => this._clients.delete(ws));
|
||||
}
|
||||
|
||||
clientCount() {
|
||||
return this._clients.size;
|
||||
}
|
||||
|
||||
publish(event) {
|
||||
this.emit("event", event);
|
||||
const payload = JSON.stringify(event);
|
||||
for (const ws of this._clients) {
|
||||
try {
|
||||
if (ws.readyState === 1 /* OPEN */) ws.send(payload);
|
||||
} catch (e) {
|
||||
this._clients.delete(ws);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const HUB = new Hub();
|
||||
|
||||
module.exports = { Hub, HUB };
|
||||
@@ -0,0 +1,72 @@
|
||||
// 上次执行参数(per 账号 + per 插件):供场景执行台「恢复上次参数」使用,免去每次逐项重填。
|
||||
// 存储:%LOCALAPPDATA%\37duAutomation\last_run_fields.json(纯新增文件,不改既有契约)
|
||||
// 安全:password 类型字段一律不落盘(插件 fields 可含密码),只保存非敏感项。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("last-fields");
|
||||
|
||||
const STORE_PATH = path.join(config.APP_DATA, "last_run_fields.json");
|
||||
const MAX_FIELDS = 40; // 单插件最多记 40 项,防异常插件撑爆文件
|
||||
|
||||
function loadAll() {
|
||||
if (!fs.existsSync(STORE_PATH)) return {};
|
||||
try {
|
||||
const d = JSON.parse(fs.readFileSync(STORE_PATH, "utf-8"));
|
||||
return d && typeof d === "object" && !Array.isArray(d) ? d : {};
|
||||
} catch (e) {
|
||||
logger.warning(`上次参数读取失败:${e.message}`);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function saveAll(data) {
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
const tmp = STORE_PATH + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
|
||||
fs.renameSync(tmp, STORE_PATH); // 原子替换
|
||||
} catch (e) {
|
||||
logger.warning(`上次参数写入失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存一次执行的参数快照;schema = 插件的 fields 元数据(用于剔除 password 等敏感项)
|
||||
function remember(account, pluginId, fields, schema) {
|
||||
if (!account || !pluginId || !fields || typeof fields !== "object") return;
|
||||
const secret = new Set(
|
||||
(Array.isArray(schema) ? schema : [])
|
||||
.filter((f) => f && f.type === "password")
|
||||
.map((f) => f.key)
|
||||
);
|
||||
const keep = {};
|
||||
for (const [k, v] of Object.entries(fields)) {
|
||||
if (secret.has(k)) continue;
|
||||
if (Object.keys(keep).length >= MAX_FIELDS) break;
|
||||
keep[k] = v;
|
||||
}
|
||||
const all = loadAll();
|
||||
if (!all[account] || typeof all[account] !== "object") all[account] = {};
|
||||
all[account][pluginId] = {
|
||||
fields: keep,
|
||||
at: new Date().toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
saveAll(all);
|
||||
}
|
||||
|
||||
// 读取上次参数;无记录返回 { fields: {}, at: "" }
|
||||
function recall(account, pluginId) {
|
||||
const all = loadAll();
|
||||
const rec = (all[account] || {})[pluginId] || null;
|
||||
if (!rec || typeof rec !== "object") return { fields: {}, at: "" };
|
||||
return {
|
||||
fields: rec.fields && typeof rec.fields === "object" ? rec.fields : {},
|
||||
at: rec.at || "",
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { STORE_PATH, MAX_FIELDS, remember, recall };
|
||||
@@ -0,0 +1,308 @@
|
||||
// 部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
|
||||
// 对齐 Python webhost licensing.py 的路径与语义(跨端共享 %LOCALAPPDATA%\37duAutomation)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { verifyBlob, sha256Hex, versionLt, deadlinePassed, nowStr } = require("./crypto");
|
||||
const cp = require("./cpclient");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("licensing");
|
||||
|
||||
const KEYS_DIR = path.join(config.APP_DATA, "keys");
|
||||
const licensePath = path.join(config.APP_DATA, "license.json");
|
||||
const controlPath = path.join(config.APP_DATA, "control.json");
|
||||
const reportsPath = path.join(config.APP_DATA, "offline_reports.jsonl");
|
||||
|
||||
const ONLINE_TTL = 180 * 1000;
|
||||
let _lastSync = 0;
|
||||
const _CONTROLPLANE_URL = config.CONTROLPLANE_URL;
|
||||
|
||||
function touchSync() {
|
||||
_lastSync = Date.now();
|
||||
}
|
||||
function isOnline() {
|
||||
return Date.now() - _lastSync <= ONLINE_TTL;
|
||||
}
|
||||
|
||||
// ==================== 公钥缓存与验签 ====================
|
||||
function pubPemPath() {
|
||||
return path.join(KEYS_DIR, "pub.pem");
|
||||
}
|
||||
|
||||
function cachePublicKey(pemText) {
|
||||
pemText = (pemText || "").trim();
|
||||
if (!pemText) return;
|
||||
fs.mkdirSync(KEYS_DIR, { recursive: true });
|
||||
fs.writeFileSync(pubPemPath(), pemText, "ascii");
|
||||
touchSync();
|
||||
}
|
||||
|
||||
function loadPublicKey() {
|
||||
try {
|
||||
return fs.readFileSync(pubPemPath(), "utf-8");
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function verifyLicense() {
|
||||
if (!fs.existsSync(licensePath)) throw new Error("无本地授权票据(license.json)");
|
||||
const pub = loadPublicKey();
|
||||
if (!pub) throw new Error("缺少中心机公钥,无法验签授权票据");
|
||||
const data = JSON.parse(fs.readFileSync(licensePath, "utf-8"));
|
||||
return verifyBlob(data.ticket, pub);
|
||||
}
|
||||
|
||||
function emptyControl() {
|
||||
return { revokedPlugins: [], disabledPlugins: [], forcedUpdates: [] };
|
||||
}
|
||||
|
||||
function verifyControl() {
|
||||
if (!fs.existsSync(controlPath)) return emptyControl();
|
||||
const pub = loadPublicKey();
|
||||
if (!pub) return emptyControl();
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(controlPath, "utf-8"));
|
||||
const payload = verifyBlob(data.ticket, pub);
|
||||
return payload && typeof payload === "object" ? payload : {};
|
||||
} catch (e) {
|
||||
return emptyControl();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 授权周期(离线最多 7 天) ====================
|
||||
function licenseStatus() {
|
||||
if (!fs.existsSync(licensePath)) return { status: "missing", payload: null };
|
||||
let lic;
|
||||
try {
|
||||
lic = verifyLicense();
|
||||
} catch (e) {
|
||||
return { status: "invalid", payload: null };
|
||||
}
|
||||
const exp = lic.expiresAt;
|
||||
if (!exp || Date.now() > parseInt(exp, 10) * 1000) {
|
||||
return { status: "expired", payload: lic };
|
||||
}
|
||||
return { status: "ok", payload: lic };
|
||||
}
|
||||
|
||||
// 授权票据概要:供状态栏 / 授权票据卡展示"剩余 N 天"(expiresAt 为 epoch 秒,中心机签发)
|
||||
function licenseInfo() {
|
||||
const st = licenseStatus();
|
||||
const exp = st.payload && st.payload.expiresAt ? parseInt(st.payload.expiresAt, 10) : 0;
|
||||
return {
|
||||
status: st.status, // missing | invalid | expired | ok
|
||||
expire_ts: exp,
|
||||
expire_at: exp ? new Date(exp * 1000).toLocaleString("zh-CN", { hour12: false }) : "",
|
||||
days_left: exp ? Math.ceil((exp * 1000 - Date.now()) / 86400000) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function ensureLicense(account) {
|
||||
const st = licenseStatus();
|
||||
if (st.status === "ok" && (st.payload || {}).userId === account) {
|
||||
return Promise.resolve({ ok: true, payload: st.payload });
|
||||
}
|
||||
return syncLicensing(account)
|
||||
.catch((e) => {
|
||||
logger.warning(`授权票据联网刷新失败(离线或控制面不可达):${e.message}`);
|
||||
})
|
||||
.then(() => {
|
||||
const st2 = licenseStatus();
|
||||
return {
|
||||
ok: st2.status === "ok" && (st2.payload || {}).userId === account,
|
||||
payload: st2.payload,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 缓存写读 ====================
|
||||
function saveLicense(ticketJson) {
|
||||
const text = typeof ticketJson === "object"
|
||||
? JSON.stringify(ticketJson)
|
||||
: JSON.stringify({ ticket: ticketJson });
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(licensePath, text, "utf-8");
|
||||
touchSync();
|
||||
}
|
||||
|
||||
function saveControl(ticketJson) {
|
||||
const text = typeof ticketJson === "object"
|
||||
? JSON.stringify(ticketJson)
|
||||
: JSON.stringify({ ticket: ticketJson });
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(controlPath, text, "utf-8");
|
||||
touchSync();
|
||||
}
|
||||
|
||||
// ==================== 启动前校验链 ====================
|
||||
function installedVersion(pluginId) {
|
||||
try {
|
||||
const act = fs.readFileSync(path.join(config.APP_DATA, "active.json"), "utf-8");
|
||||
const d = JSON.parse(act);
|
||||
return d.pluginId === pluginId ? d.version || "" : "";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
async function runCheckAllowed(pluginId, account, online) {
|
||||
const lic = await ensureLicense(account);
|
||||
if (!lic.ok) return "授权已过期(最长离线 7 天),请联网刷新后重试";
|
||||
|
||||
const control = verifyControl();
|
||||
if ((control.revokedPlugins || []).includes(pluginId)) return "插件已被下架(revoked),禁止运行";
|
||||
if ((control.disabledPlugins || []).includes(pluginId)) return "插件已被禁用(disabled),禁止运行";
|
||||
|
||||
const licPlugins = {};
|
||||
for (const p of (lic.payload || {}).plugins || []) licPlugins[p.pluginId] = p;
|
||||
const grant = licPlugins[pluginId];
|
||||
if (!grant) return `账号 ${account} 无插件「${pluginId}」的授权`;
|
||||
if (!grant.canRun) return `账号 ${account} 无「${pluginId}」的运行授权`;
|
||||
|
||||
if (online) {
|
||||
const forced = (control.forcedUpdates || []).find((f) => f.pluginId === pluginId);
|
||||
if (forced) {
|
||||
const minVer = forced.minVersion || "";
|
||||
const deadline = forced.deadline || "";
|
||||
if (minVer && deadline && deadlinePassed(deadline)) {
|
||||
const installed = installedVersion(pluginId);
|
||||
if (installed && versionLt(installed, minVer)) {
|
||||
return `插件需强制升级到 v${minVer} 以上(deadline 已过),当前 v${installed} 已禁止启动,请先更新`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ==================== 联网同步(公钥 + 授权票据 + 管控清单,逐资源容错) ====================
|
||||
async function syncLicensing(account) {
|
||||
if (!config.CONTROLPLANE_URL || !account) return;
|
||||
const headers = cp.machineHeaders();
|
||||
let gotAny = false;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/me/pubkey", { headers, timeout: 5 });
|
||||
cachePublicKey(r.pub || "");
|
||||
gotAny = true;
|
||||
} catch (e) {
|
||||
logger.warning(`中心机公钥拉取失败:${e.message}`);
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/me/license", { headers, params: { account }, timeout: 5 });
|
||||
saveLicense(r);
|
||||
gotAny = true;
|
||||
} catch (e) {
|
||||
logger.warning(`离线授权票据拉取失败:${e.message}`);
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/me/control-list", { headers, timeout: 5 });
|
||||
saveControl(r);
|
||||
gotAny = true;
|
||||
} catch (e) {
|
||||
logger.warning(`管控清单拉取失败:${e.message}`);
|
||||
}
|
||||
if (gotAny) await flushOfflineReports();
|
||||
}
|
||||
|
||||
// ==================== 运行上报 ====================
|
||||
async function report(account, deviceId, pluginId, version, status, msg = "", durationSec = 0) {
|
||||
const rec = {
|
||||
account, device_id: deviceId, plugin_id: pluginId, version,
|
||||
status, msg, duration_sec: parseInt(durationSec, 10) || 0,
|
||||
at: nowStr(),
|
||||
};
|
||||
if (!_CONTROLPLANE_URL) return;
|
||||
try {
|
||||
await pushReport(rec);
|
||||
touchSync();
|
||||
return;
|
||||
} catch (e) {
|
||||
// 离线:暂存待补报
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.appendFileSync(reportsPath, JSON.stringify(rec) + "\n", "utf-8");
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
async function pushReport(rec) {
|
||||
const headers = cp.machineHeaders();
|
||||
await cp.request("POST", "/api/runtime/report", { headers, json: rec, timeout: 5 });
|
||||
}
|
||||
|
||||
// 重连后补报此前暂存的离线记录;返回补报条数
|
||||
async function flushOfflineReports() {
|
||||
if (!fs.existsSync(reportsPath)) return 0;
|
||||
let sent = 0;
|
||||
const pending = [];
|
||||
const lines = fs.readFileSync(reportsPath, "utf-8").split(/\r?\n/).filter((l) => l.trim());
|
||||
for (const ln of lines) {
|
||||
try {
|
||||
const rec = JSON.parse(ln);
|
||||
await pushReport(rec);
|
||||
sent++;
|
||||
} catch (e) {
|
||||
pending.push(ln);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (pending.length === 0) fs.unlinkSync(reportsPath);
|
||||
else fs.writeFileSync(reportsPath, pending.join("\n") + "\n", "utf-8");
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
// 设备上报(心跳 + Chrome 环境):int 0/1 语义
|
||||
async function deviceReport(deviceId, account, info) {
|
||||
if (!_CONTROLPLANE_URL) return false;
|
||||
const payload = {
|
||||
device_id: deviceId,
|
||||
account: account || "",
|
||||
hostname: (info && info.hostname) || "",
|
||||
os: (info && info.os) || "windows",
|
||||
ip: (info && info.ip) || "",
|
||||
chrome_installed: (info && info.chromeInstalled) ? 1 : 0,
|
||||
chrome_version: (info && info.chromeVersion) || "",
|
||||
chrome_ok: (info && info.chromeOk) ? 1 : 0,
|
||||
status: 1,
|
||||
};
|
||||
try {
|
||||
await cp.request("POST", "/api/device/report", { headers: cp.machineHeaders(), json: payload, timeout: 5 });
|
||||
touchSync();
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.warning(`设备上报失败:${e.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
KEYS_DIR,
|
||||
licensePath,
|
||||
controlPath,
|
||||
reportsPath,
|
||||
touchSync,
|
||||
isOnline,
|
||||
cachePublicKey,
|
||||
verifyLicense,
|
||||
verifyControl,
|
||||
licenseStatus,
|
||||
licenseInfo,
|
||||
ensureLicense,
|
||||
saveLicense,
|
||||
saveControl,
|
||||
runCheckAllowed,
|
||||
syncLicensing,
|
||||
report,
|
||||
flushOfflineReports,
|
||||
deviceReport,
|
||||
sha256Hex,
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
// 日志:INFO 屏蔽大体积 JSON 调试日志;DEBUG 模式开启完整输出(AGENTS.md 规范)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const LEVELS = { DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40 };
|
||||
const DEBUG = process.env.DEBUG === "1" || process.env.DEBUG === "true";
|
||||
const MAX_LOG_BYTES = 10 * 1024 * 1024; // 单文件 10MB,超出轮转(保留 3 份)
|
||||
|
||||
let _file = null; // { fd 简化:按行 append 即可 }
|
||||
|
||||
function setLogFile(filePath) {
|
||||
_file = filePath;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
} catch (e) {
|
||||
_file = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 按大小轮转:shell.log → shell.log.1 → .2 → .3(丢弃最旧)
|
||||
function rotateIfNeeded() {
|
||||
if (!_file) return;
|
||||
try {
|
||||
const st = fs.statSync(_file);
|
||||
if (st.size < MAX_LOG_BYTES) return;
|
||||
for (let i = 2; i >= 1; i--) {
|
||||
const a = `${_file}.${i}`;
|
||||
const b = `${_file}.${i + 1}`;
|
||||
if (fs.existsSync(a)) fs.renameSync(a, b);
|
||||
}
|
||||
if (fs.existsSync(_file)) fs.renameSync(_file, `${_file}.1`);
|
||||
} catch (e) {
|
||||
/* 轮转失败忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function ts() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function write(level, name, msg) {
|
||||
if (LEVELS[level] < LEVELS[DEBUG ? "DEBUG" : "INFO"]) return;
|
||||
const line = `${ts()} ${level.padEnd(7)} ${name} ${msg}`;
|
||||
console.log(line);
|
||||
if (_file) {
|
||||
try {
|
||||
rotateIfNeeded();
|
||||
fs.appendFileSync(_file, line + "\n", "utf-8");
|
||||
} catch (e) {
|
||||
/* 落盘失败静默 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeLogger(name) {
|
||||
return {
|
||||
debug: (msg) => write("DEBUG", name, msg),
|
||||
info: (msg) => write("INFO", name, msg),
|
||||
warning: (msg) => write("WARNING", name, msg),
|
||||
error: (msg) => write("ERROR", name, msg),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { makeLogger, setLogFile, isDebug: DEBUG };
|
||||
@@ -0,0 +1,22 @@
|
||||
// 入口:CLI 模式(node electron/main.js --cli,无 Electron)或 Electron 模式(electron .)。
|
||||
"use strict";
|
||||
|
||||
const isCli = process.argv.includes("--cli") || !process.versions || !process.versions.electron;
|
||||
|
||||
if (isCli) {
|
||||
const { init } = require("./app");
|
||||
const { listen } = require("./server");
|
||||
const { makeLogger } = require("./logger");
|
||||
const logger = makeLogger("main");
|
||||
|
||||
(async () => {
|
||||
await init();
|
||||
listen();
|
||||
logger.info("CLI 模式运行中(Ctrl+C 退出)。Electron 窗口模式:npm run electron");
|
||||
})().catch((e) => {
|
||||
logger.error(`启动失败:${e.stack || e}`);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
require("./electron-main");
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// 宿主插件元数据 / 平台权限解析(/api/meta 聚合)。
|
||||
// 对齐 Python core/meta.py:插件可见性 = 本地授权票据快照;平台白名单来自中心机。
|
||||
"use strict";
|
||||
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const licensing = require("./licensing");
|
||||
const registry = require("./registry");
|
||||
const platformAuth = require("./platform-auth");
|
||||
const state = require("./state");
|
||||
const envSync = require("./env-sync");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("meta");
|
||||
|
||||
// 调中心机获取账号可登录平台白名单;控制面不可达返回 null(调用方决定拒绝)
|
||||
async function accountAllowedPlatforms(account) {
|
||||
if (!config.CONTROLPLANE_URL) return null;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/platforms/allowed", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { account },
|
||||
timeout: 5,
|
||||
});
|
||||
return new Set(r.allowed || []);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/meta 聚合响应
|
||||
async function buildMeta(account) {
|
||||
let authExpired = false;
|
||||
let plugins = [];
|
||||
if (account) {
|
||||
const lic = await licensing.ensureLicense(account);
|
||||
if (lic.ok) {
|
||||
const allowed = new Set((lic.payload || {}).plugins.map((p) => p.pluginId));
|
||||
for (const entry of registry.listLocalPlugins()) {
|
||||
if (allowed.has(entry.id)) plugins.push(registry.pluginSchema(entry.id));
|
||||
}
|
||||
} else {
|
||||
authExpired = true;
|
||||
}
|
||||
}
|
||||
const allowedPlats = account ? await accountAllowedPlatforms(account) : null;
|
||||
const platforms = [];
|
||||
for (const [pid, m] of Object.entries(state.PLATFORMS)) {
|
||||
platforms.push({
|
||||
id: pid,
|
||||
label: m.label,
|
||||
online: await platformAuth.isOnline(pid, account), // 按当前账号的会话校验
|
||||
allowed: allowedPlats === null ? true : allowedPlats.has(pid),
|
||||
});
|
||||
}
|
||||
return {
|
||||
appName: "37du 自动化工作台",
|
||||
dingtalkScan: !!config.CONTROLPLANE_URL,
|
||||
authExpired,
|
||||
// 授权票据概要:常驻态进状态栏 / 票据卡(剩余天数),异常态才升级为横幅
|
||||
license: licensing.licenseInfo(),
|
||||
platforms,
|
||||
plugins,
|
||||
// 环境包(便携 Python 运行时)概要:设置页/状态栏展示,空 = 未安装
|
||||
env: {
|
||||
version: envSync.readCurrent() || "",
|
||||
installed: !!envSync.readCurrent(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { buildMeta, accountAllowedPlatforms };
|
||||
@@ -0,0 +1,249 @@
|
||||
// 平台登录态(HR/OA):真实登录/登出/在线校验。
|
||||
// 保持 Python 子进程执行登录自动化(shared/hr_login、oa_login,DrissionPage 滑块),
|
||||
// Node 壳只负责拉起子进程与解析结果。
|
||||
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
|
||||
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { spawn } = require("child_process");
|
||||
const config = require("./config");
|
||||
const platformCreds = require("./platform-creds");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("platform-auth");
|
||||
|
||||
const LABELS = { hr: "HR 系统", oa: "OA 系统" };
|
||||
const COOKIE_FILES = {
|
||||
hr: "hr_cookies.json",
|
||||
oa: "oa_cookies.json",
|
||||
};
|
||||
const BASE_SESSIONS_DIR = path.join(config.APP_DATA, ".sessions");
|
||||
|
||||
const _onlineCache = new Map(); // `${account}:${pid}` -> {ts, value}
|
||||
const ONLINE_CACHE_TTL = 15 * 1000;
|
||||
|
||||
function platforms() {
|
||||
return Object.keys(LABELS).map((pid) => ({ id: pid, label: LABELS[pid] }));
|
||||
}
|
||||
|
||||
// 账号隔离的会话目录;无账号时回退共享目录(兼容旧数据)
|
||||
function sessionDir(account) {
|
||||
const base = account ? path.join(BASE_SESSIONS_DIR, String(account)) : BASE_SESSIONS_DIR;
|
||||
try {
|
||||
fs.mkdirSync(base, { recursive: true });
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// spawn python 子进程执行 snippet,返回 stdout 最后一行 JSON(或文本)
|
||||
function runPython(snippet, timeoutMs = 120000, extraEnv = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const args = ["-c", snippet];
|
||||
const child = spawn(config.pythonExe(), args, {
|
||||
// webhost 包解析:环境包模式 cwd=环境包根(webhost/ 在其中);dev = desktop/(仓库内 webhost)
|
||||
cwd: config.runtimeRoot(),
|
||||
windowsHide: true,
|
||||
env: { ...process.env, PYTHONIOENCODING: "utf-8", PYTHONUTF8: "1", ...extraEnv },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let out = "";
|
||||
let err = "";
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
treeKill(child.pid);
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
reject(new Error("平台登录子进程超时"));
|
||||
}, timeoutMs);
|
||||
child.stdout.on("data", (d) => (out += d.toString("utf-8")));
|
||||
child.stderr.on("data", (d) => (err += d.toString("utf-8")));
|
||||
child.on("error", (e) => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error(`拉起 Python 子进程失败: ${e.message}`));
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (code !== 0) {
|
||||
reject(new Error(`平台子进程退出(${code}): ${err.slice(0, 300)}`));
|
||||
return;
|
||||
}
|
||||
resolve(out.trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function treeKill(pid) {
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
killer.unref();
|
||||
} else {
|
||||
try {
|
||||
process.kill(-pid, "SIGKILL");
|
||||
} catch (e) {
|
||||
process.kill(pid, "SIGKILL");
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function extractJson(out) {
|
||||
// 兼容模块 print("最终结果:", dict) 与纯 JSON 输出:取最后一个 JSON 对象
|
||||
const lines = out.split(/\r?\n/).filter((l) => l.trim());
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i];
|
||||
const idx = line.indexOf("{");
|
||||
if (idx >= 0) {
|
||||
try {
|
||||
return JSON.parse(line.slice(idx));
|
||||
} catch (e) {
|
||||
/* 继续找 */
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 真实校验平台登录态(发起轻量 API 校验,非内存假状态);结果短缓存避免频繁请求平台。
|
||||
const VALIDATE = {
|
||||
hr: {
|
||||
url: "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo",
|
||||
method: "POST",
|
||||
},
|
||||
oa: {
|
||||
url: "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do?method=sumTodoCount",
|
||||
method: "GET",
|
||||
},
|
||||
};
|
||||
|
||||
function loadCookies(pid, account) {
|
||||
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
|
||||
if (!fs.existsSync(file)) return [];
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function isOnline(pid, account) {
|
||||
const cacheKey = `${account || ""}:${pid}`;
|
||||
const cached = _onlineCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.ts < ONLINE_CACHE_TTL) return cached.value;
|
||||
let value = false;
|
||||
const def = VALIDATE[pid];
|
||||
if (!def) return false;
|
||||
try {
|
||||
const cookies = loadCookies(pid, account);
|
||||
if (cookies.length === 0) {
|
||||
value = false;
|
||||
} else {
|
||||
const pairs = [];
|
||||
for (const c of cookies) {
|
||||
if (c && c.name && c.value && (!c.domain || String(c.domain).includes("37du.co"))) {
|
||||
pairs.push(`${c.name}=${c.value}`);
|
||||
}
|
||||
}
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 8000);
|
||||
const resp = await fetch(def.url, {
|
||||
method: def.method,
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
...(pairs.length ? { Cookie: pairs.join("; ") } : {}),
|
||||
},
|
||||
body: def.method === "POST" ? "" : undefined,
|
||||
signal: ctrl.signal,
|
||||
redirect: "manual",
|
||||
});
|
||||
clearTimeout(timer);
|
||||
const text = await resp.text();
|
||||
value = resp.status === 200 && text.trim().startsWith("{") || text.trim().startsWith("[");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`平台 ${pid} 在线校验失败:${e.message}`);
|
||||
value = false;
|
||||
}
|
||||
_onlineCache.set(cacheKey, { ts: Date.now(), value });
|
||||
return value;
|
||||
}
|
||||
|
||||
// 真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
// account:当前登录账号;其个人 HR/OA 账号密码通过环境变量注入登录子进程。
|
||||
async function login(pid, account) {
|
||||
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
|
||||
const cacheKey = `${account || ""}:${pid}`;
|
||||
_onlineCache.delete(cacheKey);
|
||||
const extraEnv = { PLATFORM_ACCOUNT: account || "" };
|
||||
const credEnv = platformCreds.envFor(account, pid);
|
||||
if (credEnv) {
|
||||
Object.assign(extraEnv, credEnv);
|
||||
logger.info(`平台 ${pid} 使用账号「${credEnv[`${pid}_login_username`]}」登录(账号 ${account})`);
|
||||
} else {
|
||||
logger.warning(`平台 ${pid} 登录:账号 ${account} 未配置个人平台账号密码,将回退共享配置`);
|
||||
}
|
||||
try {
|
||||
const snippet =
|
||||
pid === "hr"
|
||||
? `from webhost.backend.shared import hr_login; import json; print(json.dumps(hr_login.main({"force": False}), ensure_ascii=False))`
|
||||
: `from webhost.backend.shared import oa_login; import json; print(json.dumps(oa_login.main(force=False), ensure_ascii=False))`;
|
||||
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
|
||||
const result = extractJson(out) || {};
|
||||
const ok = !!result.success;
|
||||
const online = ok ? await isOnline(pid, account) : false;
|
||||
return {
|
||||
id: pid,
|
||||
label: LABELS[pid],
|
||||
online,
|
||||
message: result.message || (ok ? "登录成功" : "登录失败"),
|
||||
};
|
||||
} catch (e) {
|
||||
logger.error(`平台 ${pid} 登录失败(账号 ${account}):${e.message}`);
|
||||
return { id: pid, label: LABELS[pid], online: false, message: `登录过程异常:${e.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
// 登出平台:删除该账号的 cookies 文件,使该账号的平台登录态失效。
|
||||
function logout(pid, account) {
|
||||
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
|
||||
_onlineCache.delete(`${account || ""}:${pid}`);
|
||||
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
|
||||
try {
|
||||
if (fs.existsSync(file)) fs.unlinkSync(file);
|
||||
} catch (e) {
|
||||
logger.warning(`清除平台 ${pid} cookies 失败(账号 ${account}):${e.message}`);
|
||||
}
|
||||
return { id: pid, label: LABELS[pid], online: false };
|
||||
}
|
||||
|
||||
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
|
||||
async function status(account) {
|
||||
const creds = platformCreds.get(account) || {};
|
||||
const out = [];
|
||||
for (const pid of Object.keys(LABELS)) {
|
||||
const c = creds[pid] || {};
|
||||
out.push({
|
||||
id: pid,
|
||||
label: LABELS[pid],
|
||||
online: await isOnline(pid, account),
|
||||
has_creds: !!(c.user && c.pass),
|
||||
user: c.user || "",
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { platforms, sessionDir, isOnline, login, logout, status, BASE_SESSIONS_DIR };
|
||||
@@ -0,0 +1,111 @@
|
||||
// 平台账号凭据(HR/OA)按账号本机加密保存:AES-256-GCM,随机密钥落盘。
|
||||
// 每人在壳里「个人中心→平台账号」填写自己的 HR/OA 账号密码;
|
||||
// 登录时注入 Python 登录模块环境变量(hr_login_username / hr_login_password 等)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("platform-creds");
|
||||
|
||||
const DIR = path.join(config.APP_DATA, "platform-creds");
|
||||
const KEY_FILE = path.join(DIR, ".key");
|
||||
const DATA_FILE = path.join(DIR, "creds.json");
|
||||
|
||||
// 密文结构:{iv, tag, data}(base64)
|
||||
function loadKey() {
|
||||
try {
|
||||
if (fs.existsSync(KEY_FILE)) return fs.readFileSync(KEY_FILE);
|
||||
const key = crypto.randomBytes(32);
|
||||
fs.mkdirSync(DIR, { recursive: true });
|
||||
fs.writeFileSync(KEY_FILE, key, { mode: 0o600 });
|
||||
return key;
|
||||
} catch (e) {
|
||||
logger.warning(`平台账号凭据密钥初始化失败: ${e.message}`);
|
||||
return crypto.randomBytes(32); // 进程内可用;重启后不可解(仅兜底,几乎不会走到)
|
||||
}
|
||||
}
|
||||
|
||||
function encrypt(obj) {
|
||||
const key = loadKey();
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
||||
const data = Buffer.from(JSON.stringify(obj), "utf-8");
|
||||
const enc = Buffer.concat([cipher.update(data), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return { iv: iv.toString("base64"), tag: tag.toString("base64"), data: enc.toString("base64") };
|
||||
}
|
||||
|
||||
function decrypt(payload) {
|
||||
const key = loadKey();
|
||||
const iv = Buffer.from(payload.iv, "base64");
|
||||
const tag = Buffer.from(payload.tag, "base64");
|
||||
const data = Buffer.from(payload.data, "base64");
|
||||
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
return JSON.parse(Buffer.concat([decipher.update(data), decipher.final()]).toString("utf-8"));
|
||||
}
|
||||
|
||||
function loadAll() {
|
||||
if (!fs.existsSync(DATA_FILE)) return {};
|
||||
try {
|
||||
return decrypt(JSON.parse(fs.readFileSync(DATA_FILE, "utf-8")));
|
||||
} catch (e) {
|
||||
logger.warning(`平台账号凭据读取失败: ${e.message}`);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function saveAll(all) {
|
||||
try {
|
||||
fs.mkdirSync(DIR, { recursive: true });
|
||||
fs.writeFileSync(DATA_FILE, JSON.stringify(encrypt(all)), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`平台账号凭据保存失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// account → {hr: {user, pass}, oa: {user, pass}}
|
||||
function get(account) {
|
||||
if (!account) return null;
|
||||
return loadAll()[account] || null;
|
||||
}
|
||||
|
||||
// 保存当前账号某平台的凭据;pass 为空串表示保留原密码(仅更新用户名/不清除)
|
||||
function upsert(account, pid, creds) {
|
||||
if (!account) throw new Error("缺少账号");
|
||||
if (!creds) return false;
|
||||
const all = loadAll();
|
||||
const entry = all[account] || {};
|
||||
const cur = entry[pid] || {};
|
||||
const user = typeof creds.user === "string" ? creds.user.trim() : "";
|
||||
let pass = typeof creds.pass === "string" ? creds.pass : "";
|
||||
if (user === "" && pass === "") {
|
||||
// 清空该平台凭据
|
||||
delete entry[pid];
|
||||
} else {
|
||||
if (user === "") user = cur.user || ""; // 未填用户名:沿用
|
||||
if (pass === "") pass = cur.pass || ""; // 未填密码:沿用
|
||||
entry[pid] = { user, pass };
|
||||
}
|
||||
all[account] = entry;
|
||||
saveAll(all);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 供登录注入环境变量:{hr_login_username, hr_login_password};未配置返回 null
|
||||
function envFor(account, pid) {
|
||||
const c = get(account);
|
||||
if (!c) return null;
|
||||
const p = c[pid];
|
||||
if (!p || !p.user) return null;
|
||||
return {
|
||||
[`${pid}_login_username`]: p.user,
|
||||
[`${pid}_login_password`]: p.pass || "",
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { get, upsert, envFor, DIR };
|
||||
@@ -0,0 +1,73 @@
|
||||
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
|
||||
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
|
||||
// 安全:password 类型字段一律不落盘(与 last-fields.js 一致,仅保存非敏感项)。
|
||||
"use strict";
|
||||
|
||||
const { db } = require("./db");
|
||||
|
||||
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
|
||||
|
||||
// 过滤敏感字段:schema = 插件的 fields 元数据,password 类型不入库
|
||||
function sanitize(fields, schema) {
|
||||
const secret = new Set(
|
||||
(Array.isArray(schema) ? schema : [])
|
||||
.filter((f) => f && f.type === "password")
|
||||
.map((f) => f.key)
|
||||
);
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(fields || {})) {
|
||||
if (secret.has(k)) continue;
|
||||
out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rowToCfg(row) {
|
||||
if (!row) return null;
|
||||
let fields = {};
|
||||
try { fields = JSON.parse(row.fields || "{}"); } catch (_) { fields = {}; }
|
||||
return { id: String(row.id), name: row.name, fields, at: row.at || "" };
|
||||
}
|
||||
|
||||
function listConfigs(account, pluginId) {
|
||||
const rows = db.prepare(
|
||||
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? ORDER BY id"
|
||||
).all(account, pluginId);
|
||||
return rows.map(rowToCfg);
|
||||
}
|
||||
|
||||
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
|
||||
function saveConfig(account, pluginId, name, fields, schema) {
|
||||
const trimmed = String(name || "").trim().slice(0, 20);
|
||||
if (!trimmed) return null;
|
||||
const keep = sanitize(fields, schema);
|
||||
const at = new Date().toLocaleString("zh-CN", { hour12: false });
|
||||
const exists = db.prepare(
|
||||
"SELECT id FROM plugin_configs WHERE account = ? AND plugin_id = ? AND name = ?"
|
||||
).get(account, pluginId, trimmed);
|
||||
if (exists) {
|
||||
db.prepare(
|
||||
"UPDATE plugin_configs SET fields = ?, at = ? WHERE id = ?"
|
||||
).run(JSON.stringify(keep), at, exists.id);
|
||||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(exists.id));
|
||||
}
|
||||
const count = db.prepare(
|
||||
"SELECT COUNT(*) AS n FROM plugin_configs WHERE account = ? AND plugin_id = ?"
|
||||
).get(account, pluginId);
|
||||
if (count.n >= MAX_CONFIGS_PER_PLUGIN) {
|
||||
throw Object.assign(new Error(`每个场景最多保存 ${MAX_CONFIGS_PER_PLUGIN} 套配置`), { status: 400 });
|
||||
}
|
||||
const r = db.prepare(
|
||||
"INSERT INTO plugin_configs (account, plugin_id, name, fields, at) VALUES (?, ?, ?, ?, ?)"
|
||||
).run(account, pluginId, trimmed, JSON.stringify(keep), at);
|
||||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(r.lastInsertRowid));
|
||||
}
|
||||
|
||||
function deleteConfig(account, pluginId, cfgId) {
|
||||
const r = db.prepare(
|
||||
"DELETE FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
|
||||
).run(account, pluginId, cfgId);
|
||||
return r.changes > 0;
|
||||
}
|
||||
|
||||
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, saveConfig, deleteConfig };
|
||||
@@ -0,0 +1,375 @@
|
||||
// 插件按账号权限自下载 + 版本更新(执行机主动拉取;下载/校验/原子安装)。
|
||||
// 对齐 Python webhost plugin_sync.py:清单 diff → download-ticket → sha256 → 临时目录原子替换。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const os = require("os");
|
||||
const crypto = require("crypto");
|
||||
const AdmZip = require("adm-zip");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { sha256Hex, versionLt } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
const { pluginRoot } = require("./registry");
|
||||
|
||||
const logger = makeLogger("plugin-sync");
|
||||
|
||||
const DL_TIMEOUT = 300;
|
||||
const MAX_PKG_BYTES = 200 * 1024 * 1024;
|
||||
|
||||
// 回滚存储:升级前把上一版整体拷贝到 APP_DATA/plugin_rollback/<id>@<version>/(只保留每插件最新一版)。
|
||||
// 放 APP_DATA 而非插件根,避免污染插件目录(pruneStale 遍历/版本目录混入)与 dev 仓库。
|
||||
const ROLLBACK_DIR = path.join(config.APP_DATA, "plugin_rollback");
|
||||
|
||||
// 升级前备份当前版本(仅已装插件),返回 "id@version";失败返回 null(不阻断升级)
|
||||
function backupForRollback(pluginId) {
|
||||
const target = path.join(pluginRoot(), pluginId);
|
||||
const mf = path.join(target, "plugin.json");
|
||||
if (!fs.existsSync(mf)) return null; // 首次安装无需备份
|
||||
const ver = localVersion(pluginId) || "unknown";
|
||||
try {
|
||||
fs.mkdirSync(ROLLBACK_DIR, { recursive: true });
|
||||
// 只保留最新一版回滚:先清掉该插件的旧备份
|
||||
for (const name of fs.readdirSync(ROLLBACK_DIR)) {
|
||||
if (name.startsWith(pluginId + "@")) {
|
||||
fs.rmSync(path.join(ROLLBACK_DIR, name), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
fs.cpSync(target, path.join(ROLLBACK_DIR, `${pluginId}@${ver}`), { recursive: true });
|
||||
logger.info(`插件 ${pluginId}@${ver} 已备份(可回滚)`);
|
||||
return `${pluginId}@${ver}`;
|
||||
} catch (e) {
|
||||
logger.warning(`插件 ${pluginId} 回滚备份失败:${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 某插件可回滚的版本列表(按版本降序)
|
||||
function rollbackAvailable(pluginId) {
|
||||
try {
|
||||
if (!fs.existsSync(ROLLBACK_DIR)) return [];
|
||||
return fs
|
||||
.readdirSync(ROLLBACK_DIR)
|
||||
.filter((n) => n.startsWith(pluginId + "@"))
|
||||
.map((n) => n.slice(pluginId.length + 1))
|
||||
.sort((a, b) => (versionLt(a, b) ? 1 : -1));
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 全部可回滚插件的索引(供前端展示)
|
||||
function rollbackIndex() {
|
||||
try {
|
||||
if (!fs.existsSync(ROLLBACK_DIR)) return [];
|
||||
return fs
|
||||
.readdirSync(ROLLBACK_DIR)
|
||||
.filter((n) => n.includes("@"))
|
||||
.map((n) => {
|
||||
const idx = n.lastIndexOf("@");
|
||||
return { id: n.slice(0, idx), version: n.slice(idx + 1) };
|
||||
});
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 回滚到备份版本(取最新备份);失败抛错
|
||||
function rollbackPlugin(pluginId) {
|
||||
const versions = rollbackAvailable(pluginId);
|
||||
if (!versions.length) throw new Error("该插件无可用回滚版本");
|
||||
const ver = versions[0];
|
||||
const src = path.join(ROLLBACK_DIR, `${pluginId}@${ver}`);
|
||||
const target = path.join(pluginRoot(), pluginId);
|
||||
if (!fs.existsSync(src)) throw new Error("回滚备份缺失");
|
||||
fs.mkdirSync(pluginRoot(), { recursive: true });
|
||||
if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
|
||||
fs.cpSync(src, target, { recursive: true });
|
||||
logger.info(`插件 ${pluginId} 已回滚到 ${ver}`);
|
||||
return `${pluginId}@${ver}`;
|
||||
}
|
||||
|
||||
// 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用
|
||||
let _syncPromise = Promise.resolve();
|
||||
function withSyncLock(fn) {
|
||||
const run = _syncPromise.then(fn, fn);
|
||||
// 无论成功失败都继续链,保证后续同步不被前一次卡死
|
||||
_syncPromise = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
|
||||
function localVersion(pluginId) {
|
||||
const mf = path.join(pluginRoot(), pluginId, "plugin.json");
|
||||
if (!fs.existsSync(mf)) return "";
|
||||
try {
|
||||
return String(JSON.parse(fs.readFileSync(mf, "utf-8")).version || "");
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// 中心机可用插件清单(id/name/version);不可达返回 null(离线用本地)
|
||||
async function cloudPluginManifest(account) {
|
||||
if (!config.CONTROLPLANE_URL || !account) return null;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/plugins", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { account },
|
||||
timeout: 5,
|
||||
});
|
||||
return r.plugins || [];
|
||||
} catch (e) {
|
||||
logger.warning(`拉取插件清单失败(离线用本地插件):${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function dlTicket(pluginId, version, account) {
|
||||
try {
|
||||
return await cp.request(
|
||||
"GET",
|
||||
`/api/plugins/${encodeURIComponent(pluginId)}/versions/${encodeURIComponent(version)}/download-ticket`,
|
||||
{ headers: cp.machineHeaders(), params: { account }, timeout: 5 }
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(`获取下载票据失败 ${pluginId}@${version}:${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPkg(ticket) {
|
||||
try {
|
||||
const r = await cp.request("GET", `/api/download/${encodeURIComponent(ticket)}`, {
|
||||
headers: cp.machineHeaders(),
|
||||
timeout: DL_TIMEOUT,
|
||||
raw: true,
|
||||
});
|
||||
return r.body;
|
||||
} catch (e) {
|
||||
logger.warning(`下载插件包失败:${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 版本兼容校验:manifest 声明 minRuntimeVersion 且当前运行时不满足 → 抛错(安装前调用)
|
||||
function assertRuntimeCompat(pluginId, manifest) {
|
||||
const need = String((manifest && manifest.minRuntimeVersion) || "").trim();
|
||||
const cur = config.runtimeVersion();
|
||||
if (need && cur && versionLt(cur, need)) {
|
||||
throw new Error(`插件 ${pluginId} 要求运行时 >= ${need},当前运行时 ${cur}(请先升级客户端)`);
|
||||
}
|
||||
}
|
||||
|
||||
// 解压安装:临时目录 → 校验非法路径 → 版本兼容校验 → 原子替换(升级前自动备份上一版)
|
||||
function installPkg(pluginId, content) {
|
||||
if (content.length > MAX_PKG_BYTES) {
|
||||
logger.error(`插件包 ${pluginId} 超大小上限,拒绝安装`);
|
||||
return false;
|
||||
}
|
||||
let zip;
|
||||
try {
|
||||
zip = new AdmZip(content);
|
||||
} catch (e) {
|
||||
logger.error(`插件包 ${pluginId} 不是合法 ZIP`);
|
||||
return false;
|
||||
}
|
||||
const entries = zip.getEntries();
|
||||
const names = entries.map((en) => en.entryName);
|
||||
if (!names.includes("plugin.json")) {
|
||||
logger.error(`插件包 ${pluginId} 缺 plugin.json`);
|
||||
return false;
|
||||
}
|
||||
for (const n of names) {
|
||||
if (n.startsWith("/") || n.split("/").includes("..")) {
|
||||
logger.error(`插件包 ${pluginId} 含非法路径:${n}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `.pkg_${pluginId}_`));
|
||||
try {
|
||||
zip.extractAllTo(tmp, true /* overwrite */);
|
||||
} catch (e) {
|
||||
logger.error(`解压插件包 ${pluginId} 失败:${e.message}`);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
return false;
|
||||
}
|
||||
// 版本兼容校验:新包 plugin.json 声明 minRuntimeVersion 且当前运行时不满足 → 拒绝安装(防坏包)
|
||||
let mf;
|
||||
try {
|
||||
mf = JSON.parse(fs.readFileSync(path.join(tmp, "plugin.json"), "utf-8"));
|
||||
} catch (e) {
|
||||
logger.error(`插件包 ${pluginId} 的 plugin.json 解析失败:${e.message}`);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
assertRuntimeCompat(pluginId, mf);
|
||||
} catch (e) {
|
||||
logger.error(`插件 ${pluginId} 拒绝安装:${e.message}`);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
return false;
|
||||
}
|
||||
const target = path.join(pluginRoot(), pluginId);
|
||||
try {
|
||||
fs.mkdirSync(pluginRoot(), { recursive: true });
|
||||
backupForRollback(pluginId); // 升级前保留上一版(首次安装自动跳过)
|
||||
if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
|
||||
fs.renameSync(tmp, target);
|
||||
} catch (e) {
|
||||
logger.error(`安装插件 ${pluginId} 失败:${e.message}`);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function localPluginEntries() {
|
||||
const root = pluginRoot();
|
||||
const out = [];
|
||||
if (!fs.existsSync(root)) return out;
|
||||
for (const name of fs.readdirSync(root)) {
|
||||
if (name.startsWith("_") || name === "__pycache__") continue;
|
||||
const full = path.join(root, name);
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.statSync(full);
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
if (stat.isDirectory() && (fs.existsSync(path.join(full, "__init__.py")) || fs.existsSync(path.join(full, "plugin.json")))) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 清理中心机已删除/收回授权的本地插件(仅云端清单可达时;设备忙则整轮跳过)
|
||||
function pruneStale(keepIds) {
|
||||
const scheduler = require("./scheduler");
|
||||
const root = pluginRoot();
|
||||
if (!fs.existsSync(root) || scheduler.isBusy()) return [];
|
||||
const removed = [];
|
||||
for (const entry of localPluginEntries()) {
|
||||
const pid = path.basename(entry);
|
||||
if (keepIds.has(pid)) continue;
|
||||
try {
|
||||
fs.rmSync(entry, { recursive: true, force: true });
|
||||
removed.push(pid);
|
||||
logger.info(`插件 ${pid} 已在中心机删除/收回授权,本地目录同步移除`);
|
||||
} catch (e) {
|
||||
logger.warning(`清理本地插件 ${pid} 失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// 按账号权限同步插件:首次下载 + 版本更新 + 清理已删除。离线/失败静默降级。
|
||||
async function syncPlugins(account) {
|
||||
const result = { downloaded: [], updated: [], up_to_date: [], failed: [], removed: [] };
|
||||
if (!config.CONTROLPLANE_URL || !account) return result;
|
||||
const manifest = await cloudPluginManifest(account);
|
||||
if (manifest === null) return result;
|
||||
result.removed = pruneStale(new Set(manifest.map((p) => p.id)));
|
||||
for (const p of manifest) {
|
||||
const pid = p.id;
|
||||
const ver = p.version || p.latest_version || "";
|
||||
if (!pid || !ver) continue;
|
||||
const local = localVersion(pid);
|
||||
if (local === ver || (local && !versionLt(local, ver))) {
|
||||
result.up_to_date.push(pid);
|
||||
continue;
|
||||
}
|
||||
const tkt = await dlTicket(pid, ver, account);
|
||||
if (!tkt) {
|
||||
result.failed.push(pid);
|
||||
continue;
|
||||
}
|
||||
const content = await fetchPkg(tkt.ticket || "");
|
||||
if (!content) {
|
||||
result.failed.push(pid);
|
||||
continue;
|
||||
}
|
||||
const expect = (tkt.sha256 || "").toLowerCase();
|
||||
if (expect && sha256Hex(content) !== expect) {
|
||||
logger.error(`插件包 ${pid}@${ver} sha256 校验失败,拒绝安装`);
|
||||
result.failed.push(pid);
|
||||
continue;
|
||||
}
|
||||
if (installPkg(pid, content)) {
|
||||
(local ? result.updated : result.downloaded).push(pid);
|
||||
} else {
|
||||
result.failed.push(pid);
|
||||
}
|
||||
}
|
||||
logger.info(
|
||||
`插件同步完成:下载=${result.downloaded.join(",")} 更新=${result.updated.join(",")} ` +
|
||||
`最新=${result.up_to_date.join(",")} 清理=${result.removed.join(",")} 失败=${result.failed.join(",")}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
// 权限白名单:控制面拉取 + 本地缓存(fail-closed:无账号/离线无缓存 = 空集)
|
||||
const ALLOW_CACHE = path.join(config.APP_DATA, "plugin_allow.json");
|
||||
|
||||
function saveAllowedCache(ids) {
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(ALLOW_CACHE, JSON.stringify([...ids].sort()), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`插件权限清单缓存写入失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function loadAllowedCache() {
|
||||
if (!fs.existsSync(ALLOW_CACHE)) return null;
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(ALLOW_CACHE, "utf-8"));
|
||||
return new Set((raw || []).map(String));
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveAllowed(account) {
|
||||
if (!config.CONTROLPLANE_URL) return new Set();
|
||||
if (!account) {
|
||||
logger.info("未登录(无会话账号),插件零权限加载");
|
||||
return new Set();
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/plugins", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { account },
|
||||
timeout: 5,
|
||||
});
|
||||
const allowed = new Set((r.plugins || []).map((p) => p.id));
|
||||
logger.info(`控制面权限清单(${account}):${[...allowed].sort().join(",") || "(空)"}`);
|
||||
saveAllowedCache(allowed);
|
||||
return allowed;
|
||||
} catch (e) {
|
||||
const cached = loadAllowedCache();
|
||||
if (cached !== null) {
|
||||
logger.info(`权限清单拉取失败,用本地缓存(${account}):${e.message}`);
|
||||
return cached;
|
||||
}
|
||||
logger.warning(`权限清单拉取失败且无缓存,插件零权限加载:${e.message}`);
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
withSyncLock,
|
||||
syncPlugins,
|
||||
cloudPluginManifest,
|
||||
localVersion,
|
||||
resolveAllowed,
|
||||
pluginRoot,
|
||||
backupForRollback,
|
||||
rollbackAvailable,
|
||||
rollbackIndex,
|
||||
rollbackPlugin,
|
||||
installPkg,
|
||||
assertRuntimeCompat,
|
||||
ROLLBACK_DIR,
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
// preload:contextBridge 白名单 IPC(渲染层主通道走 HTTP 兼容层,此处仅暴露只读环境信息)。
|
||||
"use strict";
|
||||
|
||||
const { contextBridge } = require("electron");
|
||||
|
||||
contextBridge.exposeInMainWorld("dshShell", {
|
||||
platform: process.platform,
|
||||
versions: {
|
||||
electron: process.versions.electron,
|
||||
node: process.versions.node,
|
||||
chrome: process.versions.chrome,
|
||||
},
|
||||
// 渲染层可通过 window.open 打开中心机控制面(外部 URL 需在渲染层显式触发)
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
// 插件注册表:读取 plugins/<id>/plugin.json 元数据(manifest 驱动,与 Python meta.py 语义一致)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("registry");
|
||||
|
||||
function pluginRoot() {
|
||||
return config.pluginRoot();
|
||||
}
|
||||
|
||||
// 本地已落盘插件条目(目录包含 __init__.py 或 plugin.json,后者兜底下载中断的残缺目录)
|
||||
function listLocalPlugins() {
|
||||
const root = pluginRoot();
|
||||
const out = [];
|
||||
if (!fs.existsSync(root)) return out;
|
||||
for (const name of fs.readdirSync(root)) {
|
||||
if (name.startsWith("_") || name === "__pycache__") continue;
|
||||
const full = path.join(root, name);
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.statSync(full);
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
if (fs.existsSync(path.join(full, "__init__.py")) || fs.existsSync(path.join(full, "plugin.json"))) {
|
||||
out.push({ id: name, dir: full });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 读取插件 manifest;缺文件/解析失败返回 null(不阻断)
|
||||
function readManifest(pluginId) {
|
||||
const mf = path.join(pluginRoot(), pluginId, "plugin.json");
|
||||
if (!fs.existsSync(mf)) return null;
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(mf, "utf-8"));
|
||||
return data && typeof data === "object" ? data : null;
|
||||
} catch (e) {
|
||||
logger.warning(`插件 ${pluginId} plugin.json 解析失败:${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options,description}]
|
||||
function fieldsFromSchema(schema) {
|
||||
if (!schema || schema.type !== "object" || !schema.properties) return null;
|
||||
const out = [];
|
||||
for (const [key, prop] of Object.entries(schema.properties)) {
|
||||
const item = { key, label: prop.title || key, default: prop.default ?? "" };
|
||||
const t = prop.type || "string";
|
||||
if (t === "integer" || t === "number") item.type = "int";
|
||||
else if (t === "string" && Array.isArray(prop.enum)) {
|
||||
item.type = "select";
|
||||
item.options = prop.enum;
|
||||
} else if (t === "string" && prop.format === "password") item.type = "password";
|
||||
else if (t === "array") {
|
||||
item.type = "multiselect";
|
||||
if (prop.items && Array.isArray(prop.items.enum)) item.options = prop.items.enum;
|
||||
} else item.type = "text";
|
||||
if (prop.description) item.description = prop.description;
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 组装插件元数据(manifest 驱动,与 Python meta._plugin_schema 一致)
|
||||
function pluginSchema(pluginId) {
|
||||
const manifest = readManifest(pluginId);
|
||||
const base = {
|
||||
id: pluginId,
|
||||
name: pluginId,
|
||||
version: "0",
|
||||
description: "",
|
||||
uses_month: false,
|
||||
ui: false,
|
||||
capabilities: [],
|
||||
permissions: {},
|
||||
fields: [],
|
||||
};
|
||||
if (!manifest) return base;
|
||||
const fields = fieldsFromSchema(manifest.fields);
|
||||
return {
|
||||
id: manifest.id || pluginId,
|
||||
name: manifest.name || pluginId,
|
||||
version: manifest.version || "0",
|
||||
description: manifest.description || "",
|
||||
uses_month: !!manifest.uses_month,
|
||||
ui: !!manifest.ui,
|
||||
platform: manifest.platform || "", // hr / oa / ""(前端平台徽章 + 运行并发闸按(账号,平台)隔离)
|
||||
min_runtime_version: manifest.minRuntimeVersion || "", // 版本兼容校验声明(安装时强校验,此处透传前端展示)
|
||||
capabilities: manifest.capabilities || [],
|
||||
permissions: manifest.permissions || {},
|
||||
fields: fields || [],
|
||||
};
|
||||
}
|
||||
|
||||
function find(pluginId) {
|
||||
const dir = path.join(pluginRoot(), pluginId);
|
||||
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`插件不存在: ${pluginId}`);
|
||||
const manifest = readManifest(pluginId);
|
||||
if (!manifest && !fs.existsSync(path.join(dir, "__init__.py"))) {
|
||||
throw new Error(`插件不存在: ${pluginId}`);
|
||||
}
|
||||
return { id: pluginId, dir, manifest, ...pluginSchema(pluginId) };
|
||||
}
|
||||
|
||||
function findByName(name) {
|
||||
// 供 /api/runs 以插件名查找(与 PLUGINS.find 语义对齐)
|
||||
return find(name);
|
||||
}
|
||||
|
||||
module.exports = { pluginRoot, listLocalPlugins, readManifest, fieldsFromSchema, pluginSchema, find };
|
||||
@@ -0,0 +1,205 @@
|
||||
// 运行历史(壳子本地持久化):每次运行的结论 + 该次运行的日志,供「最近运行 / 点击回放」使用。
|
||||
// 存储:%LOCALAPPDATA%\37duAutomation\
|
||||
// run_history.jsonl 索引(只存结论,一行一次运行,无日志)
|
||||
// run_history/<run_id>.jsonl 该次运行的日志(一行一条)
|
||||
// 分离存储的原因:列表接口只读索引(几百行、恒定体积),详情才读单个日志文件,
|
||||
// 避免"列表要解析所有历史日志"这种随使用时长线性劣化的写法。
|
||||
// 职责划分:state.RUNS 内存态只服务"正在跑的那一次";本模块服务"跑过的那些次"。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("run-history");
|
||||
|
||||
const HISTORY_PATH = path.join(config.APP_DATA, "run_history.jsonl");
|
||||
const RUNS_DIR = path.join(config.APP_DATA, "run_history");
|
||||
|
||||
// 上限:历史是"回顾"用的,不追求全量归档
|
||||
const MAX_RECORDS = 300; // 裁剪目标:每次裁剪后保留最近 300 次运行(实际条数在 300 ~ 350 之间浮动)
|
||||
const PRUNE_SLACK = 50; // 超出裁剪目标这么多条才做一次整体裁剪(避免每次运行都重写整个索引)
|
||||
const MAX_LOGS_PER_RUN = 400; // 单次运行最多保留 400 条日志
|
||||
const MAX_MSG_LEN = 1000; // 单条日志最大长度(防插件打印大体积 JSON 灌爆历史)
|
||||
const MAX_LOG_BYTES_PER_RUN = 32 * 1024; // 单次运行日志总量上限,超出即停止记录(软截断)
|
||||
|
||||
// run_id 形如 32 位 hex;做白名单校验,杜绝路径穿越
|
||||
function safeRunId(runId) {
|
||||
const s = String(runId || "");
|
||||
return /^[A-Za-z0-9_-]{8,64}$/.test(s) ? s : "";
|
||||
}
|
||||
|
||||
function logFilePath(runId) {
|
||||
const id = safeRunId(runId);
|
||||
return id ? path.join(RUNS_DIR, `${id}.jsonl`) : "";
|
||||
}
|
||||
|
||||
// 截断超长日志(对齐"正常 INFO 级别屏蔽大体积 JSON"的日志规范精神)
|
||||
function clip(msg) {
|
||||
const s = String(msg === undefined || msg === null ? "" : msg);
|
||||
return s.length > MAX_MSG_LEN ? s.slice(0, MAX_MSG_LEN) + "…(已截断)" : s;
|
||||
}
|
||||
|
||||
// 逐行读取 JSONL;单行损坏(例如写入中断)只跳过该行,不拖垮整个文件
|
||||
function readLines(file) {
|
||||
if (!file || !fs.existsSync(file)) return [];
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`运行历史读取失败(${path.basename(file)}):${e.message}`);
|
||||
return [];
|
||||
}
|
||||
const out = [];
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const s = line.trim();
|
||||
if (!s) continue;
|
||||
try {
|
||||
out.push(JSON.parse(s));
|
||||
} catch (e) {
|
||||
/* 跳过损坏行 */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 原子整体替换(临时文件 + rename),避免写一半留下半行
|
||||
function writeLines(file, records) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = file + ".tmp";
|
||||
const body = records.length ? records.map((r) => JSON.stringify(r)).join("\n") + "\n" : "";
|
||||
fs.writeFileSync(tmp, body, "utf-8");
|
||||
fs.renameSync(tmp, file);
|
||||
} catch (e) {
|
||||
logger.warning(`运行历史写入失败(${path.basename(file)}):${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function readIndex() {
|
||||
return readLines(HISTORY_PATH).filter((r) => r && typeof r === "object" && r.run_id);
|
||||
}
|
||||
|
||||
// 写单次运行的日志文件(受条数与总字节双上限约束)
|
||||
function writeRunLogs(runId, logs) {
|
||||
const file = logFilePath(runId);
|
||||
if (!file || !Array.isArray(logs) || !logs.length) return;
|
||||
const kept = [];
|
||||
let bytes = 0;
|
||||
for (const l of logs.slice(-MAX_LOGS_PER_RUN)) {
|
||||
const rec = {
|
||||
t: l && l.t ? String(l.t) : "",
|
||||
level: (l && l.level) || "INFO",
|
||||
msg: clip(l && l.msg),
|
||||
};
|
||||
bytes += rec.msg.length + 32;
|
||||
if (bytes > MAX_LOG_BYTES_PER_RUN) {
|
||||
kept.push({ t: "", level: "WARN", msg: "(日志过长,后续内容已省略,完整日志请查看运行日志面板)" });
|
||||
break;
|
||||
}
|
||||
kept.push(rec);
|
||||
}
|
||||
writeLines(file, kept);
|
||||
}
|
||||
|
||||
// 索引条数缓存:本模块是索引的唯一写入方,可安全缓存,避免每次追加都整文件读取
|
||||
let _count = -1;
|
||||
|
||||
function indexCount() {
|
||||
if (_count < 0) _count = readIndex().length;
|
||||
return _count;
|
||||
}
|
||||
|
||||
// 裁剪索引到上限,并清理不再被引用的日志文件(避免目录无限膨胀)
|
||||
function prune() {
|
||||
const all = readIndex();
|
||||
_count = all.length;
|
||||
if (all.length <= MAX_RECORDS) return;
|
||||
const kept = all.slice(-MAX_RECORDS);
|
||||
writeLines(HISTORY_PATH, kept);
|
||||
_count = kept.length;
|
||||
const alive = new Set(kept.map((r) => safeRunId(r.run_id)).filter(Boolean));
|
||||
let removed = 0;
|
||||
try {
|
||||
for (const name of fs.readdirSync(RUNS_DIR)) {
|
||||
const id = name.replace(/\.jsonl$/, "");
|
||||
if (!name.endsWith(".jsonl") || alive.has(id)) continue;
|
||||
fs.unlinkSync(path.join(RUNS_DIR, name));
|
||||
removed++;
|
||||
}
|
||||
} catch (e) {
|
||||
/* 目录不存在或个别文件被占用:忽略,不影响主流程 */
|
||||
}
|
||||
if (removed) logger.info(`运行历史已裁剪至最近 ${MAX_RECORDS} 次,清理日志文件 ${removed} 个`);
|
||||
}
|
||||
|
||||
// 追加一次已结束的运行(结论进索引,日志单独落文件)
|
||||
function append(rec) {
|
||||
if (!rec || !safeRunId(rec.run_id)) return;
|
||||
writeRunLogs(rec.run_id, rec.logs);
|
||||
const briefRec = { ...rec };
|
||||
delete briefRec.logs;
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.appendFileSync(HISTORY_PATH, JSON.stringify(briefRec) + "\n", "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`运行历史追加失败:${e.message}`);
|
||||
return;
|
||||
}
|
||||
_count = indexCount() + 1;
|
||||
// 留出 slack 再裁剪:否则一旦到达上限,之后每次运行都会重写整个索引
|
||||
if (_count > MAX_RECORDS + PRUNE_SLACK) prune();
|
||||
}
|
||||
|
||||
// 列表视图:只给列表需要的字段(不含日志)
|
||||
function brief(rec) {
|
||||
return {
|
||||
run_id: rec.run_id,
|
||||
plugin_id: rec.plugin_id || "",
|
||||
name: rec.name || rec.plugin_id || "",
|
||||
version: rec.version || "",
|
||||
trigger: rec.trigger || "manual",
|
||||
schedule_id: rec.schedule_id || "",
|
||||
status: rec.status || "",
|
||||
ok: !!rec.ok,
|
||||
error: rec.error || "",
|
||||
started: rec.started || 0,
|
||||
finished: rec.finished || 0,
|
||||
duration_sec: rec.duration_sec || 0,
|
||||
summary: rec.summary || "",
|
||||
};
|
||||
}
|
||||
|
||||
// 当前账号最近 limit 次运行(新的在前)
|
||||
function list(account, limit) {
|
||||
const n = Math.max(1, Math.min(100, parseInt(limit, 10) || 20));
|
||||
const mine = readIndex().filter((r) => r.account === account);
|
||||
return mine.slice(-n).reverse().map(brief);
|
||||
}
|
||||
|
||||
// 单次运行详情(结论 + 日志);account 用于隔离,取不到返回 null
|
||||
function get(runId, account) {
|
||||
const id = safeRunId(runId);
|
||||
if (!id) return null;
|
||||
const all = readIndex();
|
||||
for (let i = all.length - 1; i >= 0; i--) {
|
||||
if (all[i].run_id === id && all[i].account === account) {
|
||||
return { ...brief(all[i]), logs: readLines(logFilePath(id)) };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
HISTORY_PATH,
|
||||
RUNS_DIR,
|
||||
MAX_RECORDS,
|
||||
PRUNE_SLACK,
|
||||
MAX_LOGS_PER_RUN,
|
||||
MAX_MSG_LEN,
|
||||
MAX_LOG_BYTES_PER_RUN,
|
||||
append,
|
||||
list,
|
||||
get,
|
||||
};
|
||||
@@ -0,0 +1,356 @@
|
||||
// 插件执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||||
// 对齐 Python runner.py 完整执行链:spawn python plugin_runner(★ 逐字节协议)
|
||||
// → stdin 单行 JSON fields → stdout JSON 事件行 → 超时整树强杀(taskkill /T /F)。
|
||||
"use strict";
|
||||
|
||||
const { spawn } = require("child_process");
|
||||
const readline = require("readline");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const state = require("./state");
|
||||
const scheduler = require("./scheduler");
|
||||
const licensing = require("./licensing");
|
||||
const runHistory = require("./run-history");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("runner");
|
||||
|
||||
// 手动停止登记:run_id → 停止标记
|
||||
const _USER_STOPPED = new Set();
|
||||
// run_id → kill 函数(执行中,供整树强杀)
|
||||
const _ACTIVE = new Map();
|
||||
|
||||
function isUserStopped(runId) {
|
||||
return _USER_STOPPED.has(runId);
|
||||
}
|
||||
|
||||
function treeKill(pid) {
|
||||
// Windows 整树强杀(含 DrissionPage 浏览器等孙进程);非 Windows 直接 kill 子进程组
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
killer.unref();
|
||||
} else {
|
||||
try {
|
||||
process.kill(-pid, "SIGKILL");
|
||||
} catch (e) {
|
||||
process.kill(pid, "SIGKILL");
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`整树强杀失败 pid=${pid}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function terminateRun(runId) {
|
||||
_USER_STOPPED.add(runId);
|
||||
const kill = _ACTIVE.get(runId);
|
||||
if (!kill) return false; // 尚未拉起执行子进程(排队中)或已结束
|
||||
try {
|
||||
kill();
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies
|
||||
function nsKey(account, platform) {
|
||||
return `${account || "anon"}:${platform || "local"}`;
|
||||
}
|
||||
|
||||
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
|
||||
function emitLog(runId, pluginId, level, msg) {
|
||||
const text = String(msg === undefined || msg === null ? "" : msg);
|
||||
state.appendRunLog(runId, {
|
||||
t: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
|
||||
level: level || "INFO",
|
||||
msg: text,
|
||||
});
|
||||
HUB.publish({ t: "log", run_id: runId, plugin_id: pluginId, level: level || "INFO", msg: text });
|
||||
}
|
||||
|
||||
// 结束一次运行:写终态 → 落盘运行历史 → 广播 run_done。
|
||||
// 所有结束路径(队列拒绝 / 队列异常 / 子进程收尾)共用,避免漏记历史。
|
||||
function finishRun(runId, plugin, status, error, summary) {
|
||||
const ok = status === "done";
|
||||
const finished = Date.now() / 1000;
|
||||
const run = state.RUNS.get(runId) || {};
|
||||
const durationSec = run.started ? Math.max(0, Math.round(finished - run.started)) : 0;
|
||||
state.setRun(runId, {
|
||||
status,
|
||||
error: ok ? "" : error || "",
|
||||
summary: summary || "",
|
||||
finished,
|
||||
duration_sec: durationSec,
|
||||
});
|
||||
runHistory.append({
|
||||
run_id: runId,
|
||||
account: run.account || "",
|
||||
plugin_id: plugin.id,
|
||||
name: run.name || plugin.name || plugin.id,
|
||||
version: run.version || plugin.version || "0",
|
||||
trigger: run.trigger || "manual",
|
||||
schedule_id: run.schedule_id || "",
|
||||
status,
|
||||
ok,
|
||||
error: ok ? "" : error || "",
|
||||
summary: summary || "",
|
||||
started: run.started || 0,
|
||||
finished,
|
||||
duration_sec: durationSec,
|
||||
logs: Array.isArray(run.logs) ? run.logs : [],
|
||||
});
|
||||
HUB.publish({
|
||||
t: "run_done",
|
||||
run_id: runId,
|
||||
plugin_id: plugin.id,
|
||||
name: run.name || plugin.name || plugin.id,
|
||||
trigger: run.trigger || "manual",
|
||||
ok,
|
||||
error: ok ? "" : error || "",
|
||||
duration_sec: durationSec,
|
||||
summary: summary || "",
|
||||
});
|
||||
}
|
||||
|
||||
// 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。
|
||||
// opts: { trigger: "manual" | "schedule", schedule_id } —— 用于区分"谁触发的",落进运行历史
|
||||
function submitRun(account, plugin, fields, opts) {
|
||||
const o = opts && typeof opts === "object" ? opts : {};
|
||||
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
|
||||
const runId = crypto.randomBytes(16).toString("hex");
|
||||
state.registerRun(runId, {
|
||||
status: "running",
|
||||
account,
|
||||
plugin_id: plugin.id,
|
||||
name: plugin.name || plugin.id,
|
||||
version: plugin.version || "0",
|
||||
trigger,
|
||||
schedule_id: o.schedule_id || "",
|
||||
started: Date.now() / 1000,
|
||||
result: null,
|
||||
error: null,
|
||||
logs: [],
|
||||
});
|
||||
HUB.publish({
|
||||
t: "run_start",
|
||||
run_id: runId,
|
||||
plugin_id: plugin.id,
|
||||
name: plugin.name || plugin.id,
|
||||
trigger,
|
||||
at: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
|
||||
});
|
||||
licensing.report(account, "", plugin.id, plugin.version || "0", "start");
|
||||
|
||||
void runQueued(plugin, fields, runId, account);
|
||||
return runId;
|
||||
}
|
||||
|
||||
async function runQueued(plugin, fields, runId, account) {
|
||||
try {
|
||||
// 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)
|
||||
if (scheduler.nsLocked(nsKey(account, plugin.platform))) {
|
||||
emitLog(runId, plugin.id, "INFO", `同平台任务执行中,排队等待(命名空间 ${nsKey(account, plugin.platform)})…`);
|
||||
}
|
||||
await scheduler.withNsLock(nsKey(account, plugin.platform), async () => {
|
||||
const startFn = async () => {
|
||||
if (isUserStopped(runId)) {
|
||||
// 排队期间用户已点停止:不真正拉起插件
|
||||
throw new Error("用户已取消该排队任务");
|
||||
}
|
||||
await startChild(plugin, fields, runId, account);
|
||||
return runId;
|
||||
};
|
||||
const r = await scheduler.requestStart(account, plugin.id, plugin.version || "0", startFn);
|
||||
if (!r.ok) {
|
||||
const err = isUserStopped(runId) ? "用户手动强制停止" : r.error;
|
||||
if (isUserStopped(runId)) _USER_STOPPED.delete(runId);
|
||||
finishRun(runId, plugin, "error", err, "");
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error(`运行队列异常:${e.message}`);
|
||||
finishRun(runId, plugin, "error", `运行队列异常:${e.message}`, "");
|
||||
}
|
||||
}
|
||||
|
||||
// 拉起执行子进程:子进程 spawn 成功后立即 resolve(runId)(requestStart 随即标记 running);
|
||||
// 执行结束(close)后异步落终态 + 上报 + 回空闲。
|
||||
function startChild(plugin, fields, runId, account) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = config.RUN_TIMEOUT;
|
||||
// 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限
|
||||
// + 整树托管)拉起 plugin_runner;无环境包(dev 直接 .venv)保持原直拉链路。
|
||||
// 两种模式协议逐字节一致(plugin_runner stdout JSON 事件行经 stdio 原样透传)。
|
||||
const python = config.pythonExe();
|
||||
const envRoot = config.pythonEnvRoot();
|
||||
const guard = config.jobGuardScript();
|
||||
const baseArgs = ["-u", config.runnerScript(), "--plugin", plugin.id, "--run", runId];
|
||||
if (state.ALLOWED !== null) {
|
||||
baseArgs.push("--allowed", [...state.ALLOWED].sort().join(","));
|
||||
}
|
||||
let cmd;
|
||||
let cwd;
|
||||
if (envRoot && guard) {
|
||||
// 环境包模式:python -u job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...
|
||||
cmd = [
|
||||
python, "-u", guard,
|
||||
"--mem", String(config.RUN_MAX_MEM_MB),
|
||||
"--timeout", String(timeout),
|
||||
"--", python, ...baseArgs,
|
||||
];
|
||||
cwd = envRoot;
|
||||
} else {
|
||||
cmd = [python, ...baseArgs];
|
||||
cwd = envRoot || config.REPO_ROOT;
|
||||
}
|
||||
let child;
|
||||
try {
|
||||
child = spawn(cmd[0], cmd.slice(1), {
|
||||
cwd,
|
||||
windowsHide: true,
|
||||
env: {
|
||||
...process.env,
|
||||
PYTHONIOENCODING: "utf-8",
|
||||
PYTHONUTF8: "1",
|
||||
PLATFORM_ACCOUNT: account || "",
|
||||
// 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害)
|
||||
PLUGINS_ROOT: config.pluginRoot(),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
} catch (e) {
|
||||
reject(new Error(`拉起执行子进程失败: ${e.message}`));
|
||||
return;
|
||||
}
|
||||
|
||||
let resolved = false;
|
||||
const killFn = () => treeKill(child.pid);
|
||||
_ACTIVE.set(runId, killFn);
|
||||
|
||||
const result = {};
|
||||
const publish = (ev) => {
|
||||
const t = ev.ev;
|
||||
if (t === "log") {
|
||||
emitLog(runId, plugin.id, ev.level, ev.msg);
|
||||
} else if (t === "progress") {
|
||||
HUB.publish({ t: "progress", run_id: runId, plugin_id: plugin.id, pct: Math.max(0, Math.min(100, parseInt(ev.pct, 10) || 0)) });
|
||||
} else if (t === "result") {
|
||||
Object.assign(result, ev);
|
||||
}
|
||||
};
|
||||
|
||||
const rlOut = readline.createInterface({ input: child.stdout });
|
||||
rlOut.on("line", (line) => {
|
||||
const s = String(line).trim();
|
||||
if (!s) return;
|
||||
try {
|
||||
const ev = JSON.parse(s);
|
||||
if (ev && typeof ev === "object" && ev.ev) publish(ev);
|
||||
} catch (e) {
|
||||
/* 非 JSON 行忽略 */
|
||||
}
|
||||
});
|
||||
|
||||
const rlErr = readline.createInterface({ input: child.stderr });
|
||||
rlErr.on("line", (line) => {
|
||||
const s = String(line).trim();
|
||||
if (s) {
|
||||
emitLog(runId, plugin.id, "ERROR", s);
|
||||
}
|
||||
});
|
||||
|
||||
// 写 fields(单行 JSON,UTF-8)并关闭 stdin
|
||||
try {
|
||||
child.stdin.write(Buffer.from(JSON.stringify(fields || {}), "utf-8"));
|
||||
child.stdin.end();
|
||||
} catch (e) {
|
||||
/* 子进程可能已退出 */
|
||||
}
|
||||
|
||||
let timedOut = false;
|
||||
let finalized = false;
|
||||
let timer = null;
|
||||
|
||||
const finalize = (code, spawnErr) => {
|
||||
if (finalized) return;
|
||||
finalized = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
_ACTIVE.delete(runId);
|
||||
const hasResult = result && Object.keys(result).length > 0;
|
||||
let status;
|
||||
let error;
|
||||
if (hasResult) {
|
||||
status = result.ok ? "done" : "error";
|
||||
error = result.error || "";
|
||||
} else if (spawnErr) {
|
||||
status = "error";
|
||||
error = spawnErr;
|
||||
} else if (isUserStopped(runId)) {
|
||||
status = "error";
|
||||
error = "用户手动强制停止";
|
||||
} else if (timedOut) {
|
||||
status = "error";
|
||||
error = `插件执行超时(${timeout}s)已强制终止`;
|
||||
} else {
|
||||
status = "error";
|
||||
error = `执行进程异常退出(exit=${code})且未返回结果`;
|
||||
}
|
||||
state.setRun(runId, { result: hasResult ? result.result : null });
|
||||
finishRun(
|
||||
runId,
|
||||
plugin,
|
||||
status,
|
||||
status === "done" ? "" : error,
|
||||
hasResult ? ((result.result || {}).summary || "") : ""
|
||||
);
|
||||
_USER_STOPPED.delete(runId);
|
||||
scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求
|
||||
reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报)
|
||||
};
|
||||
|
||||
child.once("spawn", () => {
|
||||
resolved = true;
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
logger.warning(`插件执行超时(${timeout}s)已强制终止:${plugin.id}`);
|
||||
killFn();
|
||||
}, timeout * 1000);
|
||||
resolve(runId);
|
||||
});
|
||||
|
||||
child.on("error", (err) => {
|
||||
if (!resolved) {
|
||||
_ACTIVE.delete(runId);
|
||||
reject(new Error(`拉起执行子进程失败: ${err.message}`));
|
||||
return;
|
||||
}
|
||||
finalize(null, `执行子进程异常: ${err.message}`);
|
||||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
finalize(code, null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function reportRun(plugin, runId) {
|
||||
try {
|
||||
const run = state.RUNS.get(runId) || {};
|
||||
const account = run.account || "";
|
||||
const status = run.status === "done" ? "done" : run.status === "running" ? "running" : "error";
|
||||
const msg = run.error || "";
|
||||
const duration = run.started ? Math.floor(Date.now() / 1000 - run.started) : 0;
|
||||
licensing.report(account, "", plugin.id, run.version || "", status, msg, duration);
|
||||
} catch (e) {
|
||||
logger.warning(`运行上报失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { submitRun, terminateRun, isUserStopped };
|
||||
@@ -0,0 +1,157 @@
|
||||
// 设备级单活调度器:整机同一时刻只运行一个插件进程(对齐 Python scheduler.py)。
|
||||
// active.json 同路径同格式(跨端共享);switching/running 均视为忙;启动失败回滚空闲。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { nowStr } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("scheduler");
|
||||
|
||||
const ACTIVE_PATH = path.join(config.APP_DATA, "active.json");
|
||||
|
||||
function readActive() {
|
||||
try {
|
||||
if (!fs.existsSync(ACTIVE_PATH)) return {};
|
||||
const d = JSON.parse(fs.readFileSync(ACTIVE_PATH, "utf-8"));
|
||||
return d && typeof d === "object" ? d : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function isBusy() {
|
||||
const s = readActive().status;
|
||||
return s === "running" || s === "switching";
|
||||
}
|
||||
|
||||
function writeActive(fields) {
|
||||
const d = { ...readActive(), ...fields };
|
||||
d.userId = d.userId ?? "";
|
||||
d.pluginId = d.pluginId ?? "";
|
||||
d.version = d.version ?? "";
|
||||
d.status = d.status ?? "idle";
|
||||
d.startedAt = d.startedAt ?? "";
|
||||
d.runId = d.runId ?? "";
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
const tmp = ACTIVE_PATH + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(d), "utf-8");
|
||||
fs.renameSync(tmp, ACTIVE_PATH); // 原子写
|
||||
} catch (e) {
|
||||
logger.warning(`写 active.json 失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function initActive() {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
if (!fs.existsSync(ACTIVE_PATH)) {
|
||||
writeActive({ userId: "", pluginId: "", version: "", status: "idle", runId: "", startedAt: "" });
|
||||
} else {
|
||||
const s = readActive().status;
|
||||
if (s === "running" || s === "switching") {
|
||||
logger.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲");
|
||||
writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function current() {
|
||||
return readActive();
|
||||
}
|
||||
|
||||
function isActive(pluginId) {
|
||||
const a = readActive();
|
||||
return a.status === "running" && a.pluginId === pluginId;
|
||||
}
|
||||
|
||||
// ==================== 设备级单活(Promise 门闩) ====================
|
||||
const _waiters = [];
|
||||
|
||||
function _wake() {
|
||||
const ws = _waiters.splice(0);
|
||||
for (const r of ws) r();
|
||||
}
|
||||
|
||||
async function waitIdle() {
|
||||
while (isBusy()) {
|
||||
await new Promise((resolve) => _waiters.push(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
// 抢占链(原子门闩):把「检查空闲 → 写 switching → 拉起 → 写 running」这段临界区串行化,
|
||||
// 保证同一时刻只有一个 requestStart 能进入启动段(不同平台命名空间并发提交时也不会双开进程)。
|
||||
let _claimChain = Promise.resolve();
|
||||
|
||||
// 阻塞等待设备空闲后启动:startFn 负责拉起子进程并返回 run_id(不可阻塞)。
|
||||
// 启动失败回滚"空闲"并唤醒等待者。
|
||||
function requestStart(user, pluginId, version, startFn) {
|
||||
const run = _claimChain.then(async () => {
|
||||
await waitIdle();
|
||||
writeActive({ status: "switching", startedAt: nowStr() });
|
||||
try {
|
||||
const runId = await startFn();
|
||||
writeActive({ userId: user, pluginId, version, status: "running", runId, startedAt: nowStr() });
|
||||
return { ok: true, run_id: runId };
|
||||
} catch (e) {
|
||||
writeActive({ status: "idle" });
|
||||
_wake();
|
||||
return { ok: false, error: `启动失败:${e.message}` };
|
||||
}
|
||||
});
|
||||
// 无论成功失败都推进链,避免一次异常卡死后续排队请求
|
||||
_claimChain = run.then(
|
||||
() => {},
|
||||
() => {}
|
||||
);
|
||||
return run;
|
||||
}
|
||||
|
||||
// 运行结束:若 active 仍是该插件则回空闲并唤醒等待者(幂等)
|
||||
function markDone(pluginId, runId) {
|
||||
const a = readActive();
|
||||
if (a.pluginId === pluginId && (a.runId === runId || a.status === "running")) {
|
||||
writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" });
|
||||
_wake();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 平台命名空间并发闸(同平台串行,保护共享 cookies) ====================
|
||||
const _nsQueues = {};
|
||||
const _nsInflight = {};
|
||||
|
||||
function nsLocked(platform) {
|
||||
const key = (platform || "").trim() || "local";
|
||||
return (_nsInflight[key] || 0) > 0;
|
||||
}
|
||||
|
||||
async function withNsLock(platform, fn) {
|
||||
const key = (platform || "").trim() || "local";
|
||||
const prev = _nsQueues[key] || Promise.resolve();
|
||||
const run = prev.then(async () => {
|
||||
_nsInflight[key] = (_nsInflight[key] || 0) + 1;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
_nsInflight[key] = (_nsInflight[key] || 0) - 1;
|
||||
}
|
||||
});
|
||||
_nsQueues[key] = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ACTIVE_PATH,
|
||||
readActive,
|
||||
isBusy,
|
||||
writeActive,
|
||||
initActive,
|
||||
current,
|
||||
isActive,
|
||||
requestStart,
|
||||
markDone,
|
||||
nsLocked,
|
||||
withNsLock,
|
||||
};
|
||||
@@ -0,0 +1,923 @@
|
||||
// 本地 HTTP/WS 兼容层(127.0.0.1:8799):壳 UI 本地 API 全集 + /pui 插件 UI + /ws 事件 + 静态前端。
|
||||
// 路由与返回结构对齐 Python webhost backend/apis/*(渲染层主通道走 HTTP,插件 iframe 同源调用)。
|
||||
"use strict";
|
||||
|
||||
const http = require("http");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const { URL } = require("url");
|
||||
const { WebSocketServer } = require("ws");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const state = require("./state");
|
||||
const session = require("./session");
|
||||
const licensing = require("./licensing");
|
||||
const registry = require("./registry");
|
||||
const meta = require("./meta");
|
||||
const runner = require("./runner");
|
||||
const runHistory = require("./run-history");
|
||||
const lastFields = require("./last-fields");
|
||||
const pluginConfigs = require("./plugin-configs");
|
||||
const scheduler = require("./scheduler");
|
||||
const tasks = require("./tasks");
|
||||
const platformAuth = require("./platform-auth");
|
||||
const platformCreds = require("./platform-creds");
|
||||
const shellUpdater = require("./shell-updater");
|
||||
const chromeManager = require("./chrome-manager");
|
||||
const pluginSync = require("./plugin-sync");
|
||||
const envSync = require("./env-sync");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("server");
|
||||
|
||||
const 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", ".jpeg": "image/jpeg",
|
||||
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
|
||||
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain",
|
||||
};
|
||||
|
||||
// ==================== 工具 ====================
|
||||
function parseCookies(req) {
|
||||
const out = {};
|
||||
const raw = req.headers.cookie || "";
|
||||
for (const part of raw.split(";")) {
|
||||
const idx = part.indexOf("=");
|
||||
if (idx > 0) {
|
||||
const k = part.slice(0, idx).trim();
|
||||
const v = part.slice(idx + 1).trim();
|
||||
try {
|
||||
out[k] = decodeURIComponent(v);
|
||||
} catch (e) {
|
||||
out[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readJsonBody(req, limit = 2 * 1024 * 1024) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
if (size > limit) {
|
||||
const e = new Error("请求体过大");
|
||||
e.status = 413;
|
||||
reject(e);
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (buf.length === 0) return resolve({});
|
||||
try {
|
||||
resolve(JSON.parse(buf.toString("utf-8")));
|
||||
} catch (e) {
|
||||
const err = new Error("JSON 解析失败");
|
||||
err.status = 400;
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function readRawBody(req, limit = 5 * 1024 * 1024) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
if (size > limit) {
|
||||
const e = new Error("请求体过大");
|
||||
e.status = 413;
|
||||
reject(e);
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function sendJson(res, status, obj) {
|
||||
const body = JSON.stringify(obj);
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(body),
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function sendHtml(res, status, html) {
|
||||
const body = Buffer.from(html, "utf-8");
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Content-Length": body.length,
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function setSessionCookie(res, token) {
|
||||
res.setHeader("Set-Cookie", `${session.SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax`);
|
||||
}
|
||||
|
||||
function clearSessionCookie(res) {
|
||||
res.setHeader("Set-Cookie", `${session.SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
|
||||
}
|
||||
|
||||
function handleError(res, err) {
|
||||
if (err && err.status) {
|
||||
sendJson(res, err.status, { detail: err.message || String(err.status) });
|
||||
} else {
|
||||
logger.error(`请求处理异常:${err && err.stack ? err.stack : err}`);
|
||||
sendJson(res, 500, { detail: "内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 钉钉登录 state(防 CSRF) ====================
|
||||
const _LOGIN_STATES = new Map();
|
||||
const LOGIN_STATE_TTL = 5 * 60 * 1000;
|
||||
|
||||
function loginStateNew() {
|
||||
const now = Date.now();
|
||||
for (const [s, exp] of _LOGIN_STATES) {
|
||||
if (exp < now) _LOGIN_STATES.delete(s);
|
||||
}
|
||||
const s = crypto.randomBytes(24).toString("base64url");
|
||||
_LOGIN_STATES.set(s, now + LOGIN_STATE_TTL);
|
||||
return s;
|
||||
}
|
||||
|
||||
function loginStateTake(s) {
|
||||
const exp = _LOGIN_STATES.get(s);
|
||||
_LOGIN_STATES.delete(s);
|
||||
return !!exp && exp >= Date.now();
|
||||
}
|
||||
|
||||
// ==================== 业务组装 ====================
|
||||
async function dingtalkEstablish(account, nickname, dingtalkUid, res) {
|
||||
if (!account) throw Object.assign(new Error("工号不能为空"), { status: 400 });
|
||||
const r = await cp.request("POST", "/api/admin/dingtalk/auth", {
|
||||
headers: { ...cp.machineHeaders(), "Content-Type": "application/json" },
|
||||
json: { account, nickname, dingtalk_uid: dingtalkUid },
|
||||
timeout: 15,
|
||||
});
|
||||
const acct = r.account || account;
|
||||
const token = session.establishSession(acct, null);
|
||||
setSessionCookie(res, token);
|
||||
if (config.CONTROLPLANE_URL) {
|
||||
try {
|
||||
await licensing.syncLicensing(acct);
|
||||
} catch (e) {
|
||||
logger.warning(`登录后同步离线授权票据失败:${e.message}`);
|
||||
}
|
||||
// 异步刷新敏感凭证(不阻断)
|
||||
require("./creds-sync")
|
||||
.load(acct)
|
||||
.then((creds) => {
|
||||
if (creds && Object.keys(creds).length) config.applyCreds(creds);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
account: acct,
|
||||
is_admin: !!r.is_admin,
|
||||
created: !!r.created,
|
||||
must_change_pwd: !!r.must_change_pwd,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 路由表 ====================
|
||||
async function route(req, res, url) {
|
||||
const cookies = parseCookies(req);
|
||||
const p = url.pathname;
|
||||
const method = req.method;
|
||||
|
||||
// ---------- 静态前端 ----------
|
||||
if (method === "GET" && !p.startsWith("/api") && !p.startsWith("/pui") && !p.startsWith("/auth")) {
|
||||
return serveStatic(res, url);
|
||||
}
|
||||
|
||||
// ---------- 认证 / 会话 ----------
|
||||
if (p === "/api/admin/me" && method === "GET") {
|
||||
const account = session.sessAccount(cookies);
|
||||
if (!account) {
|
||||
return sendJson(res, 200, { account: "", is_admin: false, dept: "", nickname: "", avatar: "" });
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/admin/me", { headers: session.cpHeaders(cookies), timeout: 10 });
|
||||
if (r.account === account) return sendJson(res, 200, r);
|
||||
} catch (e) {
|
||||
/* 云端不可达降级 */
|
||||
}
|
||||
return sendJson(res, 200, { account, is_admin: false, dept: "", nickname: "", avatar: "" });
|
||||
}
|
||||
|
||||
if (p === "/api/admin/login" && method === "POST") {
|
||||
const body = await readJsonBody(req);
|
||||
const account = String(body.account || "").trim();
|
||||
if (!account) throw Object.assign(new Error("账号不能为空"), { status: 400 });
|
||||
const r = await cp.request("POST", "/api/admin/auth", {
|
||||
headers: {
|
||||
"X-Admin-User": account,
|
||||
...(config.CONTROLPLANE_TOKEN ? { "X-API-Token": config.CONTROLPLANE_TOKEN } : {}),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json: { account, password: body.password },
|
||||
timeout: 15,
|
||||
});
|
||||
if (!r.ok) return sendJson(res, 200, r);
|
||||
const token = session.establishSession(account, r.cloud_token || "");
|
||||
setSessionCookie(res, token);
|
||||
// 登录成功即后台同步:授权票据 + 插件 + 敏感凭证(失败不阻断登录)
|
||||
afterLogin(account);
|
||||
return sendJson(res, 200, { ...r, account });
|
||||
}
|
||||
|
||||
if (p === "/api/admin/logout" && method === "POST") {
|
||||
const token = cookies[session.SESSION_COOKIE] || "";
|
||||
session.clearSession(token);
|
||||
clearSessionCookie(res);
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
if (p === "/api/admin/password" && method === "POST") {
|
||||
const body = await readJsonBody(req);
|
||||
const r = await cp.request("POST", "/api/admin/password", {
|
||||
headers: { ...session.cpHeaders(cookies), "Content-Type": "application/json" },
|
||||
json: body,
|
||||
timeout: 15,
|
||||
});
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
if (p === "/api/admin/overview" && method === "GET") {
|
||||
return sendJson(res, 200, { plugins: [], accounts: [], admins: [] });
|
||||
}
|
||||
|
||||
// ---------- 头像 ----------
|
||||
const avatarMatch = p.match(/^\/api\/avatar\/([^/]+)$/);
|
||||
if (avatarMatch && method === "GET") {
|
||||
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("统一后端未配置(CONTROLPLANE_URL)"), { status: 503 });
|
||||
const r = await cp.request("GET", `/api/avatar/${encodeURIComponent(avatarMatch[1])}`, { timeout: 10, raw: true });
|
||||
res.writeHead(200, {
|
||||
"Content-Type": r.headers.get("content-type") || "application/octet-stream",
|
||||
"Content-Length": r.body.length,
|
||||
});
|
||||
return res.end(r.body);
|
||||
}
|
||||
|
||||
if (p === "/api/avatar" && method === "POST") {
|
||||
const account = session.sessAccount(cookies);
|
||||
if (!account) throw Object.assign(new Error("未登录"), { status: 401 });
|
||||
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("统一后端未配置(CONTROLPLANE_URL)"), { status: 503 });
|
||||
const raw = await readRawBody(req);
|
||||
if (raw.length === 0) throw Object.assign(new Error("头像文件为空"), { status: 400 });
|
||||
const r = await cp.request("POST", `/api/admin/avatar?account=${encodeURIComponent(account)}`, {
|
||||
headers: { ...session.cpHeaders(cookies), "Content-Type": req.headers["content-type"] || "multipart/form-data" },
|
||||
body: raw,
|
||||
timeout: 30,
|
||||
});
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
// ---------- 钉钉 ----------
|
||||
if (p === "/api/admin/dingtalk/login" && method === "POST") {
|
||||
const body = await readJsonBody(req);
|
||||
const r = await dingtalkEstablish(String(body.account || "").trim(), body.nickname || "", body.dingtalk_uid || "", res);
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
if (p === "/api/admin/dingtalk/inline" && method === "POST") {
|
||||
const body = await readJsonBody(req);
|
||||
if (!String(body.code || "").trim()) throw Object.assign(new Error("缺少扫码截图码"), { status: 400 });
|
||||
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址,无法扫码登录"), { status: 503 });
|
||||
const info = await cp.request("POST", "/api/admin/dingtalk/sns", {
|
||||
headers: { ...cp.machineHeaders(), "Content-Type": "application/json" },
|
||||
json: { code: String(body.code).trim() },
|
||||
timeout: 15,
|
||||
});
|
||||
const account = String(info.account || "").trim();
|
||||
if (!account) throw Object.assign(new Error("扫码未解析到有效账号,请重新扫码"), { status: 401 });
|
||||
const r = await dingtalkEstablish(account, info.nickname || "", info.unionid || "", res);
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
if (p === "/api/admin/dingtalk/inline_qr" && method === "GET") {
|
||||
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址,无法扫码登录"), { status: 503 });
|
||||
const back = `http://${url.host}/api/admin/dingtalk/cb`;
|
||||
const r = await cp.request("GET", "/api/admin/dingtalk/inline_qr", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { back },
|
||||
timeout: 15,
|
||||
});
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
if (p === "/api/auth/dingtalk" && method === "GET") {
|
||||
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址(CONTROLPLANE_URL)"), { status: 503 });
|
||||
const stateParam = loginStateNew();
|
||||
const redirectUri = `http://localhost:${config.PORT}/auth/done`;
|
||||
const r = await cp.request("GET", "/api/dingtalk/login-url", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { back: redirectUri, state: stateParam },
|
||||
timeout: 15,
|
||||
});
|
||||
return sendJson(res, 200, { url: r.url || "", state: stateParam });
|
||||
}
|
||||
|
||||
if (p === "/auth/done" && method === "GET") {
|
||||
const code = url.searchParams.get("code") || "";
|
||||
const stateParam = url.searchParams.get("state") || "";
|
||||
const error = url.searchParams.get("error") || "";
|
||||
if (error) return sendHtml(res, 200, authDonePage("钉钉登录被取消或失败,请返回重试。"));
|
||||
if (!(code && stateParam) || !loginStateTake(stateParam)) {
|
||||
return sendHtml(res, 200, authDonePage("登录状态无效或已过期,请返回重新扫码。"));
|
||||
}
|
||||
let info;
|
||||
try {
|
||||
info = await cp.request("POST", "/auth/exchange", { json: { code }, timeout: 15 });
|
||||
} catch (e) {
|
||||
return sendHtml(res, 200, authDonePage(`登录失败:${e.message}`));
|
||||
}
|
||||
const account = String(info.account || "").trim();
|
||||
if (!account || !info.exists) return sendHtml(res, 200, authDonePage("账号未开通或未解析到有效工号,请联系管理员。"));
|
||||
const token = session.establishSession(account, info.token || "");
|
||||
setSessionCookie(res, token);
|
||||
if (config.CONTROLPLANE_URL) {
|
||||
try {
|
||||
await licensing.syncLicensing(account);
|
||||
} catch (e) {
|
||||
logger.warning(`登录后同步离线授权票据失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
res.writeHead(302, { Location: "/" });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
if (p === "/api/admin/dingtalk/qr" && method === "GET") {
|
||||
if (!config.CONTROLPLANE_URL) return sendJson(res, 200, { url: "" });
|
||||
const back = `http://${url.host}/api/admin/dingtalk/cb`;
|
||||
return sendJson(res, 200, {
|
||||
url: `${config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?${encodeURIComponent("back")}=${encodeURIComponent(back)}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (p === "/api/admin/dingtalk/cb" && method === "GET") {
|
||||
return sendHtml(res, 200, DINGTALK_CB_HTML);
|
||||
}
|
||||
|
||||
// ---------- 元数据 / 插件同步 ----------
|
||||
if (p === "/api/meta" && method === "GET") {
|
||||
const account = session.sessAccount(cookies);
|
||||
const data = await meta.buildMeta(account);
|
||||
return sendJson(res, 200, data);
|
||||
}
|
||||
|
||||
if (p === "/api/plugins/sync" && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const result = await pluginSync.withSyncLock(async () => {
|
||||
const r = await pluginSync.syncPlugins(account);
|
||||
const manifest = await pluginSync.cloudPluginManifest(account);
|
||||
if (manifest !== null) state.setAllowed(new Set(manifest.map((pl) => pl.id)));
|
||||
return r;
|
||||
});
|
||||
try {
|
||||
await licensing.syncLicensing(account);
|
||||
} catch (e) {
|
||||
logger.warning(`同步后刷新授权票据失败:${e.message}`);
|
||||
}
|
||||
return sendJson(res, 200, result);
|
||||
}
|
||||
|
||||
// ---------- 插件回滚(升级前自动备份上一版,坏包可回退) ----------
|
||||
if (p === "/api/plugins/rollback" && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, { items: pluginSync.rollbackIndex() });
|
||||
}
|
||||
const rollbackMatch = p.match(/^\/api\/plugins\/rollback\/([^/]+)$/);
|
||||
if (rollbackMatch && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
const pluginId = decodeURIComponent(rollbackMatch[1]);
|
||||
if (scheduler.isBusy()) {
|
||||
throw Object.assign(new Error("设备正在执行任务,请结束后再回滚"), { status: 409 });
|
||||
}
|
||||
const done = pluginSync.rollbackPlugin(pluginId);
|
||||
return sendJson(res, 200, { ok: true, rollback: done });
|
||||
}
|
||||
|
||||
// ---------- 壳子更新 ----------
|
||||
if (p === "/api/shell/update-status" && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, shellUpdater.pendingStatus());
|
||||
}
|
||||
if (p === "/api/shell/check" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
shellUpdater.startCheck();
|
||||
return sendJson(res, 200, { ok: true, checking: true });
|
||||
}
|
||||
if (p === "/api/shell/download" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
shellUpdater.startDownload();
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
if (p === "/api/shell/apply" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
shellUpdater.applyUpdate();
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// ---------- Chrome ----------
|
||||
if (p === "/api/chrome/status" && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, await chromeManager.status());
|
||||
}
|
||||
if (p === "/api/chrome/check" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
await chromeManager.refresh();
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
if (p === "/api/chrome/download" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
chromeManager.startDownload();
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
if (p === "/api/chrome/install" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, chromeManager.install());
|
||||
}
|
||||
|
||||
// ---------- 环境包(便携 Python 运行时) ----------
|
||||
if (p === "/api/env/status" && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, envSync.status());
|
||||
}
|
||||
if (p === "/api/env/sync" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
const r = await envSync.checkAndSync(true);
|
||||
return sendJson(res, 200, { ok: r.ok, reason: r.reason || "", version: r.version || "" });
|
||||
}
|
||||
if (p === "/api/env/rollback" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
return sendJson(res, 200, envSync.rollback());
|
||||
}
|
||||
|
||||
// ---------- 平台登录(按账号隔离会话与账号密码) ----------
|
||||
// 当前账号的平台状态:在线态 + 是否已配置个人 HR/OA 账号密码 + 已存用户名
|
||||
if (p === "/api/platforms/status" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
return sendJson(res, 200, { platforms: await platformAuth.status(account) });
|
||||
}
|
||||
|
||||
// 保存当前账号的 HR/OA 账号密码(本机加密);pass 留空表示保留原密码
|
||||
if (p === "/api/platforms/creds" && method === "PUT") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
const updated = [];
|
||||
for (const pid of ["hr", "oa"]) {
|
||||
if (body && body[pid] && (body[pid].user !== undefined || body[pid].pass !== undefined)) {
|
||||
platformCreds.upsert(account, pid, body[pid]);
|
||||
updated.push(pid);
|
||||
}
|
||||
}
|
||||
logger.info(`账号 ${account} 更新平台账号密码:${updated.join(",") || "无"}`);
|
||||
return sendJson(res, 200, { ok: true, updated });
|
||||
}
|
||||
|
||||
const platLogin = p.match(/^\/api\/platforms\/([^/]+)\/(login|logout)$/);
|
||||
if (platLogin && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const pid = platLogin[1];
|
||||
const action = platLogin[2];
|
||||
if (!state.PLATFORMS[pid]) throw Object.assign(new Error("平台不存在"), { status: 404 });
|
||||
if (action === "logout") {
|
||||
return sendJson(res, 200, platformAuth.logout(pid, account));
|
||||
}
|
||||
// login:授权票据有效 + 平台白名单
|
||||
const lic = await licensing.ensureLicense(account);
|
||||
if (!lic.ok) throw Object.assign(new Error("授权已过期(最长离线 7 天),请联网刷新后重试"), { status: 403 });
|
||||
const allowed = await meta.accountAllowedPlatforms(account);
|
||||
if (allowed === null) throw Object.assign(new Error("控制面不可达,无法校验平台权限"), { status: 503 });
|
||||
if (!allowed.has(pid)) throw Object.assign(new Error("无该平台访问权限,请联系管理员在控制面授权"), { status: 403 });
|
||||
const r = await platformAuth.login(pid, account);
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
|
||||
// ---------- 运行 ----------
|
||||
if (p === "/api/runs" && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
let plugin;
|
||||
try {
|
||||
plugin = registry.find(body.plugin_id);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("插件不存在"), { status: 404 });
|
||||
}
|
||||
const online = licensing.isOnline();
|
||||
const deny = await licensing.runCheckAllowed(plugin.id, account, online);
|
||||
if (deny) {
|
||||
logger.info(`插件 ${plugin.id} 启动被拒(账号 ${account}):${deny}`);
|
||||
throw Object.assign(new Error(deny), { status: 403 });
|
||||
}
|
||||
// 记住本次参数(不含 password 字段),供执行台「恢复上次参数」
|
||||
lastFields.remember(account, plugin.id, body.fields || {}, plugin.fields);
|
||||
const runId = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" });
|
||||
return sendJson(res, 202, { run_id: runId });
|
||||
}
|
||||
|
||||
// 运行历史列表(当前账号,新的在前):右轨「最近运行」与执行台「已完成」态的数据源
|
||||
if (p === "/api/runs" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const limit = url.searchParams.get("limit") || 20;
|
||||
return sendJson(res, 200, { runs: runHistory.list(account, limit) });
|
||||
}
|
||||
|
||||
const runMatch = p.match(/^\/api\/runs\/([^/]+)(\/stop)?$/);
|
||||
if (runMatch && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const run = state.RUNS.get(runMatch[1]);
|
||||
if (run && run.account === account) return sendJson(res, 200, run);
|
||||
// 内存态已淘汰(壳子重启 / 超过 MAX_RUNS)时回落到持久化历史,保证「点击回放」仍可用
|
||||
const hist = runHistory.get(runMatch[1], account);
|
||||
if (!hist) throw Object.assign(new Error("运行不存在"), { status: 404 });
|
||||
return sendJson(res, 200, hist);
|
||||
}
|
||||
if (runMatch && runMatch[2] && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const run = state.RUNS.get(runMatch[1]);
|
||||
if (!run || run.account !== account) throw Object.assign(new Error("运行不存在"), { status: 404 });
|
||||
if (run.status !== "running") throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 });
|
||||
if (!runner.terminateRun(runMatch[1])) {
|
||||
throw Object.assign(new Error("任务尚未真正启动(排队中或刚结束),请稍候再试"), { status: 409 });
|
||||
}
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// ---------- 定时任务 ----------
|
||||
if (p === "/api/schedules" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
return sendJson(res, 200, { schedules: tasks.listSchedules(account) });
|
||||
}
|
||||
if (p === "/api/schedules" && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
if (!body.plugin_id) throw Object.assign(new Error("请选择插件"), { status: 400 });
|
||||
try {
|
||||
registry.find(body.plugin_id);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("插件不存在"), { status: 404 });
|
||||
}
|
||||
let rec;
|
||||
try {
|
||||
rec = tasks.createSchedule(account, body);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(`cron 表达式无效:${e.message}`), { status: 400 });
|
||||
}
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 201, rec);
|
||||
}
|
||||
|
||||
const schedMatch = p.match(/^\/api\/schedules\/([^/]+)(\/toggle)?$/);
|
||||
if (schedMatch && method === "PUT") {
|
||||
const account = session.requireLogin(cookies);
|
||||
findOwned(schedMatch[1], account);
|
||||
const body = await readJsonBody(req);
|
||||
if (body.plugin_id) {
|
||||
try {
|
||||
registry.find(body.plugin_id);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("插件不存在"), { status: 404 });
|
||||
}
|
||||
}
|
||||
let rec;
|
||||
try {
|
||||
rec = tasks.updateSchedule(schedMatch[1], body);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(`cron 表达式无效:${e.message}`), { status: 400 });
|
||||
}
|
||||
if (!rec) throw Object.assign(new Error("任务不存在"), { status: 404 });
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, rec);
|
||||
}
|
||||
if (schedMatch && !schedMatch[2] && method === "DELETE") {
|
||||
const account = session.requireLogin(cookies);
|
||||
findOwned(schedMatch[1], account);
|
||||
if (!tasks.deleteSchedule(schedMatch[1])) throw Object.assign(new Error("任务不存在"), { status: 404 });
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
if (schedMatch && schedMatch[2] && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
findOwned(schedMatch[1], account);
|
||||
const body = await readJsonBody(req);
|
||||
const rec = tasks.toggleSchedule(schedMatch[1], !!body.enabled);
|
||||
if (!rec) throw Object.assign(new Error("任务不存在"), { status: 404 });
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, rec);
|
||||
}
|
||||
|
||||
// ---------- 插件配置 / UI ----------
|
||||
const cfgMatch = p.match(/^\/api\/plugin-config\/([^/]+)$/);
|
||||
if (cfgMatch && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
checkUiAllowed(cfgMatch[1]);
|
||||
const data = readPluginConfig(cfgMatch[1]);
|
||||
return sendJson(res, 200, data);
|
||||
}
|
||||
if (cfgMatch && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
checkUiAllowed(cfgMatch[1]);
|
||||
const data = await readJsonBody(req);
|
||||
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
||||
throw Object.assign(new Error("配置体必须是 JSON 对象"), { status: 400 });
|
||||
}
|
||||
savePluginConfig(cfgMatch[1], data);
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// 上次执行参数(执行台「恢复上次参数」):只含非敏感项,password 字段不落盘
|
||||
const lastFieldsMatch = p.match(/^\/api\/plugins\/([^/]+)\/last-fields$/);
|
||||
if (lastFieldsMatch && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
checkUiAllowed(lastFieldsMatch[1]);
|
||||
const rec = lastFields.recall(account, lastFieldsMatch[1]);
|
||||
return sendJson(res, 200, { fields: rec.fields, at: rec.at });
|
||||
}
|
||||
|
||||
// ---------- 场景配置方案(多配置,SQLite 存储)----------
|
||||
if (p === "/api/plugin-configs" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const pluginId = url.searchParams.get("plugin_id") || "";
|
||||
if (!pluginId) throw Object.assign(new Error("缺少 plugin_id"), { status: 400 });
|
||||
checkUiAllowed(pluginId);
|
||||
return sendJson(res, 200, { configs: pluginConfigs.listConfigs(account, pluginId) });
|
||||
}
|
||||
if (p === "/api/plugin-configs" && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
if (!body.plugin_id) throw Object.assign(new Error("缺少 plugin_id"), { status: 400 });
|
||||
checkUiAllowed(body.plugin_id);
|
||||
const plugin = registry.find(body.plugin_id);
|
||||
const cfg = pluginConfigs.saveConfig(account, body.plugin_id, body.name, body.fields, plugin.fields);
|
||||
if (!cfg) throw Object.assign(new Error("配置名称不能为空"), { status: 400 });
|
||||
return sendJson(res, 200, { ok: true, config: cfg });
|
||||
}
|
||||
const cfgDelMatch = p.match(/^\/api\/plugin-configs\/([^/]+)\/([^/]+)$/);
|
||||
if (cfgDelMatch && method === "DELETE") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const pluginId = decodeURIComponent(cfgDelMatch[1]);
|
||||
const cfgId = decodeURIComponent(cfgDelMatch[2]);
|
||||
checkUiAllowed(pluginId);
|
||||
const ok = pluginConfigs.deleteConfig(account, pluginId, cfgId);
|
||||
if (!ok) throw Object.assign(new Error("配置不存在"), { status: 404 });
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
const puiMatch = p.match(/^\/pui\/([^/]+)(\/.*)?$/);
|
||||
if (puiMatch && method === "GET") {
|
||||
session.requireLogin(cookies);
|
||||
checkUiAllowed(puiMatch[1]);
|
||||
return servePluginUi(res, puiMatch[1], puiMatch[2] || "");
|
||||
}
|
||||
|
||||
sendJson(res, 404, { detail: "Not Found" });
|
||||
}
|
||||
|
||||
function findOwned(sid, account) {
|
||||
const s = tasks.getSchedule(sid);
|
||||
if (!s) throw Object.assign(new Error("任务不存在"), { status: 404 });
|
||||
if (s.account !== account) throw Object.assign(new Error("仅创建者可管理该任务"), { status: 403 });
|
||||
}
|
||||
|
||||
function checkUiAllowed(pluginId) {
|
||||
try {
|
||||
registry.find(pluginId);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("插件不存在"), { status: 404 });
|
||||
}
|
||||
if (state.ALLOWED !== null && !state.ALLOWED.has(pluginId)) {
|
||||
throw Object.assign(new Error("插件不存在"), { status: 404 });
|
||||
}
|
||||
}
|
||||
|
||||
function readPluginConfig(pluginId) {
|
||||
const p = path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`);
|
||||
if (!fs.existsSync(p)) return {};
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(p, "utf-8"));
|
||||
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function savePluginConfig(pluginId, data) {
|
||||
const p = path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`);
|
||||
try {
|
||||
fs.mkdirSync(config.PLUGIN_CONFIG_DIR, { recursive: true });
|
||||
const tmp = p + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
|
||||
fs.renameSync(tmp, p); // 原子替换
|
||||
} catch (e) {
|
||||
logger.warning(`插件 ${pluginId} 配置保存失败:${e.message}`);
|
||||
throw Object.assign(new Error("配置保存失败"), { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function servePluginUi(res, pluginId, rel) {
|
||||
const uiRoot = path.resolve(path.join(registry.pluginRoot(), pluginId, "ui"));
|
||||
if (!fs.existsSync(uiRoot) || !fs.statSync(uiRoot).isDirectory()) {
|
||||
throw Object.assign(new Error("该插件未提供前端界面"), { status: 404 });
|
||||
}
|
||||
let target;
|
||||
if (!rel.trim()) target = path.join(uiRoot, "index.html");
|
||||
else target = path.resolve(path.join(uiRoot, rel));
|
||||
if (!target.startsWith(uiRoot + path.sep) && target !== uiRoot) {
|
||||
throw Object.assign(new Error("not found"), { status: 404 });
|
||||
}
|
||||
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, "index.html");
|
||||
if (!fs.existsSync(target) || !fs.statSync(target).isFile()) {
|
||||
const fallback = path.join(uiRoot, "index.html");
|
||||
if (!fs.existsSync(fallback)) throw Object.assign(new Error("not found"), { status: 404 });
|
||||
target = fallback;
|
||||
}
|
||||
const mediaType = MIME[path.extname(target).toLowerCase()] || "application/octet-stream";
|
||||
const cache = path.basename(target) === "index.html" ? "no-cache" : "public, max-age=86400";
|
||||
const body = fs.readFileSync(target);
|
||||
// 插件 UI 内容安全策略:仅允许同源资源(内网离线部署),阻断外联脚本/图片/跳转外域
|
||||
const CSP =
|
||||
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'";
|
||||
res.writeHead(200, {
|
||||
"Content-Type": mediaType,
|
||||
"Cache-Control": cache,
|
||||
"Content-Length": body.length,
|
||||
"Content-Security-Policy": CSP,
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function serveStatic(res, url) {
|
||||
const dist = config.frontendDist();
|
||||
let rel = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
|
||||
let target = path.resolve(path.join(dist, rel));
|
||||
if (!target.startsWith(dist + path.sep) && target !== dist) {
|
||||
return sendJson(res, 404, { detail: "Not Found" });
|
||||
}
|
||||
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, "index.html");
|
||||
if (!fs.existsSync(target) || !fs.statSync(target).isFile()) {
|
||||
// SPA 兜底:回 index.html(history 路由)
|
||||
target = path.join(dist, "index.html");
|
||||
if (!fs.existsSync(target)) return sendJson(res, 404, { detail: "Not Found" });
|
||||
}
|
||||
const mediaType = MIME[path.extname(target).toLowerCase()] || "application/octet-stream";
|
||||
const body = fs.readFileSync(target);
|
||||
res.writeHead(200, { "Content-Type": mediaType, "Content-Length": body.length });
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s === undefined || s === null ? "" : s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function authDonePage(text) {
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>${escapeHtml(text)}</p><p><a href="/">返回</a></p></body></html>`;
|
||||
}
|
||||
|
||||
const 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>`;
|
||||
|
||||
// ==================== 登录后异步同步(不阻断登录响应) ====================
|
||||
function afterLogin(account) {
|
||||
if (!config.CONTROLPLANE_URL) return;
|
||||
void licensing
|
||||
.syncLicensing(account)
|
||||
.catch((e) => logger.warning(`登录后同步离线授权票据失败:${e.message}`));
|
||||
void pluginSync
|
||||
.withSyncLock(async () => {
|
||||
await pluginSync.syncPlugins(account);
|
||||
const manifest = await pluginSync.cloudPluginManifest(account);
|
||||
if (manifest !== null) state.setAllowed(new Set(manifest.map((pl) => pl.id)));
|
||||
})
|
||||
.catch((e) => logger.warning(`登录后插件同步失败:${e.message}`));
|
||||
void require("./creds-sync")
|
||||
.load(account)
|
||||
.then((creds) => {
|
||||
if (creds && Object.keys(creds).length) config.applyCreds(creds);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// ==================== 服务器启动 ====================
|
||||
function createServer() {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${config.PORT}`}`);
|
||||
logger.debug(`${req.method} ${url.pathname}`); // 请求级调试日志(DEBUG 模式)
|
||||
try {
|
||||
await route(req, res, url);
|
||||
} catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
// WS /ws:握手需有效统一账户会话
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const url = new URL(req.url, `http://127.0.0.1:${config.PORT}`);
|
||||
if (url.pathname !== "/ws") {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
const cookies = parseCookies(req);
|
||||
if (!session.sessAccount(cookies)) {
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, req);
|
||||
});
|
||||
});
|
||||
wss.on("connection", (ws) => {
|
||||
// 心跳标记:30s ping 一次,连续一个周期无 pong 视为僵尸连接 terminate(浏览器会自动回 pong)
|
||||
ws.isAlive = true;
|
||||
ws.on("pong", () => {
|
||||
ws.isAlive = true;
|
||||
});
|
||||
HUB.addClient(ws);
|
||||
});
|
||||
// 心跳巡检:防 WS 连接泄漏(页面刷新残留/半开连接)
|
||||
const heartbeat = setInterval(() => {
|
||||
for (const ws of wss.clients) {
|
||||
if (!ws.isAlive) {
|
||||
ws.terminate();
|
||||
continue;
|
||||
}
|
||||
ws.isAlive = false;
|
||||
try {
|
||||
ws.ping();
|
||||
} catch (e) {
|
||||
ws.terminate();
|
||||
}
|
||||
}
|
||||
}, 30 * 1000);
|
||||
if (heartbeat.unref) heartbeat.unref(); // 不阻碍进程退出
|
||||
server.on("close", () => clearInterval(heartbeat));
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
function listen(cb) {
|
||||
const server = createServer();
|
||||
server.listen(config.PORT, "127.0.0.1", () => {
|
||||
logger.info(`本地服务已启动:http://127.0.0.1:${config.PORT}`);
|
||||
if (cb) cb(server);
|
||||
});
|
||||
server.on("error", (e) => {
|
||||
if (e.code === "EADDRINUSE") {
|
||||
logger.error(`端口 ${config.PORT} 已被占用(旧实例?),请先停止旧底座`);
|
||||
} else {
|
||||
logger.error(`本地服务启动失败:${e.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
module.exports = { createServer, listen, parseCookies };
|
||||
@@ -0,0 +1,148 @@
|
||||
// 统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
|
||||
// 对齐 Python webhost session.py:cp_session cookie、7 天滑动续期、重启恢复。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("session");
|
||||
|
||||
const SESSION_COOKIE = "cp_session";
|
||||
const SESS_TTL = 7 * 24 * 3600 * 1000; // ms
|
||||
|
||||
const _SESS = new Map(); // token -> { account, ts }
|
||||
// account -> 最近云端会话 token(7 天,供 /api/plugins 等用 Bearer)
|
||||
const _ACCT_CLOUD_TOKEN = new Map();
|
||||
|
||||
const SESS_FILE = path.join(config.SHELL_ROOT, "_cp_sessions.json");
|
||||
|
||||
function persist() {
|
||||
const payload = {};
|
||||
for (const [token, item] of _SESS) {
|
||||
payload[token] = [item.account, Math.floor(item.ts / 1000), _ACCT_CLOUD_TOKEN.get(item.account) || ""];
|
||||
}
|
||||
try {
|
||||
fs.writeFileSync(SESS_FILE, JSON.stringify(payload), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`本机会话持久化失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (!fs.existsSync(SESS_FILE)) return;
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(SESS_FILE, "utf-8"));
|
||||
const now = Date.now();
|
||||
for (const [token, item] of Object.entries(raw || {})) {
|
||||
try {
|
||||
const [acct, ts, cloudTok] = item;
|
||||
const t = parseFloat(ts) * 1000;
|
||||
if (now - t <= SESS_TTL) {
|
||||
_SESS.set(token, { account: acct, ts: t });
|
||||
if (cloudTok) _ACCT_CLOUD_TOKEN.set(acct, cloudTok);
|
||||
}
|
||||
} catch (e) {
|
||||
/* 跳过坏条目 */
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
/* 损坏则忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
// cookies: {name: value};返回当前登录账号(滑动续期)
|
||||
function sessAccount(cookies) {
|
||||
const token = (cookies || {})[SESSION_COOKIE] || "";
|
||||
if (!token) return "";
|
||||
const item = _SESS.get(token);
|
||||
if (!item) return "";
|
||||
const now = Date.now();
|
||||
if (now - item.ts > SESS_TTL) {
|
||||
_SESS.delete(token);
|
||||
return "";
|
||||
}
|
||||
item.ts = now; // 滑动续期
|
||||
persist();
|
||||
return item.account;
|
||||
}
|
||||
|
||||
function requireLogin(cookies) {
|
||||
const account = sessAccount(cookies);
|
||||
if (!account) {
|
||||
const err = new Error("未登录:请先登录统一账户");
|
||||
err.status = 401;
|
||||
throw err;
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
// 建立会话(登录成功):写入内存 + 落盘 + 返回新 token(调用方 set-cookie)
|
||||
function establishSession(account, cloudToken) {
|
||||
const token = crypto.randomBytes(16).toString("hex");
|
||||
_SESS.set(token, { account, ts: Date.now() });
|
||||
if (cloudToken) _ACCT_CLOUD_TOKEN.set(account, cloudToken);
|
||||
persist();
|
||||
return token;
|
||||
}
|
||||
|
||||
function clearSession(token) {
|
||||
if (token) _SESS.delete(token);
|
||||
persist();
|
||||
}
|
||||
|
||||
function sessActiveAccount() {
|
||||
let best = "";
|
||||
let bestTs = 0;
|
||||
for (const item of _SESS.values()) {
|
||||
if (item.ts > bestTs) {
|
||||
bestTs = item.ts;
|
||||
best = item.account;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function accountSet() {
|
||||
return new Set([..._SESS.values()].map((i) => i.account));
|
||||
}
|
||||
|
||||
function cloudToken(account) {
|
||||
return _ACCT_CLOUD_TOKEN.get(account) || "";
|
||||
}
|
||||
|
||||
// 到中心机调用头:Bearer 云令牌优先 + X-Admin-User 兜底 + X-API-Token
|
||||
function cpHeaders(cookies) {
|
||||
const h = {};
|
||||
const account = sessAccount(cookies);
|
||||
if (account) {
|
||||
const tok = cloudToken(account);
|
||||
if (tok) h["Authorization"] = `Bearer ${tok}`;
|
||||
h["X-Admin-User"] = account;
|
||||
}
|
||||
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||
return h;
|
||||
}
|
||||
|
||||
// 启动恢复
|
||||
load();
|
||||
|
||||
module.exports = {
|
||||
SESSION_COOKIE,
|
||||
SESS_FILE,
|
||||
sessAccount,
|
||||
requireLogin,
|
||||
establishSession,
|
||||
clearSession,
|
||||
sessActiveAccount,
|
||||
accountSet,
|
||||
cloudToken,
|
||||
setCloudToken: (account, tok) => {
|
||||
if (tok) _ACCT_CLOUD_TOKEN.set(account, tok);
|
||||
else _ACCT_CLOUD_TOKEN.delete(account);
|
||||
persist();
|
||||
},
|
||||
cpHeaders,
|
||||
};
|
||||
@@ -0,0 +1,313 @@
|
||||
// 壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
|
||||
// 对齐 Python shell_updater.py 的状态结构与并发控制。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { spawn } = require("child_process");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { versionLt, sha256Hex } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("shell-updater");
|
||||
|
||||
const SHELL_CACHE = path.join(config.APP_DATA, "shell");
|
||||
const PERIODIC_INTERVAL = 30 * 60 * 1000;
|
||||
|
||||
let _checking = false;
|
||||
let _downloading = false;
|
||||
let _pendingVersion = "";
|
||||
let _pendingNotes = "";
|
||||
|
||||
const _STATE = {
|
||||
checking: false,
|
||||
check_at: 0,
|
||||
latest: "",
|
||||
notes: "",
|
||||
available: false,
|
||||
check_error: "",
|
||||
dl_version: "",
|
||||
dl_status: "idle", // idle | downloading | downloaded | failed
|
||||
dl_received: 0,
|
||||
dl_total: 0,
|
||||
dl_pct: 0,
|
||||
dl_error: "",
|
||||
applying: false,
|
||||
};
|
||||
|
||||
function shellVersionFile() {
|
||||
// 打包运行:exe 同级 shell.version
|
||||
if (process.env.ELECTRON_RUN_AS_NODE) return null;
|
||||
if (process.resourcesPath) return path.join(path.dirname(process.execPath), "shell.version");
|
||||
return null;
|
||||
}
|
||||
|
||||
function localShellVersion() {
|
||||
const vf = shellVersionFile();
|
||||
if (!vf) return ""; // 源码/CLI 开发模式:不参与自更新
|
||||
try {
|
||||
return fs.existsSync(vf) ? fs.readFileSync(vf, "utf-8").trim() : "";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCloudVersion() {
|
||||
if (!localShellVersion() || !config.CONTROLPLANE_URL) {
|
||||
_STATE.check_error = !localShellVersion() ? "源码开发模式,不参与自更新" : "未配置中心机地址";
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/shell/version", { headers: cp.machineHeaders(), timeout: 5 });
|
||||
return r;
|
||||
} catch (e) {
|
||||
logger.info(`检查壳子更新失败(离线跳过):${e.message}`);
|
||||
_STATE.check_error = `控制面不可达(${e.constructor.name})`;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function cachedPkg(version) {
|
||||
const p = path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
function restorePending(cloud, notes) {
|
||||
_pendingVersion = cloud;
|
||||
_pendingNotes = notes;
|
||||
_STATE.dl_version = cloud;
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
logger.info(`壳子新版本 ${cloud} 已在缓存中,等待用户重启更新`);
|
||||
}
|
||||
|
||||
async function checkUpdate() {
|
||||
if (_checking) return;
|
||||
_checking = true;
|
||||
try {
|
||||
_STATE.checking = true;
|
||||
const cur = localShellVersion();
|
||||
const info = await fetchCloudVersion();
|
||||
_STATE.check_at = Date.now();
|
||||
if (!cur) {
|
||||
_STATE.latest = "";
|
||||
_STATE.notes = "";
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
if (!info) {
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
const cloud = String(info.version || "");
|
||||
const notes = String(info.notes || "");
|
||||
_STATE.latest = cloud;
|
||||
_STATE.notes = notes;
|
||||
_STATE.check_error = "";
|
||||
if (!cloud || !versionLt(cur, cloud)) {
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
_STATE.available = true;
|
||||
if (cachedPkg(cloud)) restorePending(cloud, notes);
|
||||
} finally {
|
||||
_STATE.checking = false;
|
||||
_checking = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startCheck() {
|
||||
void checkUpdate();
|
||||
}
|
||||
|
||||
function startPeriodicCheck() {
|
||||
setInterval(() => {
|
||||
try {
|
||||
void checkUpdate();
|
||||
} catch (e) {
|
||||
logger.warning(`周期检查壳子更新失败:${e.message}`);
|
||||
}
|
||||
}, PERIODIC_INTERVAL);
|
||||
}
|
||||
|
||||
async function startDownload() {
|
||||
const cur = localShellVersion();
|
||||
if (!cur) return;
|
||||
if (_STATE.dl_status === "downloading") return;
|
||||
if (_STATE.dl_status === "downloaded" && _pendingVersion) return;
|
||||
const info = await fetchCloudVersion();
|
||||
if (!info) return;
|
||||
const cloud = String(info.version || "");
|
||||
if (!cloud || !versionLt(cur, cloud)) return;
|
||||
if (cachedPkg(cloud)) {
|
||||
restorePending(cloud, String(info.notes || ""));
|
||||
return;
|
||||
}
|
||||
if (_downloading) return;
|
||||
_downloading = true;
|
||||
_STATE.dl_version = cloud;
|
||||
_STATE.dl_status = "downloading";
|
||||
_STATE.dl_received = 0;
|
||||
_STATE.dl_total = 0;
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
try {
|
||||
await download(cloud, info);
|
||||
} catch (e) {
|
||||
logger.warning(`下载壳子安装包失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||
cleanupPart(cloud);
|
||||
} finally {
|
||||
_downloading = false;
|
||||
}
|
||||
logger.info(`开始下载壳子新版本 ${cloud}`);
|
||||
}
|
||||
|
||||
async function download(cloud, info) {
|
||||
const innerUrl = String(info.url || "").trim();
|
||||
const tmp = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`);
|
||||
const pkg = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe`);
|
||||
const expect = String(info.sha256 || "").toLowerCase();
|
||||
fs.mkdirSync(SHELL_CACHE, { recursive: true });
|
||||
const out = fs.createWriteStream(tmp);
|
||||
const crypto = require("crypto");
|
||||
const sha = crypto.createHash("sha256");
|
||||
let received = 0;
|
||||
let total = 0;
|
||||
if (innerUrl) {
|
||||
await downloadFromUrl(innerUrl, {}, out, sha, (rcv, tot) => {
|
||||
received = rcv;
|
||||
total = tot;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
});
|
||||
} else {
|
||||
const r = await cp.streamDownload("/api/shell/pkg", {
|
||||
headers: cp.machineHeaders(),
|
||||
timeout: 600,
|
||||
onData: (chunk) => {
|
||||
out.write(chunk);
|
||||
sha.update(chunk);
|
||||
},
|
||||
onProgress: (rcv, tot) => {
|
||||
received = rcv;
|
||||
total = tot;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
},
|
||||
});
|
||||
received = r.received;
|
||||
total = r.contentLength;
|
||||
}
|
||||
await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
logger.error(`壳子安装包 sha256 校验失败,放弃更新`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包校验失败,请重试";
|
||||
cleanupPart(cloud);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmp, pkg);
|
||||
} catch (e) {
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包保存失败";
|
||||
cleanupPart(cloud);
|
||||
return;
|
||||
}
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
restorePending(cloud, String(info.notes || ""));
|
||||
}
|
||||
|
||||
async function downloadFromUrl(url, headers, out, sha, onProgress) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
|
||||
const res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
let received = 0;
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
onProgress(received, total);
|
||||
}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
function cleanupPart(cloud) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`));
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function pendingStatus() {
|
||||
let cur = localShellVersion();
|
||||
let downloaded = !!_pendingVersion && cachedPkg(_pendingVersion) !== null;
|
||||
if (!downloaded) {
|
||||
_pendingVersion = "";
|
||||
_pendingNotes = "";
|
||||
}
|
||||
return {
|
||||
current: cur,
|
||||
new: downloaded ? _pendingVersion : "",
|
||||
notes: downloaded ? _pendingNotes : "",
|
||||
downloaded,
|
||||
available: !!_STATE.available,
|
||||
latest: _STATE.latest || "",
|
||||
checked_at: _STATE.check_at || 0,
|
||||
checking: !!_STATE.checking,
|
||||
error: _STATE.check_error || "",
|
||||
applying: !!_STATE.applying,
|
||||
dl: {
|
||||
version: _STATE.dl_version || "",
|
||||
status: _STATE.dl_status || "idle",
|
||||
received: _STATE.dl_received || 0,
|
||||
total: _STATE.dl_total || 0,
|
||||
pct: _STATE.dl_pct || 0,
|
||||
error: _STATE.dl_error || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function applyUpdate() {
|
||||
const version = _pendingVersion;
|
||||
const pkg = cachedPkg(version);
|
||||
if (!pkg) throw new Error(`未找到已下载的安装包:setup-37du-host-${version}.exe`);
|
||||
_STATE.applying = true;
|
||||
logger.info(`开始静默升级到 ${version}:${pkg}`);
|
||||
const child = spawn(pkg, ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"], {
|
||||
cwd: path.dirname(pkg),
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
child.unref();
|
||||
// 给安装器接管进程,随后退出
|
||||
setTimeout(() => {
|
||||
if (typeof process.exit === "function") process.exit(0);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
startCheck,
|
||||
startPeriodicCheck,
|
||||
startDownload,
|
||||
pendingStatus,
|
||||
applyUpdate,
|
||||
cachedPkg,
|
||||
localShellVersion,
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
// 运行时共享状态:可变全局唯一真源(对齐 Python webhost state.py)。
|
||||
"use strict";
|
||||
|
||||
const PLATFORMS = {
|
||||
hr: { id: "hr", label: "HR 系统" },
|
||||
oa: { id: "oa", label: "OA 系统" },
|
||||
};
|
||||
|
||||
// 运行会话:run_id -> {status, account, plugin_id, name, version, trigger, schedule_id, started, result, error, logs}
|
||||
const RUNS = new Map();
|
||||
const MAX_RUNS = 50;
|
||||
|
||||
// 单次运行内存中累积的日志上限(结束后由 run-history 落盘,此处只服务"正在跑"的实时展示与回放)
|
||||
const MAX_RUN_LOGS = 800;
|
||||
|
||||
// 插件权限白名单(null = 全量;空集 = 零权限)。由登录/启动/同步决定。
|
||||
let ALLOWED = null;
|
||||
|
||||
function setAllowed(v) {
|
||||
ALLOWED = v === undefined ? null : v;
|
||||
}
|
||||
|
||||
function setRun(runId, fields) {
|
||||
const run = RUNS.get(runId);
|
||||
if (run) Object.assign(run, fields);
|
||||
}
|
||||
|
||||
function registerRun(runId, record) {
|
||||
if (RUNS.size >= MAX_RUNS) {
|
||||
const oldest = RUNS.keys().next().value;
|
||||
RUNS.delete(oldest);
|
||||
}
|
||||
RUNS.set(runId, record);
|
||||
}
|
||||
|
||||
// 累积"这一次运行"的日志:日志是运行的属性,跟着运行走(不再是全局单例)
|
||||
function appendRunLog(runId, entry) {
|
||||
const run = RUNS.get(runId);
|
||||
if (!run) return;
|
||||
if (!Array.isArray(run.logs)) run.logs = [];
|
||||
run.logs.push(entry);
|
||||
if (run.logs.length > MAX_RUN_LOGS) run.logs.splice(0, run.logs.length - MAX_RUN_LOGS);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PLATFORMS,
|
||||
RUNS,
|
||||
MAX_RUNS,
|
||||
MAX_RUN_LOGS,
|
||||
ALLOWED,
|
||||
setAllowed,
|
||||
setRun,
|
||||
registerRun,
|
||||
appendRunLog,
|
||||
};
|
||||
@@ -0,0 +1,483 @@
|
||||
// 定时任务(壳子内置定时):5 段 cron 解析 + schedules.json 存储 + 中心机备份/恢复 + 后台触发。
|
||||
// 语义对齐 Python tasks.py(★ 契约:dom/dow OR 规则、0/7 周日归一、30s tick、last_run_at 记忆)。
|
||||
// 差异:错过不补跑——壳子停机/离线期间到点的任务直接跳过(时间过了就过了,要补就人工运行一次);
|
||||
// 触发失败(授权被拒/插件缺失/启动异常)同样跳过本次到点,等下一个 cron 点再试,不每 tick 重试。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const cp = require("./cpclient");
|
||||
const session = require("./session");
|
||||
const { newId, nowStr, versionLt: _unused } = require("./crypto");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("tasks");
|
||||
|
||||
const SCHED_FILE = path.join(config.APP_DATA, "schedules.json");
|
||||
const TICK_SECS = 30;
|
||||
const DENY_LOG_CD = 300;
|
||||
// 到点判定容差:nxt 落在 now 前该时长内仍算"及时到点"正常触发;超过则视为错过(停机/离线期间到点),跳过。
|
||||
// 正常 tick 每 30s 一轮,单轮最坏耗时(deny 检查 5s 超时 + 多任务串行)远小于 4×TICK。
|
||||
const CATCHUP_SKIP_MS = TICK_SECS * 4 * 1000;
|
||||
|
||||
// 到点且未错过(供 tick 使用;独立成纯函数便于测试)
|
||||
function isDueNow(nxt, now) {
|
||||
if (!nxt) return false;
|
||||
const lag = now.getTime() - nxt.getTime();
|
||||
return lag >= 0 && lag <= CATCHUP_SKIP_MS;
|
||||
}
|
||||
|
||||
// 最小触发间隔(分钟):同一小时内相邻命中点的最小间距。
|
||||
// 分钟字段集合内任意相邻命中点间隔 < 60 → 存在 < 1 小时的连续触发(每分钟/每 30 分钟等),禁止。
|
||||
function minGapMinutes(cron) {
|
||||
const mins = [...cron.minute].sort((a, b) => a - b);
|
||||
if (mins.length <= 1) return 60; // 单点(如 `0`)= 每小时一次(或更稀疏)
|
||||
let gap = Infinity;
|
||||
for (let i = 0; i < mins.length; i++) {
|
||||
const a = mins[i];
|
||||
const b = i + 1 < mins.length ? mins[i + 1] : mins[0] + 60;
|
||||
gap = Math.min(gap, b - a);
|
||||
}
|
||||
return gap;
|
||||
}
|
||||
|
||||
// 校验:定时任务最低支持小时级间隔,分钟级禁止(避免高频触发 + 每 tick 无效检查影响性能)
|
||||
function assertHourlyMin(cron) {
|
||||
if (minGapMinutes(cron) < 60) {
|
||||
const err = new Error("定时任务最小间隔为 1 小时,不支持分钟级触发(每分钟/每 30 分钟等)");
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let _schedules = [];
|
||||
let _started = false;
|
||||
const _denyLogTs = new Map();
|
||||
|
||||
// ==================== 标准 5 段 cron 解析 ====================
|
||||
function parseField(spec, lo, hi) {
|
||||
if (spec === "*" || spec === "?") {
|
||||
const s = new Set();
|
||||
for (let v = lo; v <= hi; v++) s.add(v);
|
||||
return s;
|
||||
}
|
||||
const out = new Set();
|
||||
for (let part of String(spec).split(",")) {
|
||||
part = part.trim();
|
||||
if (!part) continue;
|
||||
let step = 1;
|
||||
if (part.includes("/")) {
|
||||
const idx = part.indexOf("/");
|
||||
const stepS = part.slice(idx + 1);
|
||||
part = part.slice(0, idx);
|
||||
step = parseInt(stepS, 10);
|
||||
if (Number.isNaN(step) || step < 1) throw new Error(`无效步长:${stepS}`);
|
||||
}
|
||||
let a, b;
|
||||
if (part === "*" || part === "?") {
|
||||
a = lo; b = hi;
|
||||
} else if (part.includes("-")) {
|
||||
const idx = part.indexOf("-");
|
||||
a = parseInt(part.slice(0, idx), 10);
|
||||
b = parseInt(part.slice(idx + 1), 10);
|
||||
} else {
|
||||
a = b = parseInt(part, 10);
|
||||
}
|
||||
if (Number.isNaN(a) || Number.isNaN(b) || a < lo || a > hi || b < lo || b > hi || a > b) {
|
||||
throw new Error(`字段越界:${part}`);
|
||||
}
|
||||
for (let v = a; v <= b; v += step) out.add(v);
|
||||
}
|
||||
if (out.size === 0) throw new Error("空字段");
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseCron(expr) {
|
||||
const parts = String(expr || "").trim().split(/\s+/);
|
||||
if (parts.length !== 5) throw new Error("cron 需为 5 段:分 时 日 月 周");
|
||||
const minute = parseField(parts[0], 0, 59);
|
||||
const hour = parseField(parts[1], 0, 23);
|
||||
const dom = parseField(parts[2], 1, 31);
|
||||
const month = parseField(parts[3], 1, 12);
|
||||
const dow = parseField(parts[4], 0, 7);
|
||||
const has7 = dow.has(7);
|
||||
dow.delete(7);
|
||||
if (has7) dow.add(0);
|
||||
return { minute, hour, dom, month, dow };
|
||||
}
|
||||
|
||||
function cronDow(dt) {
|
||||
// 标准 cron 周日编号:0=周日,1=周一 … 6=周六(与 Python 底座 _cron_dow 一致)。
|
||||
// 注意:JS getDay() 本身就是该编号(周日=0),不能再做 (x+6)%7 的偏移——那会整体差一天,
|
||||
// 导致「工作日 1-5」实际落在周二~周六、且 `0`/`7`(周日)错到周一。
|
||||
return dt.getDay();
|
||||
}
|
||||
|
||||
function setRange(lo, hi) {
|
||||
const s = new Set();
|
||||
for (let v = lo; v <= hi; v++) s.add(v);
|
||||
return s;
|
||||
}
|
||||
|
||||
function nextMatch(cron, after) {
|
||||
const { minute, hour, dom, month, dow } = cron;
|
||||
const domAny = dom.size === 31 && [...dom].every((v) => v >= 1 && v <= 31);
|
||||
const dowAny = dow.size === 7;
|
||||
let t = new Date(after);
|
||||
t.setSeconds(0, 0);
|
||||
t = new Date(t.getTime() + 60000); // +1 分钟
|
||||
for (let i = 0; i < 10000; i++) {
|
||||
if (!month.has(t.getMonth() + 1)) {
|
||||
const y = t.getMonth() === 11 ? t.getFullYear() + 1 : t.getFullYear();
|
||||
const m = t.getMonth() === 11 ? 0 : t.getMonth() + 1;
|
||||
t = new Date(y, m, 1, 0, 0, 0, 0);
|
||||
continue;
|
||||
}
|
||||
let dayOk;
|
||||
if (!domAny && !dowAny) dayOk = dom.has(t.getDate()) || dow.has(cronDow(t));
|
||||
else if (!dowAny) dayOk = dow.has(cronDow(t));
|
||||
else if (!domAny) dayOk = dom.has(t.getDate());
|
||||
else dayOk = true;
|
||||
if (!dayOk) {
|
||||
t = new Date(t.getFullYear(), t.getMonth(), t.getDate() + 1, 0, 0, 0, 0);
|
||||
continue;
|
||||
}
|
||||
if (!hour.has(t.getHours())) {
|
||||
t = new Date(t.getFullYear(), t.getMonth(), t.getDate(), t.getHours() + 1, 0, 0, 0);
|
||||
continue;
|
||||
}
|
||||
if (!minute.has(t.getMinutes())) {
|
||||
t = new Date(t.getTime() + 60000);
|
||||
continue;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ==================== 本地存储与 CRUD ====================
|
||||
function load() {
|
||||
try {
|
||||
if (fs.existsSync(SCHED_FILE)) {
|
||||
const data = JSON.parse(fs.readFileSync(SCHED_FILE, "utf-8"));
|
||||
_schedules = ((data || {}).schedules || []).filter((s) => s && typeof s === "object");
|
||||
} else {
|
||||
_schedules = [];
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`定时任务配置损坏,已忽略:${SCHED_FILE}`);
|
||||
_schedules = [];
|
||||
}
|
||||
}
|
||||
|
||||
function persist() {
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(SCHED_FILE, JSON.stringify({ schedules: _schedules }, null, 2), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`定时任务配置持久化失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function getSchedule(sid) {
|
||||
for (const s of _schedules) {
|
||||
if (s.id === sid) return { ...s };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function listSchedules(account) {
|
||||
return _schedules.filter((s) => s.account === account).map(publicView);
|
||||
}
|
||||
|
||||
function createSchedule(account, payload) {
|
||||
const cron = (payload.cron || "").trim();
|
||||
parseCron(cron); // 非法抛错
|
||||
assertHourlyMin(parseCron(cron)); // 分钟级抛错
|
||||
const rec = {
|
||||
id: newId(),
|
||||
name: (payload.name || "").trim() || "定时任务",
|
||||
account,
|
||||
plugin_id: payload.plugin_id || "",
|
||||
fields: payload.fields || {},
|
||||
cron,
|
||||
enabled: !!payload.enabled,
|
||||
last_run_at: "",
|
||||
created_at: nowStr(),
|
||||
updated_at: nowStr(),
|
||||
};
|
||||
_schedules.push(rec);
|
||||
persist();
|
||||
return { ...rec };
|
||||
}
|
||||
|
||||
function updateSchedule(sid, payload) {
|
||||
if (payload.cron) {
|
||||
parseCron(payload.cron);
|
||||
assertHourlyMin(parseCron(payload.cron));
|
||||
}
|
||||
for (const s of _schedules) {
|
||||
if (s.id !== sid) continue;
|
||||
if ("name" in payload) s.name = (payload.name || "").trim() || "定时任务";
|
||||
if ("plugin_id" in payload) s.plugin_id = payload.plugin_id;
|
||||
if ("fields" in payload) s.fields = payload.fields || {};
|
||||
if (payload.cron) s.cron = payload.cron.trim();
|
||||
if ("enabled" in payload) s.enabled = !!payload.enabled;
|
||||
s.updated_at = nowStr();
|
||||
persist();
|
||||
return { ...s };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function deleteSchedule(sid) {
|
||||
const idx = _schedules.findIndex((s) => s.id === sid);
|
||||
if (idx < 0) return false;
|
||||
_schedules.splice(idx, 1);
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
function toggleSchedule(sid, enabled) {
|
||||
for (const s of _schedules) {
|
||||
if (s.id !== sid) continue;
|
||||
s.enabled = !!enabled;
|
||||
s.updated_at = nowStr();
|
||||
persist();
|
||||
return { ...s };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function nextRunAt(s) {
|
||||
let cron;
|
||||
try {
|
||||
cron = parseCron(s.cron || "");
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
let last = null;
|
||||
if (s.last_run_at) {
|
||||
const t = Date.parse(s.last_run_at.replace(" ", "T"));
|
||||
if (!Number.isNaN(t)) last = new Date(t);
|
||||
}
|
||||
return nextMatch(cron, last || new Date());
|
||||
}
|
||||
|
||||
function publicView(s) {
|
||||
const out = { ...s };
|
||||
out.enabled = !!out.enabled;
|
||||
out.last_run_at = out.last_run_at || "";
|
||||
// 上次执行结论(计划视图要显示"上次 ✓ 成功 31s";无记录时为空,前端按"从未"处理)
|
||||
out.last_status = out.last_status || "";
|
||||
out.last_duration = parseInt(out.last_duration, 10) || 0;
|
||||
out.last_error = out.last_error || "";
|
||||
const nxt = out.enabled ? nextRunAt(s) : null;
|
||||
out.next_run_at = nxt ? fmt(nxt) : "";
|
||||
return out;
|
||||
}
|
||||
|
||||
function fmt(d) {
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function exportByAccount(account) {
|
||||
return _schedules.filter((s) => s.account === account).map((s) => ({ ...s }));
|
||||
}
|
||||
|
||||
// ==================== 后台触发 ====================
|
||||
function start() {
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
setInterval(() => {
|
||||
try {
|
||||
void tick();
|
||||
} catch (e) {
|
||||
logger.warning(`定时任务检查异常:${e.message}`);
|
||||
}
|
||||
}, TICK_SECS * 1000);
|
||||
logger.info(`定时任务后台检查已启动(每 ${TICK_SECS}s 一次)`);
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
const now = new Date();
|
||||
const due = [];
|
||||
const changed = []; // 触发成功或错过跳过都改了 last_run_at,需落盘
|
||||
for (const s of _schedules) {
|
||||
if (!s.enabled) continue;
|
||||
let cron;
|
||||
try {
|
||||
cron = parseCron(s.cron || "");
|
||||
// 防御:历史遗留的分钟级任务不触发(创建/编辑已被 assertHourlyMin 拦截)
|
||||
if (minGapMinutes(cron) < 60) {
|
||||
logger.warning(`定时任务「${s.name}」为分钟级间隔,已禁止触发,请在计划页改为小时级或以上`);
|
||||
continue;
|
||||
}
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
let last = null;
|
||||
if (s.last_run_at) {
|
||||
const t = Date.parse(s.last_run_at.replace(" ", "T"));
|
||||
if (!Number.isNaN(t)) last = new Date(t);
|
||||
}
|
||||
const nxt = nextMatch(cron, last || now);
|
||||
if (!nxt || nxt.getTime() > now.getTime()) continue; // 未来触发点
|
||||
if (!isDueNow(nxt, now)) {
|
||||
// 错过:壳子停机/离线期间到点,时间过了就过了,不补跑(要补就人工运行一次)。
|
||||
// last_run_at 推进到"现在",下次 tick 直接从未来点开始算。
|
||||
s.last_run_at = fmt(now);
|
||||
changed.push(s);
|
||||
logger.info(`定时任务「${s.name}」错过触发点 ${fmt(nxt)}(停机/离线期间),跳过不补跑`);
|
||||
continue;
|
||||
}
|
||||
due.push([s, nxt]);
|
||||
}
|
||||
for (const [s, nxt] of due) {
|
||||
if (await fire(s)) {
|
||||
s.last_run_at = fmt(nxt);
|
||||
} else {
|
||||
// 触发失败(授权被拒/插件缺失/启动异常):跳过本次到点,等下一个 cron 点再试,
|
||||
// 避免每 30s tick 对同一任务无效重试。
|
||||
s.last_run_at = fmt(now);
|
||||
}
|
||||
changed.push(s);
|
||||
}
|
||||
if (changed.length) persist();
|
||||
}
|
||||
|
||||
async function fire(s) {
|
||||
const registry = require("./registry");
|
||||
const licensing = require("./licensing");
|
||||
const runner = require("./runner");
|
||||
let plugin;
|
||||
try {
|
||||
plugin = registry.find(s.plugin_id || "");
|
||||
} catch (e) {
|
||||
logger.warning(`定时任务「${s.name}」的插件 ${s.plugin_id} 不存在,跳过触发`);
|
||||
return false;
|
||||
}
|
||||
const account = s.account || "";
|
||||
const deny = await licensing.runCheckAllowed(plugin.id, account, licensing.isOnline());
|
||||
if (deny) {
|
||||
const ts = Date.now();
|
||||
const lastLog = _denyLogTs.get(s.id);
|
||||
_denyLogTs.set(s.id, ts);
|
||||
if (lastLog === undefined || ts - lastLog >= DENY_LOG_CD * 1000) {
|
||||
logger.warning(`定时任务「${s.name}」触发被拒(账号 ${account}):${deny}`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const runId = runner.submitRun(account, plugin, s.fields || {}, {
|
||||
trigger: "schedule",
|
||||
schedule_id: s.id,
|
||||
});
|
||||
watchRun(s.id, runId);
|
||||
logger.info(`定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})`);
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.error(`定时任务「${s.name}」启动失败:${e.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 定时触发的运行结束后,把结论回写到该任务上(计划视图展示"上次 ✓ 成功 31s")
|
||||
function watchRun(scheduleId, runId) {
|
||||
let timer = null;
|
||||
const onEvent = (ev) => {
|
||||
if (!ev || ev.t !== "run_done" || ev.run_id !== runId) return;
|
||||
HUB.removeListener("event", onEvent);
|
||||
if (timer) clearTimeout(timer);
|
||||
const target = _schedules.find((x) => x.id === scheduleId);
|
||||
if (!target) return; // 任务已被删除
|
||||
target.last_status = ev.ok ? "ok" : "error";
|
||||
target.last_duration = parseInt(ev.duration_sec, 10) || 0;
|
||||
target.last_error = ev.ok ? "" : ev.error || "";
|
||||
persist();
|
||||
};
|
||||
HUB.on("event", onEvent);
|
||||
// 兜底:进程异常或事件丢失时不让监听器长期驻留(执行超时上限 + 2 分钟宽限)
|
||||
timer = setTimeout(() => HUB.removeListener("event", onEvent), (config.RUN_TIMEOUT + 120) * 1000);
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
|
||||
// ==================== 中心机备份(防丢失) ====================
|
||||
function pushBackup(account, headers) {
|
||||
if (!config.CONTROLPLANE_URL || !account) return;
|
||||
const payload = { data: { schedules: exportByAccount(account) } };
|
||||
cp.request("POST", "/api/schedules/backup", {
|
||||
headers: { ...(headers || {}), "Content-Type": "application/json" },
|
||||
json: payload,
|
||||
timeout: 10,
|
||||
})
|
||||
.then(() => logger.info(`定时任务备份成功(账号 ${account})`))
|
||||
.catch((e) => logger.warning(`定时任务备份失败(账号 ${account}):${e.message}`));
|
||||
}
|
||||
|
||||
function restoreFromCloud() {
|
||||
if (!config.CONTROLPLANE_URL) return;
|
||||
const account = session.sessActiveAccount();
|
||||
if (!account) return;
|
||||
const headers = { "X-Admin-User": account };
|
||||
if (config.CONTROLPLANE_TOKEN) headers["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||
const tok = session.cloudToken(account);
|
||||
if (tok) headers["Authorization"] = `Bearer ${tok}`;
|
||||
cp.request("GET", "/api/schedules/backup", { headers, timeout: 5 })
|
||||
.then((r) => {
|
||||
const remote = ((r.data || {}).schedules) || [];
|
||||
const localIds = new Set(_schedules.map((s) => s.id));
|
||||
let added = 0;
|
||||
for (const s of remote) {
|
||||
if (!s || typeof s !== "object" || localIds.has(s.id) || s.account !== account) continue;
|
||||
try {
|
||||
parseCron(s.cron || "");
|
||||
assertHourlyMin(parseCron(s.cron || "")); // 分钟级历史任务不恢复
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
_schedules.push(s);
|
||||
localIds.add(s.id);
|
||||
added++;
|
||||
}
|
||||
if (added) {
|
||||
persist();
|
||||
logger.info(`定时任务云端恢复 ${added} 条(账号 ${account})`);
|
||||
}
|
||||
})
|
||||
.catch((e) => logger.warning(`定时任务云端恢复失败(跳过):${e.message}`));
|
||||
}
|
||||
|
||||
function init() {
|
||||
load();
|
||||
start();
|
||||
restoreFromCloud();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseCron,
|
||||
parseField,
|
||||
nextMatch,
|
||||
cronDow,
|
||||
isDueNow,
|
||||
minGapMinutes,
|
||||
assertHourlyMin,
|
||||
CATCHUP_SKIP_MS,
|
||||
load,
|
||||
persist,
|
||||
getSchedule,
|
||||
listSchedules,
|
||||
createSchedule,
|
||||
updateSchedule,
|
||||
deleteSchedule,
|
||||
toggleSchedule,
|
||||
nextRunAt,
|
||||
watchRun,
|
||||
pushBackup,
|
||||
restoreFromCloud,
|
||||
init,
|
||||
SCHED_FILE,
|
||||
};
|
||||
@@ -0,0 +1,745 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 壳子 · 基于数据的重排版提案 v2(Run-centric Console)</title>
|
||||
<style>
|
||||
/* ============================================================
|
||||
v2 · 信息架构重排版:一切围绕「运行」组织
|
||||
左轨=场景轨 · 中央=上下文(总览/执行台/计划) · 右轨=活动轨
|
||||
单文件自包含 · 双主题 · 数据均取自真实接口字段
|
||||
============================================================ */
|
||||
:root {
|
||||
--canvas: #F4F6F9;
|
||||
--surface: #FFFFFF;
|
||||
--surface-2: #F1F4F8;
|
||||
--border: #E4E9F0;
|
||||
--border-strong: #CDD6E1;
|
||||
--text: #182230;
|
||||
--text-sub: #5A6674;
|
||||
--text-faint: #7C8896;
|
||||
--primary: #1E6FA8;
|
||||
--primary-strong: #17608F;
|
||||
--primary-tint: #E9F2FA;
|
||||
--ok: #1F8A4C; --ok-tint: #E7F5EC;
|
||||
--err: #D64545; --err-tint: #FBEBEB;
|
||||
--warn: #B26B00; --warn-tint: #FBF3E0;
|
||||
--r-frame: 14px; --r-card: 12px; --r-ctl: 8px;
|
||||
--sh-sm: 0 1px 2px rgba(15, 23, 42, .05);
|
||||
--sh-md: 0 8px 24px -12px rgba(15, 23, 42, .14);
|
||||
--font: "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif;
|
||||
--mono: "JetBrains Mono", "Cascadia Code", Consolas, monospace;
|
||||
}
|
||||
.frame[data-theme="dark"] {
|
||||
--canvas: #0E1116; --surface: #151A21; --surface-2: #1B222B;
|
||||
--border: #27303D; --border-strong: #39465A;
|
||||
--text: #E8EDF4; --text-sub: #9AA7B5; --text-faint: #6E7C8C;
|
||||
--primary: #3E93CF; --primary-strong: #5FA9DE; --primary-tint: #14304A;
|
||||
--ok: #4CC38A; --ok-tint: #12291C;
|
||||
--err: #E5726F; --err-tint: #2E1717;
|
||||
--warn: #DFA63E; --warn-tint: #2D2312;
|
||||
--sh-sm: 0 1px 2px rgba(0,0,0,.3);
|
||||
--sh-md: 0 10px 28px -14px rgba(0,0,0,.55);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; background: #E9ECF1; color: #182230;
|
||||
font-family: var(--font); font-size: 14px; line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
body.dark { background: #0B0E12; color: #E8EDF4; }
|
||||
|
||||
.intro { max-width: 1280px; margin: 0 auto; padding: 26px 24px 6px; display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; }
|
||||
.intro h1 { margin: 0; font-size: 19px; font-weight: 700; }
|
||||
.intro h1 small { color: #7C8896; font-weight: 500; font-size: 13px; }
|
||||
.intro p { margin: 4px 0 0; font-size: 12.5px; color: #5A6674; }
|
||||
body.dark .intro p { color: #9AA7B5; }
|
||||
.theme-toggle {
|
||||
border: 1px solid #CDD6E1; background: #fff; color: #182230;
|
||||
border-radius: 999px; padding: 7px 16px; font-size: 13px; cursor: pointer; font-family: inherit;
|
||||
}
|
||||
.theme-toggle:hover { border-color: #1E6FA8; color: #1E6FA8; }
|
||||
body.dark .theme-toggle { background: #1B222B; border-color: #39465A; color: #E8EDF4; }
|
||||
body.dark .theme-toggle:hover { border-color: #3E93CF; color: #3E93CF; }
|
||||
|
||||
.stage { max-width: 1280px; margin: 18px auto 0; padding: 0 24px; }
|
||||
.frame {
|
||||
border-radius: var(--r-frame); background: var(--canvas);
|
||||
border: 1px solid var(--border); box-shadow: var(--sh-md);
|
||||
overflow: hidden; display: flex; flex-direction: column; height: 820px;
|
||||
}
|
||||
|
||||
/* ---------- 标题栏 ---------- */
|
||||
.titlebar {
|
||||
height: 40px; flex-shrink: 0; display: flex; align-items: center; gap: 10px;
|
||||
padding-left: 14px; background: var(--surface); border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.titlebar .mark { width: 20px; height: 20px; border-radius: 6px; display: grid; place-items: center; background: var(--primary); color: #fff; font: 700 9px/1 var(--mono); }
|
||||
.titlebar .tname { font-size: 12.5px; font-weight: 600; }
|
||||
.titlebar .tver { font: 500 10.5px/1 var(--mono); color: var(--text-faint); border: 1px solid var(--border); border-radius: 999px; padding: 2px 8px; }
|
||||
.titlebar .tsp { flex: 1; }
|
||||
.win-ctl { display: flex; height: 100%; }
|
||||
.win-ctl span { width: 44px; display: grid; place-items: center; color: var(--text-faint); font-size: 11px; }
|
||||
.win-ctl span:hover { background: var(--surface-2); }
|
||||
.win-ctl span.close:hover { background: var(--err); color: #fff; }
|
||||
|
||||
/* ---------- 三栏骨架 ---------- */
|
||||
.shell { flex: 1; display: grid; grid-template-columns: 206px minmax(0, 1fr) 288px; min-height: 0; }
|
||||
|
||||
/* ===== 左轨 · 场景轨 ===== */
|
||||
.rail { background: var(--surface); border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 10px; min-height: 0; }
|
||||
.me {
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
padding: 8px 8px; margin-bottom: 10px;
|
||||
border: 1px solid var(--border); border-radius: var(--r-card);
|
||||
cursor: pointer; transition: border-color .13s ease;
|
||||
}
|
||||
.me:hover { border-color: var(--border-strong); }
|
||||
.me .ava { width: 28px; height: 28px; border-radius: 8px; background: var(--primary-tint); color: var(--primary); display: grid; place-items: center; font-size: 12px; font-weight: 700; flex-shrink: 0; }
|
||||
.me .mm { flex: 1; min-width: 0; display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.me .mm b { font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.me .mm span { font-size: 10.5px; color: var(--text-faint); }
|
||||
.me .ticket { font: 500 9.5px/1 var(--mono); color: var(--warn); background: var(--warn-tint); border-radius: 999px; padding: 3px 7px; flex-shrink: 0; }
|
||||
|
||||
.nav { display: flex; flex-direction: column; gap: 2px; margin-bottom: 12px; }
|
||||
.nv {
|
||||
display: flex; align-items: center; gap: 9px; height: 32px; padding: 0 9px;
|
||||
border-radius: var(--r-ctl); font-size: 12.5px; color: var(--text-sub);
|
||||
cursor: pointer; position: relative; transition: background .12s ease, color .12s ease;
|
||||
}
|
||||
.nv:hover { background: var(--surface-2); color: var(--text); }
|
||||
.nv.active { background: var(--primary-tint); color: var(--primary); font-weight: 600; }
|
||||
.nv.active::before { content: ''; position: absolute; left: -10px; top: 7px; bottom: 7px; width: 3px; border-radius: 0 3px 3px 0; background: var(--primary); }
|
||||
.nv svg { width: 14px; height: 14px; flex-shrink: 0; }
|
||||
.nv .bdg { margin-left: auto; font: 500 10px/1 var(--mono); color: var(--text-faint); background: var(--surface-2); border-radius: 999px; padding: 2px 6px; }
|
||||
.nv.active .bdg { background: transparent; color: var(--primary); }
|
||||
|
||||
.rail-head { display: flex; align-items: center; justify-content: space-between; padding: 0 9px 7px; font-size: 10.5px; font-weight: 700; letter-spacing: .07em; color: var(--text-faint); }
|
||||
.rail-head .cnt { font: 500 10px/1 var(--mono); background: var(--surface-2); border-radius: 999px; padding: 2px 6px; }
|
||||
.scenes { flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 1px; min-height: 0; }
|
||||
.sc-rail {
|
||||
display: flex; align-items: center; gap: 8px; height: 33px; padding: 0 9px;
|
||||
border-radius: var(--r-ctl); cursor: pointer; transition: background .12s ease;
|
||||
}
|
||||
.sc-rail:hover { background: var(--surface-2); }
|
||||
.sc-rail.active { background: var(--primary-tint); }
|
||||
.sc-rail .tile { width: 20px; height: 20px; border-radius: 6px; display: grid; place-items: center; font-size: 9.5px; font-weight: 700; flex-shrink: 0; }
|
||||
.t-sky { background: var(--primary-tint); color: var(--primary); }
|
||||
.t-honey { background: var(--warn-tint); color: var(--warn); }
|
||||
.t-mint { background: var(--ok-tint); color: var(--ok); }
|
||||
.t-blush { background: var(--err-tint); color: var(--err); }
|
||||
.sc-rail .nm { flex: 1; font-size: 12px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-rail.active .nm { color: var(--primary); font-weight: 600; }
|
||||
.sc-rail .dep { width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; }
|
||||
.dep.on { background: var(--ok); }
|
||||
.dep.off { background: var(--warn); }
|
||||
.rail-foot { border-top: 1px solid var(--border); padding: 9px 9px 1px; margin-top: 8px; display: flex; justify-content: space-between; font-size: 10.5px; color: var(--text-faint); }
|
||||
.rail-foot a { color: var(--primary); text-decoration: none; cursor: pointer; }
|
||||
|
||||
/* ===== 中央 · 上下文区 ===== */
|
||||
.center { min-width: 0; min-height: 0; display: flex; flex-direction: column; }
|
||||
.view { display: none; flex: 1; min-height: 0; overflow: auto; padding: 20px 22px; }
|
||||
.view.on { display: block; }
|
||||
|
||||
/* --- 执行台 --- */
|
||||
.run-head { display: flex; align-items: flex-start; gap: 14px; margin-bottom: 14px; }
|
||||
.run-head .big-tile { width: 46px; height: 46px; border-radius: 12px; display: grid; place-items: center; font-size: 19px; font-weight: 700; flex-shrink: 0; }
|
||||
.run-head .rh-m { flex: 1; min-width: 0; }
|
||||
.run-head h2 { margin: 0; font-size: 17px; font-weight: 700; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.chip { font: 500 10.5px/1 var(--mono); color: var(--text-faint); background: var(--surface); border: 1px solid var(--border); border-radius: 999px; padding: 3px 9px; }
|
||||
.chip.ok { color: var(--ok); background: var(--ok-tint); border-color: transparent; font-family: var(--font); }
|
||||
.chip.warn { color: var(--warn); background: var(--warn-tint); border-color: transparent; font-family: var(--font); cursor: pointer; }
|
||||
.run-head p { margin: 4px 0 0; font-size: 12.5px; color: var(--text-sub); }
|
||||
.rh-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
|
||||
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-card); box-shadow: var(--sh-sm); }
|
||||
.card + .card { margin-top: 12px; }
|
||||
.card-h { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px 0; }
|
||||
.card-h h3 { margin: 0; font-size: 12.5px; font-weight: 700; letter-spacing: .01em; }
|
||||
.card-h .ops { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.card-b { padding: 12px 16px 14px; }
|
||||
|
||||
/* 参数 */
|
||||
.fields { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
|
||||
.field { display: flex; flex-direction: column; gap: 5px; }
|
||||
.field label { font-size: 11.5px; color: var(--text-sub); display: flex; justify-content: space-between; }
|
||||
.field label em { font-style: normal; font-size: 10.5px; color: var(--text-faint); }
|
||||
.ctl {
|
||||
height: 32px; border: 1px solid var(--border-strong); border-radius: var(--r-ctl);
|
||||
background: var(--surface); color: var(--text); padding: 0 10px; font: 400 12.5px/1 var(--font);
|
||||
display: flex; align-items: center; justify-content: space-between; cursor: pointer;
|
||||
}
|
||||
.ctl:hover { border-color: var(--primary); }
|
||||
.ctl .arr { color: var(--text-faint); font-size: 9px; }
|
||||
.restored { display: flex; align-items: center; gap: 7px; margin-top: 11px; font-size: 11px; color: var(--text-faint); }
|
||||
.restored a { color: var(--primary); cursor: pointer; text-decoration: none; }
|
||||
|
||||
/* 运行卡 */
|
||||
.run-card { border: 1px solid var(--border); }
|
||||
.run-card.live { border-color: rgba(30, 111, 168, .45); box-shadow: 0 0 0 3px var(--primary-tint); }
|
||||
.state-pills { display: flex; gap: 2px; background: var(--surface-2); border-radius: 999px; padding: 2px; }
|
||||
.state-pill { font-size: 10.5px; color: var(--text-faint); padding: 3px 10px; border-radius: 999px; cursor: pointer; border: none; background: transparent; font-family: inherit; }
|
||||
.state-pill.on { background: var(--surface); color: var(--text); box-shadow: var(--sh-sm); font-weight: 600; }
|
||||
.run-body { padding: 14px 16px; }
|
||||
.st { display: none; }
|
||||
.run-card[data-state="idle"] .st-idle { display: block; }
|
||||
.run-card[data-state="running"] .st-running { display: block; }
|
||||
.run-card[data-state="done"] .st-done { display: block; }
|
||||
|
||||
.go-btn {
|
||||
display: inline-flex; align-items: center; gap: 9px;
|
||||
height: 40px; padding: 0 26px; border: none; border-radius: 10px;
|
||||
background: var(--primary-strong); color: #fff; font: 600 13.5px/1 var(--font);
|
||||
cursor: pointer; box-shadow: 0 6px 16px -8px rgba(23, 96, 143, .55);
|
||||
transition: transform .12s ease, box-shadow .12s ease;
|
||||
}
|
||||
.go-btn:hover { transform: translateY(-1px); box-shadow: 0 10px 20px -8px rgba(23, 96, 143, .6); }
|
||||
.go-hint { font-size: 11px; color: var(--text-faint); margin-left: 12px; }
|
||||
|
||||
.prog-row { display: flex; align-items: center; gap: 12px; margin-bottom: 11px; }
|
||||
.prog-row .pct { font: 600 19px/1 var(--mono); letter-spacing: -.02em; }
|
||||
.prog-row .track { flex: 1; height: 6px; border-radius: 999px; background: var(--surface-2); overflow: hidden; }
|
||||
.prog-row .fill { width: 62%; height: 100%; border-radius: 999px; background: var(--primary); }
|
||||
.live-b { font: 600 9.5px/1 var(--mono); letter-spacing: .08em; color: var(--ok); background: var(--ok-tint); padding: 3px 8px; border-radius: 999px; animation: pulse 1.6s ease infinite; }
|
||||
@keyframes pulse { 50% { opacity: .45; } }
|
||||
|
||||
.logs { background: var(--surface-2); border-radius: var(--r-ctl); padding: 9px 12px; font: 400 11.5px/1.8 var(--mono); max-height: 148px; overflow: auto; }
|
||||
.lg { display: flex; gap: 10px; }
|
||||
.lg .t { color: var(--text-faint); flex-shrink: 0; }
|
||||
.lg .lv { font-weight: 600; width: 40px; flex-shrink: 0; }
|
||||
.lv.i { color: var(--primary); }
|
||||
.lv.w { color: var(--warn); }
|
||||
.lg .m { color: var(--text); word-break: break-all; }
|
||||
|
||||
.done-banner { display: flex; align-items: flex-start; gap: 10px; padding: 11px 13px; border-radius: var(--r-ctl); background: var(--ok-tint); margin-bottom: 11px; }
|
||||
.done-banner .ic { width: 20px; height: 20px; border-radius: 50%; background: var(--ok); color: #fff; display: grid; place-items: center; font-size: 10px; font-weight: 700; flex-shrink: 0; }
|
||||
.done-banner .db { flex: 1; }
|
||||
.done-banner .db b { font-size: 12.5px; display: block; }
|
||||
.done-banner .db span { font-size: 11.5px; color: var(--text-sub); }
|
||||
.done-banner .again { border: 1px solid var(--border-strong); background: transparent; border-radius: var(--r-ctl); padding: 6px 13px; font: 500 12px/1 var(--font); color: var(--text-sub); cursor: pointer; }
|
||||
.done-banner .again:hover { border-color: var(--primary); color: var(--primary); }
|
||||
|
||||
/* 场景内定时 */
|
||||
.sched-inline { display: flex; align-items: center; gap: 10px; padding: 10px 0 2px; }
|
||||
.sched-inline .si { flex: 1; display: flex; align-items: center; gap: 9px; font-size: 12px; }
|
||||
.sched-inline .si b { font-weight: 600; }
|
||||
.sched-inline .si span { color: var(--text-faint); font-size: 11.5px; }
|
||||
.cron-chip { font: 500 10.5px/1 var(--mono); color: var(--primary); background: var(--primary-tint); border-radius: 6px; padding: 3px 7px; }
|
||||
.switch { width: 30px; height: 17px; border-radius: 999px; background: var(--border-strong); position: relative; flex-shrink: 0; }
|
||||
.switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 13px; height: 13px; border-radius: 50%; background: #fff; transition: left .15s ease; }
|
||||
.switch.on { background: var(--ok); }
|
||||
.switch.on::after { left: 15px; }
|
||||
.mini-btn { border: 1px solid var(--border-strong); background: transparent; color: var(--text-sub); border-radius: var(--r-ctl); padding: 5px 11px; font: 500 11.5px/1 var(--font); cursor: pointer; }
|
||||
.mini-btn:hover { border-color: var(--primary); color: var(--primary); }
|
||||
|
||||
/* --- 总览 --- */
|
||||
.ov-head { display: flex; align-items: flex-end; justify-content: space-between; margin-bottom: 14px; }
|
||||
.ov-head h2 { margin: 0; font-size: 18px; font-weight: 700; }
|
||||
.ov-head .sub { margin: 3px 0 0; font-size: 12px; color: var(--text-faint); }
|
||||
.kpis { display: flex; gap: 8px; }
|
||||
.kpi { display: flex; align-items: baseline; gap: 6px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-ctl); padding: 7px 12px; }
|
||||
.kpi b { font: 600 15px/1 var(--mono); }
|
||||
.kpi b em { font-style: normal; font-size: 10.5px; color: var(--text-faint); font-weight: 500; }
|
||||
.kpi span { font-size: 11px; color: var(--text-faint); }
|
||||
.kpi.ok b { color: var(--ok); }
|
||||
|
||||
.queue { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px; }
|
||||
.q-item { display: flex; align-items: center; gap: 11px; padding: 11px 14px; }
|
||||
.q-when { text-align: center; flex-shrink: 0; width: 46px; }
|
||||
.q-when b { display: block; font: 600 15px/1.1 var(--mono); }
|
||||
.q-when span { font-size: 10px; color: var(--text-faint); }
|
||||
.q-m { flex: 1; min-width: 0; }
|
||||
.q-m b { display: block; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.q-m span { font-size: 11px; color: var(--text-faint); font-family: var(--mono); }
|
||||
|
||||
.ov-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
||||
.ov-sc { display: flex; align-items: center; gap: 12px; padding: 13px 15px; cursor: pointer; font-family: inherit; text-align: left; border: 1px solid var(--border); background: var(--surface); border-radius: var(--r-card); box-shadow: var(--sh-sm); transition: border-color .13s ease, box-shadow .13s ease; }
|
||||
.ov-sc:hover { border-color: var(--border-strong); box-shadow: var(--sh-md); }
|
||||
.ov-sc .tile { width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center; font-size: 13px; font-weight: 700; flex-shrink: 0; }
|
||||
.ov-sc .m { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||||
.ov-sc .m b { font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ov-sc .m span { font-size: 11px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ov-sc .meta { display: flex; align-items: center; gap: 6px; margin-top: 2px; }
|
||||
.ov-sc .meta i { font-style: normal; font-size: 10px; color: var(--text-faint); font-family: var(--mono); }
|
||||
.ov-sc .meta .st2 { font-size: 10px; }
|
||||
.st2.ok { color: var(--ok); }
|
||||
.st2.warn { color: var(--warn); }
|
||||
.ov-sc .go { flex-shrink: 0; font-size: 11.5px; font-weight: 600; color: var(--primary); border: 1px solid var(--border-strong); border-radius: var(--r-ctl); padding: 5px 12px; transition: all .13s ease; }
|
||||
.ov-sc:hover .go { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
|
||||
/* --- 计划 --- */
|
||||
.sched-list { display: flex; flex-direction: column; }
|
||||
.sched-row { display: flex; align-items: center; gap: 14px; padding: 13px 16px; border-bottom: 1px solid var(--border); }
|
||||
.sched-row:last-child { border-bottom: none; }
|
||||
.sr-when { width: 108px; flex-shrink: 0; }
|
||||
.sr-when b { display: block; font-size: 12.5px; }
|
||||
.sr-when span { font-size: 10.5px; color: var(--text-faint); font-family: var(--mono); }
|
||||
.sr-m { flex: 1; min-width: 0; }
|
||||
.sr-m b { display: block; font-size: 13px; }
|
||||
.sr-m span { font-size: 11px; color: var(--text-faint); }
|
||||
.sr-last { width: 120px; flex-shrink: 0; font-size: 11px; color: var(--text-faint); }
|
||||
.sr-acts { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
.link-btn { border: none; background: none; font: 500 11.5px/1 var(--font); color: var(--primary); cursor: pointer; padding: 4px 6px; border-radius: 6px; }
|
||||
.link-btn:hover { background: var(--primary-tint); }
|
||||
.link-btn.danger { color: var(--err); }
|
||||
.link-btn.danger:hover { background: var(--err-tint); }
|
||||
|
||||
/* ===== 右轨 · 活动轨 ===== */
|
||||
.activity { background: var(--surface); border-left: 1px solid var(--border); display: flex; flex-direction: column; overflow: auto; padding: 12px; gap: 12px; min-height: 0; }
|
||||
.act-sec { display: flex; flex-direction: column; }
|
||||
.act-h { display: flex; align-items: center; justify-content: space-between; padding: 0 4px 8px; }
|
||||
.act-h h4 { margin: 0; font-size: 11px; font-weight: 700; letter-spacing: .07em; color: var(--text-faint); }
|
||||
.act-h a { font-size: 10.5px; color: var(--primary); text-decoration: none; cursor: pointer; }
|
||||
.act-item { display: flex; align-items: flex-start; gap: 9px; padding: 7px 8px; border-radius: var(--r-ctl); cursor: pointer; }
|
||||
.act-item:hover { background: var(--surface-2); }
|
||||
.act-item .aw { font: 500 10.5px/1.5 var(--mono); color: var(--text-faint); width: 62px; flex-shrink: 0; }
|
||||
.act-item .aw b { display: block; color: var(--text); font-size: 11.5px; }
|
||||
.act-item .am { flex: 1; min-width: 0; font-size: 11.5px; color: var(--text-sub); line-height: 1.45; }
|
||||
.act-item .am b { color: var(--text); font-weight: 600; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.act-item .am span { display: block; font-size: 10.5px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.act-item .am span.err { color: var(--err); }
|
||||
.act-item .st3 { width: 16px; height: 16px; border-radius: 50%; display: grid; place-items: center; font-size: 9px; font-weight: 700; flex-shrink: 0; margin-top: 1px; }
|
||||
.st3.ok { background: var(--ok-tint); color: var(--ok); }
|
||||
.st3.err { background: var(--err-tint); color: var(--err); }
|
||||
.st3.plan { background: var(--primary-tint); color: var(--primary); font-size: 8px; }
|
||||
|
||||
.plat-row { display: flex; align-items: center; gap: 9px; padding: 8px 8px; }
|
||||
.plat-row + .plat-row { border-top: 1px dashed var(--border); }
|
||||
.plat-row .pd { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
|
||||
.plat-row .pd.on { background: var(--ok); box-shadow: 0 0 0 3px var(--ok-tint); }
|
||||
.plat-row .pd.off { background: var(--border-strong); }
|
||||
.plat-row .pm { flex: 1; min-width: 0; line-height: 1.3; }
|
||||
.plat-row .pm b { font-size: 12px; display: block; }
|
||||
.plat-row .pm span { font-size: 10.5px; color: var(--text-faint); }
|
||||
.plat-row .pm span.ok2 { color: var(--ok); }
|
||||
.ticket-card { border: 1px solid var(--border); border-radius: var(--r-card); padding: 11px 13px; background: var(--warn-tint); }
|
||||
.ticket-card b { font-size: 12px; color: var(--warn); display: flex; align-items: center; gap: 6px; }
|
||||
.ticket-card p { margin: 4px 0 8px; font-size: 10.5px; color: var(--text-sub); line-height: 1.55; }
|
||||
.ticket-card .mini-btn { background: var(--surface); }
|
||||
|
||||
/* ---------- 状态栏 ---------- */
|
||||
.statusbar { height: 26px; flex-shrink: 0; display: flex; align-items: center; gap: 16px; padding: 0 14px; font-size: 10.5px; color: var(--text-faint); background: var(--surface); border-top: 1px solid var(--border); }
|
||||
.statusbar .si { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.statusbar i { width: 5px; height: 5px; border-radius: 50%; }
|
||||
.statusbar i.on { background: var(--ok); }
|
||||
.statusbar i.mid { background: var(--warn); }
|
||||
.statusbar .sp { flex: 1; }
|
||||
.statusbar .mono { font-family: var(--mono); }
|
||||
|
||||
/* ---------- IA 对照表 ---------- */
|
||||
.mapping { max-width: 1280px; margin: 34px auto 56px; padding: 0 24px; }
|
||||
.mapping h2 { font-size: 16px; margin: 0 0 12px; }
|
||||
.map-table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid #E4E9F0; border-radius: 12px; overflow: hidden; font-size: 12.5px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
|
||||
body.dark .map-table { background: #151A21; border-color: #27303D; }
|
||||
.map-table th { text-align: left; font-size: 11px; letter-spacing: .05em; color: #7C8896; background: #F7F9FB; padding: 10px 14px; border-bottom: 1px solid #E4E9F0; }
|
||||
body.dark .map-table th { background: #1B222B; border-color: #27303D; color: #6E7C8C; }
|
||||
.map-table td { padding: 10px 14px; border-bottom: 1px solid #EFF2F6; color: #3D4854; vertical-align: top; }
|
||||
body.dark .map-table td { border-color: #222B37; color: #C6D0DC; }
|
||||
.map-table tr:last-child td { border-bottom: none; }
|
||||
.map-table td:first-child { font-family: var(--mono); font-size: 11.5px; white-space: nowrap; }
|
||||
.map-table td.moved { color: #1E6FA8; font-weight: 600; }
|
||||
body.dark .map-table td.moved { color: #5FA9DE; }
|
||||
.map-table td.cut { color: #B3403E; }
|
||||
body.dark .map-table td.cut { color: #E5726F; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="intro">
|
||||
<div>
|
||||
<h1>基于数据的重排版 v2 <small>· Run-centric Console</small></h1>
|
||||
<p>原子实体是「运行」:场景=模板 · 定时=触发器 · 平台会话=前置条件 · 日志/进度/结果=过程与产物。左轨选场景,中央看上下文,右轨看活动流 —— 点左侧导航或场景可切换视图</p>
|
||||
</div>
|
||||
<button class="theme-toggle" onclick="document.body.classList.toggle('dark');document.querySelector('.frame').dataset.theme=document.body.classList.contains('dark')?'dark':'light'">◐ 深 / 浅主题</button>
|
||||
</div>
|
||||
|
||||
<div class="stage">
|
||||
<div class="frame" data-theme="light">
|
||||
<div class="titlebar">
|
||||
<span class="mark">37</span><span class="tname">自动化工作台</span><span class="tver">v2.3.1</span>
|
||||
<span class="tsp"></span>
|
||||
<div class="win-ctl"><span>—</span><span>▢</span><span class="close">✕</span></div>
|
||||
</div>
|
||||
|
||||
<div class="shell">
|
||||
<!-- ============ 左轨:场景轨 ============ -->
|
||||
<aside class="rail">
|
||||
<div class="me" title="个人中心">
|
||||
<span class="ava">张</span>
|
||||
<span class="mm"><b>张三</b><span>人力资源部 · zhangsan</span></span>
|
||||
<span class="ticket">票 5天</span>
|
||||
</div>
|
||||
|
||||
<div class="nav">
|
||||
<div class="nv" data-view="overview" onclick="switchView('overview')">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="8" height="8" rx="2"/><rect x="13" y="3" width="8" height="8" rx="2"/><rect x="3" y="13" width="8" height="8" rx="2"/><rect x="13" y="13" width="8" height="8" rx="2"/></svg>
|
||||
<span>总览</span>
|
||||
</div>
|
||||
<div class="nv" data-view="sched" onclick="switchView('sched')">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
|
||||
<span>计划</span>
|
||||
<span class="bdg">3</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rail-head"><span>场景库</span><span class="cnt">6</span></div>
|
||||
<div class="scenes">
|
||||
<div class="sc-rail active" onclick="switchView('run')"><span class="tile t-sky">考</span><span class="nm">考勤月报封存检查</span><span class="dep on"></span></div>
|
||||
<div class="sc-rail" onclick="switchView('run')"><span class="tile t-honey">假</span><span class="nm">请假单批量补录</span><span class="dep off"></span></div>
|
||||
<div class="sc-rail" onclick="switchView('run')"><span class="tile t-mint">周</span><span class="nm">周报数据汇总</span><span class="dep on"></span></div>
|
||||
<div class="sc-rail" onclick="switchView('run')"><span class="tile t-blush">邮</span><span class="nm">邮件定时巡检</span><span class="dep on"></span></div>
|
||||
<div class="sc-rail" onclick="switchView('run')"><span class="tile t-sky">薪</span><span class="nm">薪酬条分发</span><span class="dep off"></span></div>
|
||||
<div class="sc-rail" onclick="switchView('run')"><span class="tile t-mint">档</span><span class="nm">档案归档巡检</span><span class="dep on"></span></div>
|
||||
</div>
|
||||
|
||||
<div class="rail-foot"><span>壳子 v2.3.1</span><a>检查更新</a></div>
|
||||
</aside>
|
||||
|
||||
<!-- ============ 中央:上下文区 ============ -->
|
||||
<main class="center">
|
||||
|
||||
<!-- ▍执行台:选中场景后,参数/运行/日志/定时 全部围绕这一次执行组织 -->
|
||||
<section class="view on" id="view-run">
|
||||
<div class="run-head">
|
||||
<span class="big-tile t-sky">考</span>
|
||||
<div class="rh-m">
|
||||
<h2>考勤月报封存检查 <span class="chip">v1.4.0</span> <span class="chip ok">OA · 已登录</span> <span class="chip warn">装浏览器</span></h2>
|
||||
<p>抓取当月 OA 考勤原始表,校验异常打卡并生成封存报表回传中心机</p>
|
||||
</div>
|
||||
<div class="rh-actions">
|
||||
<button class="mini-btn">插件详情</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 参数卡:fields[] 数据驱动 · 恢复上次值(新增可负担性) -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<h3>执行参数</h3>
|
||||
<span class="ops">3 项 · 全部必填已就绪</span>
|
||||
</div>
|
||||
<div class="card-b">
|
||||
<div class="fields">
|
||||
<div class="field">
|
||||
<label>报表月份 <em>uses_month</em></label>
|
||||
<div class="ctl"><span>2025-11</span><span class="arr">▾</span></div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>失败重试次数 <em>int</em></label>
|
||||
<div class="ctl"><span>2</span></div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>异常通知邮箱 <em>text</em></label>
|
||||
<div class="ctl"><span style="color:var(--text-faint)">zhangsan@37du.cn</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="restored">↺ 已恢复上次执行参数(11 日 14:02) · <a>恢复默认</a></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 运行卡:待执行 / 执行中 / 已完成 三态切换(右上角示意按钮) -->
|
||||
<div class="card run-card live" id="run-card" data-state="running">
|
||||
<div class="card-h">
|
||||
<h3>运行</h3>
|
||||
<div class="state-pills" onclick="event.stopPropagation()">
|
||||
<button class="state-pill" data-s="idle" onclick="setRun('idle')">待执行</button>
|
||||
<button class="state-pill on" data-s="running" onclick="setRun('running')">执行中</button>
|
||||
<button class="state-pill" data-s="done" onclick="setRun('done')">已完成</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="run-body">
|
||||
<!-- 待执行 -->
|
||||
<div class="st st-idle">
|
||||
<button class="go-btn">▶ 一键执行</button>
|
||||
<span class="go-hint">使用本机 Chrome 会话执行 · 日志实时显示在此卡片,不再占用全局底栏</span>
|
||||
</div>
|
||||
<!-- 执行中 -->
|
||||
<div class="st st-running">
|
||||
<div class="prog-row">
|
||||
<span class="pct">62%</span>
|
||||
<div class="track"><div class="fill"></div></div>
|
||||
<span class="live-b">● LIVE</span>
|
||||
<span class="chip">run_8f3a</span>
|
||||
</div>
|
||||
<div class="logs">
|
||||
<div class="lg"><span class="t">14:02:01</span><span class="lv i">INFO</span><span class="m">启动 Chrome 会话,加载 OA 首页</span></div>
|
||||
<div class="lg"><span class="t">14:02:07</span><span class="lv i">INFO</span><span class="m">登录态校验通过(cookie 有效)</span></div>
|
||||
<div class="lg"><span class="t">14:02:09</span><span class="lv i">INFO</span><span class="m">进入 考勤月报 → 2025-11,开始抓取表格</span></div>
|
||||
<div class="lg"><span class="t">14:02:24</span><span class="lv w">WARN</span><span class="m">抓取到 2 行异常打卡,已标记待人工复核</span></div>
|
||||
<div class="lg"><span class="t">14:02:31</span><span class="lv i">INFO</span><span class="m">正在生成封存 ZIP 并回传中心机…</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 已完成 -->
|
||||
<div class="st st-done">
|
||||
<div class="done-banner">
|
||||
<span class="ic">✓</span>
|
||||
<div class="db">
|
||||
<b>执行完成 · 耗时 31s</b>
|
||||
<span>报表已封存并回传中心机 · 2 行异常打卡待人工复核</span>
|
||||
</div>
|
||||
<button class="again">↻ 再次执行</button>
|
||||
</div>
|
||||
<div class="logs">
|
||||
<div class="lg"><span class="t">14:02:31</span><span class="lv i">INFO</span><span class="m">报表封存完成,已生成 ZIP 并回传中心机</span></div>
|
||||
<div class="lg"><span class="t">14:02:32</span><span class="lv i">INFO</span><span class="m">===== 执行完成 =====(耗时 31s)</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 该场景绑定的定时(schedule 数据本来就是 per-plugin 的) -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<h3>定时触发</h3>
|
||||
<button class="mini-btn">+ 新建定时</button>
|
||||
</div>
|
||||
<div class="card-b">
|
||||
<div class="sched-inline">
|
||||
<span class="si"><b>每个工作日 08:00</b><span>下次 明天 08:00 · 上次 今天 08:00 成功</span><span class="cron-chip">0 8 * * 1-5</span></span>
|
||||
<span class="switch on"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ▍总览:原首页溶解为 KPI 行 + 队列条 + 场景网格 -->
|
||||
<section class="view" id="view-overview">
|
||||
<div class="ov-head">
|
||||
<div>
|
||||
<h2>早上好,张三</h2>
|
||||
<p class="sub">2025年12月11日 星期四 · 昨日自动执行 12 次,全部成功</p>
|
||||
</div>
|
||||
<div class="kpis">
|
||||
<div class="kpi"><b>6</b><span>场景</span></div>
|
||||
<div class="kpi"><b>3</b><span>计划</span></div>
|
||||
<div class="kpi"><b>2<em>/2</em></b><span>平台在线</span></div>
|
||||
<div class="kpi ok"><b>✓ 14:02</b><span>上次执行</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-h" style="font-size:12.5px;font-weight:700;margin-bottom:9px">接下来自动执行</div>
|
||||
<div class="queue">
|
||||
<div class="card q-item">
|
||||
<span class="q-when"><b>08:00</b><span>明天</span></span>
|
||||
<span class="q-m"><b>考勤月报封存检查</b><span>0 8 * * 1-5 · 工作日</span></span>
|
||||
<span class="chip ok">OA ✓</span>
|
||||
</div>
|
||||
<div class="card q-item">
|
||||
<span class="q-when"><b>18:00</b><span>周五</span></span>
|
||||
<span class="q-m"><b>周报数据汇总</b><span>0 18 * * 5 · 每周五</span></span>
|
||||
<span class="chip ok">OA ✓</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-h" style="font-size:12.5px;font-weight:700;margin:0 0 9px">全部场景</div>
|
||||
<div class="ov-grid">
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-sky">考</span>
|
||||
<span class="m"><b>考勤月报封存检查</b><span>抓取当月考勤原始表并封存</span>
|
||||
<span class="meta"><i>v1.4.0</i><span class="st2 ok">OA 已登录</span><span class="st2" style="color:var(--text-faint)">· 定时 1</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-honey">假</span>
|
||||
<span class="m"><b>请假单批量补录</b><span>按名单批量补录历史请假单</span>
|
||||
<span class="meta"><i>v0.9.2</i><span class="st2 warn">HR 未登录</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-mint">周</span>
|
||||
<span class="m"><b>周报数据汇总</b><span>拉取各部门周报生成汇总快照</span>
|
||||
<span class="meta"><i>v2.1.0</i><span class="st2 ok">OA 已登录</span><span class="st2" style="color:var(--text-faint)">· 定时 1</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-blush">邮</span>
|
||||
<span class="m"><b>邮件定时巡检</b><span>巡检公共邮箱未读工单</span>
|
||||
<span class="meta"><i>v1.0.3</i><span class="st2 ok">MAIL 已登录</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-sky">薪</span>
|
||||
<span class="m"><b>薪酬条分发</b><span>按月生成薪酬条并站内分发</span>
|
||||
<span class="meta"><i>v1.2.7</i><span class="st2 warn">HR 未登录</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
<button class="ov-sc" onclick="switchView('run')">
|
||||
<span class="tile t-mint">档</span>
|
||||
<span class="m"><b>档案归档巡检</b><span>巡检档案库完整性并归档</span>
|
||||
<span class="meta"><i>v0.6.1</i><span class="st2 ok">OA 已登录</span></span></span>
|
||||
<span class="go">执行</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ▍计划:schedules 从 CRUD 表格变成时间队列 -->
|
||||
<section class="view" id="view-sched">
|
||||
<div class="ov-head">
|
||||
<div>
|
||||
<h2>计划</h2>
|
||||
<p class="sub">按下次执行时间排序 · 配置自动备份到中心机</p>
|
||||
</div>
|
||||
<button class="mini-btn" style="height:32px;padding:0 15px">+ 新建任务</button>
|
||||
</div>
|
||||
<div class="card sched-list">
|
||||
<div class="sched-row">
|
||||
<span class="sr-when"><b>明天 08:00</b><span>12-12 周五</span></span>
|
||||
<span class="sr-m"><b>考勤月报封存检查</b><span>工作日触发 · 参数:2025-11 · 重试 2 次</span></span>
|
||||
<span class="cron-chip">0 8 * * 1-5</span>
|
||||
<span class="sr-last">上次 今天 08:00<br>✓ 成功 31s</span>
|
||||
<span class="sr-acts"><span class="switch on"></span><button class="link-btn">编辑</button><button class="link-btn danger">删除</button></span>
|
||||
</div>
|
||||
<div class="sched-row">
|
||||
<span class="sr-when"><b>周五 18:00</b><span>12-12 周五</span></span>
|
||||
<span class="sr-m"><b>周报数据汇总</b><span>每周触发 · 全部默认参数</span></span>
|
||||
<span class="cron-chip">0 18 * * 5</span>
|
||||
<span class="sr-last">上次 12-05 18:00<br>✓ 成功 12s</span>
|
||||
<span class="sr-acts"><span class="switch on"></span><button class="link-btn">编辑</button><button class="link-btn danger">删除</button></span>
|
||||
</div>
|
||||
<div class="sched-row">
|
||||
<span class="sr-when"><b>12-01 09:00</b><span>已过期</span></span>
|
||||
<span class="sr-m"><b>档案归档巡检</b><span>每月 1 日触发 · 已停用</span></span>
|
||||
<span class="cron-chip">0 9 1 * *</span>
|
||||
<span class="sr-last">上次 12-01 09:00<br>✓ 成功 8s</span>
|
||||
<span class="sr-acts"><span class="switch"></span><button class="link-btn">编辑</button><button class="link-btn danger">删除</button></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- ============ 右轨:活动轨(三处散落数据合并成一条流) ============ -->
|
||||
<aside class="activity">
|
||||
<div class="act-sec">
|
||||
<div class="act-h"><h4>接下来自动执行</h4><a onclick="switchView('sched')">全部</a></div>
|
||||
<div class="act-item" onclick="switchView('sched')">
|
||||
<span class="st3 plan">⏰</span>
|
||||
<span class="am"><b>考勤月报封存检查</b><span>明天 08:00 · 工作日</span></span>
|
||||
</div>
|
||||
<div class="act-item" onclick="switchView('sched')">
|
||||
<span class="st3 plan">⏰</span>
|
||||
<span class="am"><b>周报数据汇总</b><span>周五 18:00 · 每周</span></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="act-sec">
|
||||
<div class="act-h"><h4>最近运行</h4></div>
|
||||
<div class="act-item" onclick="switchView('run')">
|
||||
<span class="st3 ok">✓</span>
|
||||
<span class="am"><b>考勤月报封存检查</b><span>14:02 · 31s · 手动</span></span>
|
||||
</div>
|
||||
<div class="act-item" onclick="switchView('run')">
|
||||
<span class="st3 ok">✓</span>
|
||||
<span class="am"><b>周报数据汇总</b><span>09:31 · 12s · 定时</span></span>
|
||||
</div>
|
||||
<div class="act-item" onclick="switchView('run')">
|
||||
<span class="st3 err">✕</span>
|
||||
<span class="am"><b>请假单批量补录</b><span class="err">09:12 · HR 会话过期</span></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="act-sec">
|
||||
<div class="act-h"><h4>平台会话</h4><a>配置账号</a></div>
|
||||
<div class="plat-row">
|
||||
<span class="pd on"></span>
|
||||
<span class="pm"><b>OA 办公系统</b><span class="ok2">已登录 · zhangsan</span></span>
|
||||
<button class="mini-btn">登出</button>
|
||||
</div>
|
||||
<div class="plat-row">
|
||||
<span class="pd off"></span>
|
||||
<span class="pm"><b>HR 人事系统</b><span>未登录 · 未配置个人账号</span></span>
|
||||
<button class="mini-btn">登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="act-sec" style="margin-top:auto">
|
||||
<div class="ticket-card">
|
||||
<b>⚠ 授权票据剩余 5 天</b>
|
||||
<p>最长允许离线 7 天,到期前联网刷新即可,不影响本地已装场景。</p>
|
||||
<button class="mini-btn">立即刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div class="statusbar">
|
||||
<span class="si"><i class="on"></i>服务已连接</span>
|
||||
<span class="si"><i class="on"></i>Chrome 131</span>
|
||||
<span class="si"><i class="mid"></i>插件同步 2 分钟前</span>
|
||||
<span class="sp"></span>
|
||||
<span class="mono">127.0.0.1:8765</span>
|
||||
<span class="mono">WS 正常</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ---------- 数据 → 界面 归属对照 ---------- -->
|
||||
<div class="mapping">
|
||||
<h2>数据 → 界面归属对照(重排了什么,为什么)</h2>
|
||||
<table class="map-table">
|
||||
<tr><th>数据(接口字段)</th><th>现在的位置</th><th>新家</th><th>理由</th></tr>
|
||||
<tr>
|
||||
<td>run / progress / logs</td>
|
||||
<td>topbar 进度条 + 执行按钮环 + 全局底栏日志(三处)</td>
|
||||
<td class="moved">执行台·运行卡(日志内联,三态一体)</td>
|
||||
<td>日志是「这次运行」的属性,跟着运行走;完成后同卡片展示结果与摘要</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>schedules + next_run_at</td>
|
||||
<td>独立的定时任务页(CRUD 表格)</td>
|
||||
<td class="moved">计划视图(按时间排序的队列)+ 场景执行台内联「定时触发」</td>
|
||||
<td>next_run_at 本来就有,但现状没有「接下来发生什么」的时间感;同时定时数据绑定插件,就地可见</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>platforms + online</td>
|
||||
<td>首页卡片区 + 个人中心抽屉(两处重复)</td>
|
||||
<td class="moved">右轨·平台会话(唯一入口)+ 场景头的依赖芯片</td>
|
||||
<td>它是运行的前置条件,应该常驻可见、一键登录,而不是藏在两个地方</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>recents(最近 8 次)</td>
|
||||
<td>首页底部摘要条</td>
|
||||
<td class="moved">右轨·最近运行(点击回放 → 执行台)</td>
|
||||
<td>run_id 与 getRun 都在,点击可回放日志,把摘要升级成入口</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>fields[](插件参数)</td>
|
||||
<td>插件页平铺表单,每次进入重置默认值</td>
|
||||
<td class="moved">执行台·参数卡 + 「恢复上次参数」</td>
|
||||
<td>新增可负担性:上次值本地持久化,重复执行不再逐项重填</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>首页(问候/统计卡)</td>
|
||||
<td>独立 home 视图</td>
|
||||
<td class="cut">溶解:KPI 行并入总览头部</td>
|
||||
<td>统计数字全部可由其余视图直接得出,独立页面信息密度过低</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>WS/Chrome/更新/授权状态</td>
|
||||
<td>topbar 芯片堆 + 全局提示条(3-4 处)</td>
|
||||
<td class="cut">收敛:状态栏 + 右轨票据卡 + 更新横幅(低频事件)</td>
|
||||
<td>常驻态进状态栏,异常态才升级为横幅/卡片,topbar 不再堆芯片</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>authExpired / 票据</td>
|
||||
<td>顶部橙色横幅(挤占布局)</td>
|
||||
<td class="moved">右轨·授权票据卡(剩余天数 + 刷新)</td>
|
||||
<td>7 天倒计时是持续性状态,横幅只该在临期/过期时出现</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function switchView(v) {
|
||||
document.querySelectorAll('.view').forEach(el => el.classList.toggle('on', el.id === 'view-' + v))
|
||||
document.querySelectorAll('.nv').forEach(el => el.classList.toggle('active', el.dataset.view === v))
|
||||
document.querySelectorAll('.sc-rail').forEach(el => el.classList.toggle('active', v === 'run'))
|
||||
document.querySelector('.center').scrollTop = 0
|
||||
}
|
||||
function setRun(s) {
|
||||
const card = document.getElementById('run-card')
|
||||
card.dataset.state = s
|
||||
card.classList.toggle('live', s === 'running')
|
||||
document.querySelectorAll('.state-pill').forEach(el => el.classList.toggle('on', el.dataset.s === s))
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,603 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 壳子前端 · 重设计提案(Soft Precision)</title>
|
||||
<style>
|
||||
/* ============================================================
|
||||
提案稿 · Soft Precision(精密工作台 × 克制的奶油残留)
|
||||
单文件自包含 · 双主题 · 仅供设计评审
|
||||
============================================================ */
|
||||
:root {
|
||||
/* 中性色(冷灰,替代奶油底) */
|
||||
--canvas: #F4F6F9;
|
||||
--surface: #FFFFFF;
|
||||
--surface-2: #F1F4F8;
|
||||
--surface-3: #E9EDF3;
|
||||
--border: #E4E9F0;
|
||||
--border-strong: #CDD6E1;
|
||||
--text: #182230;
|
||||
--text-sub: #5A6674;
|
||||
--text-faint: #7C8896;
|
||||
/* 主色:保留天蓝家族,但压深到 AA 可读 */
|
||||
--primary: #1E6FA8;
|
||||
--primary-strong: #17608F;
|
||||
--primary-tint: #E9F2FA;
|
||||
--primary-ring: rgba(30, 111, 168, .16);
|
||||
/* 语义色:可读优先 */
|
||||
--ok: #1F8A4C; --ok-tint: #E7F5EC;
|
||||
--err: #D64545; --err-tint: #FBEBEB;
|
||||
--warn: #B26B00; --warn-tint: #FBF3E0;
|
||||
/* 结构 */
|
||||
--r-frame: 14px; --r-card: 12px; --r-ctl: 8px;
|
||||
--sh-sm: 0 1px 2px rgba(15, 23, 42, .05);
|
||||
--sh-md: 0 8px 24px -12px rgba(15, 23, 42, .14);
|
||||
--font: "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif;
|
||||
--mono: "JetBrains Mono", "Cascadia Code", Consolas, monospace;
|
||||
}
|
||||
.frame[data-theme="dark"] {
|
||||
--canvas: #0E1116;
|
||||
--surface: #151A21;
|
||||
--surface-2: #1B222B;
|
||||
--surface-3: #222B37;
|
||||
--border: #27303D;
|
||||
--border-strong: #39465A;
|
||||
--text: #E8EDF4;
|
||||
--text-sub: #9AA7B5;
|
||||
--text-faint: #6E7C8C;
|
||||
--primary: #3E93CF;
|
||||
--primary-strong: #5FA9DE;
|
||||
--primary-tint: #14304A;
|
||||
--primary-ring: rgba(94, 169, 222, .22);
|
||||
--ok: #4CC38A; --ok-tint: #12291C;
|
||||
--err: #E5726F; --err-tint: #2E1717;
|
||||
--warn: #DFA63E; --warn-tint: #2D2312;
|
||||
--sh-sm: 0 1px 2px rgba(0, 0, 0, .3);
|
||||
--sh-md: 0 10px 28px -14px rgba(0, 0, 0, .55);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; background: #E9ECF1; color: #182230;
|
||||
font-family: var(--font); font-size: 14px; line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.dark body, body.dark { background: #0B0E12; color: #E8EDF4; }
|
||||
|
||||
/* ---------- 顶部说明条 ---------- */
|
||||
.intro {
|
||||
max-width: 1240px; margin: 0 auto; padding: 28px 24px 8px;
|
||||
display: flex; align-items: flex-end; justify-content: space-between; gap: 16px;
|
||||
}
|
||||
.intro h1 { margin: 0; font-size: 20px; font-weight: 700; letter-spacing: .01em; }
|
||||
.intro p { margin: 4px 0 0; font-size: 12.5px; color: #5A6674; }
|
||||
body.dark .intro p { color: #9AA7B5; }
|
||||
.theme-toggle {
|
||||
border: 1px solid #CDD6E1; background: #fff; color: #182230;
|
||||
border-radius: 999px; padding: 7px 16px; font-size: 13px; cursor: pointer;
|
||||
font-family: inherit; transition: all .15s ease; white-space: nowrap;
|
||||
}
|
||||
.theme-toggle:hover { border-color: #1E6FA8; color: #1E6FA8; }
|
||||
body.dark .theme-toggle { background: #1B222B; border-color: #39465A; color: #E8EDF4; }
|
||||
body.dark .theme-toggle:hover { border-color: #3E93CF; color: #3E93CF; }
|
||||
|
||||
/* ---------- 应用框架 ---------- */
|
||||
.stage { max-width: 1240px; margin: 20px auto 0; padding: 0 24px; }
|
||||
.frame {
|
||||
border-radius: var(--r-frame);
|
||||
background: var(--canvas);
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: var(--sh-md);
|
||||
overflow: hidden;
|
||||
display: flex; flex-direction: column;
|
||||
height: 780px;
|
||||
transition: background .2s ease, border-color .2s ease;
|
||||
}
|
||||
|
||||
/* 标题栏(提案:frameless 自绘,替换系统标题栏 + 页内 topbar 的双层结构) */
|
||||
.titlebar {
|
||||
height: 40px; flex-shrink: 0;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 0 0 0 14px;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
.titlebar .mark {
|
||||
width: 20px; height: 20px; border-radius: 6px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary); color: #fff;
|
||||
font: 700 9px/1 var(--mono); letter-spacing: .02em;
|
||||
}
|
||||
.titlebar .tname { font-size: 12.5px; font-weight: 600; }
|
||||
.titlebar .tver {
|
||||
font: 500 10.5px/1 var(--mono); color: var(--text-faint);
|
||||
border: 1px solid var(--border); border-radius: 999px; padding: 2px 8px;
|
||||
}
|
||||
.titlebar .tsp { flex: 1; }
|
||||
.win-ctl { display: flex; height: 100%; -webkit-app-region: no-drag; }
|
||||
.win-ctl span {
|
||||
width: 44px; display: grid; place-items: center;
|
||||
color: var(--text-faint); font-size: 11px; cursor: default;
|
||||
}
|
||||
.win-ctl span:hover { background: var(--surface-2); }
|
||||
.win-ctl span.close:hover { background: var(--err); color: #fff; }
|
||||
|
||||
/* 主体三栏 */
|
||||
.shell { flex: 1; display: flex; min-height: 0; }
|
||||
|
||||
/* 左侧导航轨 */
|
||||
.rail {
|
||||
width: 212px; flex-shrink: 0;
|
||||
background: var(--surface);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex; flex-direction: column;
|
||||
padding: 12px 10px;
|
||||
}
|
||||
.nav-sec { display: flex; flex-direction: column; gap: 2px; margin-bottom: 14px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
height: 34px; padding: 0 10px; border-radius: var(--r-ctl);
|
||||
font-size: 13px; color: var(--text-sub); cursor: pointer;
|
||||
position: relative; transition: background .12s ease, color .12s ease;
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-2); color: var(--text); }
|
||||
.nav-item.active { background: var(--primary-tint); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.active::before {
|
||||
content: ''; position: absolute; left: -10px; top: 8px; bottom: 8px;
|
||||
width: 3px; border-radius: 0 3px 3px 0; background: var(--primary);
|
||||
}
|
||||
.nav-item svg { width: 15px; height: 15px; flex-shrink: 0; }
|
||||
.nav-item .nv-badge {
|
||||
margin-left: auto; font: 500 10.5px/1 var(--mono);
|
||||
color: var(--text-faint); background: var(--surface-2);
|
||||
border-radius: 999px; padding: 2px 7px;
|
||||
}
|
||||
.nav-item.active .nv-badge { background: transparent; color: var(--primary); }
|
||||
|
||||
.rail-head {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 0 10px 8px;
|
||||
font-size: 11px; font-weight: 700; letter-spacing: .06em;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
.rail-head .cnt { font: 500 10.5px/1 var(--mono); background: var(--surface-2); border-radius: 999px; padding: 2px 7px; }
|
||||
.scene-nav { flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 1px; }
|
||||
.sn-item {
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
height: 34px; padding: 0 10px; border-radius: var(--r-ctl);
|
||||
cursor: pointer; transition: background .12s ease;
|
||||
}
|
||||
.sn-item:hover { background: var(--surface-2); }
|
||||
.sn-item.active { background: var(--primary-tint); }
|
||||
.sn-item.active .sn-name { color: var(--primary); font-weight: 600; }
|
||||
.sn-dot { width: 22px; height: 22px; border-radius: 6px; flex-shrink: 0; display: grid; place-items: center; font-size: 10.5px; font-weight: 700; }
|
||||
.sn-dot.c1 { background: var(--primary-tint); color: var(--primary); }
|
||||
.sn-dot.c2 { background: var(--warn-tint); color: var(--warn); }
|
||||
.sn-dot.c3 { background: var(--ok-tint); color: var(--ok); }
|
||||
.sn-dot.c4 { background: var(--err-tint); color: var(--err); }
|
||||
.sn-name { flex: 1; font-size: 12.5px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sn-item.active .sn-name { color: var(--primary); }
|
||||
.sn-ver { font: 400 10px/1 var(--mono); color: var(--text-faint); }
|
||||
.rail-foot {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 10px 10px 2px; margin-top: 8px;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
font-size: 11px; color: var(--text-faint);
|
||||
}
|
||||
.rail-foot a { color: var(--primary); text-decoration: none; font-size: 11px; cursor: pointer; }
|
||||
|
||||
/* 内容区 */
|
||||
.content { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.page { flex: 1; min-height: 0; overflow: auto; padding: 22px 26px; }
|
||||
.page-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 14px; margin-bottom: 18px; }
|
||||
.page-head h2 { margin: 0; font-size: 19px; font-weight: 700; letter-spacing: .01em; }
|
||||
.page-head .sub { margin: 4px 0 0; font-size: 12.5px; color: var(--text-faint); }
|
||||
.conn-pill {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
font-size: 11.5px; color: var(--ok);
|
||||
background: var(--ok-tint); border: 1px solid transparent;
|
||||
padding: 5px 12px; border-radius: 999px; font-weight: 500;
|
||||
}
|
||||
.conn-pill i { width: 6px; height: 6px; border-radius: 50%; background: var(--ok); }
|
||||
|
||||
/* 统计行 */
|
||||
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 20px; }
|
||||
.stat {
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-card);
|
||||
padding: 14px 16px; box-shadow: var(--sh-sm);
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
}
|
||||
.st-ic {
|
||||
width: 34px; height: 34px; border-radius: var(--r-ctl); flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.st-ic svg { width: 16px; height: 16px; }
|
||||
.st-ic.sky { background: var(--primary-tint); color: var(--primary); }
|
||||
.st-ic.ok { background: var(--ok-tint); color: var(--ok); }
|
||||
.st-ic.warn { background: var(--warn-tint); color: var(--warn); }
|
||||
.st-ic.err { background: var(--err-tint); color: var(--err); }
|
||||
.st-meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
|
||||
.st-meta b { font: 600 20px/1.1 var(--mono); font-variant-numeric: tabular-nums; letter-spacing: -.02em; }
|
||||
.st-meta b em { font-style: normal; font-size: 12px; color: var(--text-faint); font-weight: 500; }
|
||||
.st-meta span { font-size: 11.5px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* 分节 */
|
||||
.sec { margin-bottom: 20px; }
|
||||
.sec-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
|
||||
.sec-head h3 { margin: 0; font-size: 13px; font-weight: 700; color: var(--text); }
|
||||
.sec-head .more { font-size: 12px; color: var(--primary); cursor: pointer; }
|
||||
.sec-head .note { font-size: 11.5px; color: var(--text-faint); }
|
||||
|
||||
/* 场景卡 */
|
||||
.scenes { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
|
||||
.sc {
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-card);
|
||||
box-shadow: var(--sh-sm);
|
||||
padding: 14px 16px; display: flex; align-items: center; gap: 13px;
|
||||
cursor: pointer; transition: border-color .13s ease, box-shadow .13s ease;
|
||||
font-family: inherit; text-align: left;
|
||||
}
|
||||
.sc:hover { border-color: var(--border-strong); box-shadow: var(--sh-md); }
|
||||
.sc-ic { width: 38px; height: 38px; border-radius: 10px; flex-shrink: 0; display: grid; place-items: center; font-weight: 700; font-size: 15px; }
|
||||
.sc-ic.c1 { background: var(--primary-tint); color: var(--primary); }
|
||||
.sc-ic.c2 { background: var(--warn-tint); color: var(--warn); }
|
||||
.sc-ic.c3 { background: var(--ok-tint); color: var(--ok); }
|
||||
.sc-ic.c4 { background: var(--err-tint); color: var(--err); }
|
||||
.sc-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.sc-body b { font-size: 13.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-desc { font-size: 11.5px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-meta { font-size: 10.5px; color: var(--text-faint); display: flex; align-items: center; gap: 7px; }
|
||||
.sc-meta .ver { font-family: var(--mono); }
|
||||
.sc-meta .plat { color: var(--ok); }
|
||||
.sc-meta .plat.off { color: var(--warn); }
|
||||
.sc-run {
|
||||
flex-shrink: 0; font-size: 12px; font-weight: 600;
|
||||
color: var(--primary); border: 1px solid var(--border-strong);
|
||||
background: var(--surface); border-radius: var(--r-ctl);
|
||||
padding: 6px 14px; transition: all .13s ease;
|
||||
}
|
||||
.sc:hover .sc-run { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
|
||||
/* 最近运行 */
|
||||
.recent { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-card); box-shadow: var(--sh-sm); padding: 4px 6px; }
|
||||
.rec {
|
||||
display: flex; align-items: center; gap: 11px; width: 100%;
|
||||
padding: 9px 10px; border: none; background: transparent; border-radius: var(--r-ctl);
|
||||
font-family: inherit; cursor: pointer; text-align: left;
|
||||
}
|
||||
.rec:hover { background: var(--surface-2); }
|
||||
.rec-ic { width: 20px; height: 20px; border-radius: 50%; flex-shrink: 0; display: grid; place-items: center; font-size: 10px; font-weight: 700; }
|
||||
.rec-ic.ok { background: var(--ok-tint); color: var(--ok); }
|
||||
.rec-ic.err { background: var(--err-tint); color: var(--err); }
|
||||
.rec-name { font-size: 12.5px; font-weight: 600; white-space: nowrap; }
|
||||
.rec-msg { flex: 1; font-size: 12px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.rec-msg.err { color: var(--err); }
|
||||
.rec-time { font: 400 11px/1 var(--mono); color: var(--text-faint); }
|
||||
|
||||
/* 底部日志抽屉(可折叠,替代常驻 230px) */
|
||||
.logdock {
|
||||
flex-shrink: 0; background: var(--surface);
|
||||
border-top: 1px solid var(--border);
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.logdock-head {
|
||||
height: 38px; display: flex; align-items: center; gap: 10px;
|
||||
padding: 0 12px 0 16px; cursor: pointer;
|
||||
}
|
||||
.logdock-head .lt { font-size: 12.5px; font-weight: 700; display: flex; align-items: center; gap: 8px; }
|
||||
.live {
|
||||
font: 600 9.5px/1 var(--mono); letter-spacing: .08em;
|
||||
color: var(--ok); background: var(--ok-tint);
|
||||
padding: 3px 8px; border-radius: 999px;
|
||||
}
|
||||
.lv-tabs { display: flex; gap: 2px; margin-left: 8px; }
|
||||
.lv-tab {
|
||||
font-size: 11px; color: var(--text-faint); padding: 4px 10px;
|
||||
border-radius: 999px; cursor: pointer; border: 1px solid transparent;
|
||||
}
|
||||
.lv-tab.on { background: var(--surface-2); color: var(--text); border-color: var(--border); }
|
||||
.lv-tab:hover { color: var(--text); }
|
||||
.logdock-head .sp { flex: 1; }
|
||||
.logdock-head .tool { font-size: 11.5px; color: var(--text-faint); cursor: pointer; padding: 4px 8px; border-radius: 6px; }
|
||||
.logdock-head .tool:hover { background: var(--surface-2); color: var(--text); }
|
||||
.chev { transition: transform .18s ease; color: var(--text-faint); }
|
||||
.logdock.collapsed .chev { transform: rotate(180deg); }
|
||||
.logdock.collapsed .logdock-body { display: none; }
|
||||
.logdock-body {
|
||||
height: 150px; overflow: auto; padding: 2px 16px 12px;
|
||||
font: 400 12px/1.85 var(--mono);
|
||||
}
|
||||
.logline { display: flex; gap: 12px; }
|
||||
.logline .t { color: var(--text-faint); flex-shrink: 0; }
|
||||
.logline .lv { font-weight: 600; flex-shrink: 0; width: 46px; }
|
||||
.logline .lv.i { color: var(--primary); }
|
||||
.logline .lv.w { color: var(--warn); }
|
||||
.logline .lv.e { color: var(--err); }
|
||||
.logline .m { color: var(--text); word-break: break-all; }
|
||||
.logline.hl { background: var(--surface-2); border-radius: 6px; }
|
||||
.logline.hl .m { color: var(--ok); font-weight: 600; }
|
||||
|
||||
/* 状态栏 */
|
||||
.statusbar {
|
||||
height: 28px; flex-shrink: 0;
|
||||
display: flex; align-items: center; gap: 18px;
|
||||
padding: 0 16px; font-size: 11px; color: var(--text-faint);
|
||||
background: var(--surface); border-top: 1px solid var(--border);
|
||||
}
|
||||
.statusbar .si { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.statusbar i { width: 6px; height: 6px; border-radius: 50%; }
|
||||
.statusbar i.on { background: var(--ok); }
|
||||
.statusbar i.mid { background: var(--warn); }
|
||||
.statusbar .sp { flex: 1; }
|
||||
.statusbar .mono { font-family: var(--mono); }
|
||||
|
||||
/* ---------- Tokens 图鉴 ---------- */
|
||||
.tokens { max-width: 1240px; margin: 40px auto 60px; padding: 0 24px; }
|
||||
.tokens h2 { font-size: 16px; margin: 0 0 14px; }
|
||||
.tok-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
|
||||
.tok-card { background: #fff; border: 1px solid #E4E9F0; border-radius: 12px; padding: 18px 20px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
|
||||
.tok-card h4 { margin: 0 0 12px; font-size: 12px; letter-spacing: .06em; color: #7C8896; text-transform: uppercase; }
|
||||
body.dark .tok-card { background: #151A21; border-color: #27303D; }
|
||||
body.dark .tok-card h4 { color: #6E7C8C; }
|
||||
.swatches { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sw-row { display: flex; align-items: center; gap: 10px; font-size: 12px; }
|
||||
.sw { width: 44px; height: 26px; border-radius: 6px; border: 1px solid rgba(15,23,42,.08); flex-shrink: 0; }
|
||||
.sw-name { width: 130px; color: #5A6674; font-family: var(--mono); font-size: 11.5px; }
|
||||
body.dark .sw-name { color: #9AA7B5; }
|
||||
.sw-note { color: #7C8896; font-size: 11.5px; }
|
||||
.type-row { display: flex; align-items: baseline; gap: 14px; padding: 7px 0; border-bottom: 1px dashed #E4E9F0; }
|
||||
body.dark .type-row { border-color: #27303D; }
|
||||
.type-row:last-child { border-bottom: none; }
|
||||
.type-tag { width: 92px; flex-shrink: 0; font: 500 11px/1 var(--mono); color: #7C8896; }
|
||||
.vs { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; font-size: 12.5px; }
|
||||
.vs .col { border-radius: 10px; padding: 14px 16px; }
|
||||
.vs .old { background: #FBF9F4; border: 1px dashed #E0D9C9; }
|
||||
.vs .new { background: #F4F8FB; border: 1px solid #CBE0EF; }
|
||||
.vs h5 { margin: 0 0 8px; font-size: 12px; }
|
||||
.vs .old h5 { color: #9C9589; }
|
||||
.vs .new h5 { color: #1E6FA8; }
|
||||
.vs ul { margin: 0; padding-left: 16px; color: #5A6674; display: flex; flex-direction: column; gap: 4px; }
|
||||
.foot-note { max-width: 1240px; margin: 0 auto 40px; padding: 0 24px; font-size: 11.5px; color: #7C8896; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="intro">
|
||||
<div>
|
||||
<h1>37du 壳子前端 · 重设计提案 <span style="color:#7C8896;font-weight:500;font-size:13px">Soft Precision</span></h1>
|
||||
<p>精密工作台的秩序 × 天蓝品牌延续 × 奶油感收束为点缀 —— 右上角可切换深浅主题预览</p>
|
||||
</div>
|
||||
<button class="theme-toggle" onclick="document.body.classList.toggle('dark');document.querySelectorAll('.frame').forEach(f=>f.dataset.theme=document.body.classList.contains('dark')?'dark':'light')">◐ 切换深 / 浅主题</button>
|
||||
</div>
|
||||
|
||||
<div class="stage">
|
||||
<div class="frame" data-theme="light">
|
||||
<!-- 标题栏:替代「系统标题栏 + 页内 topbar」双层 -->
|
||||
<div class="titlebar">
|
||||
<span class="mark">37</span>
|
||||
<span class="tname">自动化工作台</span>
|
||||
<span class="tver">v2.3.1</span>
|
||||
<span class="tsp"></span>
|
||||
<div class="win-ctl"><span>—</span><span>▢</span><span class="close">✕</span></div>
|
||||
</div>
|
||||
|
||||
<div class="shell">
|
||||
<!-- 左轨:主导航 + 场景库 -->
|
||||
<aside class="rail">
|
||||
<div class="nav-sec">
|
||||
<div class="nav-item active">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></svg>
|
||||
<span>工作台</span>
|
||||
</div>
|
||||
<div class="nav-item">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
|
||||
<span>定时任务</span>
|
||||
<span class="nv-badge">3</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rail-head"><span>场景库</span><span class="cnt">6</span></div>
|
||||
<div class="scene-nav">
|
||||
<div class="sn-item active"><span class="sn-dot c1">考</span><span class="sn-name">考勤月报封存检查</span><span class="sn-ver">1.4.0</span></div>
|
||||
<div class="sn-item"><span class="sn-dot c2">假</span><span class="sn-name">请假单批量补录</span><span class="sn-ver">0.9.2</span></div>
|
||||
<div class="sn-item"><span class="sn-dot c3">周</span><span class="sn-name">周报数据汇总</span><span class="sn-ver">2.1.0</span></div>
|
||||
<div class="sn-item"><span class="sn-dot c4">邮</span><span class="sn-name">邮件定时巡检</span><span class="sn-ver">1.0.3</span></div>
|
||||
<div class="sn-item"><span class="sn-dot c1">薪</span><span class="sn-name">薪酬条分发</span><span class="sn-ver">1.2.7</span></div>
|
||||
<div class="sn-item"><span class="sn-dot c3">档</span><span class="sn-name">档案归档巡检</span><span class="sn-ver">0.6.1</span></div>
|
||||
</div>
|
||||
<div class="rail-foot"><span>壳子 v2.3.1</span><a>检查更新</a></div>
|
||||
</aside>
|
||||
|
||||
<!-- 主内容 -->
|
||||
<div class="content">
|
||||
<div class="page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h2>早上好,张三</h2>
|
||||
<p class="sub">2025年12月11日 星期四 · 6 个可用场景 · 昨日自动执行 12 次</p>
|
||||
</div>
|
||||
<span class="conn-pill"><i></i>服务已连接</span>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<span class="st-ic sky"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg></span>
|
||||
<div class="st-meta"><b>6</b><span>可用场景</span></div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="st-ic sky"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></span>
|
||||
<div class="st-meta"><b>3</b><span>定时任务</span></div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="st-ic ok"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span>
|
||||
<div class="st-meta"><b>2<em>/2</em></b><span>平台在线</span></div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="st-ic ok"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M8.5 12.5l2.5 2.5 4.5-5"/></svg></span>
|
||||
<div class="st-meta"><b style="font-size:15px;line-height:1.3">执行成功</b><span>考勤月报 · 14:02</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec">
|
||||
<div class="sec-head"><h3>常用场景</h3><span class="more">全部场景 →</span></div>
|
||||
<div class="scenes">
|
||||
<button class="sc">
|
||||
<span class="sc-ic c1">考</span>
|
||||
<span class="sc-body">
|
||||
<b>考勤月报封存检查</b>
|
||||
<span class="sc-desc">抓取当月 OA 考勤原始表,校验异常并封存归档</span>
|
||||
<span class="sc-meta"><span class="ver">v1.4.0</span>·<span class="plat">OA 已登录</span></span>
|
||||
</span>
|
||||
<span class="sc-run">执行</span>
|
||||
</button>
|
||||
<button class="sc">
|
||||
<span class="sc-ic c2">假</span>
|
||||
<span class="sc-body">
|
||||
<b>请假单批量补录</b>
|
||||
<span class="sc-desc">按名单批量补录历史请假单并回写审批状态</span>
|
||||
<span class="sc-meta"><span class="ver">v0.9.2</span>·<span class="plat off">HR 未登录</span></span>
|
||||
</span>
|
||||
<span class="sc-run">执行</span>
|
||||
</button>
|
||||
<button class="sc">
|
||||
<span class="sc-ic c3">周</span>
|
||||
<span class="sc-body">
|
||||
<b>周报数据汇总</b>
|
||||
<span class="sc-desc">拉取各部门周报并生成汇总看板快照</span>
|
||||
<span class="sc-meta"><span class="ver">v2.1.0</span>·<span class="plat">OA 已登录</span></span>
|
||||
</span>
|
||||
<span class="sc-run">执行</span>
|
||||
</button>
|
||||
<button class="sc">
|
||||
<span class="sc-ic c4">邮</span>
|
||||
<span class="sc-body">
|
||||
<b>邮件定时巡检</b>
|
||||
<span class="sc-desc">巡检公共邮箱未读工单并推送提醒</span>
|
||||
<span class="sc-meta"><span class="ver">v1.0.3</span>·<span class="plat">MAIL 已登录</span></span>
|
||||
</span>
|
||||
<span class="sc-run">执行</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec">
|
||||
<div class="sec-head"><h3>最近动态</h3><span class="note">最近 3 次执行</span></div>
|
||||
<div class="recent">
|
||||
<button class="rec">
|
||||
<span class="rec-ic ok">✓</span><span class="rec-name">考勤月报封存检查</span>
|
||||
<span class="rec-msg">执行完成 · 生成报表 1 份,2 行异常待复核</span>
|
||||
<span class="rec-time">14:02</span>
|
||||
</button>
|
||||
<button class="rec">
|
||||
<span class="rec-ic ok">✓</span><span class="rec-name">周报数据汇总</span>
|
||||
<span class="rec-msg">执行完成 · 已同步快照至中心机</span>
|
||||
<span class="rec-time">09:31</span>
|
||||
</button>
|
||||
<button class="rec">
|
||||
<span class="rec-ic err">✕</span><span class="rec-name">请假单批量补录</span>
|
||||
<span class="rec-msg err">登录态失效:HR 会话已过期,请重新登录平台</span>
|
||||
<span class="rec-time">09:12</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日志抽屉:可折叠,不再常驻占高 -->
|
||||
<div class="logdock" id="logdock">
|
||||
<div class="logdock-head" onclick="document.getElementById('logdock').classList.toggle('collapsed')">
|
||||
<span class="lt">运行日志 <span class="live">● LIVE</span></span>
|
||||
<div class="lv-tabs" onclick="event.stopPropagation()">
|
||||
<span class="lv-tab on">全部</span><span class="lv-tab">INFO</span><span class="lv-tab">WARN</span><span class="lv-tab">ERROR</span>
|
||||
</div>
|
||||
<span class="sp"></span>
|
||||
<span class="tool">复制</span><span class="tool">清空</span>
|
||||
<svg class="chev" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="m6 14 6-6 6 6"/></svg>
|
||||
</div>
|
||||
<div class="logdock-body">
|
||||
<div class="logline"><span class="t">14:02:01</span><span class="lv i">INFO</span><span class="m">[考勤月报] 启动 Chrome 会话,加载 OA 首页</span></div>
|
||||
<div class="logline"><span class="t">14:02:07</span><span class="lv i">INFO</span><span class="m">登录态校验通过(cookie 有效)</span></div>
|
||||
<div class="logline"><span class="t">14:02:09</span><span class="lv i">INFO</span><span class="m">进入 考勤月报 → 2025-11,开始抓取表格</span></div>
|
||||
<div class="logline"><span class="t">14:02:24</span><span class="lv w">WARN</span><span class="m">抓取到 2 行异常打卡,已标记待人工复核</span></div>
|
||||
<div class="logline"><span class="t">14:02:31</span><span class="lv i">INFO</span><span class="m">报表封存完成,已生成 ZIP 并回传中心机</span></div>
|
||||
<div class="logline hl"><span class="t">14:02:32</span><span class="lv i">INFO</span><span class="m">===== 执行完成 =====(耗时 31s)</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 状态栏:收纳原 topbar 里的零散芯片 -->
|
||||
<div class="statusbar">
|
||||
<span class="si"><i class="on"></i>服务已连接</span>
|
||||
<span class="si"><i class="on"></i>Chrome 131 已就绪</span>
|
||||
<span class="si"><i class="mid"></i>授权剩余 5 天</span>
|
||||
<span class="sp"></span>
|
||||
<span class="mono">插件同步 2 分钟前</span>
|
||||
<span class="mono">127.0.0.1:8765</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ---------- Tokens 图鉴 ---------- -->
|
||||
<div class="tokens">
|
||||
<h2>设计 Token 图鉴</h2>
|
||||
<div class="tok-grid">
|
||||
<div class="tok-card">
|
||||
<h4>色彩 · 主色与语义(全部过 AA 对比度)</h4>
|
||||
<div class="swatches">
|
||||
<div class="sw-row"><span class="sw" style="background:#17608F"></span><span class="sw-name">primary-strong</span><span class="sw-note">按钮底色,白字 5.9:1</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#1E6FA8"></span><span class="sw-name">primary</span><span class="sw-note">链接 / 激活态 / 图标</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#E9F2FA"></span><span class="sw-name">primary-tint</span><span class="sw-note">选中底 / 色块容器</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#1F8A4C"></span><span class="sw-name">ok</span><span class="sw-note">成功 · 白字 4.8:1</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#D64545"></span><span class="sw-name">err</span><span class="sw-note">错误 · 替代过浅的 #E58B8B</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#B26B00"></span><span class="sw-name">warn</span><span class="sw-note">警告 · 白字 5.1:1</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tok-card">
|
||||
<h4>字体 · 收敛为 7 档,数字一律等宽</h4>
|
||||
<div class="type-row"><span class="type-tag">28 / 700</span><span style="font-size:28px;font-weight:700;letter-spacing:-.02em">28 页面大数字</span></div>
|
||||
<div class="type-row"><span class="type-tag">20 / 700</span><span style="font-size:20px;font-weight:700">20 页面标题</span></div>
|
||||
<div class="type-row"><span class="type-tag">16 / 600</span><span style="font-size:16px;font-weight:600">16 卡片区块标题</span></div>
|
||||
<div class="type-row"><span class="type-tag">14 / 600</span><span style="font-size:14px;font-weight:600">14 列表主文本</span></div>
|
||||
<div class="type-row"><span class="type-tag">13 / 400</span><span style="font-size:13px">13 正文基准</span></div>
|
||||
<div class="type-row"><span class="type-tag">12 / 400</span><span style="font-size:12px;color:#5A6674">12 辅助说明(下限)</span></div>
|
||||
<div class="type-row"><span class="type-tag">mono</span><span style="font-family:var(--mono);font-size:13px">v1.4.0 · 0 8 * * * · 14:02:31</span></div>
|
||||
</div>
|
||||
<div class="tok-card">
|
||||
<h4>结构 · 发丝线优先,阴影只做两层</h4>
|
||||
<div class="swatches">
|
||||
<div class="sw-row"><span class="sw" style="background:#fff;border:1px solid #E4E9F0"></span><span class="sw-name">surface + hairline</span><span class="sw-note">1px 边线替代大部分投影</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:#F1F4F8;border:1px solid #E4E9F0"></span><span class="sw-name">surface-2</span><span class="sw-note">hover / 次级容器</span></div>
|
||||
<div class="sw-row"><span class="sw" style="background:linear-gradient(180deg,#fff,#FBFCFE);box-shadow:0 8px 24px -12px rgba(15,23,42,.14)"></span><span class="sw-name">shadow-md</span><span class="sw-note">仅悬浮卡片与弹层使用</span></div>
|
||||
<div class="sw-row"><span class="sw" style="border-radius:12px"></span><span class="sw-name">radius 12 / 8</span><span class="sw-note">卡片 12 · 控件 8(从 16-22 收敛)</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tok-card">
|
||||
<h4>方向对照 · 为什么改</h4>
|
||||
<div class="vs">
|
||||
<div class="col old">
|
||||
<h5>现状 · 奶油治愈风</h5>
|
||||
<ul>
|
||||
<li>登录页=科技终端,工作台=可爱手账,身份分裂</li>
|
||||
<li>主按钮浅蓝底白字 ≈2:1,对比度不达标</li>
|
||||
<li>10.5px 小字遍地、字号 17 档碎片化</li>
|
||||
<li>窗口卡片套卡片,四层圆角互相打架</li>
|
||||
<li>浮动涂鸦 + 面板 hover 上浮,工具感被稀释</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="col new">
|
||||
<h5>提案 · Soft Precision</h5>
|
||||
<ul>
|
||||
<li>冷灰画布 + 发丝线,主色压深保品牌色相</li>
|
||||
<li>一套 token 管到底,深浅主题同源切换</li>
|
||||
<li>自绘标题栏 + 状态栏,像原生桌面应用</li>
|
||||
<li>日志改可折叠抽屉,状态芯片收进状态栏</li>
|
||||
<li>动效只留 120-180ms 交互反馈,去掉常驻漂浮</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="foot-note">提案稿 · 静态预览(单文件 HTML,数据为虚构示例)· 评审通过后按「token 层 → 布局壳 → 组件」三步落地到 Vue 组件</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<!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
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "37du-shell-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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,903 @@
|
||||
<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>
|
||||
<!-- 顶栏已拆分融入三栏:品牌→左轨 / 账号→右轨 / Chrome→状态栏 -->
|
||||
<!-- 主体:左场景轨 | 中上下文(总览/运行台/计划)| 右活动流 -->
|
||||
<div class="body">
|
||||
<!-- 左:品牌 + 场景轨(主导航 + 场景库) -->
|
||||
<aside class="rail side">
|
||||
<div class="side-brand">
|
||||
<span class="logo">37</span>
|
||||
<strong>{{ store.appName }}</strong>
|
||||
</div>
|
||||
<nav class="nav-main">
|
||||
<div class="nav-item" :class="{ active: store.view === 'overview' }" @click="openOverview">
|
||||
<el-icon><HomeFilled /></el-icon><span>总览</span>
|
||||
</div>
|
||||
<div class="nav-item" :class="{ active: store.view === 'scenes' }" @click="openScenes">
|
||||
<el-icon><Grid /></el-icon><span>场景</span>
|
||||
</div>
|
||||
<div class="nav-item" :class="{ active: store.view === 'plans' }" @click="openPlans">
|
||||
<el-icon><Clock /></el-icon><span>计划</span>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- 场景库 -->
|
||||
<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 === 'run' }"
|
||||
@click="openRun(p.id)"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: grad(i) }">
|
||||
{{ 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>
|
||||
</aside>
|
||||
|
||||
<!-- 中:上下文区(视图路由) -->
|
||||
<main class="rail main">
|
||||
<div class="page-scroll">
|
||||
<HomePage v-if="store.view === 'overview'" />
|
||||
<ScenesPage v-else-if="store.view === 'scenes'" />
|
||||
<PluginPage v-else-if="store.view === 'run'" />
|
||||
<SchedulePage v-else-if="store.view === 'plans'" />
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- 右:账号 + 活动流(当前运行 + 最近运行;只回显,细节在运行台) -->
|
||||
<aside class="rail activity">
|
||||
<div class="act-acct">
|
||||
<span class="acct-display">
|
||||
<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>
|
||||
</span>
|
||||
<div class="acct-ops">
|
||||
<el-tooltip content="修改密码" placement="top">
|
||||
<el-button size="small" text :icon="Key" @click="pwdDlg = true" />
|
||||
</el-tooltip>
|
||||
<el-button size="small" round @click="logout">登出</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="act-head">
|
||||
<span class="sec-title">活动</span>
|
||||
<span v-if="store.running" class="act-live">● 运行中</span>
|
||||
</div>
|
||||
|
||||
<div class="act-now" :class="{ on: store.running }">
|
||||
<template v-if="store.running">
|
||||
<div class="an-top">
|
||||
<span class="an-name">{{ runningName }}</span>
|
||||
<span class="an-pct">{{ store.progress }}%</span>
|
||||
</div>
|
||||
<el-progress :percentage="store.progress" :show-text="false" :stroke-width="6" color="var(--primary)" />
|
||||
<div class="an-tail">
|
||||
<div v-for="(l, i) in tailLogs" :key="i" class="an-line">
|
||||
<span class="lv" :class="'s-' + (l.level || 'INFO')">{{ l.level || 'INFO' }}</span>
|
||||
<span class="an-msg">{{ l.msg }}</span>
|
||||
</div>
|
||||
<div v-if="!tailLogs.length" class="an-wait">等待输出…</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="an-idle">
|
||||
<span class="an-idle-ic">✓</span>
|
||||
<div class="an-idle-meta">
|
||||
<b>当前空闲</b>
|
||||
<span>{{ lastRunText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="act-head act-head-2">
|
||||
<span class="sec-title">最近运行</span>
|
||||
<span v-if="store.recents.length" class="count">{{ store.recents.length }}</span>
|
||||
</div>
|
||||
<ul class="act-list">
|
||||
<li v-for="(r, i) in store.recents" :key="i" @click="openRun(r.pluginId, r.runId)">
|
||||
<span class="act-dot" :class="r.ok ? 'ok' : 'err'"></span>
|
||||
<div class="act-meta">
|
||||
<b>{{ r.name }}</b>
|
||||
<span>{{ r.ok ? '完成' : (r.error || '失败') }}</span>
|
||||
</div>
|
||||
<em>{{ r.time }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.recents.length" class="act-empty">本次会话暂无运行记录</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- 状态栏:机器与授权事实(品牌/账号已融入左右轨;Chrome 状态也在此) -->
|
||||
<footer class="statusbar">
|
||||
<span v-if="chromeVis" class="sb-item chrome-sb" :class="chromeInstalled ? 'ok' : 'warn'"
|
||||
:title="chromeTip" @click="onChromeClick">
|
||||
<i class="sb-dot"></i>{{ chromeLabel }}
|
||||
</span>
|
||||
<span v-if="chromeVis" class="sb-sep"></span>
|
||||
<span class="sb-item" :class="licenseCls"><i class="sb-dot"></i>{{ licenseText }}</span>
|
||||
<span class="sb-sep"></span>
|
||||
<span class="sb-item" :class="store.wsOn ? 'ok' : 'warn'">
|
||||
<i class="sb-dot"></i>{{ store.wsOn ? '本地服务已连接' : '本地服务重连中' }}
|
||||
</span>
|
||||
<span class="sb-sep"></span>
|
||||
<span class="sb-item mono">{{ localAddr }}</span>
|
||||
<span class="sb-spacer"></span>
|
||||
<span class="sb-item">壳子 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }}</span>
|
||||
<el-link type="primary" :underline="false" class="sb-link"
|
||||
:disabled="shellChecking" @click="onShellCheck">
|
||||
{{ shellChecking ? '检查中…' : '检查更新' }}
|
||||
</el-link>
|
||||
</footer>
|
||||
</div>
|
||||
<ChangePasswordDialog v-if="pwdDlg" @close="pwdDlg = 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, HomeFilled, Refresh, Key, Grid } from '@element-plus/icons-vue'
|
||||
import HomePage from './components/HomePage.vue'
|
||||
import ScenesPage from './components/ScenesPage.vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import SchedulePage from './components/SchedulePage.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ChangePasswordDialog from './components/ChangePasswordDialog.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache, accountAvatar } from './store'
|
||||
import { connectWS, fetchMeta, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate, checkShellUpdate, downloadShellUpdate, getChromeStatus, checkChrome, downloadChrome, installChrome } from './api'
|
||||
|
||||
// 场景图标:奶油系柔和渐变(与总览首页/场景页共用同一套色板)
|
||||
const GRADS = [
|
||||
'var(--grad-sky)', 'var(--grad-peach)', 'var(--grad-mint)',
|
||||
'var(--grad-lilac)', 'var(--grad-honey)', 'var(--grad-blush)',
|
||||
]
|
||||
function grad(i) { return GRADS[i % GRADS.length] }
|
||||
|
||||
// 顶栏头像加载失败:清除缓存返回首字符兜底
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
// ===== 三栏骨架:视图路由(总览 / 运行台 / 计划)=====
|
||||
function openRun(id, runId) {
|
||||
store.selectedId = id
|
||||
store.view = 'run'
|
||||
// 活动流「最近运行」点击:直达该次运行的回看(运行台消费后清空);
|
||||
// 左栏场景点击不带 runId,顺带清掉可能残留的回看意图
|
||||
store.pendingReplay = runId ? { pluginId: id, runId } : null
|
||||
}
|
||||
|
||||
function openOverview() {
|
||||
store.view = 'overview'
|
||||
}
|
||||
|
||||
function openScenes() {
|
||||
store.view = 'scenes'
|
||||
}
|
||||
|
||||
function openPlans() {
|
||||
store.view = 'plans'
|
||||
}
|
||||
|
||||
// ===== 右栏活动流 + 底栏状态:由现有 store 派生,不引入新请求 =====
|
||||
// 当前运行中的场景名(run_start 已把 run_id→plugin_id 登记在 store._runPlugins)
|
||||
const runningName = computed(() => {
|
||||
const pid = store._runPlugins[store.currentRun] || store.selectedId
|
||||
return (store.plugins.find((p) => p.id === pid) || {}).name || '正在执行'
|
||||
})
|
||||
// 运行中:右栏只回显最近几条日志,细节仍在运行台「运行日志」标签页
|
||||
const tailLogs = computed(() => store.logs.slice(-4))
|
||||
const lastRunText = computed(() => {
|
||||
const r = store.recents[0]
|
||||
if (!r) return '本次会话暂无运行记录'
|
||||
return `上次 ${r.name} · ${r.time}`
|
||||
})
|
||||
const localAddr = computed(() => (typeof location !== 'undefined' ? location.host : ''))
|
||||
|
||||
// 授权票据概要(状态栏):后端 /api/meta 的 license 字段
|
||||
const licenseText = computed(() => {
|
||||
const l = store.license
|
||||
if (!l || !l.status || l.status === 'missing') return '未授权'
|
||||
if (l.status === 'invalid') return '授权无效'
|
||||
if (l.status === 'expired') return '授权已过期'
|
||||
if (l.days_left === null || l.days_left === undefined) return '授权有效'
|
||||
return `授权有效 · 剩余 ${l.days_left} 天`
|
||||
})
|
||||
const licenseCls = computed(() => {
|
||||
const s = store.license && store.license.status
|
||||
if (s === 'ok') return 'ok'
|
||||
if (s === 'expired' || s === 'invalid') return 'err'
|
||||
return 'warn'
|
||||
})
|
||||
|
||||
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.license = meta.license || null
|
||||
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
|
||||
})
|
||||
// 常驻显示:只要后端返回过 Chrome 状态就展示(已安装绿色版本号 / 未安装橙色入口)
|
||||
const chromeVis = computed(() => 'installed' in chrome.value)
|
||||
|
||||
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 pwdDlg = ref(false)
|
||||
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
|
||||
store.license = meta.license || null
|
||||
// 选中场景不存在(被同步清理/授权收回)时回落到第一个可用场景
|
||||
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 (_) {}
|
||||
}
|
||||
</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: 18px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: var(--on-primary);
|
||||
font-size: 20px; font-weight: 800;
|
||||
box-shadow: 0 10px 26px -8px rgba(var(--primary-rgb),.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); } }
|
||||
|
||||
.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(var(--primary-rgb), .5);
|
||||
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); font-size: 13px; line-height: 1.6; }
|
||||
|
||||
/* ---------- 左轨:品牌(原顶栏品牌区融入) ---------- */
|
||||
.side-brand {
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
padding: 2px 8px 12px;
|
||||
}
|
||||
.side-brand .logo {
|
||||
width: 28px; height: 28px; border-radius: 8px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: var(--on-primary);
|
||||
font-size: 12px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(var(--primary-rgb),.6);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.side-brand strong { font-size: 13.5px; font-weight: 700; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* ---------- 右轨:账号条(原顶栏账号区融入) ---------- */
|
||||
.act-acct {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
||||
padding: 2px 4px 10px;
|
||||
}
|
||||
.act-acct {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
||||
padding: 2px 4px 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.act-acct .acct-display {
|
||||
display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1;
|
||||
}
|
||||
.act-acct .acct-avatar { flex-shrink: 0; }
|
||||
.act-acct .acct-avatar-fb { font-size: 12px; font-weight: 700; }
|
||||
.act-acct .acct-name {
|
||||
font-size: 12.5px; font-weight: 600; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.act-acct .acct-ops { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
|
||||
.act-acct .acct-ops .el-button + .el-button { margin-left: 0; }
|
||||
|
||||
.auth-expired-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: var(--warn-bg);
|
||||
border: 1px solid rgba(var(--warn-rgb), .45);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: var(--warn-text);
|
||||
}
|
||||
.auth-expired-bar .ae-txt { flex: 1; }
|
||||
|
||||
/* 状态栏里的 Chrome 状态:可点击(检测/下载/安装) */
|
||||
.chrome-sb { cursor: pointer; }
|
||||
.chrome-sb:hover { color: var(--primary); }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
/* 三栏骨架的结构面板:静态面板不做 hover 上浮(大面板浮动会晃) */
|
||||
.rail {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.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: var(--tile-fg); 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); }
|
||||
/* ---------- 右栏:活动流 ---------- */
|
||||
.activity {
|
||||
width: 268px; flex-shrink: 0;
|
||||
display: flex; flex-direction: column;
|
||||
padding: 14px 12px; min-height: 0;
|
||||
}
|
||||
.act-head { display: flex; align-items: center; justify-content: space-between; padding: 0 6px 10px; }
|
||||
.act-head-2 { padding-top: 14px; margin-top: 12px; border-top: 1px dashed var(--border); }
|
||||
.act-live { font-size: 10.5px; color: var(--ok); animation: actBlink 1s infinite; }
|
||||
@keyframes actBlink { 50% { opacity: .25; } }
|
||||
|
||||
.act-now {
|
||||
border: 1px solid var(--border); border-radius: var(--radius-sm);
|
||||
background: var(--surface-2); padding: 11px 12px;
|
||||
display: flex; flex-direction: column; gap: 9px;
|
||||
}
|
||||
.act-now.on { background: var(--primary-tint); border-color: var(--primary-line); }
|
||||
.an-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.an-name { font-size: 12.5px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.an-pct { font-size: 12px; font-weight: 700; color: var(--primary); font-variant-numeric: tabular-nums; flex-shrink: 0; }
|
||||
.an-tail { display: flex; flex-direction: column; gap: 3px; max-height: 88px; overflow: hidden; }
|
||||
.an-line { display: flex; gap: 6px; font-size: 11px; line-height: 1.5; font-family: var(--mono); }
|
||||
.an-line .lv { flex-shrink: 0; font-weight: 700; }
|
||||
.an-line .s-INFO { color: var(--primary); }
|
||||
.an-line .s-WARN { color: var(--warn); }
|
||||
.an-line .s-ERROR { color: var(--err); }
|
||||
.an-msg { color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.an-wait { font-size: 11px; color: var(--text-faint); }
|
||||
.an-idle { display: flex; align-items: center; gap: 10px; }
|
||||
.an-idle-ic {
|
||||
width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;
|
||||
display: grid; place-items: center; font-size: 12px; font-weight: 700;
|
||||
background: var(--ok-weak); color: var(--ok);
|
||||
}
|
||||
.an-idle-meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
|
||||
.an-idle-meta b { font-size: 12.5px; color: var(--text); }
|
||||
.an-idle-meta span { font-size: 11px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
.act-list { list-style: none; margin: 0; padding: 0; flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.act-list li {
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
padding: 8px 9px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
transition: background .13s;
|
||||
}
|
||||
.act-list li:hover { background: var(--surface-2); }
|
||||
.act-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
|
||||
.act-dot.ok { background: var(--ok); }
|
||||
.act-dot.err { background: var(--err); }
|
||||
.act-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||||
.act-meta b { font-size: 12px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.act-meta span { font-size: 10.5px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.act-list em { font-style: normal; font-size: 10px; color: var(--text-faint); font-variant-numeric: tabular-nums; flex-shrink: 0; }
|
||||
.act-empty { font-size: 11.5px; color: var(--text-faint); text-align: center; padding: 18px 8px; line-height: 1.8; }
|
||||
|
||||
/* ---------- 底栏:状态栏 ---------- */
|
||||
.statusbar {
|
||||
flex-shrink: 0; margin-top: 12px;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 7px 14px;
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 11.5px; color: var(--text-sub);
|
||||
}
|
||||
.sb-item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.sb-item.mono { font-family: var(--mono); font-size: 11px; color: var(--text-faint); }
|
||||
.sb-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--dot-off); flex-shrink: 0; }
|
||||
.sb-item.ok { color: var(--ok-text); }
|
||||
.sb-item.ok .sb-dot { background: var(--ok); box-shadow: 0 0 0 3px var(--ok-weak); }
|
||||
.sb-item.warn { color: var(--warn-text); }
|
||||
.sb-item.warn .sb-dot { background: var(--warn); }
|
||||
.sb-item.err { color: var(--danger); }
|
||||
.sb-item.err .sb-dot { background: var(--err); }
|
||||
.sb-sep { width: 1px; height: 12px; background: var(--border); flex-shrink: 0; }
|
||||
.sb-spacer { flex: 1; }
|
||||
.sb-link { font-size: 11px; vertical-align: baseline; }
|
||||
|
||||
/* 窄窗(如分屏):收起右栏,保证中栏可用宽度 */
|
||||
@media (max-width: 1240px) {
|
||||
.activity { display: none; }
|
||||
}
|
||||
.nav-main {
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
padding: 0 4px 12px; margin-bottom: 10px;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.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, transform .13s ease;
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-2); transform: translateX(2px); }
|
||||
.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);
|
||||
}
|
||||
.nav-item .el-icon { font-size: 15px; }
|
||||
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
/* 中栏上下文区:视图自己决定是否填满(总览/计划自然高度并整体滚动,运行台填满内部滚) */
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; display: flex; flex-direction: column; }
|
||||
</style>
|
||||
@@ -0,0 +1,172 @@
|
||||
// 与 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 listRollbacks() {
|
||||
return j('/api/plugins/rollback')
|
||||
}
|
||||
export async function rollbackPlugin(id) {
|
||||
return j(`/api/plugins/rollback/${encodeURIComponent(id)}`, { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 场景配置方案(多配置,SQLite 存储) =====
|
||||
export async function listPluginConfigs(pluginId) {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(pluginId)}`)
|
||||
}
|
||||
export async function savePluginConfig(pluginId, name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, name, fields }),
|
||||
})
|
||||
}
|
||||
export async function deletePluginConfig(pluginId, cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(pluginId)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
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 getPlatformStatus() {
|
||||
return j('/api/platforms/status')
|
||||
}
|
||||
|
||||
// 保存当前账号的 HR/OA 账号密码(本机加密);pass 留空表示保留原密码
|
||||
export async function savePlatformCreds(payload) {
|
||||
return j('/api/platforms/creds', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
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 fetchRuns(limit = 30) {
|
||||
return j(`/api/runs?limit=${limit}`)
|
||||
}
|
||||
|
||||
// ===== 定时任务(壳子内置定时,配置自动备份中心机) =====
|
||||
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 })
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<template>
|
||||
<el-dialog v-model="visible" title="修改密码" width="380px" align-center @close="emit('close')">
|
||||
<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="请输入旧密码" @keyup.enter="changePwd" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" @keyup.enter="changePwd" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" @keyup.enter="changePwd" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
const visible = ref(true)
|
||||
|
||||
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('密码已修改,下次登录请使用新密码')
|
||||
visible.value = false
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
</style>
|
||||
@@ -0,0 +1,242 @@
|
||||
<template>
|
||||
<div class="home">
|
||||
<!-- 指标行:压缩首屏信息密度(替代问候区与统计卡) -->
|
||||
<section class="kpis">
|
||||
<div class="kpi">
|
||||
<b>{{ store.plugins.length }}<em> 场景</em></b>
|
||||
<span>可用场景</span>
|
||||
</div>
|
||||
<div class="kpi">
|
||||
<b>{{ scheduleCount }}<em> 任务</em></b>
|
||||
<span>定时任务</span>
|
||||
</div>
|
||||
<div class="kpi" :class="onlineCount ? 'ok' : ''">
|
||||
<b>{{ onlineCount }}<em>/{{ store.platforms.length }}</em></b>
|
||||
<span>平台在线</span>
|
||||
</div>
|
||||
<div class="kpi" :class="lastOk === null ? '' : (lastOk ? 'ok' : 'err')">
|
||||
<b>{{ lastOk === null ? '—' : (lastOk ? '成功' : '失败') }}</b>
|
||||
<span>{{ lastRunTime || '暂无运行' }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 平台账号(当前登录人的 HR/OA 账号与登录状态,登录后场景按本人身份执行) -->
|
||||
<section class="block">
|
||||
<div class="block-head">
|
||||
<span class="sec-title">平台账号</span>
|
||||
<span class="rec-note">配置你自己的 HR/OA 账号</span>
|
||||
</div>
|
||||
<PlatformAccounts />
|
||||
</section>
|
||||
|
||||
<!-- 常用场景(只放前 6 个快捷入口,全部走「场景」视图) -->
|
||||
<section class="block">
|
||||
<div class="block-head">
|
||||
<span class="sec-title">常用场景</span>
|
||||
<el-button v-if="store.plugins.length > 6" text size="small" class="more" @click="goScenes">
|
||||
全部场景 {{ store.plugins.length }} <el-icon><ArrowRight /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-if="store.plugins.length" class="scenes" :style="{ '--n': Math.min(4, store.plugins.length) }">
|
||||
<button
|
||||
v-for="(p, i) in store.plugins.slice(0, 6)" :key="p.id" class="sc card"
|
||||
:class="{ running: store.running && store.selectedId === p.id }"
|
||||
@click="openPlugin(p.id)"
|
||||
>
|
||||
<span class="sc-ic" :style="{ background: grad(i) }">{{ p.name.slice(0, 1) }}</span>
|
||||
<span class="sc-body">
|
||||
<b>{{ p.name }}</b>
|
||||
<span class="sc-meta">
|
||||
v{{ p.version }}
|
||||
<template v-if="p.platform">
|
||||
<i class="sep-dot"></i>{{ platformLabel(p.platform) }}
|
||||
<em class="plat-state" :class="{ on: platformOnline(p.platform) }">
|
||||
{{ platformOnline(p.platform) ? '已登录' : '未登录' }}
|
||||
</em>
|
||||
</template>
|
||||
</span>
|
||||
</span>
|
||||
<span class="sc-go">
|
||||
<template v-if="store.running && store.selectedId === p.id">{{ store.progress }}%</template>
|
||||
<template v-else>执行</template>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="empty card">
|
||||
<span class="empty-emoji">🤍</span>
|
||||
<div>
|
||||
<b>当前账号暂无可用场景</b>
|
||||
<span>请联系管理员在控制面进行授权,授权后点击右上角刷新</span>
|
||||
</div>
|
||||
<el-button size="small" round type="primary" plain @click="goScenes">去同步</el-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 最近动态 -->
|
||||
<section class="block" v-if="store.recents.length">
|
||||
<div class="block-head">
|
||||
<span class="sec-title">最近动态</span>
|
||||
<span class="rec-note">最近 {{ store.recents.length }} 次执行</span>
|
||||
</div>
|
||||
<div class="recent card">
|
||||
<button v-for="(r, i) in store.recents" :key="i" class="rec" @click="openPlugin(r.pluginId, r.runId)">
|
||||
<span class="rec-ic" :class="r.ok ? 'ok' : 'err'">{{ r.ok ? '✓' : '✕' }}</span>
|
||||
<span class="rec-name">{{ r.name }}</span>
|
||||
<span class="rec-msg" :class="r.ok ? 'ok' : 'err'">{{ r.ok ? '执行完成' : (r.error || '执行失败') }}</span>
|
||||
<span class="rec-time">{{ r.time }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowRight } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
import { listSchedules } from '../api'
|
||||
import PlatformAccounts from './PlatformAccounts.vue'
|
||||
|
||||
const GRADS = [
|
||||
'var(--grad-sky)', 'var(--grad-peach)', 'var(--grad-mint)',
|
||||
'var(--grad-lilac)', 'var(--grad-honey)', 'var(--grad-blush)',
|
||||
]
|
||||
|
||||
function grad(i) { return GRADS[i % GRADS.length] }
|
||||
|
||||
const scheduleCount = ref(0)
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const r = await listSchedules()
|
||||
scheduleCount.value = (r.schedules || []).length
|
||||
} catch (_) { scheduleCount.value = 0 }
|
||||
})
|
||||
|
||||
const onlineCount = computed(() => (store.platforms || []).filter((p) => p.online).length)
|
||||
|
||||
const lastOk = computed(() => (store.lastResult ? !!store.lastResult.ok : null))
|
||||
const lastRunTime = computed(() => {
|
||||
const r = store.recents[0]
|
||||
return r ? r.time : ''
|
||||
})
|
||||
|
||||
function platformLabel(id) {
|
||||
return (store.platforms.find((p) => p.id === id) || {}).label || id
|
||||
}
|
||||
function platformOnline(id) {
|
||||
return !!(store.platforms.find((p) => p.id === id) || {}).online
|
||||
}
|
||||
function openPlugin(id, runId) {
|
||||
store.selectedId = id
|
||||
store.view = 'run'
|
||||
// 最近动态点击:直达该次运行的回看(运行台消费后清空);普通场景点击清掉残留意图
|
||||
store.pendingReplay = runId ? { pluginId: id, runId } : null
|
||||
}
|
||||
function goScenes() {
|
||||
store.view = 'scenes'
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.home { display: flex; flex-direction: column; gap: 20px; padding: 4px 2px 10px; flex-shrink: 0; }
|
||||
|
||||
/* ---------- 指标行(紧凑,替代问候区/统计卡) ---------- */
|
||||
.kpis { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
.kpi {
|
||||
flex: 1; min-width: 150px;
|
||||
display: flex; align-items: baseline; gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
.kpi b { font-size: 17px; font-weight: 700; color: var(--text); font-variant-numeric: tabular-nums; line-height: 1.1; }
|
||||
.kpi b em { font-style: normal; font-size: 11px; color: var(--text-faint); font-weight: 500; }
|
||||
.kpi span { margin-left: auto; font-size: 11px; color: var(--text-faint); white-space: nowrap; }
|
||||
.kpi.ok b { color: var(--ok); }
|
||||
.kpi.err b { color: var(--err); }
|
||||
|
||||
/* ---------- 分节 ---------- */
|
||||
.block { display: flex; flex-direction: column; gap: 10px; container-type: inline-size; }
|
||||
.block-head { display: flex; align-items: center; justify-content: space-between; padding: 0 2px; }
|
||||
.more { color: var(--text-faint); }
|
||||
.more:hover { color: var(--primary); }
|
||||
.rec-note { font-size: 11px; color: var(--text-faint); }
|
||||
|
||||
/* ---------- 场景卡:列数 = min(4, 场景数),按实际数量均分并占满整行;
|
||||
间隔数随列数变化,2 个场景即 2 列(与上方 2 列平台账号完全对齐);
|
||||
容器变窄时先降为 2 列、再降 1 列,避免卡片过窄 ---------- */
|
||||
.scenes {
|
||||
--max: 4;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(min(var(--max), var(--n, 1)), 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
@container (max-width: 620px) { .scenes { --max: 2; } }
|
||||
@container (max-width: 380px) { .scenes { --max: 1; } }
|
||||
.sc {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 13px; text-align: left;
|
||||
cursor: pointer; font-family: inherit;
|
||||
transition: border-color .15s ease, box-shadow .15s ease;
|
||||
}
|
||||
.sc:hover { border-color: var(--border-strong); box-shadow: var(--shadow-sm); }
|
||||
.sc:active { transform: scale(.99); }
|
||||
.sc.running { border-color: rgba(var(--primary-rgb), .55); background: var(--surface-glow); }
|
||||
.sc-ic {
|
||||
width: 32px; height: 32px; border-radius: 9px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: var(--tile-fg);
|
||||
font-size: 13px; font-weight: 700;
|
||||
}
|
||||
.sc-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.sc-body b { font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-meta { font-size: 10.5px; color: var(--text-faint); display: flex; align-items: center; gap: 5px; font-style: normal; white-space: nowrap; }
|
||||
.sep-dot { width: 3px; height: 3px; border-radius: 50%; background: var(--dot-muted); }
|
||||
.plat-state { font-style: normal; color: var(--text-muted-warm); }
|
||||
.plat-state.on { color: var(--ok); }
|
||||
.sc-go {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px; font-weight: 600;
|
||||
color: var(--primary); background: var(--primary-weak);
|
||||
border: 1px solid rgba(var(--primary-rgb), .35);
|
||||
padding: 4px 10px; border-radius: 999px;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.sc:hover .sc-go { background: var(--primary); color: var(--on-primary); border-color: transparent; }
|
||||
.sc.running .sc-go { color: var(--on-primary); background: var(--primary); border-color: transparent; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.empty {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 22px 20px; color: var(--text-sub);
|
||||
}
|
||||
.empty-emoji { font-size: 26px; }
|
||||
.empty b { display: block; font-size: 13.5px; color: var(--text); margin-bottom: 3px; font-weight: 600; }
|
||||
.empty span { font-size: 12px; color: var(--text-faint); }
|
||||
.empty .el-button { margin-left: auto; }
|
||||
|
||||
/* ---------- 最近动态 ---------- */
|
||||
.recent { padding: 4px 8px; }
|
||||
.rec {
|
||||
display: flex; align-items: center; gap: 11px;
|
||||
width: 100%; padding: 8px; text-align: left;
|
||||
background: transparent; border: none; border-radius: 8px;
|
||||
cursor: pointer; font-family: inherit;
|
||||
transition: background .13s;
|
||||
}
|
||||
.rec:hover { background: var(--surface-2); }
|
||||
.rec-ic {
|
||||
width: 20px; height: 20px; border-radius: 50%; flex-shrink: 0;
|
||||
display: grid; place-items: center; font-size: 10px; font-weight: 700;
|
||||
}
|
||||
.rec-ic.ok { background: var(--ok-weak); color: var(--ok); }
|
||||
.rec-ic.err { background: var(--err-weak); color: var(--err); }
|
||||
.rec-name { font-size: 12.5px; font-weight: 600; color: var(--text); min-width: 110px; }
|
||||
.rec-msg { flex: 1; font-size: 12px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.rec-msg.ok { color: var(--ok); }
|
||||
.rec-msg.err { color: var(--err); }
|
||||
.rec-time { font-size: 11px; color: var(--text-faint); font-variant-numeric: tabular-nums; }
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.kpis { flex-direction: column; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,173 @@
|
||||
<template>
|
||||
<div class="log-wrap">
|
||||
<div class="log-head">
|
||||
<div class="log-title">
|
||||
<i v-if="!isStatic" class="status" :class="store.wsOn ? 'on' : 'off'" :title="store.wsOn ? '实时连接正常' : '连接已中断'"></i>
|
||||
<span>{{ isStatic ? '历史回看' : '运行日志' }}</span>
|
||||
<span v-if="store.running && !isStatic" class="live">● LIVE</span>
|
||||
<span v-else-if="visibleLogs.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 v-if="!isStatic" 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="isStatic">该次运行没有日志记录</template>
|
||||
<template v-else-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 || l.t || '' }}</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 props = defineProps({
|
||||
// 历史回看模式:传入后显示该次运行的静态日志(替代 store.logs),并隐藏清空/LIVE
|
||||
staticLogs: { type: Array, default: null },
|
||||
})
|
||||
|
||||
const isStatic = computed(() => Array.isArray(props.staticLogs))
|
||||
|
||||
const LEVELS = ['全部', 'INFO', 'WARN', 'ERROR']
|
||||
const level = ref('全部')
|
||||
const pause = ref(false)
|
||||
const box = ref(null)
|
||||
|
||||
const visibleLogs = computed(() => {
|
||||
const src = isStatic.value ? props.staticLogs : store.logs
|
||||
if (level.value === '全部') return src
|
||||
return src.filter((l) => l.level === level.value)
|
||||
})
|
||||
|
||||
// 日志变化或过滤切换时,若未暂停则自动滚到最新
|
||||
watch(
|
||||
[() => store.logs.length, () => props.staticLogs?.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;
|
||||
flex: 1 1 auto; /* 由父级(运行台「运行日志」标签页)给高度 */
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.log-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 14px 10px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.log-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
font-size: 13.5px;
|
||||
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: var(--dot-off);
|
||||
}
|
||||
|
||||
.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>
|
||||
@@ -0,0 +1,653 @@
|
||||
<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">
|
||||
<button class="doodle-toggle" :class="{ off: !doodlesOn }"
|
||||
:title="doodlesOn ? '关闭涂鸦装饰' : '开启涂鸦装饰'" aria-label="涂鸦装饰开关"
|
||||
@click="toggleDoodles">
|
||||
<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 3c.6 4.6 3.4 7.4 8 8-4.6.6-7.4 3.4-8 8-.6-4.6-3.4-7.4-8-8 4.6-.6 7.4-3.4 8-8Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<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, onMounted } 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'])
|
||||
|
||||
// 涂鸦装饰层开关(与 main.js 的 initDoodles 同源:localStorage['37du.doodles'])
|
||||
const doodlesOn = ref(true)
|
||||
try { doodlesOn.value = (localStorage.getItem('37du.doodles') || 'on') !== 'off' } catch (_) {}
|
||||
onMounted(() => { document.documentElement.classList.toggle('no-doodles', !doodlesOn.value) })
|
||||
function toggleDoodles() {
|
||||
doodlesOn.value = !doodlesOn.value
|
||||
document.documentElement.classList.toggle('no-doodles', !doodlesOn.value)
|
||||
try { localStorage.setItem('37du.doodles', doodlesOn.value ? 'on' : 'off') } catch (_) {}
|
||||
}
|
||||
|
||||
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>
|
||||
/* ============================================================
|
||||
奶油极简治愈风登录页(Soft Minimal Cream)
|
||||
- 奶油米白画布(--bg)+ 浅天蓝强调 + 手绘涂鸦点缀
|
||||
- 全量走设计令牌,换肤只改 style.css 的 [data-skin] 块
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 画布 ---------- */
|
||||
.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: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--font-body, "Inter", -apple-system, "Segoe UI", "PingFang SC", sans-serif);
|
||||
}
|
||||
|
||||
/* 奶油点阵:边缘径向淡出(浅天蓝极淡点) */
|
||||
.login::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background-image: radial-gradient(rgba(var(--primary-rgb), .16) 1.2px, transparent 1.3px);
|
||||
background-size: 30px 30px;
|
||||
-webkit-mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 18%, transparent 76%);
|
||||
mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 18%, transparent 76%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 顶部柔光:浅天蓝辉光 */
|
||||
.login::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background: radial-gradient(660px 480px at 50% 38%, rgba(var(--primary-rgb), .12), 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(var(--primary-rgb), .10);
|
||||
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(var(--primary-rgb), .30) 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(var(--text-rgb), .10) 18%,
|
||||
rgba(var(--text-rgb), .10) 82%, transparent);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pipeline i {
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(var(--primary-rgb), .14);
|
||||
}
|
||||
|
||||
.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: 10px;
|
||||
background: var(--primary-grad);
|
||||
color: var(--on-primary);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .01em;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
box-shadow: 0 4px 10px -4px rgba(var(--primary-rgb), .65);
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .04em;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
.sys {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: var(--text-warm-faint);
|
||||
}
|
||||
|
||||
/* 涂鸦开关:小圆钮 */
|
||||
.doodle-toggle {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
margin-right: 2px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border-warm);
|
||||
border-radius: 50%;
|
||||
background: var(--surface);
|
||||
color: var(--primary);
|
||||
cursor: pointer;
|
||||
transition: all .18s ease;
|
||||
}
|
||||
.doodle-toggle:hover { transform: translateY(-1px) rotate(8deg); box-shadow: 0 4px 10px -4px rgba(var(--primary-rgb), .5); border-color: var(--primary-line); }
|
||||
.doodle-toggle.off { color: var(--text-disabled); }
|
||||
.doodle-toggle.off:hover { color: var(--primary); border-color: var(--primary-line); }
|
||||
|
||||
.dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
animation: pulse 2.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(var(--primary-rgb), .45); }
|
||||
70% { box-shadow: 0 0 0 7px rgba(var(--primary-rgb), 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(var(--primary-rgb), 0); }
|
||||
}
|
||||
|
||||
.sep { color: var(--sep-warm); }
|
||||
|
||||
/* ---------- 中央:接入终端(白底奶油卡) ---------- */
|
||||
.panel {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
padding: 46px 42px 42px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-warm-2);
|
||||
border-radius: 22px;
|
||||
box-shadow:
|
||||
0 1px 0 rgba(var(--on-primary-rgb), .95) inset,
|
||||
0 24px 48px -28px rgba(var(--text-rgb), .24);
|
||||
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: 42px;
|
||||
right: 42px;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background-image: repeating-linear-gradient(to right,
|
||||
rgba(var(--border-strong-rgb), .5) 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: var(--primary-strong);
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 31px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
letter-spacing: .01em;
|
||||
color: var(--text);
|
||||
font-family: var(--font-doodle, "Segoe Script", "Comic Sans MS", "KaiTi", cursive);
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
margin: 0 0 36px;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
/* ---------- 表单:奶油圆角输入 ---------- */
|
||||
.form :deep(.el-form-item) {
|
||||
position: relative;
|
||||
padding-left: 16px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.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: 50%;
|
||||
background: var(--switch-off);
|
||||
transition: background .2s, box-shadow .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item:focus-within .el-form-item__content)::before {
|
||||
background: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(var(--primary-rgb), .16);
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
line-height: 1.4;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
/* 圆角白底输入框 */
|
||||
.form :deep(.el-input__wrapper) {
|
||||
padding: 0 14px;
|
||||
background: var(--surface-3);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border-warm);
|
||||
box-shadow: inset 0 1px 2px rgba(var(--text-rgb), .03);
|
||||
transition: border-color .2s, box-shadow .2s;
|
||||
}
|
||||
.form :deep(.el-input__wrapper:hover) { border-color: var(--border-hover); }
|
||||
.form :deep(.el-input__wrapper.is-focus) {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(var(--primary-rgb), .14);
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner) {
|
||||
height: 48px;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
color: var(--text);
|
||||
caret-color: var(--primary);
|
||||
}
|
||||
|
||||
/* 覆盖 Chrome 自动填充的浅蓝底(登录框带 autocomplete,记住密码后会被刷成蓝底白字) */
|
||||
.form :deep(.el-input__wrapper input:-webkit-autofill),
|
||||
.form :deep(.el-input__wrapper input:-webkit-autofill:hover),
|
||||
.form :deep(.el-input__wrapper input:-webkit-autofill:focus) {
|
||||
-webkit-box-shadow: 0 0 0 1000px var(--surface-3) inset !important;
|
||||
-webkit-text-fill-color: var(--text) !important;
|
||||
caret-color: var(--primary);
|
||||
transition: background-color 9999s ease-out;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner::placeholder) { color: var(--placeholder); }
|
||||
|
||||
.form :deep(.el-input__suffix),
|
||||
.form :deep(.el-input__prefix),
|
||||
.form :deep(.el-input__suffix-inner) { color: var(--placeholder); }
|
||||
|
||||
.form :deep(.el-input__suffix-inner .el-input__icon:hover) { color: var(--text-sub); }
|
||||
|
||||
/* ---------- 主按钮:浅天蓝 ---------- */
|
||||
.primary.el-button {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
margin-top: 6px;
|
||||
border: none;
|
||||
border-radius: 14px;
|
||||
background: var(--primary-grad-2);
|
||||
color: var(--on-primary);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .12em;
|
||||
box-shadow: 0 12px 26px -14px rgba(var(--primary-rgb), .75);
|
||||
transition: background-color .15s, opacity .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.primary.el-button:hover,
|
||||
.primary.el-button:focus {
|
||||
background: var(--primary-hover);
|
||||
color: var(--on-primary);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 15px 30px -14px rgba(var(--primary-rgb), .85);
|
||||
}
|
||||
|
||||
.primary.el-button:active {
|
||||
background: var(--primary-strong);
|
||||
transform: translateY(1px) scale(.99);
|
||||
box-shadow: 0 6px 16px -12px rgba(var(--primary-rgb), .8);
|
||||
}
|
||||
|
||||
.primary.el-button.is-disabled,
|
||||
.primary.el-button.is-loading {
|
||||
background: var(--primary-soft);
|
||||
opacity: .55;
|
||||
}
|
||||
|
||||
/* ---------- 分隔线 ---------- */
|
||||
.divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin: 28px 0 16px;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: .04em;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.divider::before,
|
||||
.divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--border-warm);
|
||||
}
|
||||
|
||||
/* ---------- 钉钉按钮:白底奶卡 ---------- */
|
||||
.dingtalk.el-button {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
border-radius: 14px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-warm);
|
||||
color: var(--text-warm-sub);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .08em;
|
||||
box-shadow: 0 6px 16px -12px rgba(var(--text-rgb), .16);
|
||||
transition: all .18s ease;
|
||||
}
|
||||
|
||||
.dingtalk.el-button:hover,
|
||||
.dingtalk.el-button:focus {
|
||||
color: var(--primary-strong);
|
||||
border-color: var(--primary-line);
|
||||
background: var(--primary-tint);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 10px 22px -14px rgba(var(--primary-rgb), .55);
|
||||
}
|
||||
|
||||
.dingtalk.el-button:active { transform: translateY(1px) scale(.99); }
|
||||
|
||||
.dingtalk.el-button.is-disabled,
|
||||
.dingtalk.el-button.is-loading { background: var(--surface-2); color: var(--text-disabled); opacity: .8; }
|
||||
|
||||
.dingtalk.el-button :deep(.el-icon) { color: var(--primary); }
|
||||
|
||||
/* ---------- 键盘可达 ---------- */
|
||||
.primary.el-button:focus-visible,
|
||||
.dingtalk.el-button:focus-visible {
|
||||
outline: 2px solid var(--primary);
|
||||
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: var(--text-warm-faint);
|
||||
}
|
||||
|
||||
.f-blocks { display: flex; gap: 3px; }
|
||||
|
||||
.f-blocks i {
|
||||
width: 12px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--switch-off);
|
||||
}
|
||||
|
||||
.copyright {
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .1em;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* ---------- 自适应 ---------- */
|
||||
@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: 24px; }
|
||||
.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>
|
||||
@@ -0,0 +1,163 @@
|
||||
<template>
|
||||
<div class="paccs">
|
||||
<div v-for="p in platStatus" :key="p.id" class="pacc card">
|
||||
<div class="p-top">
|
||||
<span class="p-dot" :class="{ on: p.online }"></span>
|
||||
<span class="p-name">{{ p.label }}</span>
|
||||
<span class="p-state" :class="{ on: p.online }">{{ p.online ? '已登录' : '未登录' }}</span>
|
||||
</div>
|
||||
<div class="p-user" :class="{ none: !p.has_creds }">{{ p.has_creds ? p.user : '未配置个人账号' }}</div>
|
||||
<div class="p-acts">
|
||||
<el-button v-if="!p.online" size="small" :loading="busy === p.id" @click="login(p.id)">
|
||||
{{ busy === p.id ? '登录中…' : '登录' }}
|
||||
</el-button>
|
||||
<el-button v-else size="small" plain type="danger" :disabled="!!busy" @click="logout(p.id)">
|
||||
登出
|
||||
</el-button>
|
||||
<el-button size="small" text @click="openEdit(p)">配置账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="p-hint">账号密码仅本机加密保存;登录后场景按<b>你的身份</b>执行。</p>
|
||||
|
||||
<!-- 账号配置弹窗 -->
|
||||
<el-dialog v-model="dlg" :title="`配置 ${editLabel} 账号`" width="380px" align-center class="pacc-dlg">
|
||||
<el-form label-width="72px" @submit.prevent>
|
||||
<el-form-item label="登录账号">
|
||||
<el-input v-model="form.user" placeholder="平台登录账号" maxlength="64" />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.pass" type="password" show-password
|
||||
:placeholder="hasCreds ? '新密码(留空表示不修改)' : '平台登录密码'" maxlength="64" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref, onMounted, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { store, log } from '../store'
|
||||
import { loginPlatform, logoutPlatform, getPlatformStatus, savePlatformCreds } from '../api'
|
||||
|
||||
// 当前账号的平台状态(按账号隔离:各自 HR/OA 账号密码 + 各自会话)
|
||||
const platStatus = ref([]) // [{id, label, online, has_creds, user}]
|
||||
const dlg = ref(false) // 配置弹窗开关
|
||||
const editing = ref(null) // 正在配置的平台对象
|
||||
const form = reactive({ user: '', pass: '' })
|
||||
const busy = ref('')
|
||||
const saving = ref(false)
|
||||
|
||||
const editLabel = computed(() => (editing.value ? editing.value.label : ''))
|
||||
const hasCreds = computed(() => !!(editing.value && editing.value.has_creds))
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const r = await getPlatformStatus()
|
||||
platStatus.value = (r && r.platforms) || []
|
||||
// 同步全局平台在线态(首页统计/场景徽章按当前账号展示)
|
||||
for (const ps of platStatus.value) {
|
||||
const p = store.platforms.find((x) => x.id === ps.id)
|
||||
if (p) p.online = ps.online
|
||||
}
|
||||
} catch (_) { /* 静默 */ }
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
|
||||
function openEdit(p) {
|
||||
editing.value = p
|
||||
form.user = p.user || ''
|
||||
form.pass = ''
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true
|
||||
try {
|
||||
await savePlatformCreds({ [editing.value.id]: { user: form.user, pass: form.pass } })
|
||||
ElMessage.success(`已保存 ${editing.value.label} 账号配置`)
|
||||
dlg.value = false
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
ElMessage.error('保存失败:' + (e.message || e))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busy.value) return
|
||||
const p = platStatus.value.find((x) => x.id === id)
|
||||
if (p?.online) { ElMessage.success(`${p.label} 已登录`); return }
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const ok = !!(r && r.online)
|
||||
if (ok) log('INFO', `平台 ${p?.label || id} 登录成功`)
|
||||
else log('ERROR', `平台 ${p?.label || id} 登录未生效:${(r && r.message) || ''}`)
|
||||
ElMessage[ok ? 'success' : 'error'](
|
||||
`${p?.label || id} ${ok ? '登录成功' : '登录失败:' + ((r && r.message) || '登录态未生效')}`
|
||||
)
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${p?.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 = platStatus.value.find((x) => x.id === id)
|
||||
if (p) p.online = !!r.online
|
||||
log('INFO', `平台 ${p?.label || id} 已登出`)
|
||||
ElMessage.success(`平台 ${p?.label || id} 已登出`)
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(platStatus.value.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.paccs { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
||||
.pacc { padding: 13px 14px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.p-top { display: flex; align-items: center; gap: 8px; }
|
||||
.p-dot {
|
||||
flex: none; width: 8px; height: 8px; border-radius: 50%;
|
||||
background: var(--sep-warm);
|
||||
}
|
||||
.p-dot.on { background: var(--ok); box-shadow: 0 0 0 3px rgba(var(--ok-rgb), .16); }
|
||||
.p-name { font-size: 13.5px; font-weight: 600; color: var(--text); }
|
||||
.p-state {
|
||||
margin-left: auto; font-size: 11px; color: var(--text-faint);
|
||||
padding: 2px 9px; border-radius: 999px; background: var(--surface-2);
|
||||
}
|
||||
.p-state.on { color: var(--ok); background: var(--ok-weak); }
|
||||
.p-user {
|
||||
font-size: 11.5px; color: var(--text); font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.p-user.none { color: var(--text-faint); }
|
||||
.p-acts { display: flex; align-items: center; gap: 6px; margin-top: 2px; }
|
||||
.p-acts .el-button + .el-button { margin-left: 0; }
|
||||
.p-hint {
|
||||
grid-column: 1 / -1;
|
||||
margin: 2px 0 0; font-size: 11px; color: var(--text-faint); line-height: 1.7;
|
||||
}
|
||||
.p-hint b { color: var(--text-sub); }
|
||||
|
||||
/* 与首页常用场景共用同一容器查询断点:窄容器时同步降为 1 列,保证上下卡片始终对齐 */
|
||||
@container (max-width: 380px) { .paccs { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
@@ -0,0 +1,685 @@
|
||||
<template>
|
||||
<div v-if="plugin" class="plugin-page">
|
||||
<!-- Hero:场景身份 + 大执行按钮 -->
|
||||
<section class="hero card">
|
||||
<div class="hero-main">
|
||||
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
|
||||
<div class="hero-meta">
|
||||
<h2 class="p-name">{{ plugin.name }}
|
||||
<span class="ver-tag">v{{ plugin.version }}</span>
|
||||
</h2>
|
||||
<p class="p-desc">{{ plugin.description || '暂无描述' }}</p>
|
||||
<div class="p-badges">
|
||||
<span v-if="plugin.platform" class="badge" :class="platformOnline ? 'on' : 'off'">
|
||||
<i class="bdot"></i>{{ platformLabel }} {{ platformOnline ? '已登录' : '未登录' }}
|
||||
</span>
|
||||
<span v-if="plugin.uses_month" class="badge">
|
||||
<el-select v-model="month" size="small" class="month-sel" :disabled="store.running">
|
||||
<el-option v-for="m in months" :key="m" :value="m" :label="m" />
|
||||
</el-select>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hero-actions">
|
||||
<button class="run-btn" :class="{ running: store.running }" :disabled="store.running" @click="run">
|
||||
<template v-if="store.running">
|
||||
<span class="ring">
|
||||
<svg viewBox="0 0 36 36" width="26" height="26">
|
||||
<circle class="ring-bg" cx="18" cy="18" r="15.5" fill="none" stroke-width="3.5" />
|
||||
<circle class="ring-fg" cx="18" cy="18" r="15.5" fill="none" stroke-width="3.5"
|
||||
stroke-linecap="round" :stroke-dasharray="ringDash" transform="rotate(-90 18 18)" />
|
||||
</svg>
|
||||
</span>
|
||||
<span>执行中 {{ store.progress }}%</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="play-ic">▶</span>
|
||||
<span>一键执行</span>
|
||||
</template>
|
||||
</button>
|
||||
<el-button v-if="rollbackVer" size="small" text type="warning" class="rollback-btn"
|
||||
:disabled="store.running" @click="doRollback">回滚 v{{ rollbackVer }}</el-button>
|
||||
<span class="hero-tip">配置与运行日志都在下方运行台</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 结果横幅 -->
|
||||
<section v-if="store.lastResult" class="banner" :class="store.lastResult.ok ? 'ok' : 'err'">
|
||||
<span class="b-ic">{{ store.lastResult.ok ? '✓' : '✕' }}</span>
|
||||
<div class="b-body">
|
||||
<b>{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败' }}</b>
|
||||
<span v-if="!store.lastResult.ok">{{ store.lastResult.error }}</span>
|
||||
</div>
|
||||
<button class="b-close" @click="closeBanner" title="关闭">✕</button>
|
||||
</section>
|
||||
|
||||
<!-- 运行台:参数 / 插件界面 / 运行日志
|
||||
日志归属"本次运行"(不再是全局面板);带专属界面的插件用界面本身配置,故不并列参数表单 -->
|
||||
<div class="run-tabs card">
|
||||
<div class="rt-head">
|
||||
<div class="rt-tabs">
|
||||
<button v-for="t in tabs" :key="t.k" class="rt-tab" :class="{ on: tab === t.k }" @click="tab = t.k">
|
||||
{{ t.label }}
|
||||
<span v-if="t.k === 'log' && store.logs.length" class="rt-n">{{ store.logs.length }}</span>
|
||||
<i v-if="t.k === 'log' && store.running" class="rt-live"></i>
|
||||
</button>
|
||||
</div>
|
||||
<el-button v-if="tab === 'params' && fieldCount" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
</div>
|
||||
|
||||
<div class="rt-body">
|
||||
<!-- 参数配置 -->
|
||||
<section v-show="tab === 'params'" class="params">
|
||||
<div class="cfg-bar">
|
||||
<el-select v-model="curCfg" size="small" class="cfg-sel" placeholder="默认配置" @change="onCfgChange">
|
||||
<el-option label="默认配置" value="" />
|
||||
<el-option v-for="c in configs" :key="c.id" :value="c.id" :label="c.name" />
|
||||
</el-select>
|
||||
<el-button size="small" text :icon="FolderAdd" :disabled="store.running" @click="saveAsCfg">存为配置</el-button>
|
||||
<el-button v-if="curCfg" size="small" text type="danger" :icon="Delete" :disabled="store.running" @click="delCfg">删除</el-button>
|
||||
<span v-if="curCfgLabel" class="cfg-note">已套用「{{ curCfgLabel }}」,定时任务可引用</span>
|
||||
</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>
|
||||
</el-form>
|
||||
</section>
|
||||
|
||||
<!-- 插件专属界面(同源 iframe,自动携带会话 cookie)
|
||||
sandbox 白名单加固:允许脚本/同源/表单,禁用 top 跳转与弹窗
|
||||
仅一层容器承载尺寸,不再叠提示条/卡片 -->
|
||||
<div v-if="plugin.ui" v-show="tab === 'ui'" class="ui-pane">
|
||||
<iframe :key="plugin.id" :src="uiSrc" class="pui-frame" title="插件界面"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"></iframe>
|
||||
</div>
|
||||
|
||||
<!-- 运行日志(当前/本次运行) -->
|
||||
<div v-show="tab === 'log'" class="rt-log"><LogPanel /></div>
|
||||
|
||||
<!-- 历史运行:本场景已完成的运行,点击回看该次日志 -->
|
||||
<section v-show="tab === 'history'" class="history">
|
||||
<div v-if="!replay" class="hist-view">
|
||||
<div class="hist-head">
|
||||
<span class="hist-title">本场景最近运行</span>
|
||||
<el-button size="small" text :icon="Refresh" :loading="loadingRuns" @click="loadRuns">刷新</el-button>
|
||||
</div>
|
||||
<div v-if="!runs.length" class="hist-empty">
|
||||
{{ loadingRuns ? '加载中…' : '该场景还没有运行记录,执行一次后这里可回看' }}
|
||||
</div>
|
||||
<ul v-else class="hist-list">
|
||||
<li v-for="r in runs" :key="r.run_id" class="hist-item" @click="openReplay(r.run_id)">
|
||||
<i class="hist-dot" :class="r.ok ? 'ok' : 'err'"></i>
|
||||
<div class="hist-meta">
|
||||
<b>{{ triggerLabel(r.trigger) }}</b>
|
||||
<span class="hist-time">{{ fmtTime(r.started) }} · {{ durText(r.duration_sec) }}</span>
|
||||
</div>
|
||||
<span class="hist-state" :class="r.ok ? 'ok' : 'err'">{{ r.ok ? '成功' : '失败' }}</span>
|
||||
<el-icon class="hist-arrow"><ArrowRight /></el-icon>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<!-- 回看单次运行(结论 + 该次日志) -->
|
||||
<div v-else class="hist-replay">
|
||||
<div class="replay-head">
|
||||
<el-button size="small" text :icon="ArrowLeft" :disabled="replayBusy" @click="replay = null">返回列表</el-button>
|
||||
<div class="replay-tags">
|
||||
<span class="badge" :class="replay.ok ? 'on' : 'off'"><i class="bdot"></i>{{ replay.ok ? '成功' : '失败' }}</span>
|
||||
<span class="replay-tag">{{ triggerLabel(replay.trigger) }}</span>
|
||||
<span class="replay-tag">{{ fmtTime(replay.started) }}</span>
|
||||
<span class="replay-tag">耗时 {{ durText(replay.duration_sec) }}</span>
|
||||
<span v-if="replay.summary" class="replay-sum">{{ replay.summary }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rt-log"><LogPanel :static-logs="replay.logs || []" /></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!store.plugins.length" class="empty-note">
|
||||
<b>当前账号暂无可用场景</b><br>请联系管理员在控制面进行授权,授权后点击右上角刷新
|
||||
</div>
|
||||
<div v-else class="empty-note"><b>未选择场景</b></div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { QuestionFilled, Refresh, RefreshLeft, ArrowLeft, ArrowRight, FolderAdd, Delete } from '@element-plus/icons-vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun, fetchRuns, fetchMeta, listRollbacks, rollbackPlugin, listPluginConfigs, savePluginConfig, deletePluginConfig } from '../api'
|
||||
import LogPanel from './LogPanel.vue'
|
||||
|
||||
const GRADS = [
|
||||
'var(--grad-sky)', 'var(--grad-peach)', 'var(--grad-mint)',
|
||||
'var(--grad-lilac)', 'var(--grad-honey)', 'var(--grad-blush)',
|
||||
]
|
||||
|
||||
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 idx = computed(() => Math.max(0, store.plugins.findIndex((p) => p.id === store.selectedId)))
|
||||
const avatarBg = computed(() => GRADS[idx.value % GRADS.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))
|
||||
loadConfigs()
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function resetForm() {
|
||||
form.value = buildFormDefaults(plugin.value)
|
||||
curCfg.value = ''
|
||||
}
|
||||
|
||||
// ===== 配置方案(多配置):把当前参数存成命名方案,运行台可一键套用、定时任务可引用 =====
|
||||
const configs = ref([])
|
||||
const curCfg = ref('')
|
||||
const curCfgLabel = computed(() => {
|
||||
if (!curCfg.value) return ''
|
||||
const c = configs.value.find((x) => x.id === curCfg.value)
|
||||
return c ? c.name : ''
|
||||
})
|
||||
|
||||
async function loadConfigs() {
|
||||
if (!plugin.value?.id) {
|
||||
configs.value = []
|
||||
curCfg.value = ''
|
||||
return
|
||||
}
|
||||
try {
|
||||
const r = await listPluginConfigs(plugin.value.id)
|
||||
configs.value = r.configs || []
|
||||
if (curCfg.value && !configs.value.some((c) => c.id === curCfg.value)) curCfg.value = ''
|
||||
} catch (e) {
|
||||
ElMessage.error('配置方案加载失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
function onCfgChange(id) {
|
||||
const c = configs.value.find((x) => x.id === id)
|
||||
if (!c) return
|
||||
Object.assign(form.value, c.fields)
|
||||
ElMessage.success(`已套用配置「${c.name}」`)
|
||||
}
|
||||
|
||||
async function saveAsCfg() {
|
||||
let name
|
||||
try {
|
||||
const r = await ElMessageBox.prompt('给这套参数起个名字(同名会覆盖旧配置)', '保存为配置', {
|
||||
confirmButtonText: '保存',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S+/,
|
||||
inputErrorMessage: '名称不能为空',
|
||||
inputValue: curCfgLabel.value || '',
|
||||
})
|
||||
name = r.value
|
||||
} catch (e) {
|
||||
if (e === 'cancel') return
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
const r = await savePluginConfig(plugin.value.id, name, { ...form.value })
|
||||
await loadConfigs()
|
||||
curCfg.value = r.config.id
|
||||
ElMessage.success(`配置「${r.config.name}」已保存`)
|
||||
} catch (e) {
|
||||
ElMessage.error(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function delCfg() {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除配置「${curCfgLabel.value}」?`, '删除配置', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
})
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await deletePluginConfig(plugin.value.id, curCfg.value)
|
||||
curCfg.value = ''
|
||||
await loadConfigs()
|
||||
ElMessage.success('已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('删除失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
// 专属界面插件:插件 UI 直接内嵌在页面主体(同源自动携带会话 cookie,不再弹窗/外跳)。
|
||||
const uiSrc = computed(() => (plugin.value?.ui ? `/pui/${plugin.value.id}/` : ''))
|
||||
|
||||
// ===== 运行台标签页 =====
|
||||
// 带专属界面的插件由界面自己配置参数,故不并列参数表单(与改造前语义一致)
|
||||
const tabs = computed(() => {
|
||||
const base = plugin.value?.ui
|
||||
? [{ k: 'ui', label: '插件界面' }]
|
||||
: [{ k: 'params', label: '参数配置' }]
|
||||
return [...base, { k: 'log', label: '运行日志' }, { k: 'history', label: '历史运行' }]
|
||||
})
|
||||
const tab = ref('params')
|
||||
const fieldCount = computed(() => (plugin.value?.fields || []).length)
|
||||
|
||||
watch(
|
||||
() => plugin.value?.id,
|
||||
(id) => {
|
||||
tab.value = plugin.value?.ui ? 'ui' : 'params'
|
||||
resetHistory()
|
||||
consumePendingReplay()
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// ===== 历史运行 =====
|
||||
const runs = ref([]) // 本场景最近运行(brief 列表)
|
||||
const loadingRuns = ref(false)
|
||||
const runsLoaded = ref(false) // 本场景是否已拉过(切换场景后重置)
|
||||
const replay = ref(null) // 正在回看的单次运行 {brief..., logs:[...]}
|
||||
const replayBusy = ref(false)
|
||||
|
||||
async function loadRuns() {
|
||||
if (!plugin.value || loadingRuns.value) return
|
||||
loadingRuns.value = true
|
||||
try {
|
||||
const data = await fetchRuns(60)
|
||||
const mine = (data.runs || []).filter((r) => r.plugin_id === plugin.value.id)
|
||||
runs.value = mine.slice(0, 30)
|
||||
runsLoaded.value = true
|
||||
} catch (_) { /* 历史是辅助能力,加载失败静默(列表保持上次/空) */ }
|
||||
finally { loadingRuns.value = false }
|
||||
}
|
||||
|
||||
async function openReplay(runId) {
|
||||
if (!runId || replayBusy.value) return
|
||||
replayBusy.value = true
|
||||
try {
|
||||
const data = await getRun(runId)
|
||||
replay.value = { ...(data || {}), logs: (data && data.logs) || [] }
|
||||
} catch (e) {
|
||||
ElMessage.error('加载运行记录失败:' + (e.message || e))
|
||||
} finally {
|
||||
replayBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetHistory() {
|
||||
runs.value = []
|
||||
runsLoaded.value = false
|
||||
replay.value = null
|
||||
}
|
||||
|
||||
// 活动流「最近运行」点击 → 直达本场景回看:匹配当前场景则消费,否则等场景切换后消费
|
||||
function consumePendingReplay() {
|
||||
const p = store.pendingReplay
|
||||
if (!p || !plugin.value || plugin.value.id !== p.pluginId) return false
|
||||
store.pendingReplay = null
|
||||
tab.value = 'history'
|
||||
openReplay(p.runId)
|
||||
return true
|
||||
}
|
||||
watch(() => store.pendingReplay, consumePendingReplay)
|
||||
|
||||
// 打开「历史运行」标签页且未拉过 → 拉取;运行结束(recents 变化)→ 若已拉过则刷新
|
||||
watch(
|
||||
() => tab.value,
|
||||
(t) => { if (t === 'history' && !runsLoaded.value && !loadingRuns.value) loadRuns() }
|
||||
)
|
||||
watch(
|
||||
() => store.recents.length,
|
||||
() => { if (runsLoaded.value && !replay.value) loadRuns() }
|
||||
)
|
||||
|
||||
function triggerLabel(t) {
|
||||
return ({ manual: '手动执行', schedule: '定时任务' })[t] || t || '手动执行'
|
||||
}
|
||||
function durText(s) {
|
||||
const n = parseInt(s, 10) || 0
|
||||
if (n < 60) return n + 's'
|
||||
const m = Math.floor(n / 60)
|
||||
return m + '分' + (n % 60 ? (n % 60) + 's' : '')
|
||||
}
|
||||
function fmtTime(ts) {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
if (isNaN(d.getTime())) return '—'
|
||||
const p = (n) => String(n).padStart(2, '0')
|
||||
return `${d.getMonth() + 1}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
// 执行进度环(SVG stroke-dasharray)
|
||||
const RING_C = 2 * Math.PI * 15.5
|
||||
const ringDash = computed(() => `${(store.progress / 100) * RING_C} ${RING_C}`)
|
||||
|
||||
const platformLabel = computed(() => {
|
||||
const p = store.platforms.find((x) => x.id === plugin.value?.platform)
|
||||
return p?.label || plugin.value?.platform || ''
|
||||
})
|
||||
const platformOnline = computed(() =>
|
||||
!!(store.platforms.find((x) => x.id === plugin.value?.platform) || {}).online
|
||||
)
|
||||
|
||||
// ===== 插件回滚(升级前自动备份上一版,坏包可回退) =====
|
||||
const rollbackVer = ref('')
|
||||
async function loadRollbackInfo() {
|
||||
if (!plugin.value) return
|
||||
rollbackVer.value = ''
|
||||
try {
|
||||
const r = await listRollbacks()
|
||||
const item = (r.items || []).find((i) => i.id === plugin.value.id)
|
||||
rollbackVer.value = item ? item.version : ''
|
||||
} catch (_) { /* 本地能力,失败静默 */ }
|
||||
}
|
||||
watch(() => plugin.value?.id, loadRollbackInfo, { immediate: true })
|
||||
|
||||
async function doRollback() {
|
||||
if (!plugin.value || !rollbackVer.value) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`将「${plugin.value.name}」回滚到 v${rollbackVer.value}(当前 v${plugin.value.version})。` +
|
||||
'回滚后如需最新版,再次点击右上角同步即可。确定回滚?',
|
||||
'插件回滚',
|
||||
{ type: 'warning', confirmButtonText: '回滚', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await rollbackPlugin(plugin.value.id)
|
||||
ElMessage.success(`已回滚到 v${rollbackVer.value}`)
|
||||
// 刷新插件列表:版本号等元数据由 /api/meta 重新下发
|
||||
const meta = await fetchMeta()
|
||||
store.plugins = meta.plugins || []
|
||||
rollbackVer.value = ''
|
||||
} catch (e) {
|
||||
ElMessage.error('回滚失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
if (plugin.value.platform && !platformOnline.value) {
|
||||
log('WARN', `插件「${plugin.value.name}」需要先登录平台「${platformLabel.value}」才能正确执行`)
|
||||
}
|
||||
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: 14px;
|
||||
flex: 1 1 auto; /* 填满中栏上下文区,运行台内部自己滚 */
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* ---------- Hero ---------- */
|
||||
.hero {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
padding: 22px 24px;
|
||||
background: var(--hero-grad);
|
||||
}
|
||||
.hero-main { display: flex; align-items: center; gap: 16px; min-width: 0; }
|
||||
.avatar {
|
||||
width: 54px; height: 54px; border-radius: 16px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: var(--tile-fg);
|
||||
font-size: 22px; font-weight: 700;
|
||||
box-shadow: 0 10px 22px -10px rgba(var(--text-rgb), .35);
|
||||
}
|
||||
.hero-meta { min-width: 0; display: flex; flex-direction: column; gap: 5px; }
|
||||
.p-name { margin: 0; font-size: 19px; font-weight: 700; color: var(--text); display: flex; align-items: center; gap: 9px; }
|
||||
.ver-tag {
|
||||
font-size: 10.5px; font-weight: 500; color: var(--text-faint);
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
padding: 1px 8px; border-radius: 999px;
|
||||
}
|
||||
.p-desc { margin: 0; font-size: 12.5px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 560px; }
|
||||
.p-badges { display: flex; align-items: center; gap: 8px; margin-top: 2px; }
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
font-size: 11px; color: var(--badge-warm-text);
|
||||
background: var(--badge-warm-bg); border: 1px solid var(--badge-warm-border);
|
||||
padding: 2px 10px; border-radius: 999px;
|
||||
}
|
||||
.badge.on { color: var(--ok-text); background: var(--ok-weak); border-color: rgba(var(--ok-rgb), .3); }
|
||||
.badge.off { color: var(--badge-off-text); }
|
||||
.bdot { width: 6px; height: 6px; border-radius: 50%; background: var(--badge-dot); }
|
||||
.badge.on .bdot { background: var(--ok); }
|
||||
.month-sel { width: 108px; --el-component-size: 24px; }
|
||||
|
||||
.hero-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 7px; flex-shrink: 0; }
|
||||
.run-btn {
|
||||
display: inline-flex; align-items: center; gap: 9px;
|
||||
padding: 0 26px; height: 50px;
|
||||
border: none; border-radius: 16px;
|
||||
background: var(--primary-grad-2);
|
||||
color: var(--on-primary); font-size: 15px; font-weight: 600; letter-spacing: .06em;
|
||||
cursor: pointer; font-family: inherit;
|
||||
box-shadow: 0 12px 26px -12px rgba(var(--primary-rgb), .85);
|
||||
transition: all .16s ease;
|
||||
}
|
||||
.run-btn:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 16px 30px -12px rgba(var(--primary-rgb), .95); }
|
||||
.run-btn:active:not(:disabled) { transform: translateY(0) scale(.98); }
|
||||
.run-btn.running { background: var(--primary-grad-3); cursor: default; min-width: 168px; font-variant-numeric: tabular-nums; }
|
||||
/* 进度环用 CSS 上色(SVG 表现属性不支持 var(),故不写在 stroke="" 上) */
|
||||
.ring-bg { stroke: rgba(var(--on-primary-rgb), .35); }
|
||||
.ring-fg { stroke: var(--on-primary); }
|
||||
.run-btn:disabled { opacity: 1; }
|
||||
.play-ic { font-size: 13px; transform: translateY(-1px); }
|
||||
.ring { display: inline-flex; }
|
||||
.ring-fg { transition: stroke-dasharray .25s ease; }
|
||||
.hero-tip { font-size: 10.5px; color: var(--text-faint); letter-spacing: .02em; }
|
||||
.rollback-btn { margin-top: -3px; }
|
||||
|
||||
/* ---------- 结果横幅 ---------- */
|
||||
.banner {
|
||||
display: flex; align-items: center; gap: 11px;
|
||||
padding: 12px 16px; border-radius: 14px;
|
||||
animation: riseIn .3s var(--ease) both;
|
||||
}
|
||||
.banner.ok { background: var(--ok-weak); border: 1px solid rgba(var(--ok-rgb), .35); }
|
||||
.banner.err { background: var(--err-weak); border: 1px solid rgba(var(--err-rgb), .4); }
|
||||
.b-ic {
|
||||
width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;
|
||||
display: grid; place-items: center; font-size: 13px; font-weight: 700; color: var(--on-primary);
|
||||
}
|
||||
.banner.ok .b-ic { background: var(--ok); }
|
||||
.banner.err .b-ic { background: var(--err); }
|
||||
.b-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.b-body b { font-size: 13px; color: var(--text); font-weight: 600; }
|
||||
.b-body span { font-size: 12px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.b-close {
|
||||
border: none; background: transparent; color: rgba(var(--text-rgb), .4);
|
||||
cursor: pointer; font-size: 12px; padding: 4px; border-radius: 50%;
|
||||
}
|
||||
.b-close:hover { color: var(--text); background: rgba(var(--on-primary-rgb), .6); }
|
||||
|
||||
/* ---------- 运行台(标签页容器) ---------- */
|
||||
.run-tabs {
|
||||
flex: 1 1 auto; min-height: 300px;
|
||||
display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
.rt-head {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 10px;
|
||||
padding: 0 14px; border-bottom: 1px solid var(--border); flex-shrink: 0;
|
||||
}
|
||||
.rt-tabs { display: flex; align-items: center; gap: 2px; }
|
||||
.rt-tab {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
border: none; background: transparent; cursor: pointer; font-family: inherit;
|
||||
padding: 11px 14px; font-size: 13px; color: var(--text-sub);
|
||||
border-bottom: 2px solid transparent; margin-bottom: -1px;
|
||||
transition: color .13s, border-color .13s;
|
||||
}
|
||||
.rt-tab:hover { color: var(--text); }
|
||||
.rt-tab.on { color: var(--primary); font-weight: 600; border-bottom-color: var(--primary); }
|
||||
.rt-n {
|
||||
font-size: 10.5px; color: var(--text-faint); background: var(--surface-2);
|
||||
border: 1px solid var(--border); border-radius: 999px; padding: 0 6px;
|
||||
}
|
||||
.rt-tab.on .rt-n { color: var(--primary); background: var(--primary-weak); border-color: var(--primary-line); }
|
||||
.rt-live { width: 6px; height: 6px; border-radius: 50%; background: var(--ok); animation: rtBlink 1s infinite; }
|
||||
@keyframes rtBlink { 50% { opacity: .2; } }
|
||||
|
||||
.rt-body { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.rt-log { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
||||
|
||||
/* ---------- 专属界面插件 ---------- */
|
||||
.ui-pane { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; padding: 14px 16px 16px; }
|
||||
.pui-frame {
|
||||
display: block; width: 100%; flex: 1 1 auto; min-height: 340px;
|
||||
border: 1px solid var(--border); border-radius: 12px; background: var(--surface);
|
||||
}
|
||||
|
||||
/* ---------- 参数 ---------- */
|
||||
.params { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 18px 22px 6px; }
|
||||
.cfg-bar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 14px; }
|
||||
.cfg-sel { width: 200px; }
|
||||
.cfg-note { font-size: 11.5px; color: var(--text-faint); }
|
||||
.fields { display: flex; gap: 24px; flex-wrap: wrap; }
|
||||
.form-card .el-form-item { margin-bottom: 18px; }
|
||||
.help-ic { color: var(--text-faint); cursor: help; }
|
||||
|
||||
/* ---------- 历史运行 ---------- */
|
||||
.history { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.hist-view { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
||||
.hist-head {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 10px;
|
||||
padding: 10px 16px 6px; flex-shrink: 0;
|
||||
}
|
||||
.hist-title { font-size: 12.5px; font-weight: 600; color: var(--text-sub); }
|
||||
.hist-empty {
|
||||
flex: 1 1 auto; display: grid; place-items: center;
|
||||
color: var(--text-faint); font-size: 12.5px; padding: 30px 20px; text-align: center;
|
||||
}
|
||||
.hist-list { flex: 1 1 auto; min-height: 0; overflow: auto; list-style: none; margin: 4px 8px 10px; padding: 0; }
|
||||
.hist-item {
|
||||
display: flex; align-items: center; gap: 11px;
|
||||
padding: 10px 12px; border-radius: 12px; cursor: pointer;
|
||||
transition: background .13s ease;
|
||||
}
|
||||
.hist-item:hover { background: var(--surface-2); }
|
||||
.hist-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
|
||||
.hist-dot.ok { background: var(--ok); box-shadow: 0 0 0 3px var(--ok-weak); }
|
||||
.hist-dot.err { background: var(--err); box-shadow: 0 0 0 3px var(--err-weak); }
|
||||
.hist-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.hist-meta b { font-size: 13px; color: var(--text); font-weight: 600; }
|
||||
.hist-time { font-size: 11.5px; color: var(--text-faint); font-variant-numeric: tabular-nums; }
|
||||
.hist-state { font-size: 12px; font-weight: 600; flex-shrink: 0; }
|
||||
.hist-state.ok { color: var(--ok); }
|
||||
.hist-state.err { color: var(--err); }
|
||||
.hist-arrow { color: var(--text-faint); font-size: 13px; flex-shrink: 0; }
|
||||
|
||||
.hist-replay { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
||||
.replay-head {
|
||||
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
|
||||
padding: 8px 12px; border-bottom: 1px solid var(--border); flex-shrink: 0;
|
||||
}
|
||||
.replay-tags { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; min-width: 0; }
|
||||
.replay-tag {
|
||||
font-size: 11px; color: var(--text-faint); font-variant-numeric: tabular-nums;
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
padding: 1px 9px; border-radius: 999px;
|
||||
}
|
||||
.replay-sum {
|
||||
font-size: 11.5px; color: var(--text-sub); white-space: nowrap;
|
||||
overflow: hidden; text-overflow: ellipsis; max-width: 340px;
|
||||
}
|
||||
|
||||
@keyframes riseIn {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,124 @@
|
||||
<template>
|
||||
<div class="scenes-page">
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar"><el-icon><Collection /></el-icon></span>
|
||||
<div class="ident-meta">
|
||||
<h2>全部场景</h2>
|
||||
<p>当前账号可用的 {{ store.plugins.length }} 个场景,点击行进入运行台</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sc-list card">
|
||||
<button
|
||||
v-for="(p, i) in store.plugins" :key="p.id" class="sc-row"
|
||||
:class="{ running: store.running && store.selectedId === p.id }"
|
||||
@click="open(p.id)"
|
||||
>
|
||||
<span class="sc-ic" :style="{ background: grad(i) }">{{ p.name.slice(0, 1) }}</span>
|
||||
<span class="sc-body">
|
||||
<span class="sc-title">
|
||||
<b>{{ p.name }}</b>
|
||||
<em>v{{ p.version }}</em>
|
||||
</span>
|
||||
<span class="sc-desc">{{ p.description || '暂无描述' }}</span>
|
||||
<span v-if="p.platform" class="sc-meta">
|
||||
{{ platformLabel(p.platform) }}
|
||||
<i class="sep-dot"></i>
|
||||
<em class="plat-state" :class="{ on: platformOnline(p.platform) }">
|
||||
{{ platformOnline(p.platform) ? '已登录' : '未登录' }}
|
||||
</em>
|
||||
</span>
|
||||
</span>
|
||||
<span class="sc-go">
|
||||
<template v-if="store.running && store.selectedId === p.id">{{ store.progress }}%</template>
|
||||
<template v-else>执行</template>
|
||||
</span>
|
||||
</button>
|
||||
<div v-if="!store.plugins.length" class="sc-empty">
|
||||
<span class="empty-emoji">🤍</span>
|
||||
<b>当前账号暂无可用场景</b>
|
||||
<span>请联系管理员在控制面进行授权,授权后点左栏「同步」刷新</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { Collection } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
|
||||
const GRADS = [
|
||||
'var(--grad-sky)', 'var(--grad-peach)', 'var(--grad-mint)',
|
||||
'var(--grad-lilac)', 'var(--grad-honey)', 'var(--grad-blush)',
|
||||
]
|
||||
function grad(i) { return GRADS[i % GRADS.length] }
|
||||
|
||||
function platformLabel(id) {
|
||||
return (store.platforms.find((p) => p.id === id) || {}).label || id
|
||||
}
|
||||
function platformOnline(id) {
|
||||
return !!(store.platforms.find((p) => p.id === id) || {}).online
|
||||
}
|
||||
function open(id) {
|
||||
store.selectedId = id
|
||||
store.view = 'run'
|
||||
store.pendingReplay = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.scenes-page { display: flex; flex-direction: column; gap: 14px; padding: 4px 2px 10px; flex-shrink: 0; }
|
||||
.head { display: flex; align-items: center; justify-content: space-between; }
|
||||
.ident { display: flex; align-items: center; gap: 12px; }
|
||||
.avatar {
|
||||
width: 36px; height: 36px; border-radius: 10px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: var(--tile-fg);
|
||||
background: var(--grad-sky); font-size: 15px;
|
||||
}
|
||||
.ident-meta h2 { margin: 0; font-size: 16px; font-weight: 700; color: var(--text); }
|
||||
.ident-meta p { margin: 2px 0 0; font-size: 12px; color: var(--text-faint); }
|
||||
|
||||
.sc-list { display: flex; flex-direction: column; overflow: hidden; }
|
||||
.sc-row {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 16px; width: 100%; text-align: left;
|
||||
border: none; border-bottom: 1px solid var(--border);
|
||||
background: transparent; cursor: pointer; font-family: inherit;
|
||||
transition: background .13s;
|
||||
}
|
||||
.sc-row:last-child { border-bottom: none; }
|
||||
.sc-row:hover { background: var(--surface-2); }
|
||||
.sc-row.running { background: var(--primary-tint); }
|
||||
.sc-ic {
|
||||
width: 34px; height: 34px; border-radius: 10px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: var(--tile-fg);
|
||||
font-size: 14px; font-weight: 700;
|
||||
}
|
||||
.sc-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.sc-title { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
|
||||
.sc-title b { font-size: 13.5px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-title em { font-style: normal; font-size: 10.5px; color: var(--text-faint); font-family: var(--mono); flex-shrink: 0; }
|
||||
.sc-desc { font-size: 12px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sc-meta { display: flex; align-items: center; gap: 6px; font-size: 10.5px; color: var(--text-faint); font-style: normal; }
|
||||
.sep-dot { width: 3px; height: 3px; border-radius: 50%; background: var(--dot-muted); }
|
||||
.plat-state { font-style: normal; color: var(--text-muted-warm); }
|
||||
.plat-state.on { color: var(--ok); }
|
||||
.sc-go {
|
||||
flex-shrink: 0; font-size: 12px; font-weight: 600;
|
||||
color: var(--primary); background: var(--primary-weak);
|
||||
border: 1px solid rgba(var(--primary-rgb), .35);
|
||||
padding: 5px 14px; border-radius: 999px;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.sc-row:hover .sc-go { background: var(--primary); color: var(--on-primary); border-color: transparent; }
|
||||
.sc-row.running .sc-go { color: var(--on-primary); background: var(--primary); border-color: transparent; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.sc-empty {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 4px;
|
||||
padding: 34px 20px; color: var(--text-faint); font-size: 12.5px;
|
||||
}
|
||||
.sc-empty .empty-emoji { font-size: 26px; }
|
||||
.sc-empty b { color: var(--text-sub); font-size: 13.5px; font-weight: 600; }
|
||||
</style>
|
||||
@@ -0,0 +1,628 @@
|
||||
<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="暂无定时任务,点击右上角「新建任务」创建" />
|
||||
|
||||
<!-- 时间队列:按下次执行时间组织的任务行(替代生硬表格) -->
|
||||
<div v-else class="sched-wrap">
|
||||
<div class="sched-list card">
|
||||
<div v-for="row in pagedList" :key="row.id" class="sched-row">
|
||||
<div class="sr-when">
|
||||
<b>{{ nextWhen(row).main }}</b>
|
||||
<span>{{ nextWhen(row).sub }}</span>
|
||||
</div>
|
||||
<div class="sr-main">
|
||||
<b>{{ row.name }}</b>
|
||||
<span>{{ pluginName(row.plugin_id) }}</span>
|
||||
</div>
|
||||
<code class="cron-chip">{{ row.cron }}</code>
|
||||
<div class="sr-last" :class="row.last_status === 'ok' ? 'ok' : (row.last_status === 'error' ? 'err' : '')">
|
||||
<template v-if="row.last_run_at">
|
||||
<span>上次 {{ fmtShort(row.last_run_at) }}</span>
|
||||
<span class="st2">
|
||||
<template v-if="row.last_status === 'ok'">✓ 成功<template v-if="row.last_duration"> · {{ row.last_duration }}s</template></template>
|
||||
<template v-else-if="row.last_status === 'error'">✕ 失败</template>
|
||||
</span>
|
||||
</template>
|
||||
<span v-else class="st2 none">从未执行</span>
|
||||
</div>
|
||||
<div class="sr-acts">
|
||||
<el-switch :model-value="row.enabled" size="small" @change="(v) => onToggle(row, v)" />
|
||||
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" @click="onDelete(row)">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-pagination v-if="list.length > pageSize" class="sched-pager" small background
|
||||
layout="prev, pager, next" :total="list.length" :page-size="pageSize"
|
||||
:current-page="page" @current-change="(p) => page = p" />
|
||||
</div>
|
||||
|
||||
<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 v-if="form.plugin_id" label="使用配置">
|
||||
<el-select v-model="cfgSel" class="w-full" placeholder="默认配置">
|
||||
<el-option label="默认配置" value="" />
|
||||
<el-option v-for="c in configs" :key="c.id" :value="c.id" :label="c.name" />
|
||||
</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 均为周日)。最小间隔 1 小时,不支持分钟级触发</div>
|
||||
</div>
|
||||
|
||||
<!-- 非高级模式下实时预览生成的 cron -->
|
||||
<div v-if="freq !== 'advanced'" class="cron-preview">
|
||||
表达式 <code>{{ form.cron }}</code>
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<!-- 定时执行引用运行台保存的配置方案:不在此复刻参数字段表单(各场景字段千差万别) -->
|
||||
<el-form-item label="执行配置">
|
||||
<span class="params-tip">到点自动执行该场景,使用上方<b>所选配置</b>(默认 = 插件默认参数);自定义参数请在运行台「存为配置」后引用</span>
|
||||
</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, listPluginConfigs } from '../api'
|
||||
|
||||
const list = ref([])
|
||||
const dlg = ref(false)
|
||||
const editing = ref(null)
|
||||
const saving = ref(false)
|
||||
const preset = ref('')
|
||||
|
||||
// ---- 列表分页:任务多时避免长列表刷屏 ----
|
||||
const page = ref(1)
|
||||
const pageSize = 8
|
||||
const pagedList = computed(() => list.value.slice((page.value - 1) * pageSize, page.value * pageSize))
|
||||
// 删除/清空后当前页可能超界,自动回退
|
||||
watch(() => list.value.length, (n) => {
|
||||
const max = Math.max(1, Math.ceil(n / pageSize))
|
||||
if (page.value > max) page.value = max
|
||||
})
|
||||
|
||||
// ---- 闹钟式触发时间选择状态 ----
|
||||
// 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: {} })
|
||||
|
||||
function pluginName(id) {
|
||||
return store.plugins.find((p) => p.id === id)?.name || id
|
||||
}
|
||||
|
||||
// 下次执行时间的相对化展示(今天/明天/周几 + 日期)
|
||||
function nextWhen(row) {
|
||||
const s = row.next_run_at || ''
|
||||
if (!s) return { main: '—', sub: '无下次触发' }
|
||||
const d = new Date(String(s).replace(' ', 'T'))
|
||||
if (isNaN(d.getTime())) return { main: String(s), sub: '' }
|
||||
const now = new Date()
|
||||
const today0 = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const day0 = new Date(d.getFullYear(), d.getMonth(), d.getDate())
|
||||
const diffDay = Math.round((day0 - today0) / 86400000)
|
||||
const hm = pad2(d.getHours()) + ':' + pad2(d.getMinutes())
|
||||
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]
|
||||
const md = (d.getMonth() + 1) + '-' + d.getDate()
|
||||
let main
|
||||
if (diffDay === 0) main = '今天 ' + hm
|
||||
else if (diffDay === 1) main = '明天 ' + hm
|
||||
else if (diffDay === -1) main = '昨天 ' + hm
|
||||
else main = md + ' ' + hm
|
||||
return { main, sub: md + ' ' + week }
|
||||
}
|
||||
|
||||
// 最近执行时间简写(MM-DD HH:mm)
|
||||
function fmtShort(s) {
|
||||
if (!s) return ''
|
||||
const d = new Date(String(s).replace(' ', 'T'))
|
||||
if (isNaN(d.getTime())) return String(s)
|
||||
return pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes())
|
||||
}
|
||||
|
||||
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))
|
||||
cfgSel.value = ''
|
||||
loadConfigs(id)
|
||||
}
|
||||
|
||||
// ===== 配置方案引用:运行台「存为配置」的方案可在此选用 =====
|
||||
const configs = ref([])
|
||||
const cfgSel = ref('')
|
||||
|
||||
async function loadConfigs(pluginId) {
|
||||
configs.value = []
|
||||
if (!pluginId) return
|
||||
try {
|
||||
const r = await listPluginConfigs(pluginId)
|
||||
configs.value = r.configs || []
|
||||
} catch (e) {
|
||||
// 方案加载失败不阻塞任务编辑,静默降级为「默认配置」
|
||||
}
|
||||
}
|
||||
|
||||
// 把选中的配置方案字段应用到任务(未选 = 插件默认参数)
|
||||
function applySelectedConfig() {
|
||||
if (cfgSel.value) {
|
||||
const c = configs.value.find((x) => x.id === cfgSel.value)
|
||||
if (c) {
|
||||
form.value.fields = { ...c.fields }
|
||||
return
|
||||
}
|
||||
}
|
||||
form.value.fields = buildFields(store.plugins.find((x) => x.id === form.value.plugin_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: {} }
|
||||
cfgSel.value = ''
|
||||
configs.value = []
|
||||
// 默认:每天 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)),
|
||||
}
|
||||
cfgSel.value = ''
|
||||
loadConfigs(row.plugin_id)
|
||||
// 把已有 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 }
|
||||
applySelectedConfig()
|
||||
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;
|
||||
flex-shrink: 0; /* 自然高度,超出由中栏上下文区整体滚动 */
|
||||
}
|
||||
|
||||
.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: var(--on-primary);
|
||||
background: var(--primary-grad);
|
||||
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-wrap { display: flex; flex-direction: column; gap: 10px; }
|
||||
.sched-list { display: flex; flex-direction: column; overflow: hidden; }
|
||||
.sched-row {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
transition: background .13s;
|
||||
}
|
||||
.sched-row:last-child { border-bottom: none; }
|
||||
.sched-row:hover { background: var(--surface-2); }
|
||||
.sr-when { width: 108px; flex-shrink: 0; }
|
||||
.sr-when b { display: block; font-size: 12.5px; font-weight: 600; color: var(--text); font-variant-numeric: tabular-nums; }
|
||||
.sr-when span { font-size: 10.5px; color: var(--text-faint); font-variant-numeric: tabular-nums; }
|
||||
.sr-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||||
.sr-main b { font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sr-main span { font-size: 11px; color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.cron-chip {
|
||||
flex-shrink: 0;
|
||||
font-family: var(--mono); font-size: 11px; color: var(--primary);
|
||||
background: var(--primary-weak); border: 1px solid rgba(var(--primary-rgb), .3);
|
||||
border-radius: 6px; padding: 2px 8px;
|
||||
}
|
||||
.sr-last { width: 150px; flex-shrink: 0; display: flex; flex-direction: column; gap: 1px; font-size: 11px; color: var(--text-faint); }
|
||||
.sr-last .st2 { font-size: 10.5px; }
|
||||
.sr-last.ok .st2 { color: var(--ok); }
|
||||
.sr-last.err .st2 { color: var(--err); }
|
||||
.sr-last .st2.none { color: var(--text-faint); }
|
||||
.sr-acts { flex-shrink: 0; display: flex; align-items: center; gap: 8px; }
|
||||
.sr-acts .el-button + .el-button { margin-left: 0; }
|
||||
.sched-pager { justify-content: center; }
|
||||
|
||||
.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);
|
||||
border: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.params-tip {
|
||||
font-size: 12.5px; color: var(--text-sub); line-height: 1.7;
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
border-radius: 10px; padding: 9px 13px; width: 100%;
|
||||
}
|
||||
.params-tip b { color: var(--primary); font-weight: 600; }
|
||||
|
||||
.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>
|
||||
@@ -0,0 +1,97 @@
|
||||
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')
|
||||
|
||||
/* ============================================================
|
||||
皮肤(skin):只切 token,不改组件。
|
||||
precision = 冷灰 + 压深天蓝的精密工作台(默认)
|
||||
cream = 奶油极简治愈风(旧皮肤,保留可切换)
|
||||
切换:localStorage['37du.skin'] = 'precision' | 'cream'
|
||||
============================================================ */
|
||||
const SKIN_KEY = '37du.skin'
|
||||
const SKINS = ['cream', 'precision']
|
||||
|
||||
function initSkin() {
|
||||
let skin = 'precision'
|
||||
try { skin = localStorage.getItem(SKIN_KEY) || 'precision' } catch (_) { /* 隐私模式等 */ }
|
||||
if (!SKINS.includes(skin)) skin = 'precision'
|
||||
document.documentElement.dataset.skin = skin
|
||||
}
|
||||
|
||||
// 在挂载前应用,避免首屏闪一下默认皮肤
|
||||
initSkin()
|
||||
|
||||
/* ============================================================
|
||||
奶油涂鸦装饰层:fixed 浮于页面顶层,仅视觉点缀。
|
||||
可开关:localStorage['37du.doodles'] = 'off'(登录页顶部 ✿ 按钮同源)
|
||||
注意:涂鸦是奶油皮肤专属装饰,precision 皮肤下由 CSS 整体隐藏。
|
||||
============================================================ */
|
||||
const DOODLES = {
|
||||
squiggle:
|
||||
'<svg width="90" height="46" viewBox="0 0 90 46" fill="none">' +
|
||||
'<path d="M4 34 Q 16 6 30 28 T 58 22 T 84 26" stroke="#7CC3E8" stroke-width="3" stroke-linecap="round"/>' +
|
||||
'<path d="M6 41 Q 22 20 38 38 T 66 34" stroke="#E5D9C5" stroke-width="2.4" stroke-linecap="round"/></svg>',
|
||||
cloud:
|
||||
'<svg width="70" height="44" viewBox="0 0 70 44" fill="none">' +
|
||||
'<path d="M18 36 a10 10 0 0 1-1-19.8 A13 13 0 0 1 42 14.5 a9.5 9.5 0 0 1 10 8.6 A8 8 0 0 1 51 36Z" fill="#DCEFF9" stroke="#A8D8F2" stroke-width="2"/></svg>',
|
||||
sparkles:
|
||||
'<svg width="80" height="60" viewBox="0 0 80 60" fill="none">' +
|
||||
'<path d="M14 8 l2.6 5.4 5.4 2.6 -5.4 2.6 -2.6 5.4 -2.6 -5.4 -5.4 -2.6 5.4 -2.6Z" fill="#F2C96B"/>' +
|
||||
'<path d="M62 6 l1.8 3.7 3.7 1.8 -3.7 1.8 -1.8 3.7 -1.8 -3.7 -3.7 -1.8 3.7 -1.8Z" fill="#7CC3E8"/>' +
|
||||
'<path d="M40 30 l2 4 4 2 -4 2 -2 4 -2 -4 -4 -2 4 -2Z" fill="#E58B8B"/></svg>',
|
||||
heart:
|
||||
'<svg width="46" height="42" viewBox="0 0 46 42" fill="none">' +
|
||||
'<path d="M23 38 C 10 29 3 21 3 13 A 10 10 0 0 1 23 9 A 10 10 0 0 1 43 13 C 43 21 36 29 23 38Z" fill="#FBE3E0" stroke="#E9A7A0" stroke-width="2.4"/></svg>',
|
||||
plant:
|
||||
'<svg width="60" height="66" viewBox="0 0 60 66" fill="none">' +
|
||||
'<path d="M30 62 V 26" stroke="#9BC88F" stroke-width="3" stroke-linecap="round"/>' +
|
||||
'<path d="M30 30 C 18 30 14 18 16 10 C 24 10 28 18 30 22 C 32 15 38 9 46 10 C 46 18 40 28 30 30Z" fill="#D9EED1" stroke="#9BC88F" stroke-width="2"/>' +
|
||||
'<path d="M30 44 C 22 44 18 36 19 30 C 26 30 29 36 30 40 C 34 34 40 31 45 32 C 43 40 37 44 30 44Z" fill="#C6E6BB" stroke="#9BC88F" stroke-width="2"/></svg>',
|
||||
sun:
|
||||
'<svg width="54" height="54" viewBox="0 0 54 54" fill="none">' +
|
||||
'<circle cx="27" cy="27" r="12" fill="#FFF2C9" stroke="#F2C96B" stroke-width="2.4"/>' +
|
||||
'<g stroke="#F2C96B" stroke-width="2.6" stroke-linecap="round">' +
|
||||
'<path d="M27 4v7M27 43v7M4 27h7M43 27h7M10 10l5 5M39 39l5 5M44 10l-5 5M15 39l-5 5"/></g></svg>',
|
||||
}
|
||||
|
||||
function initDoodles() {
|
||||
if (document.getElementById('dsh-doodles')) return
|
||||
const wrap = document.createElement('div')
|
||||
wrap.id = 'dsh-doodles'
|
||||
// [类型, left, top, 水平翻转]
|
||||
const spots = [
|
||||
['squiggle', '6%', '12%', false],
|
||||
['cloud', '88%', '8%', false],
|
||||
['sun', '93%', '40%', false],
|
||||
['sparkles', '78%', '66%', false],
|
||||
['heart', '5%', '68%', false],
|
||||
['plant', '13%', '36%', true],
|
||||
]
|
||||
for (const [name, left, top, flip] of spots) {
|
||||
const el = document.createElement('span')
|
||||
el.className = 'doodle'
|
||||
el.style.left = left
|
||||
el.style.top = top
|
||||
el.innerHTML = DOODLES[name] || DOODLES.sparkles
|
||||
if (flip) el.querySelector('svg').style.transform = 'scaleX(-1)'
|
||||
wrap.appendChild(el)
|
||||
}
|
||||
document.body.appendChild(wrap)
|
||||
let on = 'on'
|
||||
try { on = localStorage.getItem('37du.doodles') || 'on' } catch (_) {}
|
||||
document.documentElement.classList.toggle('no-doodles', on === 'off')
|
||||
}
|
||||
|
||||
// 应用挂载后注入(body 已存在),不阻塞首屏
|
||||
initDoodles()
|
||||
@@ -0,0 +1,125 @@
|
||||
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 '' } })(),
|
||||
// 当前主视图(Run-centric 三栏:总览 / 运行台 / 计划)
|
||||
// overview 总览(工作台首页)· run 运行台(单场景执行)· plans 计划(定时任务)
|
||||
view: 'overview',
|
||||
authExpired: false, // 授权票据已过期(最长离线 7 天),须联网刷新才能继续使用
|
||||
license: null, // 授权票据概要 {status, expire_ts, expire_at, days_left}(/api/meta 下发,供状态栏展示)
|
||||
recents: [], // 最近运行记录(run_done 时追加):{pluginId, runId, ok, error, time, name}
|
||||
_runPlugins: {}, // run_id → plugin_id(run_start 登记,run_done 消费)
|
||||
pendingReplay: null, // 活动流点击最近运行 → 运行台回看:{pluginId, runId}(PluginPage 消费后清空)
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
// 缓存按账号隔离(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
|
||||
store._runPlugins[ev.run_id] = ev.plugin_id || ''
|
||||
// 运行态由事件驱动:定时任务触发的运行没有本地点击,必须靠 run_start 点亮
|
||||
// (设备级单活,同时只会有一个 run)。日志归属本次运行,故开始时清空。
|
||||
clearLogs()
|
||||
store.running = true
|
||||
store.progress = 0
|
||||
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 = ''
|
||||
// 最近运行记录(供总览首页展示)
|
||||
const pid = store._runPlugins[ev.run_id] || ''
|
||||
delete store._runPlugins[ev.run_id]
|
||||
const rec = {
|
||||
pluginId: pid,
|
||||
runId: ev.run_id || '',
|
||||
name: (store.plugins.find((p) => p.id === pid) || {}).name || pid || '未知场景',
|
||||
ok: !!ev.ok,
|
||||
error: ev.error || '',
|
||||
time: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
|
||||
}
|
||||
store.recents.unshift(rec)
|
||||
if (store.recents.length > 8) store.recents.pop()
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
/* ============ 37du 执行机壳 · 设计令牌(token 层) ============
|
||||
规则:组件内**只允许**引用这里的 token,不写字面色值(rgba 一律走 --*-rgb 变量)。
|
||||
换肤只需在 [data-skin="..."] 里重映射同名 token,组件代码零改动。
|
||||
默认皮肤 = cream(奶油极简治愈风,现状像素级不变)。
|
||||
============================================================ */
|
||||
:root {
|
||||
/* ---- 基础 ---- */
|
||||
--bg: #F9F7F2;
|
||||
--bg-grad: radial-gradient(1200px 720px at 50% -8%, #FDFCF8 0%, #F9F7F2 55%, #F4F1EA 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #F6F3EC;
|
||||
--surface-3: #FDFCF9; /* 输入框底 */
|
||||
--surface-glow: #FBFDFF; /* 卡片高亮底(运行中/渐变收尾) */
|
||||
--border: #EFE9DE;
|
||||
--border-strong: #E0D9C9;
|
||||
--border-warm: #E7E0D2; /* 登录页卡片描边 */
|
||||
--border-warm-2: #F1ECE2; /* 更浅一级描边 */
|
||||
--border-hover: #D6CFC0;
|
||||
--row-hover: #F8F5EF; /* 日志行 hover */
|
||||
--track: #EDE7DB; /* 进度条底槽 */
|
||||
--scrollbar: #DED7C8;
|
||||
--scrollbar-hover: #CCC4B2;
|
||||
|
||||
--text: #222222;
|
||||
--text-sub: #666666;
|
||||
--text-faint: #9C9589;
|
||||
--text-warm-sub: #5B5B5B;
|
||||
--text-warm-faint: #8A8377;
|
||||
--text-muted-warm: #C4B89E; /* 未登录/未配置的弱提示 */
|
||||
--text-disabled: #C9C2B4;
|
||||
--placeholder: #B5AD9D;
|
||||
--on-primary: #ffffff; /* 主色/渐变底上的前景 */
|
||||
--text-rgb: 34, 34, 34;
|
||||
--on-primary-rgb: 255, 255, 255;
|
||||
|
||||
--primary: #7CC3E8; /* 浅天蓝 · 辅助强调色 */
|
||||
--primary-2: #A8D8F2;
|
||||
--primary-rgb: 124, 195, 232;
|
||||
--primary-grad: linear-gradient(135deg, #92D1F0 0%, #6FBAE6 100%);
|
||||
--primary-grad-2: linear-gradient(135deg, #8FD0F0 0%, #6FBAE6 100%);
|
||||
--primary-grad-3: linear-gradient(135deg, #9BD1EE, #7CC3E8);
|
||||
--primary-strong: #5FAFD9;
|
||||
--primary-hover: #6FBAE6; /* 主按钮 hover 底(纯色,与渐变收尾同色) */
|
||||
--primary-soft: #9BD1EE;
|
||||
--primary-line: #BFE2F4;
|
||||
--primary-weak: #EFF7FC;
|
||||
--primary-weak-2: #E3F1FA;
|
||||
--primary-tint: #F4FAFD;
|
||||
--primary-disabled: #C9E6F5;
|
||||
|
||||
--ok: #5BBE96;
|
||||
--ok-weak: #E9F7F0;
|
||||
--ok-text: #3F9E77;
|
||||
--ok-text-2: #1a8f63;
|
||||
--ok-rgb: 91, 190, 150;
|
||||
--ok-rgb-2: 34, 176, 122;
|
||||
--err: #E58B8B;
|
||||
--err-weak: #FBF0F0;
|
||||
--err-rgb: 229, 139, 139;
|
||||
--danger: #e5484d; /* 对话框错误文案(比 --err 更重的红) */
|
||||
--warn: #E0A85C;
|
||||
--warn-weak: #FBF3E3;
|
||||
--warn-bg: #FFF4E5;
|
||||
--warn-text: #9A5B14;
|
||||
--warn-rgb: 224, 122, 40;
|
||||
--warn-icon-rgb: 247, 162, 58;
|
||||
|
||||
/* ---- 场景磁贴 / 装饰 ---- */
|
||||
--tile-fg: #ffffff; /* 磁贴前景(皮肤若改用淡色底需同步改这个) */
|
||||
--tile-faint-bg: #E3DED2;
|
||||
--dot-off: #c6ccdc;
|
||||
--dot-muted: #D0C9BA;
|
||||
--sep-warm: #CFC8B8;
|
||||
--switch-off: #D8D0BF;
|
||||
--badge-warm-text: #A08F6F;
|
||||
--badge-warm-bg: #FBF7EE;
|
||||
--badge-warm-border: #EFE4CB;
|
||||
--badge-off-text: #B09E7E;
|
||||
--badge-dot: #C9BFA6;
|
||||
--border-strong-rgb: 224, 217, 201;
|
||||
--chrome-rgb: 74, 140, 247;
|
||||
--chrome-icon: radial-gradient(circle at 30% 30%, #e6f2ff, #4a8cf7 55%, #2b6be0);
|
||||
--chrome-icon-warn: radial-gradient(circle at 30% 30%, #fff6e6, #f7a23a 55%, #e07324);
|
||||
--hero-grad: linear-gradient(120deg, #FFFFFF 0%, #FBFDFF 55%, #F7FBFE 100%);
|
||||
--profile-head-grad: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
--surface-cool: #f6f8fd;
|
||||
--surface-cool-2: #fafbfe;
|
||||
|
||||
/* ---- 阴影:仅极柔和浅阴影 ---- */
|
||||
--shadow-sm: 0 1px 3px rgba(var(--text-rgb), .05), 0 2px 10px -4px rgba(var(--text-rgb), .06);
|
||||
--shadow-md: 0 8px 24px -14px rgba(var(--text-rgb), .14);
|
||||
--shadow-lift: 0 14px 34px -16px rgba(var(--text-rgb), .18);
|
||||
|
||||
/* ---- 圆角:全局大圆角 ---- */
|
||||
--radius: 16px;
|
||||
--radius-sm: 11px;
|
||||
|
||||
/* ---- 字体:正文无衬线 Inter;标题可用圆润手写装饰字体 ---- */
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Segoe UI", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
--font-doodle: "Segoe Script", "Comic Sans MS", "KaiTi", "STKaiti", "cursive";
|
||||
|
||||
/* ---- element-plus 主题与浅天蓝统一 ---- */
|
||||
--el-color-primary: #7CC3E8;
|
||||
--el-color-primary-light-3: #9BD1EE;
|
||||
--el-color-primary-light-5: #BFE2F4;
|
||||
--el-color-primary-light-7: #DCEFF9;
|
||||
--el-color-primary-light-8: #E9F5FB;
|
||||
--el-color-primary-light-9: #F4FAFD;
|
||||
--el-color-primary-dark-2: #5FAFD9;
|
||||
--el-border-radius-base: 12px;
|
||||
--el-border-radius-small: 10px;
|
||||
--el-border-radius-round: 999px;
|
||||
--el-box-shadow: 0 8px 24px -16px rgba(var(--text-rgb), .14);
|
||||
--el-box-shadow-light: 0 6px 18px -14px rgba(var(--text-rgb), .10);
|
||||
|
||||
/* ---- 产品级排版/间距/动效 ---- */
|
||||
--radius-lg: 22px;
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 28px;
|
||||
--dur: .18s;
|
||||
--ease: cubic-bezier(.22, 1, .36, 1);
|
||||
--grad-sky: linear-gradient(135deg, #A8D8F2, #7CC3E8);
|
||||
--grad-peach: linear-gradient(135deg, #F2C9B8, #E8A98E);
|
||||
--grad-mint: linear-gradient(135deg, #C9E6BB, #9BC88F);
|
||||
--grad-lilac: linear-gradient(135deg, #D9C7F0, #B79AE3);
|
||||
--grad-honey: linear-gradient(135deg, #F7D9A0, #EFBE6B);
|
||||
--grad-blush: linear-gradient(135deg, #F2B8C6, #E48E9F);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
皮肤 · precision(冷灰 + 压深天蓝的"精密工作台")
|
||||
—— 只是 token 重映射的**首版脚手架**,用于后续「双皮肤同页对比」评审;
|
||||
尚未做像素级打磨,也不改变任何组件代码。默认不启用:
|
||||
启用方式 = <html data-skin="precision">(localStorage['37du.skin'])。
|
||||
============================================================ */
|
||||
[data-skin="precision"] {
|
||||
--bg: #F4F6F9;
|
||||
--bg-grad: #F4F6F9; /* 冷灰画布:去掉奶油径向渐变 */
|
||||
--surface: #FFFFFF;
|
||||
--surface-2: #F1F4F8;
|
||||
--surface-3: #FFFFFF;
|
||||
--surface-glow: #F8FAFC;
|
||||
--border: #E4E9F0;
|
||||
--border-strong: #CDD6E1;
|
||||
--border-warm: #E4E9F0;
|
||||
--border-warm-2: #EEF2F7;
|
||||
--border-hover: #CDD6E1;
|
||||
--row-hover: #F1F4F8;
|
||||
--track: #E4E9F0;
|
||||
--scrollbar: #CBD5E1;
|
||||
--scrollbar-hover: #94A3B8;
|
||||
|
||||
--text: #182230;
|
||||
--text-sub: #5A6674;
|
||||
--text-faint: #7C8896;
|
||||
--text-warm-sub: #5A6674;
|
||||
--text-warm-faint: #7C8896;
|
||||
--text-muted-warm: #7C8896;
|
||||
--text-disabled: #A8B3C1;
|
||||
--placeholder: #94A3B8;
|
||||
--on-primary: #FFFFFF;
|
||||
--text-rgb: 15, 23, 42;
|
||||
--on-primary-rgb: 255, 255, 255;
|
||||
|
||||
--primary: #1E6FA8;
|
||||
--primary-2: #3E93CF;
|
||||
--primary-rgb: 30, 111, 168;
|
||||
--primary-grad: #17608F; /* 皮肤可把渐变 token 设成纯色 */
|
||||
--primary-grad-2: #1E6FA8;
|
||||
--primary-grad-3: #3E93CF;
|
||||
--primary-strong: #17608F;
|
||||
--primary-hover: #1E6FA8;
|
||||
--primary-soft: #3E93CF;
|
||||
--primary-line: #CDD6E1;
|
||||
--primary-weak: #E9F2FA;
|
||||
--primary-weak-2: #E9F2FA;
|
||||
--primary-tint: #E9F2FA;
|
||||
--primary-disabled: #BFD8EA;
|
||||
|
||||
/* element-plus 主题同步(否则表单/表格等内置组件会残留奶油浅蓝) */
|
||||
--el-color-primary: #1E6FA8;
|
||||
--el-color-primary-light-3: #3E93CF;
|
||||
--el-color-primary-light-5: #7FB4D8;
|
||||
--el-color-primary-light-7: #BFD8EA;
|
||||
--el-color-primary-light-8: #D9E8F4;
|
||||
--el-color-primary-light-9: #E9F2FA;
|
||||
--el-color-primary-dark-2: #17608F;
|
||||
|
||||
--ok: #1F8A4C;
|
||||
--ok-weak: #E7F5EC;
|
||||
--ok-text: #1F8A4C;
|
||||
--ok-text-2: #1F8A4C;
|
||||
--ok-rgb: 31, 138, 76;
|
||||
--ok-rgb-2: 31, 138, 76;
|
||||
--err: #D64545;
|
||||
--err-weak: #FBEBEB;
|
||||
--err-rgb: 214, 69, 69;
|
||||
--danger: #D64545;
|
||||
--warn: #B26B00;
|
||||
--warn-weak: #FBF3E0;
|
||||
--warn-bg: #FBF3E0;
|
||||
--warn-text: #B26B00;
|
||||
--warn-rgb: 178, 107, 0;
|
||||
--warn-icon-rgb: 178, 107, 0;
|
||||
|
||||
/* 场景磁贴:淡色底 + 同色系前景(v2 的 tile 风格),故前景不能再用白色 */
|
||||
--tile-fg: #1E6FA8;
|
||||
--grad-sky: #E9F2FA;
|
||||
--grad-peach: #FBF3E0;
|
||||
--grad-mint: #E7F5EC;
|
||||
--grad-lilac: #EFEAF7;
|
||||
--grad-honey: #FBF3E0;
|
||||
--grad-blush: #FBEBEB;
|
||||
--tile-faint-bg: #E9EDF3;
|
||||
--dot-off: #CBD5E1;
|
||||
--dot-muted: #CBD5E1;
|
||||
--sep-warm: #CDD6E1;
|
||||
--switch-off: #CBD5E1;
|
||||
--badge-warm-text: #B26B00;
|
||||
--badge-warm-bg: #FBF3E0;
|
||||
--badge-warm-border: #E7C88F;
|
||||
--badge-off-text: #7C8896;
|
||||
--badge-dot: #CBD5E1;
|
||||
--border-strong-rgb: 205, 214, 225;
|
||||
--chrome-rgb: 74, 140, 247;
|
||||
--hero-grad: #FFFFFF;
|
||||
--profile-head-grad: #F1F4F8;
|
||||
--surface-cool: #F1F4F8;
|
||||
--surface-cool-2: #F8FAFC;
|
||||
|
||||
--radius: 12px;
|
||||
--radius-sm: 8px;
|
||||
--radius-lg: 14px;
|
||||
--shadow-sm: 0 1px 2px rgba(var(--text-rgb), .05);
|
||||
--shadow-md: 0 8px 24px -12px rgba(var(--text-rgb), .14);
|
||||
--shadow-lift: 0 14px 34px -16px rgba(var(--text-rgb), .18);
|
||||
|
||||
/* 精密工作台不用手写装饰字体 */
|
||||
--font-doodle: var(--font-body);
|
||||
}
|
||||
|
||||
/* 涂鸦层是奶油皮肤专属装饰,换肤时整体关闭(同一开关也支持手动 off) */
|
||||
html[data-skin="precision"] .doodle { display: none; }
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: var(--font-body);
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
.__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: var(--scrollbar); border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-hover); background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡:大圆角 + 极柔和阴影 + hover 轻微上浮 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
transition: transform .18s ease, box-shadow .18s ease, border-color .18s ease;
|
||||
}
|
||||
.panel:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: var(--shadow-md);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 白底圆角卡(通用卡片:总览首页统计/场景/最近动态等) */
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 12px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: var(--border-hover); background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: var(--text-disabled); border-color: var(--border); background: var(--surface-2); cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: var(--on-primary);
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 6px 16px -6px rgba(var(--primary-rgb), .6);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 10px 22px -8px rgba(var(--primary-rgb), .7); color: var(--on-primary); }
|
||||
.btn.primary:disabled { background: var(--primary-disabled); box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 11px;
|
||||
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='%239C9589' 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: var(--track); border-radius: 999px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 999px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(var(--primary-rgb),.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;
|
||||
flex: 1 1 auto; /* 在 .log-wrap 里填满剩余高度并自己滚 */
|
||||
min-height: 0;
|
||||
}
|
||||
.log-line:hover { background: var(--row-hover); }
|
||||
.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; }
|
||||
|
||||
/* ============================================================
|
||||
产品级通用元素:分节标题(更大更清晰)/ 空状态
|
||||
============================================================ */
|
||||
.page-title {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
letter-spacing: .01em;
|
||||
}
|
||||
.page-sub {
|
||||
font-size: 12.5px;
|
||||
color: var(--text-sub);
|
||||
line-height: 1.7;
|
||||
}
|
||||
.empty-note {
|
||||
color: var(--text-faint);
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
font-size: 12.5px;
|
||||
line-height: 2;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.empty-note b { color: var(--text-sub); font-weight: 600; }
|
||||
|
||||
|
||||
/* ============================================================
|
||||
手绘涂鸦装饰层:fixed 浮于页面顶层,仅视觉点缀,
|
||||
不参与流式布局、不拦截交互;html.no-doodles 整体关闭
|
||||
============================================================ */
|
||||
.doodle {
|
||||
position: fixed;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
z-index: 9999;
|
||||
opacity: .55;
|
||||
filter: drop-shadow(0 2px 3px rgba(var(--text-rgb), .06));
|
||||
animation: doodleFloat 7s ease-in-out infinite;
|
||||
}
|
||||
html.no-doodles .doodle { display: none; }
|
||||
@keyframes doodleFloat {
|
||||
0%, 100% { transform: translateY(0) rotate(-1deg); }
|
||||
50% { transform: translateY(-8px) rotate(1.5deg); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.doodle { animation: none; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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: {
|
||||
// 构建产物直接输出到壳的渲染层目录(Electron 壳/CLI 服务以此为前端根)
|
||||
outDir: '../renderer/dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
Generated
+4168
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "37du-electron-shell",
|
||||
"productName": "37du 自动化工作台",
|
||||
"version": "1.0.0",
|
||||
"description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)",
|
||||
"main": "electron/main.js",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
"start": "node electron/main.js --cli",
|
||||
"dev": "node electron/main.js --cli --dev",
|
||||
"electron": "electron .",
|
||||
"pack": "electron-builder --win nsis",
|
||||
"copy-renderer": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/copy-renderer.ps1"
|
||||
},
|
||||
"dependencies": {
|
||||
"adm-zip": "^0.5.18",
|
||||
"better-sqlite3": "^13.0.3",
|
||||
"ws": "^8.21.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "^30.5.1",
|
||||
"electron-builder": "^24.13.3"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.37du.automation",
|
||||
"productName": "37du 自动化工作台",
|
||||
"asar": true,
|
||||
"directories": {
|
||||
"output": "dist-app"
|
||||
},
|
||||
"files": [
|
||||
"electron/**/*",
|
||||
"renderer/**/*",
|
||||
"package.json"
|
||||
],
|
||||
"win": {
|
||||
"target": [
|
||||
{
|
||||
"target": "nsis",
|
||||
"arch": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
],
|
||||
"artifactName": "setup-37du-shell-${version}.exe"
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"perMachine": false,
|
||||
"allowToChangeInstallationDirectory": true,
|
||||
"createDesktopShortcut": true,
|
||||
"createStartMenuShortcut": true,
|
||||
"shortcutName": "37du 自动化工作台",
|
||||
"runAfterFinish": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
# 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)
|
||||
# - Dependencies: pinned to the versions validated in the project .venv
|
||||
# - Runtime subset: webhost/backend/{plugins,core,shared} (minimal for
|
||||
# plugin_runner protocol + platform login)
|
||||
# - 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):
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 [-EnvVersion 1.0.0] [-SkipLocal]
|
||||
# Needs: access to python.org / pypi.org (or an internal mirror via $PipIndex)
|
||||
# ============================================================================
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$EnvVersion = "1.0.0",
|
||||
[switch]$SkipLocal, # do NOT install into electron-shell/python-env/
|
||||
[switch]$Force # re-download embeddable / get-pip
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$Shell = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||||
$Repo = Resolve-Path (Join-Path $Shell "..\..")
|
||||
$Build = Join-Path $Shell "build\python-env"
|
||||
$Dist = Join-Path $Shell "dist-env"
|
||||
$DownloadDir = Join-Path $Build "downloads"
|
||||
$PyDir = Join-Path $Build "py" # temp root: interpreter + deps + runtime subset
|
||||
|
||||
$PythonVersion = "3.11.9"
|
||||
$EmbedUrl = "https://www.python.org/ftp/python/$PythonVersion/python-$PythonVersion-embed-amd64.zip"
|
||||
$EmbedZip = Join-Path $DownloadDir "python-$PythonVersion-embed-amd64.zip"
|
||||
$GetPip = Join-Path $DownloadDir "get-pip.py"
|
||||
$PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
|
||||
# All dependencies (top-level + key transitive), pinned to .venv-validated versions
|
||||
$Pinned = @(
|
||||
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1",
|
||||
"pandas==3.0.5", "numpy==2.3.5", "openpyxl==3.1.5",
|
||||
"python-dateutil==2.9.0.post0", "tzdata==2026.3", "et-xmlfile",
|
||||
"websocket-client==1.9.0",
|
||||
"DrissionPage==4.1.1.4", "DrissionGet==1.2.1", "DrissionRecord==2.0.1",
|
||||
"lxml==6.1.1", "psutil==7.2.2", "tldextract==5.3.2", "cssselect==1.5.0", "click==8.4.2",
|
||||
"ddddocr==1.6.1", "onnxruntime==1.28.0", "Pillow==12.3.0",
|
||||
"opencv-python-headless==5.0.0.93", "flatbuffers==25.12.19", "protobuf==7.35.1",
|
||||
"pywin32==312",
|
||||
"urllib3==2.7.0", "certifi==2026.7.22", "idna==3.18",
|
||||
"charset-normalizer==3.4.9", "six==1.17.0", "packaging==26.3"
|
||||
)
|
||||
|
||||
function Download-File([string]$Url, [string]$Dest) {
|
||||
if (-not $Force -and (Test-Path $Dest) -and (Get-Item $Dest).Length -gt 0) {
|
||||
Write-Host " cache hit: $Dest"
|
||||
return
|
||||
}
|
||||
Write-Host " downloading: $Url"
|
||||
curl.exe -sL --retry 3 -o $Dest $Url
|
||||
if (-not (Test-Path $Dest) -or (Get-Item $Dest).Length -eq 0) {
|
||||
throw "download failed: $Url"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "=== 37du portable python env build v$EnvVersion ===" -ForegroundColor Cyan
|
||||
|
||||
# ---------- 1. portable interpreter ----------
|
||||
New-Item -ItemType Directory -Force -Path $Build, $Dist, $DownloadDir | Out-Null
|
||||
Download-File $EmbedUrl $EmbedZip
|
||||
if (Test-Path $PyDir) { Remove-Item -Recurse -Force $PyDir }
|
||||
New-Item -ItemType Directory -Force -Path $PyDir | Out-Null
|
||||
Write-Host "extracting embeddable python ..."
|
||||
Expand-Archive -Path $EmbedZip -DestinationPath $PyDir -Force
|
||||
$PyExe = Join-Path $PyDir "python.exe"
|
||||
if (-not (Test-Path $PyExe)) { throw "missing python.exe in embeddable" }
|
||||
|
||||
# enable site-packages (pip / pywin32 .pth depend on 'import site')
|
||||
$Tag = ($PythonVersion.Split('.')[0..1] -join '')
|
||||
$Pth = Join-Path $PyDir "python$Tag._pth"
|
||||
Write-Host "enabling site + site-packages: $Pth"
|
||||
Set-Content -Path $Pth -Encoding ascii -Value @(
|
||||
"python$Tag.zip"
|
||||
"."
|
||||
"Lib\site-packages"
|
||||
""
|
||||
"# Enable site (pip / pywin32 .pth)"
|
||||
"import site"
|
||||
)
|
||||
|
||||
# ---------- 2. pip + dependencies ----------
|
||||
Download-File "https://bootstrap.pypa.io/get-pip.py" $GetPip
|
||||
Write-Host "bootstrapping pip ..."
|
||||
& $PyExe $GetPip --no-warn-script-location --disable-pip-version-check | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "get-pip failed (exit $LASTEXITCODE)" }
|
||||
|
||||
Write-Host "installing pinned deps ($($Pinned.Count)) with --only-binary ..."
|
||||
$PipArgs = @("-m", "pip", "install", "--no-warn-script-location",
|
||||
"--disable-pip-version-check", "--only-binary=:all:")
|
||||
if ($PipIndex) { $PipArgs += "--index-url", $PipIndex }
|
||||
$PipArgs += $Pinned
|
||||
& $PyExe $PipArgs | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "pip install failed (exit $LASTEXITCODE)" }
|
||||
|
||||
# copy pywin32 DLLs next to the interpreter (no postinstall / PATH dependency)
|
||||
$PyWin32Sys = Join-Path $PyDir "Lib\site-packages\pywin32_system32"
|
||||
if (Test-Path $PyWin32Sys) {
|
||||
Copy-Item -Path (Join-Path $PyWin32Sys "*.dll") -Destination $PyDir -Force
|
||||
Write-Host "pywin32 DLLs copied to interpreter root"
|
||||
}
|
||||
|
||||
# ---------- 3. webhost runtime subset ----------
|
||||
$Wb = Join-Path $Repo "desktop\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)."""'
|
||||
)
|
||||
|
||||
# core: plugin_runner + auth + winjob + job_guard (no scheduler/http modules)
|
||||
$CoreFiles = @("__init__.py", "plugin_runner.py", "auth.py", "winjob.py", "job_guard.py")
|
||||
foreach ($f in $CoreFiles) {
|
||||
$src = Join-Path (Join-Path $Wb "core") $f
|
||||
if (-not (Test-Path $src)) { throw "missing webhost core file: $f" }
|
||||
Copy-Item -Path $src -Destination (Join-Path $EnvWb "core") -Force
|
||||
}
|
||||
# plugins: loader + base
|
||||
foreach ($f in @("__init__.py", "base.py")) {
|
||||
$src = Join-Path (Join-Path $Wb "plugins") $f
|
||||
if (-not (Test-Path $src)) { throw "missing webhost plugins file: $f" }
|
||||
Copy-Item -Path $src -Destination (Join-Path $EnvWb "plugins") -Force
|
||||
}
|
||||
# shared: all platform login / export modules
|
||||
Get-ChildItem -Path (Join-Path $Wb "shared") -Filter "*.py" | ForEach-Object {
|
||||
Copy-Item -Path $_.FullName -Destination (Join-Path $EnvWb "shared") -Force
|
||||
}
|
||||
|
||||
# ---------- 4. smoke test ----------
|
||||
Write-Host "=== smoke test ===" -ForegroundColor Cyan
|
||||
& $PyExe -c "import sys; print(' python:', sys.version.split()[0])" | Out-Host
|
||||
& $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography; print(' core deps ok')" | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "core deps import failed" }
|
||||
& $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host
|
||||
& $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host
|
||||
& $PyExe -c "import win32com.client; print(' win32com ok')" | Out-Host
|
||||
Push-Location $PyDir
|
||||
try {
|
||||
& $PyExe -c "from webhost.backend.plugins import load_plugins; print(' webhost plugins ok')" | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "webhost plugins import failed" }
|
||||
& $PyExe -c "from webhost.backend.core import auth, job_guard; print(' webhost core ok')" | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "webhost core import failed" }
|
||||
} finally { Pop-Location }
|
||||
|
||||
# ---------- 5. package ----------
|
||||
$Zip = Join-Path $Dist "python-env-$EnvVersion.zip"
|
||||
if (Test-Path $Zip) { Remove-Item -Force $Zip }
|
||||
Write-Host "packaging: $Zip"
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
Push-Location $PyDir
|
||||
try {
|
||||
[System.IO.Compression.ZipFile]::CreateFromDirectory($PyDir, $Zip, [System.IO.Compression.CompressionLevel]::Optimal, $false)
|
||||
} finally { Pop-Location }
|
||||
$Sha = (Get-FileHash -Algorithm SHA256 $Zip).Hash.ToLower()
|
||||
Set-Content -Path "$Zip.sha256" -Value $Sha -Encoding ascii
|
||||
Set-Content -Path (Join-Path $Dist "python-env-latest.txt") -Value $EnvVersion -Encoding ascii
|
||||
Write-Host " sha256: $Sha"
|
||||
Write-Host " artifact: $Zip ($([math]::Round((Get-Item $Zip).Length / 1MB, 1)) MB)"
|
||||
|
||||
# ---------- 6. local install (for dev integration testing) ----------
|
||||
if (-not $SkipLocal) {
|
||||
$LocalEnv = Join-Path $Shell "python-env"
|
||||
$LocalVer = Join-Path $LocalEnv $EnvVersion
|
||||
if (Test-Path $LocalVer) { Remove-Item -Recurse -Force $LocalVer }
|
||||
New-Item -ItemType Directory -Force -Path $LocalEnv, $LocalVer | Out-Null
|
||||
Copy-Item -Path (Join-Path $PyDir "*") -Destination $LocalVer -Recurse -Force
|
||||
$Stamp = Get-Date -Format o
|
||||
$Json = "{`n `"version`": `"$EnvVersion`",`n `"updated_at`": `"$Stamp`"`n}"
|
||||
# BOM-less UTF-8(PS 5.1 的 Set-Content -Encoding utf8 会写 BOM,JSON.parse 会挂)
|
||||
[System.IO.File]::WriteAllText((Join-Path $LocalEnv "current.json"), $Json, (New-Object System.Text.UTF8Encoding($false)))
|
||||
Write-Host "local install done: $LocalVer (current.json -> $EnvVersion)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
Write-Host "=== build complete v$EnvVersion ===" -ForegroundColor Green
|
||||
@@ -0,0 +1,15 @@
|
||||
# Build shell frontend source -> renderer/dist (self-contained direction; old webhost untouched)
|
||||
# Usage: npm run copy-renderer
|
||||
$ErrorActionPreference = "Stop"
|
||||
$fd = Join-Path $PSScriptRoot "..\frontend"
|
||||
if (-not (Test-Path (Join-Path $fd "node_modules\vite\bin\vite.js"))) {
|
||||
Write-Error "frontend deps missing; run: cd desktop\electron-shell\frontend && npm install"
|
||||
}
|
||||
Push-Location $fd
|
||||
try {
|
||||
npm run build
|
||||
if ($LASTEXITCODE -ne 0) { throw "vite build failed" }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Write-Host "renderer/dist rebuilt"
|
||||
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""环境包链路探针插件:仅验证运行时可用性,不触网。"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
|
||||
class Dummy(ScenePlugin):
|
||||
id = "dummy_env_probe"
|
||||
name = "环境包探针"
|
||||
version = "1.0.0"
|
||||
description = "验证环境包执行链路"
|
||||
platform = ""
|
||||
fields = []
|
||||
|
||||
def run(self, fields, ctx):
|
||||
# 验证环境包内关键依赖可导入
|
||||
import pandas
|
||||
import openpyxl
|
||||
import requests
|
||||
import websocket
|
||||
ctx.log("探针插件已加载 pandas/openpyxl/requests/websocket")
|
||||
return {"summary": "env-ok", "detail": "deps-loaded", "echo": fields}
|
||||
|
||||
|
||||
PLUGINS.append(Dummy())
|
||||
Reference in New Issue
Block a user