example.js 14 KB

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