Files
puddy b891f07fd2 feat(electron-shell): 1.10.9 新增选文件接口 /api/dialog/file,通知 WS 补连与秒达
本机接口 POST /api/dialog/file:插件 UI 调原生选择文件对话框,只回绝对路径(默认过滤 xlsx/xlsm),补 /api/dialog/directory 只能选目录的缺口。

通知 WS:启动时未登录不再永久连不上(随 60s 轮询补连),旧连接 close 不再顶掉新连接;配套中心机 /ws/notifications 后通知秒达,轮询继续兜底。
2026-11-10 16:38:05 +08:00

178 lines
5.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 通知推送: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 };