const { contextBridge, ipcRenderer } = require('electron'); const path = require('path'); const os = require('os'); const fs = require('fs'); /** * 文件操作相关的预加载脚本 */ contextBridge.exposeInMainWorld('fileAPI', { /** * 使用 7z 压缩文件 * @param {Object} opts 压缩选项 * @returns {Promise} 压缩结果 */ compress: (opts) => ipcRenderer.invoke('compress-with-7z', opts), /** * 监听压缩进度 * @param {Function} cb 回调函数,接收进度文本作为参数 * @returns {Function} 用于移除监听器的函数 */ onProgress: (cb) => { const handler = (event, data) => cb(String(data)); ipcRenderer.on('compress-progress', handler); return () => ipcRenderer.removeListener('compress-progress', handler); }, /** * 监听压缩错误输出 * @param {Function} cb 回调函数,接收错误文本作为参数 * @returns {Function} 用于移除监听器的函数 */ onStderr: (cb) => { const handler = (event, data) => cb(String(data)); ipcRenderer.on('compress-stderr', handler); return () => ipcRenderer.removeListener('compress-stderr', handler); }, /** * 删除临时解压目录 * @param {string} tmpDir 临时解压目录路径 */ deleteTempDir: (tmpDir) => { return fs.rmSync(tmpDir, { recursive: true, force: true }); }, /** * 创建临时文件夹 * @param {string} prefix 临时文件夹前缀 * @returns {string} 创建的临时文件夹路径 */ createTempDir: (prefix) => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix || 'eep-')); const dirResourcePath = path.join(tmpDir, 'resource'); if (!fs.existsSync(dirResourcePath)) { fs.mkdirSync(dirResourcePath); } const dirCoursewarePath = path.join(tmpDir, 'courseware'); if (!fs.existsSync(dirCoursewarePath)) { fs.mkdirSync(dirCoursewarePath); } return tmpDir; }, /** * 读取解压后的文件内容 * @param {string} tmpDir 临时解压目录路径 * @param {string} entryName 文件条目名称 * @returns {Buffer} 文件内容 */ readZipFileSync: (tmpDir, entryName) => { const filePath = path.join(tmpDir, entryName); return fs.readFileSync(filePath); }, /** * 下载文件 * @param {string} url 文件 URL * @param {string} destPath 保存路径 */ downloadFile: (url, destPath) => { return ipcRenderer.invoke('download-file', { url, destPath }); }, /** * 打开文件对话框 * @param {Object} opts 对话框选项 * @returns {Promise} 文件路径 */ openFileDialog: (opts) => ipcRenderer.invoke('dialog:openFiles', opts), });