example.js 16 KB

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