utils.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. 'use strict';
  2. const { Controller } = require('ee-core');
  3. const { shell } = require('electron');
  4. const Addon = require('ee-core/addon');
  5. const { dialog } = require('electron');
  6. const fs = require('fs');
  7. const path = require('path');
  8. const CoreWindow = require('ee-core/electron/window');
  9. const { BrowserWindow, Menu,app } = require('electron');
  10. const { readConfigFile } = require('../utils/config');
  11. const configDeault = readConfigFile();
  12. const errData = {
  13. msg :'请求失败,请联系管理员',
  14. code:999
  15. }
  16. const sharp = require('sharp'); // 确保安装:npm install sharp
  17. /**
  18. * example
  19. * @class
  20. */
  21. class UtilsController extends Controller {
  22. constructor(ctx) {
  23. super(ctx);
  24. }
  25. /**
  26. * 所有方法接收两个参数
  27. * @param args 前端传的参数
  28. * @param event - ipc通信时才有值。详情见:控制器文档
  29. */
  30. /**
  31. * upload
  32. */
  33. async shellFun (params) {
  34. // 如果是打开路径操作,确保路径存在
  35. if (params.action === 'openMkPath') {
  36. try {
  37. // 确保目录存在,如果不存在就创建
  38. if (!fs.existsSync(params.params)) {
  39. fs.mkdirSync(params.params, { recursive: true });
  40. }
  41. shell.openPath(params.params)
  42. return;
  43. } catch (err) {
  44. console.error('创建目录失败:', err);
  45. // 即使创建目录失败,也尝试打开路径(可能已经存在)
  46. }
  47. }
  48. shell[params.action](params.params)
  49. }
  50. async openMain (config) {
  51. const { id, url } = config;
  52. if (this.app.electron[id]) {
  53. const win = this.app.electron[id];
  54. // 切换到指定的 URL
  55. await win.loadURL(url);
  56. win.focus();
  57. win.show();
  58. return;
  59. }
  60. const win = new BrowserWindow({
  61. ...config,
  62. webPreferences: {
  63. webSecurity: false,
  64. contextIsolation: false, // false -> 可在渲染进程中使用electron的api,true->需要bridge.js(contextBridge)
  65. nodeIntegration: true,
  66. // preload: path.join('../preload/preload.js','../preload/bridge.js'),
  67. },
  68. });
  69. await win.loadURL(config.url); // 设置窗口的 URL
  70. // 监听窗口关闭事件
  71. if(configDeault.debug) win.webContents.openDevTools()
  72. //
  73. win.on('close', () => {
  74. delete this.app.electron[config.id]; // 删除窗口引用
  75. });
  76. this.app.electron[config.id] = win ;
  77. }
  78. async openDirectory(optiops={
  79. title:"选择文件夹"
  80. }){
  81. const filePaths = dialog.showOpenDialogSync({
  82. title:optiops.title || '选择文件夹',
  83. properties: ['openDirectory']
  84. })
  85. if(filePaths[0]) return filePaths[0];
  86. return filePaths
  87. }
  88. /**
  89. * 关闭所有子窗口
  90. */
  91. closeAllWindows() {
  92. try {
  93. // 获取所有窗口
  94. const windows = this.app.electron;
  95. // 关闭除主窗口外的所有窗口
  96. for (const [id, window] of Object.entries(windows)) {
  97. if (!['mainWindow','extra'].includes(id)) { // 保留主窗口
  98. try {
  99. window.close();
  100. delete this.app.electron[id];
  101. } catch (error) {
  102. console.error(`关闭窗口 ${id} 失败:`, error);
  103. }
  104. }
  105. }
  106. console.log('所有子窗口已关闭');
  107. return { success: true, message: '所有子窗口已关闭' };
  108. } catch (error) {
  109. console.error('关闭所有窗口失败:', error);
  110. return { success: false, message: '关闭所有窗口失败: ' + error.message };
  111. }
  112. }
  113. async openImage(
  114. optiops= {
  115. title:"选择图片",
  116. filters:[
  117. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  118. ],
  119. }
  120. ){
  121. const filePaths = dialog.showOpenDialogSync({
  122. title:optiops.title || '选择图片',
  123. properties:['openFile'],
  124. filters:optiops.filters || [
  125. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  126. ]
  127. })
  128. const filePath = filePaths[0];
  129. const fileBuffer = fs.readFileSync(filePath);
  130. const base64Image = fileBuffer.toString('base64');
  131. // 获取文件扩展名
  132. const extension = path.extname(filePath).toLowerCase().replace('.', '');
  133. // 根据扩展名确定 MIME 类型
  134. let mimeType = '';
  135. switch (extension) {
  136. case 'jpg':
  137. case 'jpeg':
  138. mimeType = 'image/jpeg';
  139. break;
  140. case 'png':
  141. mimeType = 'image/png';
  142. break;
  143. case 'gif':
  144. mimeType = 'image/gif';
  145. break;
  146. default:
  147. mimeType = 'application/octet-stream'; // 默认 MIME 类型
  148. break;
  149. }
  150. // 构建 data URL
  151. const dataUrl = `data:${mimeType};base64,${base64Image}`;
  152. return {
  153. filePath:filePath,
  154. base64Image:dataUrl
  155. };
  156. }
  157. async openFile(optiops= {
  158. title:"选择文件",
  159. filters:[
  160. { name: '支持JPG', extensions: ['jpg','jpeg'] },
  161. ],
  162. }){
  163. const filePaths = dialog.showOpenDialogSync({
  164. title:optiops.title || '选择文件',
  165. properties: ['openFile'],
  166. filters: optiops.filters || [
  167. { name: '选择文件' },
  168. ]
  169. })
  170. if(filePaths[0]) return filePaths[0];
  171. return filePaths
  172. }
  173. getAppConfig(){
  174. const config = readConfigFile()
  175. const appPath = app.getAppPath();
  176. const pyPath = path.join(path.dirname(appPath), 'extraResources', 'py');
  177. return {
  178. ...config,
  179. userDataPath: app.getPath('userData'),
  180. appPath: appPath,
  181. pyPath:pyPath,
  182. }
  183. }
  184. async readFileImageForPath(filePath,maxWidth=1500){
  185. const getMimeType = (fileName)=>{
  186. const extension = path.extname(fileName).toLowerCase().replace('.', '');
  187. let mimeType = '';
  188. switch (extension) {
  189. case 'jpg':
  190. case 'jpeg':
  191. mimeType = 'image/jpeg';
  192. break;
  193. case 'png':
  194. mimeType = 'image/png';
  195. break;
  196. case 'gif':
  197. mimeType = 'image/gif';
  198. break;
  199. case 'webp':
  200. mimeType = 'image/webp';
  201. break;
  202. case 'avif':
  203. mimeType = 'image/avif';
  204. break;
  205. default:
  206. mimeType = 'application/octet-stream';
  207. break;
  208. }
  209. return mimeType;
  210. }
  211. try {
  212. const fileName = path.basename(filePath);
  213. const image = sharp(filePath);
  214. const metadata = await image.metadata();
  215. let mimeType = getMimeType(fileName); // 调用下面定义的私有方法获取 MIME 类型
  216. let fileBuffer;
  217. if (metadata.width > maxWidth) {
  218. // 如果宽度大于 1500px,压缩至 1500px 宽度,保持比例
  219. fileBuffer = await image.resize(maxWidth).toBuffer();
  220. } else {
  221. // 否则直接读取原图
  222. fileBuffer = fs.readFileSync(filePath);
  223. }
  224. return {
  225. fileBuffer,
  226. fileName,
  227. mimeType
  228. };
  229. } catch (error) {
  230. console.error('Error processing image:', error);
  231. throw error;
  232. }
  233. }
  234. }
  235. UtilsController.toString = () => '[class ExampleController]';
  236. module.exports = UtilsController;