chatStore.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import {
  2. MESSAGE_TYPE,
  3. MESSAGE_STATUS
  4. } from '@/common/enums.js';
  5. import userStore from './userStore';
  6. /*
  7. uniapp性能优化:
  8. 1.由于uniapp渲染消息性能非常拉胯,所以先把离线消息存储到cacheChats,等
  9. 待所有离线消息拉取完成后,再统一进行渲染
  10. 2.在vuex中对数组进行unshift,splice特别卡,所以删除会话、会话置顶、删
  11. 除消息等操作进行优化,不通过unshift,splice实现,改造方案如下:
  12. 删除会话: 通过delete标志判断是否删除
  13. 删除消息:通过delete标志判断是否删除
  14. 会话置顶:通过lastSendTime排序确定会话顺序
  15. */
  16. let cacheChats = [];
  17. export default {
  18. state: {
  19. chats: [],
  20. privateMsgMaxId: 0,
  21. groupMsgMaxId: 0,
  22. loadingPrivateMsg: false,
  23. loadingGroupMsg: false,
  24. },
  25. mutations: {
  26. initChats(state, chatsData) {
  27. cacheChats = [];
  28. state.chats = [];
  29. for (let chat of chatsData.chats) {
  30. // 已删除的会话直接丢弃
  31. if (chat.delete) {
  32. continue;
  33. }
  34. // 暂存至缓冲区
  35. cacheChats.push(JSON.parse(JSON.stringify(chat)));
  36. // 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间
  37. if (state.chats.length < 15) {
  38. chat.messages = [];
  39. state.chats.push(chat);
  40. }
  41. }
  42. state.privateMsgMaxId = chatsData.privateMsgMaxId || 0;
  43. state.groupMsgMaxId = chatsData.groupMsgMaxId || 0;
  44. // 防止图片一直处在加载中状态
  45. cacheChats.forEach((chat) => {
  46. chat.messages.forEach((msg) => {
  47. if (msg.loadStatus == "loading") {
  48. msg.loadStatus = "fail"
  49. }
  50. })
  51. })
  52. console.log(cacheChats.length)
  53. },
  54. openChat(state, chatInfo) {
  55. let chats = this.getters.findChats();
  56. let chat = null;
  57. for (let idx in chats) {
  58. if (chats[idx].type == chatInfo.type &&
  59. chats[idx].targetId === chatInfo.targetId) {
  60. chat = chats[idx];
  61. chat.delete = false;
  62. // 放置头部
  63. this.commit("moveTop", idx)
  64. break;
  65. }
  66. }
  67. // 创建会话
  68. if (chat == null) {
  69. chat = {
  70. targetId: chatInfo.targetId,
  71. type: chatInfo.type,
  72. showName: chatInfo.showName,
  73. headImage: chatInfo.headImage,
  74. lastContent: "",
  75. lastSendTime: new Date().getTime(),
  76. unreadCount: 0,
  77. messages: [],
  78. atMe: false,
  79. atAll: false,
  80. delete: false
  81. };
  82. chats.push(chat);
  83. this.commit("moveTop", chats.length - 1)
  84. }
  85. },
  86. activeChat(state, idx) {
  87. let chats = this.getters.findChats();
  88. if (idx >= 0) {
  89. chats[idx].unreadCount = 0;
  90. }
  91. },
  92. resetUnreadCount(state, chatInfo) {
  93. let chats = this.getters.findChats();
  94. for (let idx in chats) {
  95. if (chats[idx].type == chatInfo.type &&
  96. chats[idx].targetId == chatInfo.targetId) {
  97. chats[idx].unreadCount = 0;
  98. chats[idx].atMe = false;
  99. chats[idx].atAll = false;
  100. }
  101. }
  102. this.commit("saveToStorage");
  103. },
  104. readedMessage(state, pos) {
  105. let chats = this.getters.findChats();
  106. for (let idx in chats) {
  107. if (chats[idx].type == 'PRIVATE' &&
  108. chats[idx].targetId == pos.friendId) {
  109. chats[idx].messages.forEach((m) => {
  110. if (m.selfSend && m.status != MESSAGE_STATUS.RECALL) {
  111. // pos.maxId为空表示整个会话已读
  112. if (!pos.maxId || m.id <= pos.maxId) {
  113. m.status = MESSAGE_STATUS.READED
  114. }
  115. }
  116. })
  117. }
  118. }
  119. this.commit("saveToStorage");
  120. },
  121. removeChat(state, idx) {
  122. let chats = this.getters.findChats();
  123. chats[idx].delete = true;
  124. this.commit("saveToStorage");
  125. },
  126. removePrivateChat(state, userId) {
  127. let chats = this.getters.findChats();
  128. for (let idx in chats) {
  129. if (chats[idx].type == 'PRIVATE' &&
  130. chats[idx].targetId == userId) {
  131. this.commit("removeChat", idx);
  132. }
  133. }
  134. },
  135. moveTop(state, idx) {
  136. let chats = this.getters.findChats();
  137. let chat = chats[idx];
  138. // 最新的时间会显示在顶部
  139. chat.lastSendTime = new Date().getTime();
  140. this.commit("saveToStorage");
  141. },
  142. insertMessage(state, msgInfo) {
  143. // 获取对方id或群id
  144. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  145. // 记录消息的最大id
  146. if (msgInfo.id && type == "PRIVATE" && msgInfo.id > state.privateMsgMaxId) {
  147. state.privateMsgMaxId = msgInfo.id;
  148. }
  149. if (msgInfo.id && type == "GROUP" && msgInfo.id > state.groupMsgMaxId) {
  150. state.groupMsgMaxId = msgInfo.id;
  151. }
  152. // 如果是已存在消息,则覆盖旧的消息数据
  153. let chat = this.getters.findChat(msgInfo);
  154. let message = this.getters.findMessage(chat, msgInfo);
  155. if (message) {
  156. Object.assign(message, msgInfo);
  157. // 撤回消息需要显示
  158. if (msgInfo.type == MESSAGE_TYPE.RECALL) {
  159. chat.lastContent = msgInfo.content;
  160. }
  161. this.commit("saveToStorage");
  162. return;
  163. }
  164. // 会话列表内容
  165. if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
  166. chat.lastContent = "[图片]";
  167. } else if (msgInfo.type == MESSAGE_TYPE.FILE) {
  168. chat.lastContent = "[文件]";
  169. } else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
  170. chat.lastContent = "[语音]";
  171. } else if (msgInfo.type == MESSAGE_TYPE.TEXT || msgInfo.type == MESSAGE_TYPE.RECALL) {
  172. chat.lastContent = msgInfo.content;
  173. } else if (msgInfo.type == MESSAGE_TYPE.RT_VOICE) {
  174. chat.lastContent = "[语音通话]";
  175. } else if (msgInfo.type == MESSAGE_TYPE.RT_VIDEO) {
  176. chat.lastContent = "[视频通话]";
  177. }
  178. chat.lastSendTime = msgInfo.sendTime;
  179. chat.sendNickName = msgInfo.sendNickName;
  180. // 未读加1
  181. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED &&
  182. msgInfo.type != MESSAGE_TYPE.TIP_TEXT) {
  183. chat.unreadCount++;
  184. }
  185. // 是否有人@我
  186. if (!msgInfo.selfSend && chat.type == "GROUP" && msgInfo.atUserIds &&
  187. msgInfo.status != MESSAGE_STATUS.READED) {
  188. let userId = userStore.state.userInfo.id;
  189. if (msgInfo.atUserIds.indexOf(userId) >= 0) {
  190. chat.atMe = true;
  191. }
  192. if (msgInfo.atUserIds.indexOf(-1) >= 0) {
  193. chat.atAll = true;
  194. }
  195. }
  196. // 间隔大于10分钟插入时间显示
  197. if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
  198. chat.messages.push({
  199. sendTime: msgInfo.sendTime,
  200. type: MESSAGE_TYPE.TIP_TIME,
  201. });
  202. chat.lastTimeTip = msgInfo.sendTime;
  203. }
  204. // 根据id顺序插入,防止消息乱序
  205. let insertPos = chat.messages.length;
  206. // 防止 图片、文件 在发送方 显示 在顶端 因为还没存库,id=0
  207. if (msgInfo.id && msgInfo.id > 0) {
  208. for (let idx in chat.messages) {
  209. if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
  210. insertPos = idx;
  211. console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`);
  212. break;
  213. }
  214. }
  215. }
  216. if (insertPos == chat.messages.length) {
  217. // 这种赋值效率最高
  218. chat.messages[insertPos] = msgInfo;
  219. } else {
  220. chat.messages.splice(insertPos, 0, msgInfo);
  221. }
  222. this.commit("saveToStorage");
  223. },
  224. updateMessage(state, msgInfo) {
  225. // 获取对方id或群id
  226. let chat = this.getters.findChat(msgInfo);
  227. let message = this.getters.findMessage(chat, msgInfo);
  228. if (message) {
  229. // 属性拷贝
  230. Object.assign(message, msgInfo);
  231. this.commit("saveToStorage");
  232. }
  233. },
  234. deleteMessage(state, msgInfo) {
  235. // 获取对方id或群id
  236. let chat = this.getters.findChat(msgInfo);
  237. for (let idx in chat.messages) {
  238. // 已经发送成功的,根据id删除
  239. if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
  240. chat.messages[idx].delete = true;
  241. break;
  242. }
  243. // 正在发送中的消息可能没有id,根据发送时间删除
  244. if (msgInfo.selfSend && chat.messages[idx].selfSend &&
  245. chat.messages[idx].sendTime == msgInfo.sendTime) {
  246. chat.messages[idx].delete = true;
  247. break;
  248. }
  249. }
  250. this.commit("saveToStorage");
  251. },
  252. updateChatFromFriend(state, friend) {
  253. let chats = this.getters.findChats();
  254. for (let i in chats) {
  255. let chat = chats[i];
  256. if (chat.type == 'PRIVATE' && chat.targetId == friend.id) {
  257. chat.headImage = friend.headImageThumb;
  258. chat.showName = friend.nickName;
  259. break;
  260. }
  261. }
  262. this.commit("saveToStorage");
  263. },
  264. updateChatFromGroup(state, group) {
  265. let chats = this.getters.findChats();
  266. for (let i in chats) {
  267. let chat = chats[i];
  268. if (chat.type == 'GROUP' && chat.targetId == group.id) {
  269. chat.headImage = group.headImageThumb;
  270. chat.showName = group.remark;
  271. break;
  272. }
  273. }
  274. this.commit("saveToStorage");
  275. },
  276. loadingPrivateMsg(state, loadding) {
  277. state.loadingPrivateMsg = loadding;
  278. if (!this.getters.isLoading()) {
  279. this.commit("refreshChats")
  280. }
  281. },
  282. loadingGroupMsg(state, loadding) {
  283. state.loadingGroupMsg = loadding;
  284. if (!this.getters.isLoading()) {
  285. this.commit("refreshChats")
  286. }
  287. },
  288. refreshChats(state) {
  289. // 排序
  290. cacheChats.sort((chat1, chat2) => {
  291. return chat2.lastSendTime - chat1.lastSendTime;
  292. });
  293. // 将消息一次性装载回来
  294. state.chats = cacheChats;
  295. console.log(cacheChats.length)
  296. this.commit("saveToStorage");
  297. },
  298. saveToStorage(state) {
  299. // 加载中不保存,防止卡顿
  300. if (this.getters.isLoading()) {
  301. return;
  302. }
  303. let userId = userStore.state.userInfo.id;
  304. let key = "chats-app-" + userId;
  305. let chatsData = {
  306. privateMsgMaxId: state.privateMsgMaxId,
  307. groupMsgMaxId: state.groupMsgMaxId,
  308. chats: state.chats
  309. }
  310. uni.setStorage({
  311. key: key,
  312. data: chatsData ,
  313. })
  314. },
  315. clear(state) {
  316. cacheChats = [];
  317. state.chats = [];
  318. state.privateMsgMaxId = 0;
  319. state.groupMsgMaxId = 0;
  320. state.loadingPrivateMsg = false;
  321. state.loadingGroupMsg = false;
  322. }
  323. },
  324. actions: {
  325. loadChat(context) {
  326. return new Promise((resolve, reject) => {
  327. let userId = userStore.state.userInfo.id;
  328. uni.getStorage({
  329. key: "chats-app-" + userId,
  330. success(res) {
  331. context.commit("initChats", res.data);
  332. resolve()
  333. },
  334. fail(e) {
  335. resolve()
  336. }
  337. });
  338. })
  339. }
  340. },
  341. getters: {
  342. isLoading: (state) => () => {
  343. return state.loadingPrivateMsg || state.loadingGroupMsg
  344. },
  345. findChats: (state, getters) => () => {
  346. return getters.isLoading() ? cacheChats : state.chats;
  347. },
  348. findChatIdx: (state, getters) => (chat) => {
  349. let chats = getters.findChats();
  350. for (let idx in chats) {
  351. if (chats[idx].type == chat.type &&
  352. chats[idx].targetId === chat.targetId) {
  353. chat = state.chats[idx];
  354. return idx;
  355. }
  356. }
  357. },
  358. findChat: (state, getters) => (msgInfo) => {
  359. let chats = getters.findChats();
  360. // 获取对方id或群id
  361. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  362. let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
  363. let chat = null;
  364. for (let idx in chats) {
  365. if (chats[idx].type == type &&
  366. chats[idx].targetId === targetId) {
  367. chat = chats[idx];
  368. break;
  369. }
  370. }
  371. return chat;
  372. },
  373. findMessage: (state) => (chat, msgInfo) => {
  374. if (!chat) {
  375. return null;
  376. }
  377. for (let idx in chat.messages) {
  378. // 通过id判断
  379. if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
  380. return chat.messages[idx];
  381. }
  382. // 正在发送中的消息可能没有id,通过发送时间判断
  383. if (msgInfo.selfSend && chat.messages[idx].selfSend &&
  384. chat.messages[idx].sendTime == msgInfo.sendTime) {
  385. return chat.messages[idx];
  386. }
  387. }
  388. }
  389. }
  390. }