utils.js 6.9 KB

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