import { Menu, Tray, app } from "electron"; import path from "node:path"; import { DIST, ICON, PUBLIC, readIniFile, url, writeIniFile } from "./utils"; import { showMainWin, extra, mainWindow } from "../win/mainWin"; import log from "electron-log/main"; import { handeGet, handeSet } from "./store"; import io from "socket.io-client"; export let socket: any = null; export const initTray = () => { const handlePath = (icon: string) => { return url ? path.join(PUBLIC!, icon) : path.join(DIST, icon); }; const ICONS = { default: ICON, icon1: handlePath("./icon-1.png"), icon2: handlePath("./icon-2.png"), icon3: handlePath("./icon-3.png"), icon4: handlePath("./icon-4.png"), icon5: handlePath("./icon-5.png"), icon6: handlePath("./icon-6.png"), icon7: handlePath("./icon-7.png"), icon8: handlePath("./icon-8.png"), icon9: handlePath("./icon-9.png"), icon9plus: handlePath("./icon-9plus.png"), }; let appIcon = new Tray(ICONS.default); const isFocusOpenWin: number = handeGet("isFocusOpenWin"); let contextMenu = Menu.buildFromTemplate([ { id: "open-win", label: `${isFocusOpenWin == 1 ? "关闭" : "开启"}主动弹窗`, click: () => { updateItem(); }, }, { label: "打开弹窗", click: () => { showMainWin(); }, }, { label: "退出弹窗", click: () => { extra.activeClose = true; setTimeout(() => { app.quit(); }); }, }, ]); appIcon.setToolTip("菁苗健康"); appIcon.setContextMenu(contextMenu); // 服务端地址 const SOCKET_URL = "http://114.215.252.134:2120"; socket = io(SOCKET_URL, { reconnection: true, reconnectionDelay: 1000, timeout: 20000, }); // socket连接后等待 uid socket.on("connect", function () { console.log("Socket connected, waiting for uid..."); }); // 后端推送来消息时 socket.on("new_msg", function (msg) { const fixedData = msg.replace(/"/g, '"'); const userObj = JSON.parse(fixedData); const msgCount = userObj.count; if (msgCount <= 9) { if (msgCount === 0) { appIcon.setImage(ICONS.default); } else { appIcon.setImage(ICONS[`icon${msgCount}`]); } } else { appIcon.setImage(ICONS[`icon9plus`]); } appIcon.setToolTip(`菁苗健康-未读消息数量(${msgCount})`); if (userObj.msg_type !== 2) { // 向渲染进程发送消息 mainWindow?.webContents.send("new-notification", { ...userObj, is_read: 0, }); } }); appIcon.addListener("click", function () { showMainWin(); }); // 更新item const updateItem = async () => { let isFocusOpenWin: number = handeGet("isFocusOpenWin"); const openMenuItem = contextMenu.getMenuItemById("open-win"); if (isFocusOpenWin == 1) { isFocusOpenWin = 2; openMenuItem!.label = `开启主动弹窗`; } else { isFocusOpenWin = 1; openMenuItem!.label = `关闭主动弹窗`; } contextMenu = Menu.buildFromTemplate(contextMenu.items); appIcon.setContextMenu(contextMenu); handeSet("isFocusOpenWin", isFocusOpenWin); log.info("isFocusOpenWin==>", isFocusOpenWin); }; return appIcon; };