Pārlūkot izejas kodu

notification soft screen launch

gaoshuaixing 3 gadi atpakaļ
vecāks
revīzija
e94e593702

+ 0 - 49
app/controller/example.js

@@ -111,55 +111,6 @@ class ExampleController extends BaseController {
     self.sendSuccess(data);
   }
 
-  async autoLaunchEnable() {
-    const { service } = this;
-
-    await service.example.autoLaunchEnable();
-    const data = {
-      isEnabled: true
-    };
-
-    this.sendSuccess(data);
-  }
-  
-  async autoLaunchDisable() {
-    const { service } = this;
-    
-    await service.example.autoLaunchDisable();
-    const data = {
-      isEnabled: false
-    };
-
-    this.sendSuccess(data);
-  }
-
-  async autoLaunchIsEnabled() {
-    const { service } = this;
-
-    const data = {
-      isEnabled: null
-    };
-
-    const isEnabled = await service.example.autoLaunchIsEnabled();
-    data.isEnabled = isEnabled;
-
-    this.sendSuccess(data);
-  }
-
-  /**
-   * 调用其它程序
-   */
-  async openSoftware() {
-    const { service } = this;
-    const data = {};
-    const openResult = await service.example.openSoftware('powershell.exe');
-    if (!openResult) {
-      this.sendFail({}, '程序不存在', 100);
-      return;
-    }
-    this.sendSuccess(data);
-  }
-
   /**
    * 显示消息对话框
    */

+ 0 - 8
app/router/example.js

@@ -8,14 +8,6 @@ module.exports = app => {
 
   // upload file
   router.post('/api/example/uploadFile', controller.example.uploadFile);
-  // open launch
-  router.post('/api/example/autoLaunchEnable', controller.example.autoLaunchEnable);
-  // close launch 
-  router.post('/api/example/autoLaunchDisable', controller.example.autoLaunchDisable);
-  // is launch 
-  router.post('/api/example/autoLaunchIsEnabled', controller.example.autoLaunchIsEnabled);
-  // open software
-  router.post('/api/example/openSoftware', controller.example.openSoftware);
   // test some electron api
   router.post('/api/example/testElectronApi', controller.example.testElectronApi);
   // test2

+ 0 - 24
app/service/example.js

@@ -49,30 +49,6 @@ class ExampleService extends Service {
     return res;
   }
 
-  async autoLaunchEnable() {
-    const callResult = await socketClient.call('controller.example.autoLaunchEnable');
-
-    return callResult.data;
-  }
-
-  async autoLaunchDisable() {
-    const callResult = await socketClient.call('controller.example.autoLaunchDisable');
-
-    return callResult.data;
-  }
-
-  async autoLaunchIsEnabled() {
-    const callResult = await socketClient.call('controller.example.autoLaunchIsEnabled');
-
-    return callResult.data;
-  }
-
-  async openSoftware(softName) {
-    const callResult = await socketClient.call('controller.example.openSoftware', softName);
-    
-    return callResult.data;
-  }
-
   async messageShow() {
     await socketClient.call('controller.example.messageShow');
 

+ 207 - 0
electron/controller/example.js

@@ -2,12 +2,15 @@
 
 const _ = require('lodash');
 const path = require('path');
+const fs = require('fs');
 const is = require('electron-is');
+const { exec } = require('child_process');
 const unzip = require("unzip-crx-3");
 const Controller = require('ee-core').Controller;
 const electronApp = require('electron').app;
 const {dialog, webContents, shell, BrowserWindow, BrowserView, Notification, powerMonitor, screen, nativeTheme} = require('electron');
 const chromeExtension = require('../library/chromeExtension');
+const autoLaunchManager = require('../library/autoLaunch');
 
 let myTimer = null;
 let browserViewObj = null;
@@ -226,7 +229,211 @@ class ExampleController extends Controller {
     });
 
     return true;
+  }
+
+  /**
+   * 创建系统通知
+   */
+  sendNotification (arg, event) {
+    const channel = 'controller.example.sendNotification';
+    if (!Notification.isSupported()) {
+      return '当前系统不支持通知';
+    }
+
+    let options = {};
+    if (!_.isEmpty(arg.title)) {
+      options.title = arg.title;
+    }
+    if (!_.isEmpty(arg.subtitle)) {
+      options.subtitle = arg.subtitle;
+    }
+    if (!_.isEmpty(arg.body)) {
+      options.body = arg.body;
+    }
+    if (!_.isEmpty(arg.silent)) {
+      options.silent = arg.silent;
+    }
+
+    notificationObj = new Notification(options);
+
+    if (arg.clickEvent) {
+      notificationObj.on('click', (e) => {
+        let data = {
+          type: 'click',
+          msg: '您点击了通知消息'
+        }
+        event.reply(`${channel}`, data)
+      });
+    }
+
+    if (arg.closeEvent) {
+      notificationObj.on('close', (e) => {
+        let data = {
+          type: 'close',
+          msg: '您关闭了通知消息'
+        }
+        event.reply(`${channel}`, data)
+      });
+    }
+
+    notificationObj.show();
+
+    return true
   }  
