example.js 15 KB

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