| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294 |
- const { app, BrowserWindow, ipcMain, net, shell, dialog } = require('electron');
- const path = require('path');
- const url = require('url');
- const fs = require('fs');
- const { spawn, execFile } = require('child_process'); // 用于启动子进程
- const sevenBin = require('7zip-bin');
- const AdmZip = require('adm-zip');
- const os = require('os');
- let win = null;
- let pendingEep = null; // 如果在窗口未创建前收到文件,先缓存
- // 创建窗口
- const createWindow = () => {
- win = new BrowserWindow({
- // width: 1200,
- // height: 800,
- show: false, // 是否显示窗口
- autoHideMenuBar: true, // 隐藏菜单栏
- webPreferences: {
- nodeIntegration: true, // 是否集成 Node.js
- // enableRemoteModule: true, // 是否启用 remote 模块
- webSecurity: false, // 是否禁用同源策略
- preload: path.join(__dirname, 'preload.js'), // 预加载脚本
- },
- });
- // 全局拦截会话级别的网络请求,禁止所有外部网络访问(离线包专用)
- try {
- const ses = win.webContents.session;
- // 拦截所有协议的请求,允许本地资源协议通过
- ses.webRequest.onBeforeRequest({ urls: ['*://*/*'] }, (details, callback) => {
- const u = details && details.url ? String(details.url) : '';
- // 允许本地文件和 data/ about 等内部资源
- if (
- u.startsWith('file:') ||
- u.startsWith('data:') ||
- u.startsWith('about:') ||
- u.startsWith('chrome-devtools://')
- ) {
- return callback({ cancel: false });
- }
- // 其它所有网络请求全部取消 (http/https/ftp/...)。
- return callback({ cancel: true });
- });
- } catch (e) {
- console.error('Failed to set webRequest blocker:', e);
- }
- win.loadURL(
- url.format({
- pathname: path.join(__dirname, './dist', 'index.html'),
- protocol: 'file:',
- slashes: true, // true: file://, false: file:
- hash: '/select_eep', // 默认打开选择文件页面
- }),
- );
- win.once('ready-to-show', () => {
- win.maximize();
- win.show();
- });
- // 拦截当前窗口的导航,防止外部链接在应用内打开
- win.webContents.on('will-navigate', (event, url) => {
- if (url.startsWith('http://') || url.startsWith('https://')) {
- event.preventDefault();
- shell.openExternal(url);
- }
- });
- };
- // 当 Electron 完成初始化并准备创建浏览器窗口时调用此方法
- app.whenReady().then(() => {
- createWindow();
- // 处理首次启动时命令行传入的 .eep 文件
- const args = process.argv.slice(1);
- const encPkgPath = args.find((arg) => arg && arg.toLowerCase().endsWith('.eep'));
- if (encPkgPath && fs.existsSync(encPkgPath)) {
- // 如果窗口已经创建,通知渲染进程
- if (win) {
- win.webContents.once('did-finish-load', () => {
- win.webContents.send('open-eep', encPkgPath);
- });
- }
- } else if (pendingEep) {
- // 如果之前 second-instance 缓存了文件,在窗口创建后处理
- if (win) {
- win.webContents.once('did-finish-load', () => {
- win.webContents.send('open-eep', pendingEep);
- pendingEep = null;
- });
- }
- } else {
- // 未指定加密包文件,加载默认页面
- app.on('activate', () => {
- if (BrowserWindow.getAllWindows().length === 0) {
- createWindow();
- }
- });
- }
- });
- /**
- * 使用 7z 解压(支持 -p 密码),返回临时目录与条目列表
- * @param {string} filePath EEP 文件路径
- * @param {string} password 密码
- * @returns {Promise<{tempDir: string, entries: Array<{entryName: string, isDirectory: boolean}>}>} 解压结果
- */
- let _tempDirs = '';
- ipcMain.handle('extract-zip', async (event, { filePath, password }) => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eep-'));
- _tempDirs = tempDir;
- const sevenPath = sevenBin.path7za; // 可跨平台
- const args = ['x', filePath, `-o${tempDir}`, '-y'];
- if (password) args.push(`-p${password}`);
- await new Promise((resolve, reject) => {
- execFile(sevenPath, args, (err, stdout, stderr) => {
- if (err) {
- const output = `${String(stderr || '')}\n${String(stdout || '')}`;
- // 常见密码错误/提示匹配
- if (/wrong password|password incorrect|incorrect password|bad password|wrong mac|crc failed/i.test(output)) {
- const e = new Error('密码不正确');
- return reject(e);
- }
- if (/password required|enter password|is encrypted|requires a password|can not open encrypted/i.test(output)) {
- const e = new Error('需要密码');
- return reject(e);
- }
- const e = new Error(`解压失败: ${err.message || String(err)}`);
- return reject(e);
- }
- resolve();
- });
- });
- // 使用 AdmZip 读取压缩包内条目列表(只用于列出,不做解密)
- const zip = new AdmZip(filePath);
- const entries = zip.getEntries().map((e) => ({
- entryName: e.entryName,
- isDirectory: e.isDirectory,
- }));
- return { tempDir, entries };
- });
- /**
- * 打开文件对话框
- * @param {Object} options 对话框选项
- * @param {string} [options.title] 对话框标题
- * @param {Array<string>} [options.properties] 对话框属性,如 ['openFile', 'multiSelections']
- * @param {Array<{name: string, extensions: Array<string>}>} [options.filters] 过滤器
- * @return {Promise<{canceled: boolean, filePaths: string[]}>} 文件路径
- */
- ipcMain.handle('dialog:openFiles', async (event, options = {}) => {
- const result = await dialog.showOpenDialog({
- title: options.title || '选择.eep文件',
- properties: options.properties || ['openFile'],
- filters: options.filters || [{ name: '智慧梧桐数字教材离线包', extensions: ['eep'] }],
- });
- // result.canceled: 是否取消; result.filePaths: 字符串数组
- return { canceled: result.canceled, filePaths: result.filePaths };
- });
- // ===== 保证单实例并处理第二实例传入的文件 =====
- const gotLock = app.requestSingleInstanceLock();
- if (gotLock) {
- app.on('second-instance', (event, argv /*, workingDir */) => {
- // Windows: 被二次激活时,文件路径通常会包含在 argv 中
- const encPkgPath = argv.find((arg) => arg && arg.toLowerCase().endsWith('.eep'));
- if (encPkgPath && fs.existsSync(encPkgPath)) {
- // 如果窗口已存在,恢复并发送路径;否则缓存,等待创建窗口后使用
- if (win) {
- if (win.isMinimized()) win.restore();
- win.focus();
- win.webContents.send('open-eep', encPkgPath);
- } else {
- pendingEep = encPkgPath;
- }
- }
- });
- } else {
- // 如果无法获取锁,说明已有实例在运行,直接退出新进程
- app.quit();
- }
- // ===== 保证单实例并处理第二实例传入的文件结束 =====
- // 检查更新
- ipcMain.handle('check-update', async () => {
- const apiUrl = 'https://your-api.com/api/app/latest'; // <-- 替换为真实接口
- const currentVersion = app.getVersion();
- return new Promise((resolve, reject) => {
- const req = net.request(apiUrl);
- let body = '';
- req.on('response', (res) => {
- res.on('data', (chunk) => (body += chunk));
- res.on('end', () => {
- try {
- const latest = JSON.parse(body);
- const update = latest.version && latest.version !== currentVersion;
- resolve({ update, latest, currentVersion });
- } catch (e) {
- reject(e);
- }
- });
- });
- req.on('error', (err) => reject(err));
- req.end();
- });
- });
- // 下载更新(渲染进程发起),主进程负责流式保存并推送进度
- ipcMain.on('download-update', (event, downloadUrl) => {
- const win = BrowserWindow.getAllWindows()[0];
- const filename = path.basename(downloadUrl).split('?')[0] || `update-${Date.now()}.exe`;
- const tmpPath = path.join(app.getPath('temp'), filename);
- const fileStream = fs.createWriteStream(tmpPath);
- const req = net.request(downloadUrl);
- let received = 0;
- let total = 0;
- req.on('response', (res) => {
- total = parseInt(res.headers['content-length'] || res.headers['Content-Length'] || '0');
- res.on('data', (chunk) => {
- received += chunk.length;
- fileStream.write(chunk);
- win.webContents.send('update-download-progress', { received, total });
- });
- res.on('end', () => {
- fileStream.end();
- win.webContents.send('update-downloaded', { path: tmpPath });
- });
- });
- req.on('error', (err) => {
- win.webContents.send('update-error', { message: err.message || String(err) });
- });
- req.end();
- });
- // 安装更新(渲染进程确认安装时调用)
- ipcMain.on('install-update', (event, filePath) => {
- if (!fs.existsSync(filePath)) {
- event.sender.send('update-error', { message: '安装文件不存在' });
- return;
- }
- if (process.platform === 'win32') {
- // Windows:直接执行安装程序(根据你的安装包参数添加静默/等待参数)
- try {
- spawn(filePath, [], { detached: true, stdio: 'ignore' }).unref();
- app.quit();
- } catch (e) {
- event.sender.send('update-error', { message: e.message });
- }
- } else if (process.platform === 'darwin') {
- // macOS:打开 dmg 或者打开 .pkg
- shell.openPath(filePath).then(() => app.quit());
- } else {
- // linux:按照需要实现
- shell.openPath(filePath).then(() => app.quit());
- }
- });
- // 当所有窗口都已关闭时退出
- app.on('window-all-closed', () => {
- if (process.platform !== 'darwin') {
- // 清理临时目录
- if (_tempDirs) {
- try {
- fs.rmSync(_tempDirs, { recursive: true, force: true });
- } catch (e) {
- console.error(`Failed to remove temp directory ${_tempDirs}:`, e);
- }
- _tempDirs = '';
- }
- app.quit();
- }
- });
- app.on('activate', () => {
- if (BrowserWindow.getAllWindows().length === 0) {
- createWindow();
- }
- });
|