example.js 13 KB

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