example.js 11 KB

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