utils.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. async openImage(
  76. optiops= {
  77. title:"选择图片",
  78. filters:[
  79. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  80. ],
  81. }
  82. ){
  83. const filePaths = dialog.showOpenDialogSync({
  84. title:optiops.title || '选择图片',
  85. properties:['openFile'],
  86. filters:optiops.filters || [
  87. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  88. ]
  89. })
  90. const filePath = filePaths[0];
  91. const fileBuffer = fs.readFileSync(filePath);
  92. const base64Image = fileBuffer.toString('base64');
  93. // 获取文件扩展名
  94. const extension = path.extname(filePath).toLowerCase().replace('.', '');
  95. // 根据扩展名确定 MIME 类型
  96. let mimeType = '';
  97. switch (extension) {
  98. case 'jpg':
  99. case 'jpeg':
  100. mimeType = 'image/jpeg';
  101. break;
  102. case 'png':
  103. mimeType = 'image/png';
  104. break;
  105. case 'gif':
  106. mimeType = 'image/gif';
  107. break;
  108. default:
  109. mimeType = 'application/octet-stream'; // 默认 MIME 类型
  110. break;
  111. }
  112. // 构建 data URL
  113. const dataUrl = `data:${mimeType};base64,${base64Image}`;
  114. return {
  115. filePath:filePath,
  116. base64Image:dataUrl
  117. };
  118. }
  119. async openFile(optiops= {
  120. title:"选择文件",
  121. filters:[
  122. { name: '支持JPG', extensions: ['jpg','jpeg'] },
  123. ],
  124. }){
  125. const filePaths = dialog.showOpenDialogSync({
  126. title:optiops.title || '选择文件',
  127. properties: ['openFile'],
  128. filters: optiops.filters || [
  129. { name: '选择文件' },
  130. ]
  131. })
  132. if(filePaths[0]) return filePaths[0];
  133. return filePaths
  134. }
  135. getAppConfig(){
  136. const config = readConfigFile()
  137. return {
  138. ...config,
  139. userDataPath: app.getPath('userData'),
  140. appPath: app.getAppPath()
  141. }
  142. }
  143. async readFileImageForPath(filePath,maxWidth=1500){
  144. const getMimeType = (fileName)=>{
  145. const extension = path.extname(fileName).toLowerCase().replace('.', '');
  146. let mimeType = '';
  147. switch (extension) {
  148. case 'jpg':
  149. case 'jpeg':
  150. mimeType = 'image/jpeg';
  151. break;
  152. case 'png':
  153. mimeType = 'image/png';
  154. break;
  155. case 'gif':
  156. mimeType = 'image/gif';
  157. break;
  158. case 'webp':
  159. mimeType = 'image/webp';
  160. break;
  161. case 'avif':
  162. mimeType = 'image/avif';
  163. break;
  164. default:
  165. mimeType = 'application/octet-stream';
  166. break;
  167. }
  168. return mimeType;
  169. }
  170. try {
  171. const fileName = path.basename(filePath);
  172. const image = sharp(filePath);
  173. const metadata = await image.metadata();
  174. let mimeType = getMimeType(fileName); // 调用下面定义的私有方法获取 MIME 类型
  175. let fileBuffer;
  176. if (metadata.width > maxWidth) {
  177. // 如果宽度大于 1500px,压缩至 1500px 宽度,保持比例
  178. fileBuffer = await image.resize(maxWidth).toBuffer();
  179. } else {
  180. // 否则直接读取原图
  181. fileBuffer = fs.readFileSync(filePath);
  182. }
  183. return {
  184. fileBuffer,
  185. fileName,
  186. mimeType
  187. };
  188. } catch (error) {
  189. console.error('Error processing image:', error);
  190. throw error;
  191. }
  192. }
  193. }
  194. UtilsController.toString = () => '[class ExampleController]';
  195. module.exports = UtilsController;