Jelajahi Sumber

3.0.90 消息推送(第一版)

liuyanpeng 2 tahun lalu
induk
melakukan
09e0a50515
4 mengubah file dengan 328 tambahan dan 2 penghapusan
  1. 1 1
      package.json
  2. 1 0
      src/client/Login.vue
  3. 324 0
      src/common/pushMessage.js
  4. 2 1
      src/index.js

+ 1 - 1
package.json

@@ -1,7 +1,7 @@
 {
   "name": "client-base-v4",
   "description": "Leanwo Prodog Client",
-  "version": "3.0.88",
+  "version": "3.0.90",
   "author": "yangzhijie1488 <yangzhijie1488@163.com>",
   "scripts": {
     "dev": "cross-env webpack serve --config ./webpack.dev.js",

+ 1 - 0
src/client/Login.vue

@@ -387,6 +387,7 @@ export default {
             LoginService.setLoginInfo(loginInfo.data, _self.$router);
             LoginService.saveLocalStorage(_self);
             _self.setTokenClient();
+            localStorage.setItem('allowSound',false);
           } else {
             Notify.error(
               _self.$t('lang.login.loginFailure'),

+ 324 - 0
src/common/pushMessage.js

@@ -0,0 +1,324 @@
+import Common from './Common.js';
+import { h } from 'vue';
+import { Notify } from 'pc-component-v3';
+import TaskOpenUtil from '../workflow/TaskOpenUtil';
+import { Modal, notification } from 'ant-design-vue';
+import { MessageTwoTone } from '@ant-design/icons-vue';
+import WindowService from './WindowService.js';
+
+export default {
+
+  flag: false,
+  timer: null,
+  source: null,
+  isSound: false,
+  openDate: null,
+  allMessage: [],
+  webSocket: null,
+  messageDate: null,
+  notificationId: null,
+
+
+  // 触发通知
+  triggerNotification: function () {
+    const _self = this;
+    let token = localStorage.getItem('#token');
+    if (!token) {
+      _self.timer = null;
+      _self.allMessage.splice(0, _self.allMessage.length);
+      notification.close(_self.notificationId);
+      return;
+    }
+    _self.timer = setInterval(function () {
+      let allowSound = localStorage.getItem('allowSound');
+      if (_self.allMessage.length > 0) {
+        let index = Math.floor(Math.random() * _self.allMessage.length);
+        let item = _self.allMessage[index];
+        notification.close(_self.notificationId);
+        _self.openNotification(item);
+        _self.isShowNotification(item);
+        if (!window.opener && window.opener !== window && allowSound == 'true') {
+          _self.playSound(true);
+        }
+        _self.allMessage.splice(index, 1);
+      } else {
+        clearInterval(_self.timer);
+        _self.timer = null;
+      }
+    }, 5000);
+  },
+  // 播放声音
+  playSound: async function (isPlay) {
+    const _self = this;
+    if (_self.flag && isPlay) {
+      return;
+    }
+    let ctx = new (window.AudioContext || window.webkitAudioContext)();
+    const audioUrl = '/static/assets/client-base-v4/sound/sound.mp3';
+    const res = await fetch(audioUrl);
+    const arrayBuffer = await res.arrayBuffer();
+    ctx.decodeAudioData(
+      arrayBuffer,
+      function (buffer) {
+        //处理成功返回的数据类型为AudioBuffer
+        //创建AudioBufferSourceNode对象
+        _self.source = ctx.createBufferSource();
+        _self.source.buffer = buffer;
+        _self.source.connect(ctx.destination);
+        _self.source.currentTime = 0;
+        if (isPlay) {
+          _self.source.start(0);
+          setTimeout(() => {
+            _self.source.stop();
+            _self.flag = false;
+          }, 5000);
+          _self.flag = true;
+        }
+      },
+      function (e) {
+        console.info('处理出错');
+      },
+    );
+  },
+
+  // 检验是否支持系统提示
+  isShowNotification: function (message) {
+    const _self = this;
+    // 检查浏览器是否支持 Notification API
+    if (!('Notification' in window)) {
+      alert('此浏览器不支持桌面通知');
+      return;
+    }
+    // 检查用户是否已经允许显示通知
+    if (Notification.permission === 'granted') {
+      // 如果已经允许,直接显示通知
+      _self.showNotification(message);
+    } else if (Notification.permission !== 'denied') {
+      // 否则,请求用户允许显示通知
+      Notification.requestPermission().then(permission => {
+        // 如果用户允许,显示通知
+        if (permission === 'granted') {
+          _self.showNotification(message);
+        }
+      });
+    }
+  },
+
+  // 进行系统提示
+  showNotification: function (message) {
+    // 创建一个新的 Notification 对象
+    if (message.type == 'NEW_TASK') {
+      const notification = new Notification('待处理消息', {
+        body: message.content.title,
+      });
+      // 监听通知的点击事件
+      notification.onclick = () => {
+        TaskOpenUtil.openTask(message.content).then(
+          successData => {
+            if (successData.type === 'newWindow') {
+              WindowService.open(successData.url, '待处理');
+            }
+          },
+          errorData => {
+            if (errorData != null) {
+              Notify.error(errorData.title, errorData.message, false);
+            }
+          },
+        );
+      };
+    } else if (message.type == 'NEW_UserReadDocument') {
+      const notification = new Notification('待审阅消息', {
+        body: message.content.title,
+      });
+      notification.onclick = () => {
+        TaskOpenUtil.openTask(message.content).then(
+          successData => {
+            if (successData.type === 'newWindow') {
+              WindowService.open(successData.url, '待处理');
+            }
+          },
+          errorData => {
+            if (errorData != null) {
+              Notify.error(errorData.title, errorData.message, false);
+            }
+          },
+        );
+      };
+    }
+  },
+
+  // 打开消息提示框
+  openNotification: function (messageData) {
+    const _self = this;
+    _self.notificationId = messageData.uuid;
+    if (messageData.type == 'NEW_TASK') {
+      notification.open({
+        key: messageData.uuid,
+        message: messageData.content.title,
+        description: messageData.content.description,
+        icon: () =>
+          h(MessageTwoTone, {
+            style: 'color: #108ee9',
+          }),
+        duration: 5,
+        style: {
+          marginTop: '30px',
+        },
+        onClick: () => {
+          notification.close(messageData.uuid);
+          _self.replyMessage(messageData.content.id);
+          TaskOpenUtil.openTask(messageData.content).then(
+            successData => {
+              if (successData.type === 'newWindow') {
+                WindowService.open(successData.url, '待处理');
+              }
+            },
+            errorData => {
+              if (errorData != null) {
+                Notify.error(errorData.title, errorData.message, false);
+              }
+            },
+          );
+        },
+      });
+    } else if (messageData.type == 'NEW_UserReadDocument') {
+      notification.open({
+        key: messageData.uuid,
+        message: messageData.content.title,
+        description: '您有一条待审阅消息',
+        icon: () =>
+          h(MessageTwoTone, {
+            style: 'color: #108ee9',
+          }),
+        duration: 5,
+        onClick: () => {
+          notification.close(messageData.uuid);
+          _self.replyDocument(messageData.content.id);
+          TaskOpenUtil.openCopyTask(messageData.content).then(
+            successData => {
+              if (successData.type === 'newWindow') {
+                WindowService.open(successData.url, '抄送我的', function () {
+                  console.log('打开审阅单');
+                });
+              }
+            },
+            errorData => {
+              if (errorData != null) {
+                Notify.error(errorData.title, errorData.message, false);
+              }
+            },
+          );
+        },
+      });
+    }
+  },
+
+
+  // 确认收到待处理消息
+  replyMessage: function (id) {
+    let requestUrl = 'UnPushTaskResource/Task?id=' + id;
+    $.ajax({
+      url: Common.getApiURL(requestUrl),
+      type: 'get',
+      dataType: 'json',
+      beforeSend: function (request) {
+        Common.addTokenToRequest(request);
+      },
+      success: function (data) {
+        // console.log(data, 'data---------');
+      },
+      error: function (XMLHttpRequest, textStatus, errorThrown) {
+        Common.processException(XMLHttpRequest, textStatus, errorThrown);
+      },
+    });
+  },
+  // 确认收到待审阅消息
+  replyDocument: function (id) {
+    let requestUrl = 'UnPushTaskResource/UserReadDocument?id=' + id;
+    $.ajax({
+      url: Common.getApiURL(requestUrl),
+      type: 'get',
+      dataType: 'json',
+      beforeSend: function (request) {
+        Common.addTokenToRequest(request);
+      },
+      success: function (data) {
+        // console.log(data, 'data---------');
+      },
+      error: function (XMLHttpRequest, textStatus, errorThrown) {
+        Common.processException(XMLHttpRequest, textStatus, errorThrown);
+      },
+    });
+  },
+  // 弹出打开声音提示框
+  messageModal: function () {
+    const _self = this;
+    Modal.warning({
+      okText: '我知道了',
+      title: '温馨提示',
+      content: '由于您的浏览器设置,音乐无法自动播放,请您确认。',
+      onOk() {
+        _self.playSound(false);
+        localStorage.setItem('allowSound', true);
+      },
+    });
+  },
+
+  // 打开websocket
+  openWebSocket: function () {
+    const _self = this;
+
+    // 如果websocket已连接就不在连接
+    if (_self.webSocket && _self.webSocket.readyState == 1) {
+      return;
+    }
+    let token = localStorage.getItem('#token');
+    let websocketUrl = Common.getHostPageBaseURL() + 'WebSocket/MessageQueue';
+    if (websocketUrl.indexOf('https') == 0) {
+      websocketUrl = websocketUrl.replace('https', 'wss').replace('/api', '');
+    } else if (websocketUrl.indexOf('http') == 0) {
+      websocketUrl = websocketUrl.replace('http', 'ws').replace('/api', '');
+    }
+    _self.webSocket = new WebSocket(websocketUrl, [token]);
+    _self.webSocket.onopen = function () {
+      _self.openDate = new Date().getTime();
+      console.log('websocket打开');
+    };
+    _self.webSocket.onmessage = function (message) {
+      _self.messageDate = new Date().getTime();
+      const difference = Math.abs(_self.messageDate - _self.openDate);
+      if (difference > 10000) {
+        // 刷新数量
+        console.log('刷新数量');
+      }
+      let taskData = JSON.parse(message.data);
+      console.log('websocket 收到信息 : ' + taskData);
+      if (taskData) {
+        _self.allMessage.push(taskData);
+      }
+      if (_self.timer == null) {
+        _self.triggerNotification();
+      }
+    };
+    _self.webSocket.onclose = function () {
+      console.log('websocket关闭');
+      _self.webSocket = null;
+    };
+    _self.webSocket.onerror = function (event) {
+      console.log('websocket异常');
+      _self.webSocket.close();
+    };
+
+  },
+  // 注销后关闭websocket和循环
+  closeWebsocket: function () {
+    const _self = this;
+    if (_self.webSocket && _self.timer) {
+      _self.timer = null;
+      _self.webSocket.close();
+      _self.webSocket = null;
+      _self.allMessage.splice(0, _self.allMessage.length);
+      notification.close(_self.notificationId);
+    }
+  },
+};

+ 2 - 1
src/index.js

@@ -9,6 +9,7 @@ import langZhCn from './locales/zh-CN.json';
 import langEnUs from './locales/en-US.json';
 
 import Common from './common/Common.js';
+import PushMessage from './common/pushMessage.js';
 
 import App from './App.vue';
 
@@ -80,7 +81,7 @@ export {
   langZhCn,
   langEnUs,
   Common,
-
+  PushMessage,
   Login,
   Desktop,
   LowcodePage,