feat: 新增通知推送功能及离线登录,优化重连逻辑

- 新增通知推送模块:支持 WebSocket 实时推送与轮询兜底,新增通知管理界面
- 新增离线登录功能:断网时凭本地 7 天授权票据自动登录或手动登录
- 优化 Electron 客户端 WebSocket 重连逻辑,避免死循环
- 调整工作流脚本,拆分重构合同相关分支逻辑
- 新增设备上报客户端版本字段,用于升级追踪与关旧依据
This commit is contained in:
2026-10-13 17:46:49 +08:00
parent 2e86f0a3f6
commit 3dcedf95fd
38 changed files with 2113 additions and 388 deletions
+9
View File
@@ -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());
@@ -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 });
+170
View File
@@ -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 };
@@ -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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function buildHTML(title, body, level) {
const color = levelColor(level);
const label = levelLabel(level);
return `<!doctype html><html><head><meta charset="utf-8"><style>
* { margin:0; padding:0; box-sizing:border-box; font-family:"Segoe UI","Microsoft YaHei",sans-serif; }
html,body { background:transparent; }
.toast {
position:fixed; inset:0; border-radius:14px; overflow:hidden;
background:#fff; border:1px solid #e6eaf2;
box-shadow:0 12px 32px -14px rgba(20,26,40,.45);
display:flex; flex-direction:column;
animation: in .28s ease;
}
@keyframes in { from { transform:translateY(14px); opacity:0 } to { transform:none; opacity:1 } }
.bar { padding:9px 12px 2px; display:flex; align-items:center; gap:8px; }
.logo { width:20px;height:20px;border-radius:6px;background:linear-gradient(135deg,#2f5cf0,#0f9f9b);
color:#fff;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center; }
.lvl { font-size:11px;font-weight:700;color:${color};letter-spacing:.3px; }
.close { margin-left:auto;cursor:pointer;color:#9aa2b4;font-size:14px;line-height:1;padding:2px 5px; }
.close:hover { color:#4a5468; }
.ttl { padding:0 14px; font-size:14px;font-weight:700;color:#232a3a; }
.bdy { padding:4px 14px 12px; font-size:12.5px;color:#3b4358;line-height:1.45;
overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
</style></head><body>
<div class="toast">
<div class="bar">
<span class="logo">37</span>
<span class="lvl">${label}</span>
<span class="close" onclick="window.close()">✕</span>
</div>
<div class="ttl">${esc(title)}</div>
<div class="bdy">${esc(body)}</div>
</div>
</body></html>`;
}
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 };
+58 -6
View File
@@ -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", {
@@ -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(避免反复走启动引导)
@@ -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')
@@ -53,6 +53,12 @@
<el-button size="large" class="dingtalk" :loading="dingBusy" :icon="ChatDotRound" @click="openDing">
钉钉扫码接入
</el-button>
<div class="offline-row">
<el-button link type="primary" size="small" :loading="offlineBusy" @click="doOffline">
离线登录(凭本机 7 天授权票据进入)
</el-button>
</div>
</main>
<!-- 底部:流程状态 -->
@@ -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 {
+1 -1
View File
@@ -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,