example.js 15 KB

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