example.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. 'use strict';
  2. const _ = require('lodash');
  3. const path = require('path');
  4. const fs = require('fs');
  5. const { exec } = require('child_process');
  6. const { Controller } = require('ee-core');
  7. const {
  8. app: electronApp,
  9. dialog, shell, BrowserView, Notification,
  10. powerMonitor, screen, nativeTheme
  11. } = require('electron');
  12. const dayjs = require('dayjs');
  13. const { ChildJob } = require('ee-core/jobs');
  14. const Ps = require('ee-core/ps');
  15. const Log = require('ee-core/log');
  16. let myTimer = null;
  17. let browserViewObj = null;
  18. let notificationObj = null;
  19. /**
  20. * 示例控制器
  21. * @class
  22. */
  23. class ExampleController extends Controller {
  24. constructor(ctx) {
  25. super(ctx);
  26. }
  27. /**
  28. * 所有方法接收两个参数
  29. * @param args 前端传的参数
  30. * @param event - ipc通信时才有值。invoke()方法时,event == IpcMainInvokeEvent; send()/sendSync()方法时,event == IpcMainEvent
  31. */
  32. /**
  33. * test
  34. */
  35. async test () {
  36. const result = await this.service.example.test('electron');
  37. let tmpDir = Ps.getLogDir();
  38. Log.info('tmpDir:', tmpDir);
  39. return result;
  40. }
  41. /**
  42. * json数据库操作
  43. */
  44. async dbOperation(args) {
  45. const { service } = this;
  46. const paramsObj = args;
  47. //Log.info('eeeee paramsObj:', paramsObj);
  48. const data = {
  49. action: paramsObj.action,
  50. result: null,
  51. all_list: []
  52. };
  53. switch (paramsObj.action) {
  54. case 'add' :
  55. data.result = await service.storage.addTestData(paramsObj.info);;
  56. break;
  57. case 'del' :
  58. data.result = await service.storage.delTestData(paramsObj.delete_name);;
  59. break;
  60. case 'update' :
  61. data.result = await service.storage.updateTestData(paramsObj.update_name, paramsObj.update_age);
  62. break;
  63. case 'get' :
  64. data.result = await service.storage.getTestData(paramsObj.search_age);
  65. break;
  66. }
  67. data.all_list = await service.storage.getAllTestData();
  68. return data;
  69. }
  70. /**
  71. * sqlite数据库操作
  72. */
  73. async sqlitedbOperation(args) {
  74. const { service } = this;
  75. const paramsObj = args;
  76. //Log.info('eeeee paramsObj:', paramsObj);
  77. const data = {
  78. action: paramsObj.action,
  79. result: null,
  80. all_list: []
  81. };
  82. switch (paramsObj.action) {
  83. case 'add' :
  84. data.result = await service.storage.addTestDataSqlite(paramsObj.info);;
  85. break;
  86. case 'del' :
  87. data.result = await service.storage.delTestDataSqlite(paramsObj.delete_name);;
  88. break;
  89. case 'update' :
  90. data.result = await service.storage.updateTestDataSqlite(paramsObj.update_name, paramsObj.update_age);
  91. break;
  92. case 'get' :
  93. data.result = await service.storage.getTestDataSqlite(paramsObj.search_age);
  94. break;
  95. case 'getDataDir' :
  96. data.result = await service.storage.getDataDir();
  97. break;
  98. case 'setDataDir' :
  99. data.result = await service.storage.setCustomDataDir(paramsObj.data_dir);
  100. break;
  101. }
  102. data.all_list = await service.storage.getAllTestDataSqlite();
  103. return data;
  104. }
  105. /**
  106. * 消息提示对话框
  107. */
  108. messageShow () {
  109. dialog.showMessageBoxSync({
  110. type: 'info', // "none", "info", "error", "question" 或者 "warning"
  111. title: '自定义标题-message',
  112. message: '自定义消息内容',
  113. detail: '其它的额外信息'
  114. })
  115. return '打开了消息框';
  116. }
  117. /**
  118. * 消息提示与确认对话框
  119. */
  120. messageShowConfirm () {
  121. const res = dialog.showMessageBoxSync({
  122. type: 'info',
  123. title: '自定义标题-message',
  124. message: '自定义消息内容',
  125. detail: '其它的额外信息',
  126. cancelId: 1, // 用于取消对话框的按钮的索引
  127. defaultId: 0, // 设置默认选中的按钮
  128. buttons: ['确认', '取消'], // 按钮及索引
  129. })
  130. let data = (res === 0) ? '点击确认按钮' : '点击取消按钮';
  131. return data;
  132. }
  133. /**
  134. * 选择目录
  135. */
  136. selectFolder () {
  137. const filePaths = dialog.showOpenDialogSync({
  138. properties: ['openDirectory', 'createDirectory']
  139. });
  140. if (_.isEmpty(filePaths)) {
  141. return null
  142. }
  143. return filePaths[0];
  144. }
  145. /**
  146. * 打开目录
  147. */
  148. openDirectory (args) {
  149. if (!args.id) {
  150. return false;
  151. }
  152. let dir = '';
  153. if (path.isAbsolute(args.id)) {
  154. dir = args.id;
  155. } else {
  156. dir = electronApp.getPath(args.id);
  157. }
  158. shell.openPath(dir);
  159. return true;
  160. }
  161. /**
  162. * 加载视图内容
  163. */
  164. loadViewContent (args) {
  165. let content = null;
  166. if (args.type == 'html') {
  167. content = path.join('file://', electronApp.getAppPath(), args.content)
  168. } else {
  169. content = args.content;
  170. }
  171. // electron实验性功能,慎用
  172. browserViewObj = new BrowserView();
  173. this.app.electron.mainWindow.setBrowserView(browserViewObj)
  174. browserViewObj.setBounds({
  175. x: 300,
  176. y: 170,
  177. width: 650,
  178. height: 400
  179. });
  180. browserViewObj.webContents.loadURL(content);
  181. return true
  182. }
  183. /**
  184. * 移除视图内容
  185. */
  186. removeViewContent () {
  187. // removeBrowserView移除视图后,进程依然存在,估计是electron bug
  188. this.app.electron.mainWindow.removeBrowserView(browserViewObj);
  189. return true
  190. }
  191. /**
  192. * 打开新窗口
  193. */
  194. createWindow (args) {
  195. let content = null;
  196. if (args.type == 'html') {
  197. content = path.join('file://', electronApp.getAppPath(), args.content)
  198. } else if (args.type == 'web') {
  199. content = args.content;
  200. } else if (args.type == 'vue') {
  201. let addr = 'http://localhost:8080'
  202. if (this.config.env == 'prod') {
  203. const mainServer = this.app.config.mainServer;
  204. addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
  205. }
  206. content = addr + args.content;
  207. } else {
  208. // some
  209. }
  210. const addonWindow = this.app.addon.window;
  211. let opt = {
  212. title: args.windowName || 'new window'
  213. }
  214. const name = args.windowName || 'window-1';
  215. const win = addonWindow.create(name, opt);
  216. const winContentsId = win.webContents.id;
  217. // load page
  218. win.loadURL(content);
  219. return winContentsId
  220. }
  221. /**
  222. * 获取窗口contents id
  223. */
  224. getWCid (args) {
  225. const addonWindow = this.app.addon.window;
  226. // 主窗口的name默认是main,其它窗口name开发者自己定义
  227. const name = args;
  228. const id = addonWindow.getWCid(name);
  229. return id;
  230. }
  231. /**
  232. * 加载扩展程序
  233. */
  234. // async loadExtension (args) {
  235. // const crxFile = args[0];
  236. // if (_.isEmpty(crxFile)) {
  237. // return false;
  238. // }
  239. // const extensionId = path.basename(crxFile, '.crx');
  240. // const chromeExtensionDir = chromeExtension.getDirectory();
  241. // const extensionDir = path.join(chromeExtensionDir, extensionId);
  242. // Log.info("[api] [example] [loadExtension] extension id:", extensionId);
  243. // unzip(crxFile, extensionDir).then(() => {
  244. // Log.info("[api] [example] [loadExtension] unzip success!");
  245. // chromeExtension.load(extensionId);
  246. // });
  247. // return true;
  248. // }
  249. /**
  250. * 创建系统通知
  251. */
  252. sendNotification (arg, event) {
  253. const channel = 'controller.example.sendNotification';
  254. if (!Notification.isSupported()) {
  255. return '当前系统不支持通知';
  256. }
  257. let options = {};
  258. if (!_.isEmpty(arg.title)) {
  259. options.title = arg.title;
  260. }
  261. if (!_.isEmpty(arg.subtitle)) {
  262. options.subtitle = arg.subtitle;
  263. }
  264. if (!_.isEmpty(arg.body)) {
  265. options.body = arg.body;
  266. }
  267. if (!_.isEmpty(arg.silent)) {
  268. options.silent = arg.silent;
  269. }
  270. notificationObj = new Notification(options);
  271. if (arg.clickEvent) {
  272. notificationObj.on('click', (e) => {
  273. let data = {
  274. type: 'click',
  275. msg: '您点击了通知消息'
  276. }
  277. event.reply(`${channel}`, data)
  278. });
  279. }
  280. if (arg.closeEvent) {
  281. notificationObj.on('close', (e) => {
  282. let data = {
  283. type: 'close',
  284. msg: '您关闭了通知消息'
  285. }
  286. event.reply(`${channel}`, data)
  287. });
  288. }
  289. notificationObj.show();
  290. return true
  291. }
  292. /**
  293. * 电源监控
  294. */
  295. initPowerMonitor (arg, event) {
  296. const channel = 'controller.example.initPowerMonitor';
  297. powerMonitor.on('on-ac', (e) => {
  298. let data = {
  299. type: 'on-ac',
  300. msg: '接入了电源'
  301. }
  302. event.reply(`${channel}`, data)
  303. });
  304. powerMonitor.on('on-battery', (e) => {
  305. let data = {
  306. type: 'on-battery',
  307. msg: '使用电池中'
  308. }
  309. event.reply(`${channel}`, data)
  310. });
  311. powerMonitor.on('lock-screen', (e) => {
  312. let data = {
  313. type: 'lock-screen',
  314. msg: '锁屏了'
  315. }
  316. event.reply(`${channel}`, data)
  317. });
  318. powerMonitor.on('unlock-screen', (e) => {
  319. let data = {
  320. type: 'unlock-screen',
  321. msg: '解锁了'
  322. }
  323. event.reply(`${channel}`, data)
  324. });
  325. return true
  326. }
  327. /**
  328. * 获取屏幕信息
  329. */
  330. getScreen (arg) {
  331. let data = [];
  332. let res = {};
  333. if (arg == 0) {
  334. let res = screen.getCursorScreenPoint();
  335. data = [
  336. {
  337. title: '横坐标',
  338. desc: res.x
  339. },
  340. {
  341. title: '纵坐标',
  342. desc: res.y
  343. },
  344. ]
  345. return data;
  346. }
  347. if (arg == 1) {
  348. res = screen.getPrimaryDisplay();
  349. }
  350. if (arg == 2) {
  351. let resArr = screen.getAllDisplays();
  352. // 数组,只取一个吧
  353. res = resArr[0];
  354. }
  355. // Log.info('[electron] [ipc] [example] [getScreen] res:', res);
  356. data = [
  357. {
  358. title: '分辨率',
  359. desc: res.bounds.width + ' x ' + res.bounds.height
  360. },
  361. {
  362. title: '单色显示器',
  363. desc: res.monochrome ? '是' : '否'
  364. },
  365. {
  366. title: '色深',
  367. desc: res. colorDepth
  368. },
  369. {
  370. title: '色域',
  371. desc: res.colorSpace
  372. },
  373. {
  374. title: 'scaleFactor',
  375. desc: res.scaleFactor
  376. },
  377. {
  378. title: '加速器',
  379. desc: res.accelerometerSupport
  380. },
  381. {
  382. title: '触控',
  383. desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
  384. },
  385. ]
  386. return data;
  387. }
  388. /**
  389. * 调用其它程序(exe、bash等可执行程序)
  390. */
  391. openSoftware (softName) {
  392. if (!softName) {
  393. return false;
  394. }
  395. let softwarePath = path.join(Ps.getExtraResourcesDir(), softName);
  396. Log.info('[openSoftware] softwarePath:', softwarePath);
  397. // 检查程序是否存在
  398. if (!fs.existsSync(softwarePath)) {
  399. return false;
  400. }
  401. // 命令行字符串 并 执行
  402. let cmdStr = 'start ' + softwarePath;
  403. exec(cmdStr);
  404. return true;
  405. }
  406. /**
  407. * 获取系统主题
  408. */
  409. getTheme () {
  410. let theme = 'system';
  411. if (nativeTheme.shouldUseHighContrastColors) {
  412. theme = 'light';
  413. } else if (nativeTheme.shouldUseInvertedColorScheme) {
  414. theme = 'dark';
  415. }
  416. return theme;
  417. }
  418. /**
  419. * 设置系统主题
  420. */
  421. setTheme (args) {
  422. // TODO 好像没有什么明显效果
  423. nativeTheme.themeSource = args;
  424. return args;
  425. }
  426. /**
  427. * 检查是否有新版本
  428. */
  429. checkForUpdater () {
  430. const autoUpdaterAddon = this.app.addon.autoUpdater;
  431. autoUpdaterAddon.checkUpdate();
  432. return;
  433. }
  434. /**
  435. * 下载新版本
  436. */
  437. downloadApp () {
  438. const autoUpdaterAddon = this.app.addon.autoUpdater;
  439. autoUpdaterAddon.download();
  440. return;
  441. }
  442. /**
  443. * 检测http服务是否开启
  444. */
  445. async checkHttpServer () {
  446. const httpServerConfig = this.app.config.httpServer;
  447. const url = httpServerConfig.protocol + httpServerConfig.host + ':' + httpServerConfig.port;
  448. const data = {
  449. enable: httpServerConfig.enable,
  450. server: url
  451. }
  452. return data;
  453. }
  454. /**
  455. * 一个http请求访问此方法
  456. */
  457. async doHttpRequest () {
  458. // http方法
  459. const method = this.app.request.method;
  460. // http get 参数
  461. let params = this.app.request.query;
  462. params = (params instanceof Object) ? params : JSON.parse(JSON.stringify(params));
  463. // http post 参数
  464. const body = this.app.request.body;
  465. const httpInfo = {
  466. method,
  467. params,
  468. body
  469. }
  470. Log.info('httpInfo:', httpInfo);
  471. if (!body.id) {
  472. return false;
  473. }
  474. const dir = electronApp.getPath(body.id);
  475. shell.openPath(dir);
  476. return true;
  477. }
  478. /**
  479. * 一个socket io请求访问此方法
  480. */
  481. async doSocketRequest (args) {
  482. if (!args.id) {
  483. return false;
  484. }
  485. const dir = electronApp.getPath(args.id);
  486. shell.openPath(dir);
  487. return true;
  488. }
  489. /**
  490. * 异步消息类型
  491. * @param args 前端传的参数
  492. * @param event - IpcMainInvokeEvent 文档:https://www.electronjs.org/zh/docs/latest/api/structures/ipc-main-invoke-event
  493. */
  494. async ipcInvokeMsg (args, event) {
  495. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  496. const data = args + ' - ' + timeNow;
  497. return data;
  498. }
  499. /**
  500. * 同步消息类型
  501. * @param args 前端传的参数
  502. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  503. */
  504. async ipcSendSyncMsg (args) {
  505. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  506. const data = args + ' - ' + timeNow;
  507. return data;
  508. }
  509. /**
  510. * 双向异步通信
  511. * @param args 前端传的参数
  512. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  513. */
  514. ipcSendMsg (args, event) {
  515. // 前端ipc频道 channel
  516. const channel = 'controller.example.ipcSendMsg';
  517. if (args.type == 'start') {
  518. // 每隔1秒,向前端页面发送消息
  519. // 用定时器模拟
  520. myTimer = setInterval(function(e, c, msg) {
  521. let timeNow = Date.now();
  522. let data = msg + ':' + timeNow;
  523. e.reply(`${c}`, data)
  524. }, 1000, event, channel, args.content)
  525. return '开始了'
  526. } else if (args.type == 'end') {
  527. clearInterval(myTimer);
  528. return '停止了'
  529. } else {
  530. return 'ohther'
  531. }
  532. }
  533. /**
  534. * 上传文件
  535. */
  536. async uploadFile() {
  537. let tmpDir = Ps.getLogDir();
  538. const files = this.app.request.files;
  539. let file = files.file;
  540. let tmpFilePath = path.join(tmpDir, file.originalFilename);
  541. try {
  542. let tmpFile = fs.readFileSync(file.filepath);
  543. fs.writeFileSync(tmpFilePath, tmpFile);
  544. } finally {
  545. await fs.unlink(file.filepath, function(){});
  546. }
  547. const fileStream = fs.createReadStream(tmpFilePath);
  548. const uploadRes = await this.service.example.uploadFileToSMMS(fileStream);
  549. return uploadRes;
  550. }
  551. /**
  552. * 启动java项目
  553. */
  554. async startJavaServer () {
  555. let data = {
  556. code: 0,
  557. msg: '',
  558. server: ''
  559. }
  560. const javaCfg = this.app.config.addons.javaServer || {};
  561. if (!javaCfg.enable) {
  562. data.code = -1;
  563. data.msg = 'addon not enabled!';
  564. return data;
  565. }
  566. const javaServerAddon = this.app.addon.javaServer;
  567. await javaServerAddon.createServer();
  568. data.server = 'http://localhost:' + javaCfg.port;
  569. return data;
  570. }
  571. /**
  572. * 关闭java项目
  573. */
  574. async closeJavaServer () {
  575. let data = {
  576. code: 0,
  577. msg: '',
  578. }
  579. const javaCfg = this.app.config.addons.javaServer || {};
  580. if (!javaCfg.enable) {
  581. data.code = -1;
  582. data.msg = 'addon not enabled!';
  583. return data;
  584. }
  585. const javaServerAddon = this.app.addon.javaServer;
  586. await javaServerAddon.kill();
  587. return data;
  588. }
  589. /**
  590. * 任务
  591. */
  592. someJob (args, event) {
  593. let jobId = args.id;
  594. if (args.type == 'timer') {
  595. let myjob = new ChildJob();
  596. // 执行任务及监听进度
  597. const channel = 'controller.example.timerJobProgress';
  598. const timerTask = myjob.exec('./jobs/example/timer', {jobId});
  599. timerTask.emitter.on('job-timer-progress', (data) => {
  600. Log.info('[main-process] timerTask, from TimerJob data:', data);
  601. // 发送数据到渲染进程
  602. event.reply(`${channel}`, data)
  603. })
  604. // 执行任务及监听进度 异步
  605. // myjob.execPromise('./jobs/example/timer', {jobId}).then(task => {
  606. // task.emitter.on('job-timer-progress', (data) => {
  607. // Log.info('[main-process] timerTask, from TimerJob data:', data);
  608. // // 发送数据到渲染进程
  609. // event.reply(`${channel}`, data)
  610. // })
  611. // });
  612. }
  613. return;
  614. }
  615. /**
  616. * 创建任务池
  617. */
  618. createJobPool (args, event) {
  619. return;
  620. }
  621. /**
  622. * 测试接口
  623. */
  624. hello (args) {
  625. Log.info('hello ', args);
  626. }
  627. }
  628. ExampleController.toString = () => '[class ExampleController]';
  629. module.exports = ExampleController;