// 通知推送: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"); const sock = new WebSocket(wsUrl(account), { headers: cp.machineHeaders(), handshakeTimeout: 8000, }); ws = sock; sock.on("open", () => { wsRetry = 0; logger.info(`通知 WebSocket 已连接(${account})`); }); sock.on("message", (data) => { try { const msg = JSON.parse(String(data)); if (msg.type === "notify" && msg.notification) { handleNotification(msg.notification); } } catch (e) { /* 忽略坏帧 */ } }); sock.on("ping", () => { try { sock.pong(); } catch (e) { /* 忽略 */ } }); // 只有「当前这一条」连接关闭才安排重连,避免旧连接把新连接顶掉(重复连接/定时器抖动) sock.on("close", () => { if (ws !== sock) return; scheduleWsReconnect(wsAccount); }); sock.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; // 启动时可能还没登录(connectWs 无账号直接返回),随轮询补连;已连/连接中幂等返回 if (active) connectWs(active); 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 };