getCloudMsg.js 6.4 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3
import $state from '@/uni_modules/uni-im/sdk/state/index.js';
const uniImCo = uniCloud.importObject("uni-im-co", {
  customUI: false
4
})
DCloud_JSON's avatar
DCloud_JSON 已提交
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
const dbJQL = uniCloud.databaseForJQL();
// 获得云端数据,适用于:socket突然断开丢失,或者应用iOS切到后台拿不到透传等场景使用 获取丢失的数据
let getCloudMsgIng = false

function getCloudMsg({
  loadingTitle,
  callback
} = {
  "callback": () => {}
}) {
  console.log('开始 getCloudMsg');


  if ($state.isDisabled) {
    return console.log('$state isDisabled')
  }

  if (getCloudMsgIng) {
    callback()
    return // 防止重复发起,比如即被切换到后台,socket又断开的场景
  }

  getCloudMsgIng = true

  if (loadingTitle) {
    uni.showLoading({
      title: loadingTitle,
      mask: true
    });
  }

  // 下一次事件循环执行
  setTimeout(async () => {
    try {

      await getConversationList()
      async function getConversationList() {
        // 根据本地会话的最大更新时间,查询云端数据
        let maxConversation = ([...$state.conversation.dataList].sort((a, b) => b.update_time - a.update_time))[0]
44 45 46
        console.log('maxConversation:' + maxConversation)
        
        if (!maxConversation) {
DCloud_JSON's avatar
DCloud_JSON 已提交
47 48
          getCloudMsgIng = false
          return
49 50 51
        }
        let minUpdateTime = maxConversation.update_time
        
DCloud_JSON's avatar
DCloud_JSON 已提交
52 53 54 55 56 57 58 59 60 61
         
        console.log('minUpdateTime', minUpdateTime);
        let {data:conversationDatas} = await uniImCo.getConversationList({
          minUpdateTime,
          limit: 30
        })

        conversationDatas.forEach(newConversationInfo => {
          // console.error('newConversationInfo',newConversationInfo)
          // 判断是否已经存在
62
          let conversation = $state.conversation.getCached(newConversationInfo.id)
DCloud_JSON's avatar
DCloud_JSON 已提交
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
          if (conversation) {
            // 更新本地会话数据
            Object.assign(conversation, newConversationInfo)
          } else {
            // 不存在则插入
            [conversation] = $state.conversation.add(newConversationInfo)
          }
          // 如果当前会话已经被打开则需要设置未读消息数为0
          if ($state.currentConversationId === conversation.id) {
            conversation.unread_count = 0
          }
        })

        for (let i = 0; i < conversationDatas.length; i++) {
          console.log('需要查询的msg有:'+conversationDatas.length,i)
          // 判断是否已经存在
          const conversation = conversationDatas[i]
          // 查询云端消息数据
          await getConversationMsgs({conversation,minUpdateTime})
        }

        // await getMsgList({minUpdateTime,conversation_ids: conversationDatas.map(item => item.id)})

        if (conversationDatas.length === 30) {
          console.error("可能存在下一页数据");
          return await getConversationList()
89
        }
DCloud_JSON's avatar
DCloud_JSON 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        console.error(`更新会话:${conversationDatas.length}`)
      }
      getCloudMsgIng = false
      callback()
      console.log('离线数据同步完毕')
      if (loadingTitle) {
        uni.hideLoading()
      }
    } catch (e) {
      console.error('getCloudMsg error', e);
      getCloudMsgIng = false
    }
  }, 0);
}

export default getCloudMsg

107 108 109
async function seaveMsgs(msgs) {
  if (msgs.length === 0) {
    return
DCloud_JSON's avatar
DCloud_JSON 已提交
110
  }
111
  const conversation = $state.conversation.getCached(msgs[0].conversation_id)
DCloud_JSON's avatar
DCloud_JSON 已提交
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
  msgs.sort((a, b) => a.update_time - b.update_time)
  msgs.forEach(async msg => {
    // 判断是否出现重复          
    let [localHasThisMsg] = await conversation.msgManager.localMsg.get({
      _id: msg._id
    })
    if (localHasThisMsg) {
      // console.log('出现重复', localHasThisMsg);
      // 更新本地的这条消息内容
      const unique_id = localHasThisMsg.unique_id
      msg.unique_id = unique_id
      await conversation.msgManager.localMsg.update(unique_id, msg)
      // 如果内存中存在也更新(这种情况,会话确定已经初始化(打开)过)
      let memoryMsg = conversation.msgList.find(item => item._id === msg._id)
      if (memoryMsg) {
        // console.log('出现重复', memoryMsg);
        Object.assign(memoryMsg, msg)
      }
    } else {
      // 本地库插入新消息
      conversation.msgManager.localMsg.add(msg)
      // console.log('本地库插入新消息', msg);
      // 初始化(打开)过的会话,需要更新内存
      if (conversation.isInit) {
        conversation.msgList.push(msg)
      }
    }
  })
140 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
}

async function getConversationMsgs({
  limit = 100,
  conversation,
  minUpdateTime = 0
}){
  // console.error('getConversationMsgs minUpdateTime',minUpdateTime);
  // 按会话查
  const conversation_id = conversation.id
  let res = await dbJQL.collection('uni-im-msg').where({
      conversation_id,
      "update_time": dbJQL.command.gt(minUpdateTime),
    })
    .orderBy('update_time', 'asc')
    .limit(limit)
    .get()
  console.log('查询到新msg数据', res,res.data.length);
  seaveMsgs(res.data)
  // 递推查询
  if (res.data.length === limit) {
    arguments[0].minUpdateTime = res.data[limit - 1].update_time
    await getConversationMsgs(arguments[0])
  }
}

// async function getMsgList({
//   minUpdateTime = 0,
//   conversation_ids
DCloud_JSON's avatar
DCloud_JSON 已提交
169 170
// }) {
//   const limit = 1000
171
//   console.log('minUpdateTime', minUpdateTime);
DCloud_JSON's avatar
DCloud_JSON 已提交
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
//   console.log('conversation_ids', conversation_ids);
//   let res = await uniImCo.getMsgList({
//     conversation_ids,
//     minUpdateTime,
//     limit
//   })

//   console.error('查询到新消息数据', res.data.length);
//   // 按会话id分组
//   let conversationMsgs = {}
//   res.data.forEach(msg => {
//     if (!conversationMsgs[msg.conversation_id]) {
//       conversationMsgs[msg.conversation_id] = []
//     }
//     conversationMsgs[msg.conversation_id].push(msg)
//   })
//   // console.log('conversationMsgs', conversationMsgs);
//   // 逐个会话处理
//   for (let conversation_id in conversationMsgs) {
//     let msgs = conversationMsgs[conversation_id]
//     // console.log('msgs', msgs);
//     seaveMsgs(msgs)
//   }

//   if (res.data.length === limit) {
197
//     minUpdateTime = res.data[limit - 1].update_time
DCloud_JSON's avatar
DCloud_JSON 已提交
198 199 200 201 202 203 204
//     let res2 = await getMsgList(arguments[0])
//     res.data = res.data.concat(res2.data)
//     return res
//   } else {
//     return res
//   }
// }