const { remote, ipcRenderer } = require('electron'); const fs = require('fs'); const { tr } = require('../core/translate'); const { readJson } = require('../core/utils'); // 监听 Electron 发送的 IPC,并将其转发到 hostAPI 中设置的监听器中 let panelWinStateChangedListener = null; ipcRenderer.on("im-plugin:panel-win-state-changed", (event, eventName) => { panelWinStateChangedListener && panelWinStateChangedListener(eventName); }); global.hostAPI = { imPluginVersion: readJson(`${__dirname}/../package.json`).version, sendToHost: (channel, param) => { if (channel === "new-msg") { ipcRenderer.sendToHost("new-msg", { newMsgCount: param, }); } else if (channel === "download") { let options = {}; if (param.type === "image") { options = { title: tr("save-image"), defaultPath: param.fileName, filters: [ { name: tr("image-filter-name"), extensions: ["jpg", "jpeg", "png", "gif"], }, ], }; } else { options = { title: tr("save-file"), defaultPath: param.fileName, filters: [{ name: tr("file-filter-name"), extensions: ["*"] }], }; } remote.dialog.showSaveDialog(options, (filePath) => { if (!filePath) return; ipcRenderer.sendToHost("download", { url: param.url, path: filePath, }); }); } }, isReady(isReady) { ipcRenderer.sendToHost("is-ready", isReady); }, setWindowListener: (listener) => { panelWinStateChangedListener = listener; }, selectFile(type) { let result; if (type === "image") { result = remote.dialog.showOpenDialog({ title: tr("select-image"), properties: ["openFile"], filters: [ { name: tr("image-filter-name"), extensions: ["jpg", "jpeg", "png", "gif"], }, ], }); } else { result = remote.dialog.showOpenDialog({ title: tr("select-file"), properties: ["openFile"], filters: [ { name: tr("file-filter-name"), extensions: ["*"], }, ], }); } function getFileByPath(path) { const fileName = path.split("/").slice(-1)[0]; const fileBuffer = fs.readFileSync(path); const file = new File([fileBuffer], fileName); return file; } if (!result) { return Promise.resolve(""); } if (result.then) { return result.then((res) => { if (res.canceled) { return ""; } // 单选 const filePath = res.filePaths[0]; return getFileByPath(filePath); }); } // 单选 const filePath = result[0]; return Promise.resolve(getFileByPath(filePath)); }, };