example.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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, Utils } = 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. let myTimer = null;
  14. let browserViewObj = null;
  15. let notificationObj = null;
  16. /**
  17. * 示例控制器
  18. * @class
  19. */
  20. class ExampleController extends Controller {
  21. constructor(ctx) {
  22. super(ctx);
  23. }
  24. /**
  25. * 所有方法接收两个参数
  26. * @param args 前端传的参数
  27. * @param event - ipc通信时才有值。invoke()方法时,event == IpcMainInvokeEvent; send()/sendSync()方法时,event == IpcMainEvent
  28. */
  29. /**
  30. * test
  31. */
  32. async test () {
  33. const result = await this.service.example.test('electron');
  34. let tmpDir = Utils.getLogDir();
  35. console.log('tmpDir:', tmpDir);
  36. // console.log('this.app.request:', this.app.request.query);
  37. // const exampleAddon = this.app.addon.example;
  38. // const str = exampleAddon.hello();
  39. // console.log('str:', str);
  40. return result;
  41. }
  42. /**
  43. * json数据库操作
  44. */
  45. async dbOperation(args) {
  46. const { service } = this;
  47. const paramsObj = args;
  48. //console.log('eeeee paramsObj:', paramsObj);
  49. const data = {
  50. action: paramsObj.action,
  51. result: null,
  52. all_list: []
  53. };
  54. switch (paramsObj.action) {
  55. case 'add' :
  56. data.result = await service.storage.addTestData(paramsObj.info);;
  57. break;
  58. case 'del' :
  59. data.result = await service.storage.delTestData(paramsObj.delete_name);;
  60. break;
  61. case 'update' :
  62. data.result = await service.storage.updateTestData(paramsObj.update_name, paramsObj.update_age);
  63. break;
  64. case 'get' :
  65. data.result = await service.storage.getTestData(paramsObj.search_age);
  66. break;
  67. }
  68. data.all_list = await service.storage.getAllTestData();
  69. return data;
  70. }
  71. /**
  72. * sqlite数据库操作
  73. */
  74. async sqlitedbOperation(args) {
  75. const { service } = this;
  76. const paramsObj = args;
  77. //console.log('eeeee paramsObj:', paramsObj);
  78. const data = {
  79. action: paramsObj.action,
  80. result: null,
  81. all_list: []
  82. };
  83. switch (paramsObj.action) {
  84. case 'add' :
  85. data.result = await service.storage.addTestDataSqlite(paramsObj.info);;
  86. break;
  87. case 'del' :
  88. data.result = await service.storage.delTestDataSqlite(paramsObj.delete_name);;
  89. break;
  90. case 'update' :
  91. data.result = await service.storage.updateTestDataSqlite(paramsObj.update_name, paramsObj.update_age);
  92. break;
  93. case 'get' :
  94. data.result = await service.storage.getTestDataSqlite(paramsObj.search_age);
  95. break;
  96. case 'getDataDir' :
  97. data.result = await service.storage.getDataDir();
  98. break;
  99. case 'setDataDir' :
  100. data.result = await service.storage.setCustomDataDir(paramsObj.data_dir);
  101. break;
  102. }
  103. data.all_list = await service.storage.getAllTestDataSqlite();
  104. return data;
  105. }
  106. /**
  107. * 消息提示对话框
  108. */
  109. messageShow () {
  110. dialog.showMessageBoxSync({
  111. type: 'info', // "none", "info", "error", "question" 或者 "warning"
  112. title: '自定义标题-message',
  113. message: '自定义消息内容',
  114. detail: '其它的额外信息'
  115. })
  116. return '打开了消息框';
  117. }
  118. /**
  119. * 消息提示与确认对话框
  120. */
  121. messageShowConfirm () {
  122. const res = dialog.showMessageBoxSync({
  123. type: 'info',
  124. title: '自定义标题-message',
  125. message: '自定义消息内容',
  126. detail: '其它的额外信息',
  127. cancelId: 1, // 用于取消对话框的按钮的索引
  128. defaultId: 0, // 设置默认选中的按钮
  129. buttons: ['确认', '取消'], // 按钮及索引
  130. })
  131. let data = (res === 0) ? '点击确认按钮' : '点击取消按钮';
  132. return data;
  133. }
  134. /**
  135. * 选择目录
  136. */
  137. selectFolder () {
  138. const filePaths = dialog.showOpenDialogSync({
  139. properties: ['openDirectory', 'createDirectory']
  140. });
  141. if (_.isEmpty(filePaths)) {
  142. return null
  143. }
  144. return filePaths[0];
  145. }
  146. /**
  147. * 打开目录
  148. */
  149. openDirectory (args) {
  150. if (!args.id) {
  151. return false;
  152. }
  153. let dir = '';
  154. if (path.isAbsolute(args.id)) {
  155. dir = args.id;
  156. } else {
  157. dir = electronApp.getPath(args.id);
  158. }
  159. shell.openPath(dir);
  160. return true;
  161. }
  162. /**
  163. * 加载视图内容
  164. */
  165. loadViewContent (args) {
  166. let content = null;
  167. if (args.type == 'html') {
  168. content = path.join('file://', electronApp.getAppPath(), args.content)
  169. } else {
  170. content = args.content;
  171. }
  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. 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. // console.log("[api] [example] [loadExtension] extension id:", extensionId);
  242. // unzip(crxFile, extensionDir).then(() => {
  243. // console.log("[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. // console.log('[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(Utils.getExtraResourcesDir(), softName);
  395. this.app.logger.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. console.log('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 = Utils.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. hello (args) {
  592. console.log('hello ', args);
  593. }
  594. }
  595. ExampleController.toString = () => '[class ExampleController]';
  596. module.exports = ExampleController;