example.js 16 KB

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