example.js 12 KB

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