example.js 15 KB

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