example.js 14 KB

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