msgEvent.js 6.6 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
import $utils from '@/uni_modules/uni-im/sdk/utils/index.js';
import $extensions from '@/uni_modules/uni-im/sdk/methods/extensions.js';
import $state from '../state/index.js';
// #ifdef H5
import EasyWebNotification from './EasyWebNotification';
const easyWebNotification = new EasyWebNotification();
// #endif
// nvue下页面之间数据是隔离的需要挂载到$state上
$state.ext.onMsgFnList = []
const msgEvent = {
  emitMsg(res) {
    if ($state.isDisabled) {
      return console.log('uniIm isDisabled')
    }
    if (res.data.payload.device_id == $state.systemInfo.deviceId) {
      return console.log('当前设备发的消息,不用接收;忽略');
    }
    $state.ext.onMsgFnList.forEach(fn => {
      fn(res)
    })
  },
  onMsg(res) {
    $state.ext.onMsgFnList.push(res)
  },
  offMsg(fn) {
    $state.ext.onMsgFnList = $state.ext.onMsgFnList.filter(item => item != fn)
  }
}

export default msgEvent;

// 默认注册了一个监听收到im消息后的事件
msgEvent.onMsg(async res=>{
    // console.log('收到im消息', res);
    const {
      payload
    } = res.data;
    const msg = payload.data
    // console.log({msg});
    // 超长文本传输时的id
    if (msg.LongMsg) {
      const db = uniCloud.database();
      let res = await db.collection('uni-im-msg')
        .where({
          "_id": msg._id,
          "conversation_id": msg.conversation_id // conversation_id 必传否则会被触发器拦截
        })
        .get()
      // console.log(res);
      if (res.result.errCode == 0) {
        payload.data.body = res.result.data[0].body
      } else {
        console.error('超长文本类型消息查库失败', msg._id);
      }
    }
    // console.log('payload------', payload.device_id, $state.systemInfo.deviceId);
    // console.log(777);
    const {
      conversation_id,
      group_id
    } = msg
    // console.log('msgmsgmsgmsgmsg.msg',msg);
    // 拿到收到消息的会话对象
    let conversation = await $state.conversation.get(conversation_id)
    
    // 处理其他设备已读某会话的情况
    if (msg.type == 'clear-conversation-unreadCount') {
      if (conversation.update_time < msg.create_time) {
        conversation.update_time = msg.create_time
        conversation.unread_count = 0
        // 同时去掉通知栏消息
        // #ifdef H5
        //关闭所有通知栏
        easyWebNotification.closeAllNotification()
        easyWebNotification.recoverTitle()
        // #endif
        
        // #ifdef APP
        //清理系统通知栏消息和app角标
        plus.push.clear()
        plus.runtime.setBadgeNumber(0)
        // #endif
        
      }
      // 阻止后续动作
      return
    }
    const isReadableMsg = $utils.isReadableMsg(msg)
    const isMuteMsg = $utils.isMuteMsg(msg)
    const canCreateNotification = isReadableMsg && 
                                  // 会话不是免打扰的
                                  !conversation.mute &&
                                  // 消息不是系统配置了免打扰的
                                  !isMuteMsg &&
                                  // 不是自己发的消息
                                  msg.from_uid != uniCloud.getCurrentUserInfo().uid
    // 判断并创建通知栏消息
    // #ifdef H5
    if (canCreateNotification) {
      if (!$state.ext.appIsActive) {
        easyWebNotification.create({
          "title": payload.title + "" + payload.content,
          "option": {
            conversation_id,
            "icon": payload.avatar_file ? payload.avatar_file.url :
              'https://web-assets.dcloud.net.cn/unidoc/zh/uni.png'
          }
        })
      }

      // 调用扩展程序告知有新消息到达
      $extensions.invokeExts('ui-new-message')
    }
    // #endif
    
    /**
     * 排除会话中已包含此消息的情况
     */
    let msgList = conversation.msgList
    if (!msgList.find(item => item._id == msg._id)) {
      msgList.push(msg)
      if (
        // 不是正在对话的会话,且不是自己发的消息,就给会话的未读消息数+1
        $state.currentConversationId != msg.conversation_id &&
        // 为可读消息
        isReadableMsg &&
        // 消息不是系统配置了免打扰的
        !isMuteMsg &&
        msg.from_uid != uniCloud.getCurrentUserInfo().uid
      ) {
        conversation.unread_count++
      }
    }
    // 如果socket已经关闭的情况下收到消息,说明消息来源浏览器页签之间通讯 不需要重复存库
    if (!$state.socketIsClose) {
      conversation.msgManager.localMsg.add(msg)
    }
    
    // #ifdef APP
140
    // console.log('notification type=>',res.type);
DCloud_JSON's avatar
DCloud_JSON 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    if (res.type == 'click'){
      let currentPages = getCurrentPages()
      let topViewRoute = currentPages[currentPages.length - 1].route
      // console.log('topViewRoute',topViewRoute);
      if (topViewRoute == 'uni_modules/uni-im/pages/chat/chat') {
        uni.redirectTo({
          url: '/uni_modules/uni-im/pages/chat/chat?conversation_id=' + msg.conversation_id,
          complete(e) {
            console.log(e);
          }
        })
      } else {
        uni.navigateTo({
          url: '/uni_modules/uni-im/pages/chat/chat?conversation_id=' + msg.conversation_id,
          complete(e) {
            console.log(e);
          }
        })
      }
    }else{
      let currentPages = getCurrentPages()
      let topViewRoute = currentPages[currentPages.length - 1].route
      // console.log('topViewRoute',topViewRoute);
      let pathList = [
        'uni_modules/uni-im/pages/chat/chat',
        'uni_modules/uni-im/pages/index/index',
        'uni_modules/uni-im/pages/userList/userList',
        'uni_modules/uni-im/pages/contacts/contacts'
      ]
      if (canCreateNotification && !$state.ext.appIsActive || !pathList.includes(topViewRoute)) {
        // console.log('payload',payload);
        let {
          content,
          data,
          title,
          avatar_file
        } = payload
        let url = avatar_file ? avatar_file.url : ''
        let icon = '_www/uni_modules/uni-im/static/avatarUrl.png'
        //安卓才有头像功能,再执行下载
        if ($state.systemInfo.platform == "android") {
          if (avatar_file) {
            let downloadFileRes = await uni.downloadFile({
              url: avatar_file.url
            });
            icon = downloadFileRes[1]?.tempFilePath
          }
        }
        plus.push.createMessage(content, payload, {
          title,
          icon
        })
      } else if (conversation_id != $state.currentConversationId) {
        // uni.showToast({
        // 	title: '收到新消息请注意查看',
        // 	icon: 'none'
        // });
      }
    }
    // #endif
})