+
+  /**
+   * 电源监控
+   */
+  initPowerMonitor (arg, event) {
+    const channel = 'controller.example.initPowerMonitor';
+    powerMonitor.on('on-ac', (e) => {
+      let data = {
+        type: 'on-ac',
+        msg: '接入了电源'
+      }
+      event.reply(`${channel}`, data)
+    });
+
+    powerMonitor.on('on-battery', (e) => {
+      let data = {
+        type: 'on-battery',
+        msg: '使用电池中'
+      }
+      event.reply(`${channel}`, data)
+    });
+
+    powerMonitor.on('lock-screen', (e) => {
+      let data = {
+        type: 'lock-screen',
+        msg: '锁屏了'
+      }
+      event.reply(`${channel}`, data)
+    });
+
+    powerMonitor.on('unlock-screen', (e) => {
+      let data = {
+        type: 'unlock-screen',
+        msg: '解锁了'
+      }
+      event.reply(`${channel}`, data)
+    });
+
+    return true
+  }  
+
+  /**
+   * 获取屏幕信息
+   */
+  getScreen (arg) {
+    let data = [];
+    let res = {};
+    if (arg == 0) {
+      let res = screen.getCursorScreenPoint();
+      data = [
+        {
+          title: '横坐标',
+          desc: res.x
+        },
+        {
+          title: '纵坐标',
+          desc: res.y
+        },
+      ]
+      
+      return data;
+    }
+    if (arg == 1) {
+      res = screen.getPrimaryDisplay();
+    }
+    if (arg == 2) {
+      let resArr = screen.getAllDisplays();
+      // 数组,只取一个吧
+      res = resArr[0];
+    }
+    // console.log('[electron] [ipc] [example] [getScreen] res:', res);
+    data = [
+      {
+        title: '分辨率',
+        desc: res.bounds.width + ' x ' + res.bounds.height
+      },
+      {
+        title: '单色显示器',
+        desc: res.monochrome ? '是' : '否'
+      },
+      {
+        title: '色深',
+        desc: res. colorDepth
+      },
+      {
+        title: '色域',
+        desc: res.colorSpace
+      },
+      {
+        title: 'scaleFactor',
+        desc: res.scaleFactor
+      },
+      {
+        title: '加速器',
+        desc: res.accelerometerSupport
+      },
+      {
+        title: '触控',
+        desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
+      },
+    ]
+
+    return data;
+  }  
+
+  /**
+   * 调用其它程序(exe、bash等可执行程序)
+   */
+  openSoftware (softName) {
+    if (!softName) {
+      return false;
+    }
+
+    // 资源路径不同
+    let softwarePath = '';
+    if (electronApp.isPackaged) {
+      // 打包后
+      softwarePath = path.join(electronApp.getAppPath(), "..", "extraResources", softName);
+    } else {
+      // 打包前
+      softwarePath = path.join(electronApp.getAppPath(), "build", "extraResources", softName);
+    }
+    // 检查程序是否存在
+    if (!fs.existsSync(softwarePath)) {
+      return false;
+    }
+    // 命令行字符串 并 执行
+    let cmdStr = 'start ' + softwarePath;
+    exec(cmdStr);
+
+    return true;
+  }  
+
+  /**
+   * 开机启动-开启
+   */
+  autoLaunch (type) {
+    console.log('type:', type);
+    let res = {
+      type: type,
+      status: null
+    };
+    if (type == 'check') {
+      res.status = autoLaunchManager.isEnabled();
+    } else if (type == 'open') {
+      autoLaunchManager.enable();
+      res.status = true;
+    } else if (type == 'close') {
+      autoLaunchManager.disable();
+      res.status = false;
+    }
+
+    return res
+  } 
 }
 
 module.exports = ExampleController;

