example.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. 'use strict';
  2. const _ = require('lodash');
  3. const path = require('path');
  4. const fs = require('fs');
  5. const { exec } = require('child_process');
  6. const { Controller, Utils } = require('ee-core');
  7. const electronApp = require('electron').app;
  8. const {dialog, shell, BrowserView,
  9. Notification, powerMonitor, screen, nativeTheme} = require('electron');
  10. const dayjs = require('dayjs');
  11. let myTimer = null;
  12. let browserViewObj = null;
  13. let notificationObj = null;
  14. /**
  15. * 示例控制器
  16. * @class
  17. */
  18. class ExampleController extends Controller {
  19. constructor(ctx) {
  20. super(ctx);
  21. }
  22. /**
  23. * 所有方法接收两个参数
  24. * @param args 前端传的参数
  25. * @param event - ipc通信时才有值。invoke()方法时,event == IpcMainInvokeEvent; send()/sendSync()方法时,event == IpcMainEvent
  26. */
  27. /**
  28. * test
  29. */
  30. async test () {
  31. const result = await this.service.example.test('electron');
  32. let tmpDir = Utils.getLogDir();
  33. console.log('tmpDir:', tmpDir);
  34. let obj = {
  35. env: Utils.getEnv(),
  36. getStorageDir: Utils.getStorageDir(),
  37. getLogDir: Utils.getLogDir(),
  38. getHomeDir: Utils.getHomeDir(),
  39. getBaseDir: Utils.getBaseDir(),
  40. getRootDir: Utils.getRootDir(),
  41. getAppUserDataDir: Utils.getAppUserDataDir(),
  42. getAppVersion: Utils.getAppVersion(),
  43. getExecDir: Utils.getExecDir(),
  44. getAddonConfig: Utils.getAddonConfig(),
  45. getMainServerConfig: Utils.getMainServerConfig(),
  46. getHttpServerConfig: Utils.getHttpServerConfig(),
  47. getSocketServerConfig: Utils.getSocketServerConfig(),
  48. }
  49. console.log('obj:', obj);
  50. // console.log('this.app.request:', this.app.request.query);
  51. // const exampleAddon = this.app.addon.example;
  52. // const str = exampleAddon.hello();
  53. // console.log('str:', str);
  54. return result;
  55. }
  56. /**
  57. * json数据库操作
  58. */
  59. async dbOperation(args) {
  60. const { service } = this;
  61. const paramsObj = args;
  62. //console.log('eeeee paramsObj:', paramsObj);
  63. const data = {
  64. action: paramsObj.action,
  65. result: null,
  66. all_list: []
  67. };
  68. switch (paramsObj.action) {
  69. case 'add' :
  70. data.result = await service.storage.addTestData(paramsObj.info);;
  71. break;
  72. case 'del' :
  73. data.result = await service.storage.delTestData(paramsObj.delete_name);;
  74. break;
  75. case 'update' :
  76. data.result = await service.storage.updateTestData(paramsObj.update_name, paramsObj.update_age);
  77. break;
  78. case 'get' :
  79. data.result = await service.storage.getTestData(paramsObj.search_age);
  80. break;
  81. }
  82. data.all_list = await service.storage.getAllTestData();
  83. return data;
  84. }
  85. /**
  86. * sqlite数据库操作
  87. */
  88. async sqlitedbOperation(args) {
  89. const { service } = this;
  90. const paramsObj = args;
  91. //console.log('eeeee paramsObj:', paramsObj);
  92. const data = {
  93. action: paramsObj.action,
  94. result: null,
  95. all_list: []
  96. };
  97. switch (paramsObj.action) {
  98. case 'add' :
  99. data.result = await service.storage.addTestDataSqlite(paramsObj.info);;
  100. break;
  101. case 'del' :
  102. data.result = await service.storage.delTestDataSqlite(paramsObj.delete_name);;
  103. break;
  104. case 'update' :
  105. data.result = await service.storage.updateTestDataSqlite(paramsObj.update_name, paramsObj.update_age);
  106. break;
  107. case 'get' :
  108. data.result = await service.storage.getTestDataSqlite(paramsObj.search_age);
  109. break;
  110. }
  111. data.all_list = await service.storage.getAllTestDataSqlite();
  112. return data;
  113. }
  114. /**
  115. * 消息提示对话框
  116. */
  117. messageShow () {
  118. dialog.showMessageBoxSync({
  119. type: 'info', // "none", "info", "error", "question" 或者 "warning"
  120. title: '自定义标题-message',
  121. message: '自定义消息内容',
  122. detail: '其它的额外信息'
  123. })
  124. return '打开了消息框';
  125. }
  126. /**
  127. * 消息提示与确认对话框
  128. */
  129. messageShowConfirm () {
  130. const res = dialog.showMessageBoxSync({
  131. type: 'info',
  132. title: '自定义标题-message',
  133. message: '自定义消息内容',
  134. detail: '其它的额外信息',
  135. cancelId: 1, // 用于取消对话框的按钮的索引
  136. defaultId: 0, // 设置默认选中的按钮
  137. buttons: ['确认', '取消'], // 按钮及索引
  138. })
  139. let data = (res === 0) ? '点击确认按钮' : '点击取消按钮';
  140. return data;
  141. }
  142. /**
  143. * 选择目录
  144. */
  145. selectFolder () {
  146. const filePaths = dialog.showOpenDialogSync({
  147. properties: ['openDirectory', 'createDirectory']
  148. });
  149. if (_.isEmpty(filePaths)) {
  150. return null
  151. }
  152. return filePaths[0];
  153. }
  154. /**
  155. * 打开目录
  156. */
  157. openDirectory (args) {
  158. if (!args.id) {
  159. return false;
  160. }
  161. const dir = electronApp.getPath(args.id);
  162. shell.openPath(dir);
  163. return true;
  164. }
  165. /**
  166. * 加载视图内容
  167. */
  168. loadViewContent (args) {
  169. let content = null;
  170. if (args.type == 'html') {
  171. content = path.join('file://', electronApp.getAppPath(), args.content)
  172. } else {
  173. content = args.content;
  174. }
  175. browserViewObj = new BrowserView();
  176. this.app.electron.mainWindow.setBrowserView(browserViewObj)
  177. browserViewObj.setBounds({
  178. x: 300,
  179. y: 170,
  180. width: 650,
  181. height: 400
  182. });
  183. browserViewObj.webContents.loadURL(content);
  184. return true
  185. }
  186. /**
  187. * 移除视图内容
  188. */
  189. removeViewContent () {
  190. this.app.electron.mainWindow.removeBrowserView(browserViewObj);
  191. return true
  192. }
  193. /**
  194. * 打开新窗口
  195. */
  196. createWindow (args) {
  197. let content = null;
  198. if (args.type == 'html') {
  199. content = path.join('file://', electronApp.getAppPath(), args.content)
  200. } else if (args.type == 'web') {
  201. content = args.content;
  202. } else if (args.type == 'vue') {
  203. let addr = 'http://localhost:8080'
  204. if (this.config.env == 'prod') {
  205. const mainServer = this.app.config.mainServer;
  206. addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
  207. }
  208. content = addr + args.content;
  209. } else {
  210. // some
  211. }
  212. const addonWindow = this.app.addon.window;
  213. let opt = {
  214. title: args.windowName || 'new window'
  215. }
  216. const name = args.windowName || 'window-1';
  217. const win = addonWindow.create(name, opt);
  218. const winContentsId = win.webContents.id;
  219. // load page
  220. win.loadURL(content);
  221. return winContentsId
  222. }
  223. /**
  224. * 获取窗口contents id
  225. */
  226. getWCid (args) {
  227. const addonWindow = this.app.addon.window;
  228. // 主窗口的name默认是main,其它窗口name开发者自己定义
  229. const name = args;
  230. const id = addonWindow.getWCid(name);
  231. return id;
  232. }
  233. /**
  234. * 加载扩展程序
  235. */
  236. // async loadExtension (args) {
  237. // const crxFile = args[0];
  238. // if (_.isEmpty(crxFile)) {
  239. // return false;
  240. // }
  241. // const extensionId = path.basename(crxFile, '.crx');
  242. // const chromeExtensionDir = chromeExtension.getDirectory();
  243. // const extensionDir = path.join(chromeExtensionDir, extensionId);
  244. // console.log("[api] [example] [loadExtension] extension id:", extensionId);
  245. // unzip(crxFile, extensionDir).then(() => {
  246. // console.log("[api] [example] [loadExtension] unzip success!");
  247. // chromeExtension.load(extensionId);
  248. // });
  249. // return true;
  250. // }
  251. /**
  252. * 创建系统通知
  253. */
  254. sendNotification (arg, event) {
  255. const channel = 'controller.example.sendNotification';
  256. if (!Notification.isSupported()) {
  257. return '当前系统不支持通知';
  258. }
  259. let options = {};
  260. if (!_.isEmpty(arg.title)) {
  261. options.title = arg.title;
  262. }
  263. if (!_.isEmpty(arg.subtitle)) {
  264. options.subtitle = arg.subtitle;
  265. }
  266. if (!_.isEmpty(arg.body)) {
  267. options.body = arg.body;
  268. }
  269. if (!_.isEmpty(arg.silent)) {
  270. options.silent = arg.silent;
  271. }
  272. notificationObj = new Notification(options);
  273. if (arg.clickEvent) {
  274. notificationObj.on('click', (e) => {
  275. let data = {
  276. type: 'click',
  277. msg: '您点击了通知消息'
  278. }
  279. event.reply(`${channel}`, data)
  280. });
  281. }
  282. if (arg.closeEvent) {
  283. notificationObj.on('close', (e) => {
  284. let data = {
  285. type: 'close',
  286. msg: '您关闭了通知消息'
  287. }
  288. event.reply(`${channel}`, data)
  289. });
  290. }
  291. notificationObj.show();
  292. return true
  293. }
  294. /**
  295. * 电源监控
  296. */
  297. initPowerMonitor (arg, event) {
  298. const channel = 'controller.example.initPowerMonitor';
  299. powerMonitor.on('on-ac', (e) => {
  300. let data = {
  301. type: 'on-ac',
  302. msg: '接入了电源'
  303. }
  304. event.reply(`${channel}`, data)
  305. });
  306. powerMonitor.on('on-battery', (e) => {
  307. let data = {
  308. type: 'on-battery',
  309. msg: '使用电池中'
  310. }
  311. event.reply(`${channel}`, data)
  312. });
  313. powerMonitor.on('lock-screen', (e) => {
  314. let data = {
  315. type: 'lock-screen',
  316. msg: '锁屏了'
  317. }
  318. event.reply(`${channel}`, data)
  319. });
  320. powerMonitor.on('unlock-screen', (e) => {
  321. let data = {
  322. type: 'unlock-screen',
  323. msg: '解锁了'
  324. }
  325. event.reply(`${channel}`, data)
  326. });
  327. return true
  328. }
  329. /**
  330. * 获取屏幕信息
  331. */
  332. getScreen (arg) {
  333. let data = [];
  334. let res = {};
  335. if (arg == 0) {
  336. let res = screen.getCursorScreenPoint();
  337. data = [
  338. {
  339. title: '横坐标',
  340. desc: res.x
  341. },
  342. {
  343. title: '纵坐标',
  344. desc: res.y
  345. },
  346. ]
  347. return data;
  348. }
  349. if (arg == 1) {
  350. res = screen.getPrimaryDisplay();
  351. }
  352. if (arg == 2) {
  353. let resArr = screen.getAllDisplays();
  354. // 数组,只取一个吧
  355. res = resArr[0];
  356. }
  357. // console.log('[electron] [ipc] [example] [getScreen] res:', res);
  358. data = [
  359. {
  360. title: '分辨率',
  361. desc: res.bounds.width + ' x ' + res.bounds.height
  362. },
  363. {
  364. title: '单色显示器',
  365. desc: res.monochrome ? '是' : '否'
  366. },
  367. {
  368. title: '色深',
  369. desc: res. colorDepth
  370. },
  371. {
  372. title: '色域',
  373. desc: res.colorSpace
  374. },
  375. {
  376. title: 'scaleFactor',
  377. desc: res.scaleFactor
  378. },
  379. {
  380. title: '加速器',
  381. desc: res.accelerometerSupport
  382. },
  383. {
  384. title: '触控',
  385. desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
  386. },
  387. ]
  388. return data;
  389. }
  390. /**
  391. * 调用其它程序(exe、bash等可执行程序)
  392. */
  393. openSoftware (softName) {
  394. if (!softName) {
  395. return false;
  396. }
  397. let softwarePath = path.join(Utils.getExtraResourcesDir(), softName);
  398. this.app.logger.info('[openSoftware] softwarePath:', softwarePath);
  399. // 检查程序是否存在
  400. if (!fs.existsSync(softwarePath)) {
  401. return false;
  402. }
  403. // 命令行字符串 并 执行
  404. let cmdStr = 'start ' + softwarePath;
  405. exec(cmdStr);
  406. return true;
  407. }
  408. /**
  409. * 获取系统主题
  410. */
  411. getTheme () {
  412. let theme = 'system';
  413. if (nativeTheme.shouldUseHighContrastColors) {
  414. theme = 'light';
  415. } else if (nativeTheme.shouldUseInvertedColorScheme) {
  416. theme = 'dark';
  417. }
  418. return theme;
  419. }
  420. /**
  421. * 设置系统主题
  422. */
  423. setTheme (args) {
  424. // TODO 好像没有什么明显效果
  425. nativeTheme.themeSource = args;
  426. return args;
  427. }
  428. /**
  429. * 检查是否有新版本
  430. */
  431. checkForUpdater () {
  432. const autoUpdaterAddon = this.app.addon.autoUpdater;
  433. autoUpdaterAddon.checkUpdate();
  434. return;
  435. }
  436. /**
  437. * 下载新版本
  438. */
  439. downloadApp () {
  440. const autoUpdaterAddon = this.app.addon.autoUpdater;
  441. autoUpdaterAddon.download();
  442. return;
  443. }
  444. /**
  445. * 检测http服务是否开启
  446. */
  447. async checkHttpServer () {
  448. const httpServerConfig = this.app.config.httpServer;
  449. const url = httpServerConfig.protocol + httpServerConfig.host + ':' + httpServerConfig.port;
  450. const data = {
  451. enable: httpServerConfig.enable,
  452. server: url
  453. }
  454. return data;
  455. }
  456. /**
  457. * 一个http请求访问此方法
  458. */
  459. async doHttpRequest () {
  460. // http方法
  461. const method = this.app.request.method;
  462. // http get 参数
  463. let params = this.app.request.query;
  464. params = (params instanceof Object) ? params : JSON.parse(JSON.stringify(params));
  465. // http post 参数
  466. const body = this.app.request.body;
  467. const httpInfo = {
  468. method,
  469. params,
  470. body
  471. }
  472. console.log('httpInfo:', httpInfo);
  473. if (!body.id) {
  474. return false;
  475. }
  476. const dir = electronApp.getPath(body.id);
  477. shell.openPath(dir);
  478. return true;
  479. }
  480. /**
  481. * 一个socket io请求访问此方法
  482. */
  483. async doSocketRequest (args) {
  484. if (!args.id) {
  485. return false;
  486. }
  487. const dir = electronApp.getPath(args.id);
  488. shell.openPath(dir);
  489. return true;
  490. }
  491. /**
  492. * 异步消息类型
  493. * @param args 前端传的参数
  494. * @param event - IpcMainInvokeEvent 文档:https://www.electronjs.org/zh/docs/latest/api/structures/ipc-main-invoke-event
  495. */
  496. async ipcInvokeMsg (args, event) {
  497. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  498. const data = args + ' - ' + timeNow;
  499. return data;
  500. }
  501. /**
  502. * 同步消息类型
  503. * @param args 前端传的参数
  504. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  505. */
  506. async ipcSendSyncMsg (args) {
  507. let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
  508. const data = args + ' - ' + timeNow;
  509. return data;
  510. }
  511. /**
  512. * 双向异步通信
  513. * @param args 前端传的参数
  514. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  515. */
  516. ipcSendMsg (args, event) {
  517. // 前端ipc频道 channel
  518. const channel = 'controller.example.ipcSendMsg';
  519. if (args.type == 'start') {
  520. // 每隔1秒,向前端页面发送消息
  521. // 用定时器模拟
  522. myTimer = setInterval(function(e, c, msg) {
  523. let timeNow = Date.now();
  524. let data = msg + ':' + timeNow;
  525. e.reply(`${c}`, data)
  526. }, 1000, event, channel, args.content)
  527. return '开始了'
  528. } else if (args.type == 'end') {
  529. clearInterval(myTimer);
  530. return '停止了'
  531. } else {
  532. return 'ohther'
  533. }
  534. }
  535. /**
  536. * 上传文件
  537. */
  538. async uploadFile() {
  539. let tmpDir = Utils.getLogDir();
  540. const files = this.app.request.files;
  541. let file = files.file;
  542. let tmpFilePath = path.join(tmpDir, file.originalFilename);
  543. try {
  544. let tmpFile = fs.readFileSync(file.filepath);
  545. fs.writeFileSync(tmpFilePath, tmpFile);
  546. } finally {
  547. await fs.unlink(file.filepath, function(){});
  548. }
  549. const fileStream = fs.createReadStream(tmpFilePath);
  550. const uploadRes = await this.service.example.uploadFileToSMMS(fileStream);
  551. return uploadRes;
  552. }
  553. /**
  554. * 启动java项目
  555. */
  556. async startJavaServer () {
  557. let data = {
  558. code: 0,
  559. msg: '',
  560. server: ''
  561. }
  562. const javaCfg = this.app.config.addons.javaServer || {};
  563. if (!javaCfg.enable) {
  564. data.code = -1;
  565. data.msg = 'addon not enabled!';
  566. return data;
  567. }
  568. const javaServerAddon = this.app.addon.javaServer;
  569. await javaServerAddon.createServer();
  570. data.server = 'http://localhost:' + javaCfg.port;
  571. return data;
  572. }
  573. /**
  574. * 关闭java项目
  575. */
  576. async closeJavaServer () {
  577. let data = {
  578. code: 0,
  579. msg: '',
  580. }
  581. const javaCfg = this.app.config.addons.javaServer || {};
  582. if (!javaCfg.enable) {
  583. data.code = -1;
  584. data.msg = 'addon not enabled!';
  585. return data;
  586. }
  587. const javaServerAddon = this.app.addon.javaServer;
  588. await javaServerAddon.kill();
  589. return data;
  590. }
  591. /**
  592. * 测试接口
  593. */
  594. hello (args) {
  595. console.log('hello ', args);
  596. }
  597. }
  598. ExampleController.toString = () => '[class ExampleController]';
  599. module.exports = ExampleController;