example.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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/module/jobs/child');
  14. const Ps = require('ee-core/module/ps');
  15. const Log = require('ee-core/module/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. 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. this.app.electron.mainWindow.removeBrowserView(browserViewObj);
  187. return true
  188. }
  189. /**
  190. * 打开新窗口
  191. */
  192. createWindow (args) {
  193. let content = null;
  194. if (args.type == 'html') {
  195. content = path.join('file://', electronApp.getAppPath(), args.content)
  196. } else if (args.type == 'web') {
  197. content = args.content;
  198. } else if (args.type == 'vue') {
  199. let addr = 'http://localhost:8080'
  200. if (this.config.env == 'prod') {
  201. const mainServer = this.app.config.mainServer;
  202. addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
  203. }
  204. content = addr + args.content;
  205. } else {
  206. // some
  207. }
  208. const addonWindow = this.app.addon.window;
  209. let opt = {
  210. title: args.windowName || 'new window'
  211. }
  212. const name = args.windowName || 'window-1';
  213. const win = addonWindow.create(name, opt);
  214. const winContentsId = win.webContents.id;
  215. // load page
  216. win.loadURL(content);
  217. return winContentsId
  218. }
  219. /**
  220. * 获取窗口contents id
  221. */
  222. getWCid (args) {
  223. const addonWindow = this.app.addon.window;
  224. // 主窗口的name默认是main,其它窗口name开发者自己定义
  225. const name = args;
  226. const id = addonWindow.getWCid(name);
  227. return id;
  228. }
  229. /**
  230. * 加载扩展程序
  231. */
  232. // async loadExtension (args) {
  233. // const crxFile = args[0];
  234. // if (_.isEmpty(crxFile)) {
  235. // return false;
  236. // }
  237. // const extensionId = path.basename(crxFile, '.crx');
  238. // const chromeExtensionDir = chromeExtension.getDirectory();
  239. // const extensionDir = path.join(chromeExtensionDir, extensionId);
  240. // Log.info("[api] [example] [loadExtension] extension id:", extensionId);
  241. // unzip(crxFile, extensionDir).then(() => {
  242. // Log.info("[api] [example] [loadExtension] unzip success!");
  243. // chromeExtension.load(extensionId);
  244. // });
  245. // return true;
  246. // }
  247. /**
  248. * 创建系统通知
  249. */
  250. sendNotification (arg, event) {
  251. const channel = 'controller.example.sendNotification';
  252. if (!Notification.isSupported()) {
  253. return '当前系统不支持通知';
  254. }
  255. let options = {};
  256. if (!_.isEmpty(arg.title)) {
  257. options.title = arg.title;
  258. }
  259. if (!_.isEmpty(arg.subtitle)) {
  260. options.subtitle = arg.subtitle;
  261. }
  262. if (!_.isEmpty(arg.body)) {
  263. options.body = arg.body;
  264. }
  265. if (!_.isEmpty(arg.silent)) {
  266. options.silent = arg.silent;
  267. }
  268. notificationObj = new Notification(options);
  269. if (arg.clickEvent) {
  270. notificationObj.on('click', (e) => {
  271. let data = {
  272. type: 'click',
  273. msg: '您点击了通知消息'
  274. }
  275. event.reply(`${channel}`, data)
  276. });
  277. }
  278. if (arg.closeEvent) {
  279. notificationObj.on('close', (e) => {
  280. let data = {
  281. type: 'close',
  282. msg: '您关闭了通知消息'
  283. }
  284. event.reply(`${channel}`, data)
  285. });
  286. }
  287. notificationObj.show();
  288. return true
  289. }
  290. /**
  291. * 电源监控
  292. */
  293. initPowerMonitor (arg, event) {
  294. const channel = 'controller.example.initPowerMonitor';
  295. powerMonitor.on('on-ac', (e) => {
  296. let data = {
  297. type: 'on-ac',
  298. msg: '接入了电源'
  299. }
  300. event.reply(`${channel}`, data)
  301. });
  302. powerMonitor.on('on-battery', (e) => {
  303. let data = {
  304. type: 'on-battery',
  305. msg: '使用电池中'
  306. }
  307. event.reply(`${channel}`, data)
  308. });
  309. powerMonitor.on('lock-screen', (e) => {
  310. let data = {
  311. type: 'lock-screen',
  312. msg: '锁屏了'
  313. }
  314. event.reply(`${channel}`, data)
  315. });
  316. powerMonitor.on('unlock-screen', (e) => {
  317. let data = {
  318. type: 'unlock-screen',
  319. msg: '解锁了'
  320. }
  321. event.reply(`${channel}`, data)
  322. });
  323. return true
  324. }
  325. /**
  326. * 获取屏幕信息
  327. */
  328. getScreen (arg) {
  329. let data = [];
  330. let res = {};
  331. if (arg == 0) {
  332. let res = screen.getCursorScreenPoint();
  333. data = [
  334. {
  335. title: '横坐标',
  336. desc: res.x
  337. },
  338. {
  339. title: '纵坐标',
  340. desc: res.y
  341. },
  342. ]
  343. return data;
  344. }
  345. if (arg == 1) {
  346. res = screen.getPrimaryDisplay();
  347. }
  348. if (arg == 2) {
  349. let resArr = screen.getAllDisplays();
  350. // 数组,只取一个吧
  351. res = resArr[0];
  352. }
  353. // Log.info('[electron] [ipc] [example] [getScreen] res:', res);
  354. data = [
  355. {
  356. title: '分辨率',
  357. desc: res.bounds.width + ' x ' + res.bounds.height
  358. },
  359. {
  360. title: '单色显示器',
  361. desc: res.monochrome ? '是' : '否'
  362. },
  363. {
  364. title: '色深',
  365. desc: res. colorDepth
  366. },
  367. {
  368. title: '色域',
  369. desc: res.colorSpace
  370. },
  371. {
  372. title: 'scaleFactor',
  373. desc: res.scaleFactor
  374. },
  375. {
  376. title: '加速器',
  377. desc: res.accelerometerSupport
  378. },
  379. {
  380. title: '触控',
  381. desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
  382. },
  383. ]
  384. return data;
  385. }
  386. /**
  387. * 调用其它程序(exe、bash等可执行程序)
  388. */
  389. openSoftware (softName) {
  390. if (!softName) {
  391. return false;
  392. }
  393. let softwarePath = path.join(Ps.getExtraResourcesDir(), softName);
  394. Log.info('[openSoftware] softwarePath:', softwarePath);
  395. // 检查程序是否存在
  396. if (!fs.existsSync(softwarePath)) {
  397. return false;
  398. }
  399. // 命令行字符串 并 执行
  400. let cmdStr = 'start ' + softwarePath;
  401. exec(cmdStr);
  402. return true;
  403. }
  404. /**
  405. * 获取系统主题
  406. */
  407. getTheme () {
  408. let theme = 'system';
  409. if (nativeTheme.shouldUseHighContrastColors) {
  410. theme = 'light';
  411. } else if (nativeTheme.shouldUseInvertedColorScheme) {
  412. theme = 'dark';
  413. }
  414. return theme;
  415. }
  416. /**
  417. * 设置系统主题
  418. */
  419. setTheme (args) {
  420. // TODO 好像没有什么明显效果
  421. nativeTheme.themeSource = args;
  422. return args;
  423. }
  424. /**
  425. * 检查是否有新版本
  426. */
  427. checkForUpdater () {
  428. const autoUpdaterAddon = this.app.addon.autoUpdater;
  429. autoUpdaterAddon.checkUpdate();
  430. return;
  431. }
  432. /**
  433. * 下载新版本
  434. */
  435. downloadApp () {
  436. const autoUpdaterAddon = this.app.addon.autoUpdater;
  437. autoUpdaterAddon.download();
  438. return;
  439. }
  440. /**
  441. * 检测http服务是否开启
  442. */
  443. async checkHttpServer () {
  444. const httpServerConfig = this.app.config.httpServer;
  445. const url = httpServerConfig.protocol + httpServerConfig.host + ':' + httpServerConfig.port;
  446. const data = {
  447. enable: httpServerConfig.enable,
  448. server: url
  449. }
  450. return data;
  451. }
  452. /**
  453. * 一个http请求访问此方法
  454. */
  455. async doHttpRequest () {
  456. // http方法
  457. const method = this.app.request.method;
  458. // http get 参数
  459. let params = this.app.request.query;
  460. params = (params instanceof Object) ? params : JSON.parse(JSON.stringify(params));
  461. // http post 参数
  462. const body = this.app.request.body;
  463. const httpInfo = {
  464. method,
  465. params,
  466. body
  467. }
  468. Log.info('httpInfo:', httpInfo);
  469. if (!body.id) {
  470. return false;
  471. }
  472. const dir = electronApp.getPath(body.id);
  473. shell.openPath(dir);
  474. return true;
  475. }
  476. /**
  477. * 一个socket io请求访问此方法
  478. */
  479. async doSocketRequest (args) {
  480. if (!args.id) {
  481. return false;
  482. }
  483. const dir = electronApp.getPath(args.id);
  484. shell.openPath(dir);
  485. return true;
  486. }
  487. /**
  488. * 异步消息类型
  489. * @param args 前端传的参数
  490. * @param event - IpcMainInvokeEvent 文档:https://www.electronjs.org/zh/docs/latest/api/structures/ipc-main-invoke-event
  491. */
  492. async ipcInvokeMsg (args, event) {
  493. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  494. const data = args + ' - ' + timeNow;
  495. return data;
  496. }
  497. /**
  498. * 同步消息类型
  499. * @param args 前端传的参数
  500. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  501. */
  502. async ipcSendSyncMsg (args) {
  503. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  504. const data = args + ' - ' + timeNow;
  505. return data;
  506. }
  507. /**
  508. * 双向异步通信
  509. * @param args 前端传的参数
  510. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  511. */
  512. ipcSendMsg (args, event) {
  513. // 前端ipc频道 channel
  514. const channel = 'controller.example.ipcSendMsg';
  515. if (args.type == 'start') {
  516. // 每隔1秒,向前端页面发送消息
  517. // 用定时器模拟
  518. myTimer = setInterval(function(e, c, msg) {
  519. let timeNow = Date.now();
  520. let data = msg + ':' + timeNow;
  521. e.reply(`${c}`, data)
  522. }, 1000, event, channel, args.content)
  523. return '开始了'
  524. } else if (args.type == 'end') {
  525. clearInterval(myTimer);
  526. return '停止了'
  527. } else {
  528. return 'ohther'
  529. }
  530. }
  531. /**
  532. * 上传文件
  533. */
  534. async uploadFile() {
  535. let tmpDir = Ps.getLogDir();
  536. const files = this.app.request.files;
  537. let file = files.file;
  538. let tmpFilePath = path.join(tmpDir, file.originalFilename);
  539. try {
  540. let tmpFile = fs.readFileSync(file.filepath);
  541. fs.writeFileSync(tmpFilePath, tmpFile);
  542. } finally {
  543. await fs.unlink(file.filepath, function(){});
  544. }
  545. const fileStream = fs.createReadStream(tmpFilePath);
  546. const uploadRes = await this.service.example.uploadFileToSMMS(fileStream);
  547. return uploadRes;
  548. }
  549. /**
  550. * 启动java项目
  551. */
  552. async startJavaServer () {
  553. let data = {
  554. code: 0,
  555. msg: '',
  556. server: ''
  557. }
  558. const javaCfg = this.app.config.addons.javaServer || {};
  559. if (!javaCfg.enable) {
  560. data.code = -1;
  561. data.msg = 'addon not enabled!';
  562. return data;
  563. }
  564. const javaServerAddon = this.app.addon.javaServer;
  565. await javaServerAddon.createServer();
  566. data.server = 'http://localhost:' + javaCfg.port;
  567. return data;
  568. }
  569. /**
  570. * 关闭java项目
  571. */
  572. async closeJavaServer () {
  573. let data = {
  574. code: 0,
  575. msg: '',
  576. }
  577. const javaCfg = this.app.config.addons.javaServer || {};
  578. if (!javaCfg.enable) {
  579. data.code = -1;
  580. data.msg = 'addon not enabled!';
  581. return data;
  582. }
  583. const javaServerAddon = this.app.addon.javaServer;
  584. await javaServerAddon.kill();
  585. return data;
  586. }
  587. /**
  588. * 测试接口
  589. */
  590. hello (args) {
  591. Log.info('hello ', args);
  592. }
  593. }
  594. ExampleController.toString = () => '[class ExampleController]';
  595. module.exports = ExampleController;