utils.js 6.4 KB

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