example.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. let myTimer = null;
  14. let browserViewObj = null;
  15. let notificationObj = null;
  16. /**
  17. * 示例控制器
  18. * @class
  19. */
  20. class ExampleController extends Controller {
  21. constructor(ctx) {
  22. super(ctx);
  23. }
  24. /**
  25. * 所有方法接收两个参数
  26. * @param args 前端传的参数
  27. * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event
  28. */
  29. /**
  30. * test
  31. */
  32. async test () {
  33. const result = await this.service.example.test('electron');
  34. let tmpDir = Utils.getLogDir();
  35. console.log('tmpDir:', tmpDir);
  36. return result;
  37. }
  38. /**
  39. * json数据库操作
  40. */
  41. async dbOperation(args) {
  42. const { service } = this;
  43. const paramsObj = args;
  44. //console.log('eeeee paramsObj:', paramsObj);
  45. const data = {
  46. action: paramsObj.action,
  47. result: null,
  48. all_list: []
  49. };
  50. switch (paramsObj.action) {
  51. case 'add' :
  52. data.result = await service.storage.addTestData(paramsObj.info);;
  53. break;
  54. case 'del' :
  55. data.result = await service.storage.delTestData(paramsObj.delete_name);;
  56. break;
  57. case 'update' :
  58. data.result = await service.storage.updateTestData(paramsObj.update_name, paramsObj.update_age);
  59. break;
  60. case 'get' :
  61. data.result = await service.storage.getTestData(paramsObj.search_age);
  62. break;
  63. }
  64. data.all_list = await service.storage.getAllTestData();
  65. return data;
  66. }
  67. /**
  68. * hello
  69. */
  70. hello (args) {
  71. let newMsg = args + " +1";
  72. let content = '';
  73. content = '收到:' + args + ',返回:' + newMsg;
  74. return content;
  75. }
  76. /**
  77. * 消息提示对话框
  78. */
  79. messageShow () {
  80. dialog.showMessageBoxSync({
  81. type: 'info', // "none", "info", "error", "question" 或者 "warning"
  82. title: '自定义标题-message',
  83. message: '自定义消息内容',
  84. detail: '其它的额外信息'
  85. })
  86. return '打开了消息框';
  87. }
  88. /**
  89. * 消息提示与确认对话框
  90. */
  91. messageShowConfirm () {
  92. const res = dialog.showMessageBoxSync({
  93. type: 'info',
  94. title: '自定义标题-message',
  95. message: '自定义消息内容',
  96. detail: '其它的额外信息',
  97. cancelId: 1, // 用于取消对话框的按钮的索引
  98. defaultId: 0, // 设置默认选中的按钮
  99. buttons: ['确认', '取消'], // 按钮及索引
  100. })
  101. let data = (res === 0) ? '点击确认按钮' : '点击取消按钮';
  102. return data;
  103. }
  104. /**
  105. * 选择目录
  106. */
  107. selectFolder () {
  108. const filePaths = dialog.showOpenDialogSync({
  109. properties: ['openDirectory', 'createDirectory']
  110. });
  111. if (_.isEmpty(filePaths)) {
  112. return null
  113. }
  114. return filePaths[0];
  115. }
  116. /**
  117. * 打开目录
  118. */
  119. openDirectory (args) {
  120. if (!args.id) {
  121. return false;
  122. }
  123. const dir = electronApp.getPath(args.id);
  124. shell.openPath(dir);
  125. return true;
  126. }
  127. /**
  128. * 长消息 - 开始
  129. */
  130. socketMessageStart (args, event) {
  131. // 每隔1秒,向前端页面发送消息
  132. // 用定时器模拟
  133. // 前端ipc频道 channel
  134. const channel = 'controller.example.socketMessageStart';
  135. myTimer = setInterval(function(e, c, msg) {
  136. let timeNow = Date.now();
  137. let data = msg + ':' + timeNow;
  138. e.reply(`${c}`, data)
  139. }, 1000, event, channel, args)
  140. return '开始了'
  141. }
  142. /**
  143. * 长消息 - 停止
  144. */
  145. socketMessageStop () {
  146. clearInterval(myTimer);
  147. return '停止了'
  148. }
  149. /**
  150. * 执行js语句
  151. */
  152. executeJS (args) {
  153. let jscode = `(()=>{alert('${args}');return 'fromJs:${args}';})()`;
  154. return webContents.fromId(1).executeJavaScript(jscode);
  155. }
  156. /**
  157. * 加载视图内容
  158. */
  159. loadViewContent (args) {
  160. let content = null;
  161. if (args.type == 'html') {
  162. content = path.join('file://', electronApp.getAppPath(), args.content)
  163. } else {
  164. content = args.content;
  165. }
  166. browserViewObj = new BrowserView();
  167. this.app.electron.mainWindow.setBrowserView(browserViewObj)
  168. browserViewObj.setBounds({
  169. x: 300,
  170. y: 170,
  171. width: 650,
  172. height: 400
  173. });
  174. browserViewObj.webContents.loadURL(content);
  175. return true
  176. }
  177. /**
  178. * 移除视图内容
  179. */
  180. removeViewContent () {
  181. this.app.electron.mainWindow.removeBrowserView(browserViewObj);
  182. return true
  183. }
  184. /**
  185. * 打开新窗口
  186. */
  187. createWindow (args) {
  188. let content = null;
  189. if (args.type == 'html') {
  190. content = path.join('file://', electronApp.getAppPath(), args.content)
  191. } else {
  192. content = args.content;
  193. }
  194. let winObj = new BrowserWindow({
  195. x: 10,
  196. y: 10,
  197. width: 980,
  198. height: 650
  199. })
  200. winObj.loadURL(content);
  201. return winObj.id
  202. }
  203. /**
  204. * 加载扩展程序
  205. */
  206. // async loadExtension (args) {
  207. // const crxFile = args[0];
  208. // if (_.isEmpty(crxFile)) {
  209. // return false;
  210. // }
  211. // const extensionId = path.basename(crxFile, '.crx');
  212. // const chromeExtensionDir = chromeExtension.getDirectory();
  213. // const extensionDir = path.join(chromeExtensionDir, extensionId);
  214. // console.log("[api] [example] [loadExtension] extension id:", extensionId);
  215. // unzip(crxFile, extensionDir).then(() => {
  216. // console.log("[api] [example] [loadExtension] unzip success!");
  217. // chromeExtension.load(extensionId);
  218. // });
  219. // return true;
  220. // }
  221. /**
  222. * 创建系统通知
  223. */
  224. sendNotification (arg, event) {
  225. const channel = 'controller.example.sendNotification';
  226. if (!Notification.isSupported()) {
  227. return '当前系统不支持通知';
  228. }
  229. let options = {};
  230. if (!_.isEmpty(arg.title)) {
  231. options.title = arg.title;
  232. }
  233. if (!_.isEmpty(arg.subtitle)) {
  234. options.subtitle = arg.subtitle;
  235. }
  236. if (!_.isEmpty(arg.body)) {
  237. options.body = arg.body;
  238. }
  239. if (!_.isEmpty(arg.silent)) {
  240. options.silent = arg.silent;
  241. }
  242. notificationObj = new Notification(options);
  243. if (arg.clickEvent) {
  244. notificationObj.on('click', (e) => {
  245. let data = {
  246. type: 'click',
  247. msg: '您点击了通知消息'
  248. }
  249. event.reply(`${channel}`, data)
  250. });
  251. }
  252. if (arg.closeEvent) {
  253. notificationObj.on('close', (e) => {
  254. let data = {
  255. type: 'close',
  256. msg: '您关闭了通知消息'
  257. }
  258. event.reply(`${channel}`, data)
  259. });
  260. }
  261. notificationObj.show();
  262. return true
  263. }
  264. /**
  265. * 电源监控
  266. */
  267. initPowerMonitor (arg, event) {
  268. const channel = 'controller.example.initPowerMonitor';
  269. powerMonitor.on('on-ac', (e) => {
  270. let data = {
  271. type: 'on-ac',
  272. msg: '接入了电源'
  273. }
  274. event.reply(`${channel}`, data)
  275. });
  276. powerMonitor.on('on-battery', (e) => {
  277. let data = {
  278. type: 'on-battery',
  279. msg: '使用电池中'
  280. }
  281. event.reply(`${channel}`, data)
  282. });
  283. powerMonitor.on('lock-screen', (e) => {
  284. let data = {
  285. type: 'lock-screen',
  286. msg: '锁屏了'
  287. }
  288. event.reply(`${channel}`, data)
  289. });
  290. powerMonitor.on('unlock-screen', (e) => {
  291. let data = {
  292. type: 'unlock-screen',
  293. msg: '解锁了'
  294. }
  295. event.reply(`${channel}`, data)
  296. });
  297. return true
  298. }
  299. /**
  300. * 获取屏幕信息
  301. */
  302. getScreen (arg) {
  303. let data = [];
  304. let res = {};
  305. if (arg == 0) {
  306. let res = screen.getCursorScreenPoint();
  307. data = [
  308. {
  309. title: '横坐标',
  310. desc: res.x
  311. },
  312. {
  313. title: '纵坐标',
  314. desc: res.y
  315. },
  316. ]
  317. return data;
  318. }
  319. if (arg == 1) {
  320. res = screen.getPrimaryDisplay();
  321. }
  322. if (arg == 2) {
  323. let resArr = screen.getAllDisplays();
  324. // 数组,只取一个吧
  325. res = resArr[0];
  326. }
  327. // console.log('[electron] [ipc] [example] [getScreen] res:', res);
  328. data = [
  329. {
  330. title: '分辨率',
  331. desc: res.bounds.width + ' x ' + res.bounds.height
  332. },
  333. {
  334. title: '单色显示器',
  335. desc: res.monochrome ? '是' : '否'
  336. },
  337. {
  338. title: '色深',
  339. desc: res. colorDepth
  340. },
  341. {
  342. title: '色域',
  343. desc: res.colorSpace
  344. },
  345. {
  346. title: 'scaleFactor',
  347. desc: res.scaleFactor
  348. },
  349. {
  350. title: '加速器',
  351. desc: res.accelerometerSupport
  352. },
  353. {
  354. title: '触控',
  355. desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
  356. },
  357. ]
  358. return data;
  359. }
  360. /**
  361. * 调用其它程序(exe、bash等可执行程序)
  362. */
  363. openSoftware (softName) {
  364. if (!softName) {
  365. return false;
  366. }
  367. // 资源路径不同
  368. let softwarePath = '';
  369. if (electronApp.isPackaged) {
  370. // 打包后
  371. softwarePath = path.join(this.app.config.execDir, "resources", "extraResources", softName);
  372. } else {
  373. // 打包前
  374. softwarePath = path.join(this.app.config.execDir, "build", "extraResources", softName);
  375. }
  376. // 检查程序是否存在
  377. if (!fs.existsSync(softwarePath)) {
  378. return false;
  379. }
  380. // 命令行字符串 并 执行
  381. let cmdStr = 'start ' + softwarePath;
  382. exec(cmdStr);
  383. return true;
  384. }
  385. /**
  386. * 开机启动-开启
  387. */
  388. autoLaunch (type) {
  389. console.log('type:', type);
  390. let res = {
  391. type: type,
  392. status: null
  393. };
  394. if (type == 'check') {
  395. res.status = autoLaunchManager.isEnabled();
  396. } else if (type == 'open') {
  397. autoLaunchManager.enable();
  398. res.status = true;
  399. } else if (type == 'close') {
  400. autoLaunchManager.disable();
  401. res.status = false;
  402. }
  403. return res
  404. }
  405. /**
  406. * 获取系统主题
  407. */
  408. getTheme () {
  409. let theme = 'system';
  410. if (nativeTheme.shouldUseHighContrastColors) {
  411. theme = 'light';
  412. } else if (nativeTheme.shouldUseInvertedColorScheme) {
  413. theme = 'dark';
  414. }
  415. return theme;
  416. }
  417. /**
  418. * 设置系统主题
  419. */
  420. setTheme (args) {
  421. // TODO 好像没有什么明显效果
  422. nativeTheme.themeSource = args;
  423. return args;
  424. }
  425. /**
  426. * 检查是否有新版本
  427. */
  428. checkForUpdater () {
  429. const config = this.app.config.autoUpdate;
  430. if ( (is.windows() && config.windows) || (is.macOS() && config.macOS) || (is.linux() && config.linux) ) {
  431. const autoUpdater = require('../library/autoUpdater');
  432. autoUpdater.checkUpdate();
  433. }
  434. return;
  435. }
  436. /**
  437. * 下载新版本
  438. */
  439. downloadApp () {
  440. const config = this.app.config.autoUpdate;
  441. if ( (is.windows() && config.windows) || (is.macOS() && config.macOS) || (is.linux() && config.linux) ) {
  442. const autoUpdater = require('../library/autoUpdater');
  443. autoUpdater.download();
  444. }
  445. return;
  446. }
  447. /**
  448. * 上传文件
  449. */
  450. async uploadFile() {
  451. // const self = this;
  452. // const { ctx, service } = this;
  453. // let tmpDir = Utils.getLogDir();
  454. // const file = ctx.request.files[0];
  455. // try {
  456. // let tmpFile = fs.readFileSync(file.filepath)
  457. // fs.writeFileSync(path.join(tmpDir, file.filename), tmpFile)
  458. // } finally {
  459. // await fs.unlink(file.filepath, function(){});
  460. // }
  461. // const fileStream = fs.createReadStream(path.join(tmpDir, file.filename))
  462. // const uploadRes = await service.example.uploadFileToSMMS(fileStream);
  463. // return uploadRes;
  464. }
  465. }
  466. module.exports = ExampleController;