+ 46 - 0
electron/library/autoLaunch.js

@@ -0,0 +1,46 @@
+'use strict';
+
+const { app } = require('electron');
+const LOGIN_SETTING_OPTIONS = {
+  // For Windows
+  args: [
+    '--opened-at-login=1'
+  ]
+}
+
+/**
+ * 开机启动模块
+ */
+module.exports = {
+
+  /**
+   * 设置为开机启动
+   */ 
+  enable () {
+    const enabled = app.getLoginItemSettings(LOGIN_SETTING_OPTIONS).openAtLogin;
+    if (enabled) {
+      return true;
+    }
+    app.setLoginItemSettings({
+      ...LOGIN_SETTING_OPTIONS,
+      openAtLogin: true
+    })
+    return true;
+  },
+  
+  /**
+   * 关闭开机启动
+   */   
+  disable () {
+    app.setLoginItemSettings({ openAtLogin: false })
+    return true;
+  },
+
+  /**
+   * 检查是否开启
+   */   
+  isEnabled () {
+    const enabled = app.getLoginItemSettings(LOGIN_SETTING_OPTIONS).openAtLogin;
+    return enabled;
+  }
+}

+ 5 - 3
frontend/src/api/main.js

@@ -2,9 +2,6 @@ import request from '@/utils/request'
 
 const eggApiroute = {
   uploadFile: '/api/example/uploadFile',
-  autoLaunchEnable: '/api/example/autoLaunchEnable',
-  autoLaunchDisable: '/api/example/autoLaunchDisable',
-  autoLaunchIsEnabled: '/api/example/autoLaunchIsEnabled',
   openSoftware: '/api/example/openSoftware',
   messageShow: '/api/example/messageShow',
   messageShowConfirm: '/api/example/messageShowConfirm',
@@ -24,6 +21,11 @@ const ipcApiRoute = {
   loadViewContent: 'controller.example.loadViewContent',
   removeViewContent: 'controller.example.removeViewContent',
   createWindow: 'controller.example.createWindow',
+  sendNotification: 'controller.example.sendNotification',
+  initPowerMonitor: 'controller.example.initPowerMonitor',
+  getScreen: 'controller.example.getScreen',
+  openSoftware: 'controller.example.openSoftware', 
+  autoLaunch: 'controller.example.autoLaunch',
 }
 
 /**

+ 0 - 5
frontend/src/config/router.config.js

@@ -74,11 +74,6 @@ export const constantRouterMap = [
             component: () => import('@/views/base/theme/Index')
           },                               
           {
-            path: '/base/shortcut/index',
-            name: 'BaseShortcutIndex',
-            component: () => import('@/views/base/shortcut/Index')
-          },
-          {
             path: '/base/software/open',
             name: 'BaseSoftwareIndex',
             component: () => import('@/views/base/software/Index')

+ 3 - 2
frontend/src/views/base/notification/Index.vue

@@ -16,6 +16,7 @@
   </div>
 </template>
 <script>
+import { ipcApiRoute } from '@/api/main'
 
 export default {
   data() {
@@ -59,14 +60,14 @@ export default {
   methods: {
     init () {
       const self = this;
-      self.$ipc.on('example.sendNotification', (event, result) => {
+      self.$ipc.on(ipcApiRoute.sendNotification, (event, result) => {
         if (Object.prototype.toString.call(result) == '[object Object]') {
           self.$message.info(result.msg);
         }  
       })
     },
     sendNotification (index) {
-      this.$ipc.send('example.sendNotification', this.views[index]);
+      this.$ipc.send(ipcApiRoute.sendNotification, this.views[index]);
     },
   }
 };

+ 3 - 2
frontend/src/views/base/powermonitor/Index.vue

@@ -17,6 +17,7 @@
   </div>
 </template>
 <script>
+import { ipcApiRoute } from '@/api/main'
 
 export default {
   data() {
@@ -30,13 +31,13 @@ export default {
   methods: {
     init () {
       const self = this;
-      self.$ipc.on('example.initPowerMonitor', (event, result) => {
+      self.$ipc.on(ipcApiRoute.initPowerMonitor, (event, result) => {
         if (Object.prototype.toString.call(result) == '[object Object]') {
           self.currentStatus = result.msg;
           self.$message.info(result.msg);
         }
       })
-      this.$ipc.send('example.initPowerMonitor', '');
+      this.$ipc.send(ipcApiRoute.initPowerMonitor, '');
     }
   }
 };

+ 3 - 2
frontend/src/views/base/screen/Index.vue

@@ -27,6 +27,7 @@
   </div>
 </template>
 <script>
+import { ipcApiRoute } from '@/api/main'
 
 export default {
   data() {
@@ -40,12 +41,12 @@ export default {
   methods: {
     init () {
       const self = this;
-      self.$ipc.on('example.getScreen', (event, result) => {
+      self.$ipc.on(ipcApiRoute.getScreen, (event, result) => {
         self.data = result;
       })
     },
     getScreen (index) {
-      this.$ipc.send('example.getScreen', index);
+      this.$ipc.send(ipcApiRoute.getScreen, index);
     },
   }
 };

+ 0 - 99
frontend/src/views/base/shortcut/Index.vue

@@ -1,99 +0,0 @@
-<template>
-  <div id="app-base-shortcut">
-    <div class="one-block-1">
-      <span>
-        1. 快捷键
-      </span>
-    </div>  
-    <div class="one-block-2">
-      <a-row :gutter="[16,16]">
-        <a-col :span="24">
-          【窗口最小化】
-          <a-form :form="form" @submit="handleSubmit">
-            <a-form-item>
-              <hot-key-input
-                style="width: 100%;"
-                :hotkey.sync="hotKeyObj.keys"
-                :verify="handleHotkeyVerify"
-                :max="1"
-                type="lowser"
-                :reset="true"
-                :shake="false"
-                :range="null"
-                placeholder="快捷键">
-              </hot-key-input>
-            </a-form-item>
-            <a-form-item
-              :wrapperCol="{ span: 24 }"
-              style="text-align: center"
-            >
-              <a-button htmlType="submit" type="primary">保存</a-button>
-            </a-form-item>
-          </a-form>  
-        </a-col>
-      </a-row>
-    </div>
-  </div>
-</template>
-<script>
-import { requestEggApi } from '@/api/main'
-
-export default {
-  components: {},
-  data() {
-    return {
-      form: this.$form.createForm(this),
-      cmd: '',
-      hotKeyObj: {
-        tab: 'save',
-        keys: ['Ctrl+k']
-      },
-    };
-  },
-  methods: {
-    handleHotkeyVerify(hotkey) {
-      console.log('组合键:', hotkey)
-      return true;
-    },
-    handleSubmit (e) {
-      e.preventDefault()
-      console.log('submit 验证:', this.hotKeyObj)
-      const shortcutStr = this.hotKeyObj.keys[0];
-      const params = {
-        id: 'mini_window',
-        name: '窗口最小化',
-        cmd: shortcutStr
-      }
-      requestEggApi('setShortcut', params).then(res => {
-        if (res.code !== 0) {
-          // this.$message.info('error')
-          return false
-        }
-        this.$message.info('设置成功,请按【设置的快捷键】查看效果')
-      }).catch(err => {
-        console.log('err:', err)
-      })
-
-      this.form.validateFields((err, values) => {
-        if (!err) {
-          console.log('Received values of form: ', values)
-        }
-      })
-    }
-  }
-};
-</script>
-<style lang="less" scoped>
-#app-base-shortcut {
-  padding: 0px 10px;
-  text-align: left;
-  width: 100%;
-  .one-block-1 {
-    font-size: 16px;
-    padding-top: 10px;
-  }
-  .one-block-2 {
-    padding-top: 10px;
-  }
-}
-</style>

+ 9 - 10
frontend/src/views/base/software/Index.vue

@@ -22,12 +22,12 @@
   </div>
 </template>
 <script>
-import { requestEggApi } from '@/api/main'
+import { ipcApiRoute } from '@/api/main'
 
 const data = [
   {
     content: 'powershell.exe',
-    id: 'powershell'
+    id: 'powershell.exe'
   }
 ];
 
@@ -39,14 +39,13 @@ export default {
   },
   methods: {
     openSoft (id) {
-			requestEggApi('openSoftware', {id:id}).then(res => {
-				if (res.code !== 0) {
-					this.$message.info(res.msg)
-					return false
-				}
-			}).catch(err => {
-				console.log('err:', err)
-			})
+      const self = this;
+      this.$ipc.on(ipcApiRoute.openSoftware, (event, result) => {
+        if (!result) {
+          self.$message.error('程序不存在');
+        }
+      })
+      this.$ipc.send(ipcApiRoute.openSoftware, id);      
     },
   }
 };

+ 11 - 29
frontend/src/views/base/system/Index.vue

@@ -22,7 +22,7 @@
   </div>
 </template>
 <script>
-import { requestEggApi } from '@/api/main'
+import { ipcApiRoute } from '@/api/main'
 
 export default {
   data () {
@@ -31,41 +31,23 @@ export default {
     }
   },
   mounted () {
-    this.autoLaunchInit()
+    this.init();
   },
   methods: {
-    autoLaunchInit () {
-      requestEggApi('autoLaunchIsEnabled', {}).then(res => {
-        if (res.code !== 0) {
-          return false
-        }
-        this.autoLaunchChecked = res.data.isEnabled;
-      }).catch(err => {
-        console.log('err:', err)
+    init () {
+      const self = this;
+      this.$ipc.on(ipcApiRoute.autoLaunch, (event, result) => {
+        console.log('[ipcRenderer] [autoLaunch] result:', result)
+        self.autoLaunchChecked = result.status;
       })
+      this.$ipc.send(ipcApiRoute.autoLaunch, 'check');
     },
     autoLaunchChange (checkStatus) {
-      const params = {
-        'checkStatus': checkStatus
-      }
+      console.log('[ipcRenderer] [autoLaunch] checkStatus:', checkStatus)
       if (checkStatus) {
-        requestEggApi('autoLaunchEnable', params).then(res => {
-          if (res.code !== 0) {
-            return false
-          }
-          this.autoLaunchChecked = res.data.isEnabled;
-        }).catch(err => {
-          console.log('err:', err)
-        })
+        this.$ipc.send(ipcApiRoute.autoLaunch, 'close');
       } else {
-        requestEggApi('autoLaunchDisable', params).then(res => {
-          if (res.code !== 0) {
-            return false
-          }
-          this.autoLaunchChecked = res.data.isEnabled;
-        }).catch(err => {
-          console.log('err:', err)
-        })        
+        this.$ipc.send(ipcApiRoute.autoLaunch, 'open');       
       }
     },
   }