example.js 11 KB

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