diff --git a/desktop/controlplane/apis/admin.py b/desktop/controlplane/apis/admin.py index 4d7fa4f..64734d1 100644 --- a/desktop/controlplane/apis/admin.py +++ b/desktop/controlplane/apis/admin.py @@ -14,6 +14,7 @@ from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile from fastapi.responses import FileResponse from controlplane import config, schemas +from controlplane.apis.notifications import push_account, push_all from controlplane.core.auth import _identity, _require_admin, _revoke_account_tokens from controlplane.core.crypto import _hash_password from controlplane.core.db import _audit, _db, _now @@ -738,18 +739,40 @@ def admin_devices(page: int = Query(default=1, ge=1), page_size: int = Query(default=20, ge=1, le=1000), x_admin_token: str = Header(default="", alias="X-Admin-Token"), x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: - """执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果。""" + """执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果 + 客户端版本。""" _require_admin(x_admin_token, x_api_token) limit, offset = page_bounds(page, page_size) with _db() as conn: total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices") rows = [dict(r) for r in conn.execute( "SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, " - " chrome_ok, last_seen, status, created_at, updated_at " + " chrome_ok, client_version, last_seen, status, created_at, updated_at " "FROM devices ORDER BY last_seen DESC LIMIT %s OFFSET %s", (limit, offset))] return {"items": rows, "total": total} +@router.get("/api/admin/devices/summary") +def admin_devices_summary(x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: + """客户端升级追踪汇总:按版本统计设备数 + 按账号分组展示各设备客户端版本(关旧控制面依据)。""" + _require_admin(x_admin_token, x_api_token) + with _db() as conn: + total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices") + by_version = [dict(r) for r in conn.execute( + "SELECT client_version AS client_version, COUNT(*) AS count " + "FROM devices GROUP BY client_version ORDER BY count DESC")] + by_account = [dict(r) for r in conn.execute( + "SELECT account, client_version, COUNT(*) AS device_count, " + " MAX(last_seen) AS last_seen " + "FROM devices GROUP BY account, client_version ORDER BY account")] + # 关联账号姓名/部门,方便按人识别 + nick = {dict(r)["account"]: (dict(r)["nickname"] or "", dict(r)["dept"] or "") + for r in conn.execute("SELECT account, nickname, dept FROM accounts")} + for row in by_account: + row["nickname"], row["dept"] = nick.get(row["account"], ("", "")) + return {"total": total, "by_version": by_version, "by_account": by_account} + + @router.post("/api/admin/shell-release") async def admin_shell_release(upload: UploadFile = File(...), version: str = Query(...), @@ -792,4 +815,112 @@ async def admin_shell_release(upload: UploadFile = File(...), "sha256": sha256, "notes": notes}, ensure_ascii=False, indent=2), encoding="utf-8") _audit(login, "shell-release", filename) - return {"ok": True, "version": version, "filename": filename, "sha256": sha256} \ No newline at end of file + return {"ok": True, "version": version, "filename": filename, "sha256": sha256} + + +# ==================== 通知下发管理 ==================== +_NOTIF_LEVELS = {"info", "warning", "important"} +_NOTIF_TARGETS = {"all", "account"} + + +def _notif_expiry(iso: str): + """ISO 时间串 → MySQL DATETIME;空串返回 None。""" + iso = (iso or "").strip() + if not iso: + return None + return iso.replace("T", " ")[:19] + + +@router.get("/api/admin/notifications") +def admin_notifications(page: int = Query(default=1, ge=1), + page_size: int = Query(default=20, ge=1, le=200), + q: str = Query(default=""), + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: + """通知列表(分页,按 id 倒序)。""" + _require_admin(x_admin_token, x_api_token) + limit, offset = page_bounds(page, page_size) + where, args = "", [] + if q.strip(): + where = " WHERE (title LIKE %s OR content LIKE %s OR account LIKE %s)" + args = [f"%{q.strip()}%"] * 3 + with _db() as conn: + total = count_rows(conn, "SELECT COUNT(*) AS c FROM notifications" + where, args) + rows = [dict(r) for r in conn.execute( + "SELECT id, title, content, level, target, account, created_at, expires_at, active " + "FROM notifications" + where + " ORDER BY id DESC LIMIT %s OFFSET %s", + args + [limit, offset])] + return {"items": rows, "total": total} + + +@router.post("/api/admin/notifications") +async def admin_notification_create(body: schemas.NotificationIn, + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: + """下发通知:all=全部账号 / account=指定账号;创建后即时 WebSocket 推送在线客户端。""" + login = _require_admin(x_admin_token, x_api_token) + title = (body.title or "").strip() + if not title: + raise HTTPException(400, "标题不能为空") + if body.level not in _NOTIF_LEVELS: + raise HTTPException(400, "level 仅允许 info/warning/important") + if body.target not in _NOTIF_TARGETS: + raise HTTPException(400, "target 仅允许 all/account") + if body.target == "account" and not (body.account or "").strip(): + raise HTTPException(400, "target=account 时必须指定 account") + expires = _notif_expiry(body.expires_at) + with _db() as conn: + cur = conn.execute( + "INSERT INTO notifications(title, content, level, target, account, expires_at) " + "VALUES (%s,%s,%s,%s,%s,%s)", + (title, (body.content or "").strip(), body.level, body.target, + (body.account or "").strip(), expires)) + nid = cur.lastrowid + conn.commit() + _audit(login, "notify-create", f"通知 #{nid} {title} → {body.target}") + payload = {"type": "notify", "notification": { + "id": nid, "title": title, "content": (body.content or "").strip(), + "level": body.level, "target": body.target, "account": (body.account or "").strip(), + "created_at": _now()}} + if body.target == "all": + pushed = await push_all(payload) + else: + pushed = await push_account((body.account or "").strip(), payload) + return {"ok": True, "id": nid, "title": title, "target": body.target, + "pushed": pushed} + + +@router.patch("/api/admin/notifications/{nid}") +async def admin_notification_toggle(nid: int, + active: bool = Query(...), + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: + """启用/停用通知;启用时即时推送给在线客户端。""" + login = _require_admin(x_admin_token, x_api_token) + with _db() as conn: + row = conn.execute( + "SELECT id, title, content, level, target, account, created_at, expires_at " + "FROM notifications WHERE id = %s", (nid,)).fetchone() + conn.execute("UPDATE notifications SET active = %s WHERE id = %s", (int(active), nid)) + conn.commit() + _audit(login, "notify-toggle", f"通知 #{nid} active={active}") + if active and row: + payload = {"type": "notify", "notification": dict(row)} + if row["target"] == "all": + await push_all(payload) + else: + await push_account(row["account"] or "", payload) + return {"ok": True, "id": nid, "active": active} + + +@router.delete("/api/admin/notifications/{nid}") +def admin_notification_delete(nid: int, + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token")) -> dict: + """删除通知。""" + login = _require_admin(x_admin_token, x_api_token) + with _db() as conn: + conn.execute("DELETE FROM notifications WHERE id = %s", (nid,)) + conn.commit() + _audit(login, "notify-delete", f"通知 #{nid}") + return {"ok": True, "id": nid} \ No newline at end of file diff --git a/desktop/controlplane/apis/notifications.py b/desktop/controlplane/apis/notifications.py new file mode 100644 index 0000000..3a80bf7 --- /dev/null +++ b/desktop/controlplane/apis/notifications.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +"""客户端通知:HTTP 拉取(兜底)+ WebSocket 实时推送(管理端下发即推,秒达)。""" +from __future__ import annotations + +import asyncio + +from fastapi import APIRouter, Header, HTTPException, Query, WebSocket, WebSocketDisconnect + +from controlplane import config +from controlplane.core.auth import _check_token, _cloud_account +from controlplane.core.db import _db + +router = APIRouter(tags=["notifications"]) + +# WebSocket 连接注册表:account -> set[WebSocket] +# 说明:控制面单 worker 部署时进程内共享,管理端创建/停用通知时据此即时推送在线客户端; +# 即使推送失败/客户端离线,客户端 60s 轮询兜底保证最终送达。 +_WS_CLIENTS: dict[str, set] = {} + + +@router.get("/api/notifications") +def notifications(account: str = Query(default=""), + x_api_token: str = Header(default="", alias="X-API-Token"), + authorization: str = Header(default="", alias="Authorization")) -> dict: + """客户端拉取通知:优先云会话 token 解工号;兜底 account + X-API-Token。 + 返回 target=all 与 target=该账号 的启用且未过期通知(按创建时间倒序)。""" + acct = _cloud_account(authorization) + if not acct: + _check_token(x_api_token) + acct = (account or "").strip() + if not acct: + raise HTTPException(400, "缺少有效会话或 account") + with _db() as conn: + rows = conn.execute( + """ + SELECT id, title, content, level, target, account, created_at, expires_at + FROM notifications + WHERE active = 1 + AND (target = 'all' OR (target = 'account' AND account = %s)) + AND (expires_at IS NULL OR expires_at > NOW()) + ORDER BY created_at DESC + LIMIT 50 + """, + (acct,), + ).fetchall() + return {"notifications": [dict(r) for r in rows]} + + +@router.websocket("/ws/notifications") +async def ws_notifications(websocket: WebSocket, account: str = Query(default="")): + """客户端长连接:管理端下发通知时即时推送(秒达)。鉴权用 X-API-Token 请求头。""" + token = (websocket.headers.get("x-api-token") or "").strip() + if config.CONTROLPLANE_TOKEN and token != config.CONTROLPLANE_TOKEN: + await websocket.close(code=4401) + return + acct = (account or "").strip() + if not acct: + await websocket.close(code=4400) + return + await websocket.accept() + _WS_CLIENTS.setdefault(acct, set()).add(websocket) + try: + await websocket.send_json({"type": "hello", "account": acct}) + # 保持连接:接收客户端心跳/占位帧;断开(含网络异常)自动清理 + while True: + await websocket.receive_text() + except WebSocketDisconnect: + pass + except Exception: # noqa: BLE001 + pass + finally: + ws_set = _WS_CLIENTS.get(acct) + if ws_set: + ws_set.discard(websocket) + if not ws_set: + _WS_CLIENTS.pop(acct, None) + + +async def _send_ws(ws_set: set, payload: dict) -> None: + for ws in list(ws_set): + try: + await ws.send_json(payload) + except Exception: # noqa: BLE001 + ws_set.discard(ws) + + +async def push_all(payload: dict) -> int: + """推送给全部在线客户端,返回目标连接数。""" + n = 0 + for ws_set in _WS_CLIENTS.values(): + n += len(ws_set) + await _send_ws(ws_set, payload) + return n + + +async def push_account(account: str, payload: dict) -> int: + """推送给指定账号的在线客户端,返回目标连接数。""" + ws_set = _WS_CLIENTS.get(account) + if not ws_set: + return 0 + await _send_ws(ws_set, payload) + return len(ws_set) diff --git a/desktop/controlplane/apis/plugins.py b/desktop/controlplane/apis/plugins.py index 0e3927c..ace799e 100644 --- a/desktop/controlplane/apis/plugins.py +++ b/desktop/controlplane/apis/plugins.py @@ -236,17 +236,19 @@ def device_report(b: schemas.DeviceReportIn, with _db() as conn: conn.execute( "INSERT INTO devices(device_id, account, hostname, os, ip, " - "chrome_installed, chrome_version, chrome_ok, last_seen, status) " - "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) " + "chrome_installed, chrome_version, chrome_ok, client_version, last_seen, status) " + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) " "ON DUPLICATE KEY UPDATE " "account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), " "ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), " "chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), " + "client_version = VALUES(client_version), " "last_seen = VALUES(last_seen), status = VALUES(status)", (device_id, (b.account or "").strip(), (b.hostname or "").strip(), (b.os or "").strip(), (b.ip or "").strip(), int(bool(b.chrome_installed)), (b.chrome_version or "").strip(), - int(bool(b.chrome_ok)), _now(), int(bool(b.status)))) + int(bool(b.chrome_ok)), (b.client_version or "").strip(), + _now(), int(bool(b.status)))) conn.commit() return {"ok": True, "device_id": device_id} diff --git a/desktop/controlplane/app.py b/desktop/controlplane/app.py index f750f0f..7173bd7 100644 --- a/desktop/controlplane/app.py +++ b/desktop/controlplane/app.py @@ -36,6 +36,7 @@ from controlplane.apis import dingtalk as api_dingtalk from controlplane.apis import file_sources as api_file_sources from controlplane.apis import fileserver_status as api_fileserver_status from controlplane.apis import meta as api_meta +from controlplane.apis import notifications as api_notifications from controlplane.apis import plugins as api_plugins from controlplane.apis import schedules as api_schedules @@ -67,6 +68,7 @@ app.add_middleware(CORSMiddleware, allow_origins=_CORS_ORIGINS, app.include_router(api_meta.router) app.include_router(api_plugins.router) +app.include_router(api_notifications.router) app.include_router(api_auth.router) app.include_router(api_config_push.router) app.include_router(api_file_sources.router) diff --git a/desktop/controlplane/core/db.py b/desktop/controlplane/core/db.py index dfecdbe..e5f862d 100644 --- a/desktop/controlplane/core/db.py +++ b/desktop/controlplane/core/db.py @@ -155,6 +155,7 @@ _DDL_TABLES = ( chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否', chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号', chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否', + client_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '客户端(壳子)版本号(升级追踪/关旧依据)', last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)', status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间', @@ -272,6 +273,21 @@ _DDL_TABLES = ( PRIMARY KEY (account) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录防爆破共享计数(落库,gunicorn 多 worker 通用)' """, + """ + CREATE TABLE IF NOT EXISTS notifications ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '通知ID', + title VARCHAR(200) NOT NULL COMMENT '标题', + content TEXT NOT NULL COMMENT '内容', + level VARCHAR(16) NOT NULL DEFAULT 'info' COMMENT '级别:info/warning/important', + target VARCHAR(16) NOT NULL DEFAULT 'all' COMMENT '范围:all=全部账号 account=指定账号', + account VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'target=account 时的目标账号', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + expires_at DATETIME NULL COMMENT '过期时间(NULL=长期有效)', + active TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用', + PRIMARY KEY (id), + KEY idx_active (active, target, account) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通知(管理端下发,客户端定时拉取)' + """, ) diff --git a/desktop/controlplane/core/schemas.py b/desktop/controlplane/core/schemas.py index 1f39046..0886c7f 100644 --- a/desktop/controlplane/core/schemas.py +++ b/desktop/controlplane/core/schemas.py @@ -22,7 +22,7 @@ class RuntimeReportIn(BaseModel): class DeviceReportIn(BaseModel): - """执行机心跳/环境上报(含 Chrome 检测结果),与 devices 表一一对应。""" + """执行机心跳/环境上报(含 Chrome 检测结果 + 客户端版本),与 devices 表一一对应。""" device_id: str account: str = "" hostname: str = "" @@ -32,6 +32,7 @@ class DeviceReportIn(BaseModel): chrome_version: str = "" # Chrome 版本号(检测到才填) chrome_ok: int = 0 # Chrome 是否就绪:1=是 0=否 status: int = 1 # 设备状态:1=在线 0=离线 + client_version: str = "" # 客户端(壳子)版本号(升级追踪/关旧依据) class AuthIn(BaseModel): @@ -123,4 +124,14 @@ class PluginPatchIn(BaseModel): status: str = "" # 空=不改;published / disabled / revoked force_min_version: str = "" # 与 deadline 成对生效;二者齐全=开启,否则看 clear_force force_deadline: str = "" # ISO 时间串 - clear_force: bool = False # True = 清除强制更新配置 \ No newline at end of file + clear_force: bool = False # True = 清除强制更新配置 + + +class NotificationIn(BaseModel): + """管理端下发通知:标题/内容/级别/范围(all 或指定账号)/有效期。""" + title: str + content: str = "" + level: str = "info" # info / warning / important + target: str = "all" # all=全部账号;account=指定账号 + account: str = "" # target=account 时的目标账号 + expires_at: str = "" # ISO 时间串或空(空=长期有效) \ No newline at end of file diff --git a/desktop/controlplane/frontend/controlplane-web-dist.zip b/desktop/controlplane/frontend/controlplane-web-dist.zip index bc11bfc..d9aec8a 100644 Binary files a/desktop/controlplane/frontend/controlplane-web-dist.zip and b/desktop/controlplane/frontend/controlplane-web-dist.zip differ diff --git a/desktop/controlplane/frontend/src/App.vue b/desktop/controlplane/frontend/src/App.vue index 3a4d3e2..5d9ad57 100644 --- a/desktop/controlplane/frontend/src/App.vue +++ b/desktop/controlplane/frontend/src/App.vue @@ -49,7 +49,7 @@ diff --git a/desktop/controlplane/frontend/src/views/UpgradeView.vue b/desktop/controlplane/frontend/src/views/UpgradeView.vue new file mode 100644 index 0000000..21a47fd --- /dev/null +++ b/desktop/controlplane/frontend/src/views/UpgradeView.vue @@ -0,0 +1,198 @@ + + + + + diff --git a/desktop/electron-shell/electron/app.js b/desktop/electron-shell/electron/app.js index 549ae09..44a4159 100644 --- a/desktop/electron-shell/electron/app.js +++ b/desktop/electron-shell/electron/app.js @@ -16,6 +16,7 @@ const tasks = require("./tasks"); const shellUpdater = require("./shell-updater"); const chromeManager = require("./chrome-manager"); const envSync = require("./env-sync"); +const notifier = require("./notifier"); const { HUB } = require("./hub"); const { makeLogger, setLogFile } = require("./logger"); @@ -151,6 +152,14 @@ async function init(options = {}) { void reportDevice(account) .then(() => logger.info("设备环境上报完成")) .catch(() => {}); + + // 通知推送:启动即拉取 + 每 10 分钟轮询(管理端下发的插件/客户端更新等通知) + try { + notifier.start(); + logger.info("通知推送已启动(10 分钟轮询)"); + } catch (e) { + logger.warning(`通知推送启动失败:${e.message}`); + } } else { logger.info("未配置中心机地址(CONTROLPLANE_URL),进入离线本地模式"); state.setAllowed(new Set()); diff --git a/desktop/electron-shell/electron/licensing.js b/desktop/electron-shell/electron/licensing.js index f03473e..3c7af6c 100644 --- a/desktop/electron-shell/electron/licensing.js +++ b/desktop/electron-shell/electron/licensing.js @@ -273,6 +273,8 @@ async function deviceReport(deviceId, account, info) { chrome_version: (info && info.chromeVersion) || "", chrome_ok: (info && info.chromeOk) ? 1 : 0, status: 1, + // 客户端(壳子)版本号:供中心机按版本追踪升级进度(关旧控制面的依据) + client_version: (config.runtimeVersion && config.runtimeVersion()) || "", }; try { await cp.request("POST", "/api/device/report", { headers: cp.machineHeaders(), json: payload, timeout: 5 }); diff --git a/desktop/electron-shell/electron/notifier.js b/desktop/electron-shell/electron/notifier.js new file mode 100644 index 0000000..218dd6f --- /dev/null +++ b/desktop/electron-shell/electron/notifier.js @@ -0,0 +1,170 @@ +// 通知推送:WebSocket 实时接收(秒达)+ 60s 轮询兜底;记录已读,不重复弹。 +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const config = require("./config"); +const cp = require("./cpclient"); +const session = require("./session"); +const { makeLogger } = require("./logger"); + +const logger = makeLogger("notifier"); + +const SEEN_FILE = path.join(config.APP_DATA, "notification_seen.json"); +const POLL_INTERVAL = 60 * 1000; // 轮询兜底:60 秒 +const WS_RETRY_MAX = 60000; // WS 重连退避上限 60s + +function loadSeen() { + try { + if (fs.existsSync(SEEN_FILE)) { + const arr = JSON.parse(fs.readFileSync(SEEN_FILE, "utf-8")); + if (Array.isArray(arr)) return new Set(arr.map(Number).filter(Boolean)); + } + } catch (e) { + /* 忽略损坏文件 */ + } + return new Set(); +} + +function saveSeen(set) { + try { + const arr = [...set].slice(-200); + fs.mkdirSync(config.APP_DATA, { recursive: true }); + fs.writeFileSync(SEEN_FILE, JSON.stringify(arr), "utf-8"); + } catch (e) { + /* 忽略 */ + } +} + +function isElectron() { + return !!(process.versions && process.versions.electron); +} + +function showNative(title, body, level) { + if (!isElectron()) { + logger.info(`[通知] ${title}${body ? ":" + body : ""}`); + return; + } + // 优先自定义 toast(白底品牌风,可配色);失败回退系统原生通知 + try { + if (require("./notify-toast").show(title, body, level)) return; + } catch (e) { + /* 忽略,走回退 */ + } + try { + const { Notification } = require("electron"); + if (!Notification.isSupported()) return; + const n = new Notification({ + title: String(title || "37du 通知").slice(0, 120), + body: String(body || "").slice(0, 400), + silent: level !== "important", + }); + n.on("click", () => { + try { n.close(); } catch (e) { /* 忽略 */ } + }); + n.show(); + } catch (e) { + logger.warning(`系统通知展示失败:${e.message}`); + } +} + +// 处理单条通知:去重后展示 +function handleNotification(n) { + const id = Number(n && n.id); + if (!id) return; + const seen = loadSeen(); + if (seen.has(id)) return; + seen.add(id); + saveSeen(seen); + showNative(n.title || "通知", n.content || "", n.level || "info"); +} + +// ==================== WebSocket 实时推送 ==================== +let ws = null; +let wsRetry = 0; +let wsTimer = null; +let wsAccount = ""; + +function wsUrl(account) { + const base = config.CONTROLPLANE_URL.replace(/^http/i, "ws").replace(/\/+$/, ""); + return `${base}/ws/notifications?account=${encodeURIComponent(account)}`; +} + +function connectWs(account) { + if (!config.CONTROLPLANE_URL || !account) return; + if (ws && (ws.readyState === 0 || ws.readyState === 1)) return; // CONNECTING / OPEN + wsAccount = account; + try { + const { WebSocket } = require("ws"); + ws = new WebSocket(wsUrl(account), { + headers: cp.machineHeaders(), + handshakeTimeout: 8000, + }); + ws.on("open", () => { + wsRetry = 0; + logger.info(`通知 WebSocket 已连接(${account})`); + }); + ws.on("message", (data) => { + try { + const msg = JSON.parse(String(data)); + if (msg.type === "notify" && msg.notification) { + handleNotification(msg.notification); + } + } catch (e) { + /* 忽略坏帧 */ + } + }); + ws.on("ping", () => { + try { ws.pong(); } catch (e) { /* 忽略 */ } + }); + ws.on("close", () => { scheduleWsReconnect(wsAccount); }); + ws.on("error", (e) => { logger.warning(`通知 WS 错误:${e.message}`); }); + } catch (e) { + logger.warning(`通知 WS 连接失败:${e.message}`); + scheduleWsReconnect(account); + } +} + +function scheduleWsReconnect(account) { + ws = null; + if (wsTimer) { clearTimeout(wsTimer); wsTimer = null; } + const delay = Math.min(WS_RETRY_MAX, 5000 * Math.pow(2, Math.min(wsRetry++, 4))); + wsTimer = setTimeout(() => connectWs(account), delay); +} + +// ==================== 轮询兜底 ==================== +async function pollOnce() { + if (!config.CONTROLPLANE_URL) return; + const accts = new Set(); + try { + const set = session.accountSet(); + if (set && set.size) for (const a of set) accts.add(a); + } catch (e) { /* 忽略 */ } + const active = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount(); + if (active) accts.add(active); + if (!accts.size) return; + + for (const account of accts) { + try { + const r = await cp.request("GET", "/api/notifications", { + headers: cp.machineHeaders(), + params: { account }, + timeout: 10, + }); + for (const n of r.notifications || []) handleNotification(n); + } catch (e) { + logger.warning(`通知拉取失败(${account}):${e.message}`); + } + } +} + +function start() { + const active = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount(); + connectWs(active || ""); + void pollOnce().catch((e) => logger.warning(`通知初始化异常:${e.message}`)); + setInterval(() => { + void pollOnce().catch((e) => logger.warning(`通知周期检查异常:${e.message}`)); + }, POLL_INTERVAL); +} + +module.exports = { start, pollOnce, handleNotification }; diff --git a/desktop/electron-shell/electron/notify-toast.js b/desktop/electron-shell/electron/notify-toast.js new file mode 100644 index 0000000..92e152a --- /dev/null +++ b/desktop/electron-shell/electron/notify-toast.js @@ -0,0 +1,92 @@ +// 自定义通知弹窗(右下角 toast):无边框、置顶、不抢焦点、按级别配色。 +// 替代系统原生通知(原生样式跟随 Windows 主题,深色模式下发黑、不可控)。 +"use strict"; + +const { makeLogger } = require("./logger"); +const logger = makeLogger("notify-toast"); + +const W = 380, H = 132, GAP = 10, MARGIN = 16, TTL = 9000; +let lastBottom = null; + +function levelColor(level) { + return { info: "#2f5cf0", warning: "#d97706", important: "#d6453d" }[level] || "#2f5cf0"; +} +function levelLabel(level) { + return { info: "通知", warning: "提醒", important: "重要" }[level] || "通知"; +} + +function esc(s) { + return String(s || "") + .replace(/&/g, "&").replace(//g, ">") + .replace(/"/g, """); +} + +function buildHTML(title, body, level) { + const color = levelColor(level); + const label = levelLabel(level); + return ` +
+
+ + ${label} + ✕ +
+
${esc(title)}
+
${esc(body)}
+
+ `; +} + +function show(title, body, level) { + try { + const { BrowserWindow, screen } = require("electron"); + const display = screen.getPrimaryDisplay(); + const wa = display.workArea; + const x = wa.x + wa.width - W - MARGIN; + if (lastBottom === null) lastBottom = wa.y + wa.height - H - MARGIN; + const y = lastBottom; + lastBottom = lastBottom - H - GAP; + if (lastBottom < wa.y + MARGIN) lastBottom = null; // 满屏后下一轮回到底部 + + const win = new BrowserWindow({ + width: W, height: H, x, y, + frame: false, transparent: true, resizable: false, movable: false, + alwaysOnTop: true, skipTaskbar: true, hasShadow: false, show: false, focusable: false, + backgroundColor: "#00000000", + webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true }, + }); + win.setAlwaysOnTop(true, "pop-up-menu"); + win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML(title, body, level))); + win.once("ready-to-show", () => { + try { win.showInactive(); } catch (e) { win.show(); } + }); + const t = setTimeout(() => { try { win.destroy(); } catch (e) { /* 忽略 */ } }, TTL); + win.on("closed", () => { clearTimeout(t); }); + return true; + } catch (e) { + logger.warning(`自定义通知弹窗失败:${e.message}`); + return false; + } +} + +module.exports = { show }; diff --git a/desktop/electron-shell/electron/server.js b/desktop/electron-shell/electron/server.js index 61a5d30..ee8998f 100644 --- a/desktop/electron-shell/electron/server.js +++ b/desktop/electron-shell/electron/server.js @@ -164,6 +164,35 @@ function loginStateTake(s) { return !!exp && exp >= Date.now(); } +// ==================== 离线自动登录(断网 / 服务端不可达时的 7 天离线授权入口) ==================== +// 服务端探活:用 /api/me/pubkey(无鉴权)判断控制面是否可达 +async function serverReachable() { + try { + await cp.request("GET", "/api/me/pubkey", { headers: cp.machineHeaders(), timeout: 4 }); + return true; + } catch (e) { + return false; + } +} + +// 无会话且服务端不可达时:若存在有效(未过期、验签通过)离线授权票据,为该账号建立本地会话。 +// 这样断网/服务端宕机期间,授权期内的用户仍能进入工作台并运行已授权插件(最长离线 7 天)。 +function tryOfflineSession(res) { + try { + const st = licensing.licenseStatus(); + if (st.status === "ok" && st.payload && st.payload.userId) { + const acct = st.payload.userId; + const token = session.establishSession(acct, ""); + setSessionCookie(res, token); + logger.info(`离线授权自动登录:${acct}(服务端不可达,离线模式,最长 7 天)`); + return acct; + } + } catch (e) { + /* 忽略:票据缺失/无效/过期时不自动登录 */ + } + return ""; +} + // ==================== 业务组装 ==================== async function dingtalkEstablish(account, nickname, dingtalkUid, res) { if (!account) throw Object.assign(new Error("工号不能为空"), { status: 400 }); @@ -211,15 +240,20 @@ async function route(req, res, url) { // ---------- 认证 / 会话 ---------- if (p === "/api/admin/me" && method === "GET") { - const account = session.sessAccount(cookies); + let account = session.sessAccount(cookies); + // 无会话时先探测服务端:可达走正常登录;不可达且存在有效离线授权票据(最长 7 天)时自动登录 + const reachable = account ? true : await serverReachable(); + if (!account && !reachable) account = tryOfflineSession(res); 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) { - /* 云端不可达降级 */ + if (reachable) { + 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: "" }); } @@ -252,6 +286,24 @@ async function route(req, res, url) { return sendJson(res, 200, { ok: true }); } + // 离线登录:不依赖网络,仅校验本地 7 天离线授权票据(验签 + 未过期),消费票据直接进入工作台 + if (p === "/api/admin/offline-login" && method === "POST") { + const st = licensing.licenseStatus(); + if (st.status !== "ok" || !st.payload || !st.payload.userId) { + const reason = + st.status === "missing" ? "本机无离线授权票据,请先联网登录一次以获取 7 天离线授权" + : st.status === "expired" ? "离线授权已过期(最长离线 7 天),请联网刷新后重试" + : st.status === "invalid" ? "离线授权票据无效,请联网重新登录" + : "离线登录不可用,请联网登录"; + return sendJson(res, 403, { detail: reason }); + } + const acct = st.payload.userId; + const token = session.establishSession(acct, ""); + setSessionCookie(res, token); + logger.info(`离线登录成功:${acct}(消费本地 7 天授权票据)`); + return sendJson(res, 200, { ok: true, account: acct, offline: true }); + } + if (p === "/api/admin/password" && method === "POST") { const body = await readJsonBody(req); const r = await cp.request("POST", "/api/admin/password", { diff --git a/desktop/electron-shell/frontend/src/App.vue b/desktop/electron-shell/frontend/src/App.vue index 55ff836..eb46628 100644 --- a/desktop/electron-shell/frontend/src/App.vue +++ b/desktop/electron-shell/frontend/src/App.vue @@ -353,6 +353,8 @@ const licenseCls = computed(() => { let wsRetryCount = 0 let wsRetryTimer = null function openWS() { + // 主动新建连接时,取消上一次待执行的重连(防止新旧连接交替触发 onclose 形成重连死循环) + if (wsRetryTimer) { clearTimeout(wsRetryTimer); wsRetryTimer = null } if (window.__ws) { try { window.__ws.close() } catch (_) {} } const ws = connectWS((ev) => { handleEvent(ev) @@ -365,6 +367,8 @@ function openWS() { store.wsOn = false // 未登录被拒(1008)时静默,避免死循环 if (!store.current) return + // 仅当仍是当前连接时才重连:被 openWS 主动替换/关闭的旧连接不再触发(否则无限闪烁) + if (window.__ws !== ws) return if (wsRetryCount >= 5) return // 连续 5 次失败:停止,状态栏保持"本地服务重连中" wsRetryCount++ // 指数退避重连(1/2/4/8/16s 封顶),不再整页 reload(避免反复走启动引导) diff --git a/desktop/electron-shell/frontend/src/api.js b/desktop/electron-shell/frontend/src/api.js index d92a859..6bc1868 100644 --- a/desktop/electron-shell/frontend/src/api.js +++ b/desktop/electron-shell/frontend/src/api.js @@ -171,6 +171,10 @@ export async function adminMe() { export async function adminLogin(account, password) { return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) }) } +// 离线登录:凭本机 7 天离线授权票据直接进入(不依赖网络/服务端) +export async function adminOfflineLogin() { + return j('/api/admin/offline-login', { method: 'POST' }) +} // v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL export async function authDingtalk() { return j('/api/auth/dingtalk') diff --git a/desktop/electron-shell/frontend/src/components/LoginPage.vue b/desktop/electron-shell/frontend/src/components/LoginPage.vue index e5bfefa..3b9bbe0 100644 --- a/desktop/electron-shell/frontend/src/components/LoginPage.vue +++ b/desktop/electron-shell/frontend/src/components/LoginPage.vue @@ -53,6 +53,12 @@ 钉钉扫码接入 + +
+ + 离线登录(凭本机 7 天授权票据进入) + +
@@ -72,7 +78,7 @@ import { ref, onMounted } from 'vue' import { ElMessage } from 'element-plus' import { ChatDotRound } from '@element-plus/icons-vue' -import { adminLogin, authDingtalk } from '../api' +import { adminLogin, adminOfflineLogin, authDingtalk } from '../api' defineProps({ appName: { type: String, default: '' } }) const emit = defineEmits(['ok']) @@ -91,6 +97,28 @@ const account = ref('') const password = ref('') const busy = ref(false) const dingBusy = ref(false) +const offlineBusy = ref(false) + +// 离线登录:不依赖网络,凭本机 7 天离线授权票据直接进入工作台 +async function doOffline() { + if (offlineBusy.value) return + offlineBusy.value = true + try { + const r = await adminOfflineLogin() + ElMessage.success('已离线登录:' + (r.account || '')) + emit('ok', { + account: r.account || '', + dept: '', + must_change_pwd: false, + nickname: r.nickname || '', + avatar: '' + }) + } catch (e) { + ElMessage.error('离线登录失败:' + (e.message || e)) + } finally { + offlineBusy.value = false + } +} async function doLogin() { if (busy.value) return @@ -307,7 +335,7 @@ async function openDing() { 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:hover { transform: 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); } @@ -503,7 +531,6 @@ async function openDing() { .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); } @@ -558,7 +585,6 @@ async function openDing() { 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); } @@ -569,6 +595,12 @@ async function openDing() { .dingtalk.el-button :deep(.el-icon) { color: var(--primary); } +/* ---------- 离线登录入口 ---------- */ +.offline-row { + margin-top: 18px; + text-align: center; +} + /* ---------- 键盘可达 ---------- */ .primary.el-button:focus-visible, .dingtalk.el-button:focus-visible { diff --git a/desktop/electron-shell/package.json b/desktop/electron-shell/package.json index f12f786..94da80a 100644 --- a/desktop/electron-shell/package.json +++ b/desktop/electron-shell/package.json @@ -1,7 +1,7 @@ { "name": "37du-electron-shell", "productName": "37du 自动化工作台", - "version": "1.0.9", + "version": "1.6.1", "description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)", "main": "electron/main.js", "private": true, diff --git a/desktop/fileserver/frontend/index.html b/desktop/fileserver/frontend/index.html index d5653c1..ad1c046 100644 --- a/desktop/fileserver/frontend/index.html +++ b/desktop/fileserver/frontend/index.html @@ -7,270 +7,208 @@ @@ -279,8 +217,6 @@
- - 📌
37

文件服务器管理

@@ -300,12 +236,10 @@