feat: 新增通知推送功能及离线登录,优化重连逻辑
- 新增通知推送模块:支持 WebSocket 实时推送与轮询兜底,新增通知管理界面 - 新增离线登录功能:断网时凭本地 7 天授权票据自动登录或手动登录 - 优化 Electron 客户端 WebSocket 重连逻辑,避免死循环 - 调整工作流脚本,拆分重构合同相关分支逻辑 - 新增设备上报客户端版本字段,用于升级追踪与关旧依据
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user