chatStore.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import { defineStore } from 'pinia';
  2. import { MESSAGE_TYPE, MESSAGE_STATUS } from '@/common/enums.js';
  3. import useFriendStore from './friendStore.js';
  4. import useGroupStore from './groupStore.js';
  5. import useUserStore from './userStore';
  6. let cacheChats = [];
  7. export default defineStore('chatStore', {
  8. state: () => {
  9. return {
  10. chats: [],
  11. privateMsgMaxId: 0,
  12. groupMsgMaxId: 0,
  13. loadingPrivateMsg: false,
  14. loadingGroupMsg: false
  15. }
  16. },
  17. actions: {
  18. initChats(chatsData) {
  19. cacheChats = [];
  20. this.chats = [];
  21. for (let chat of chatsData.chats) {
  22. chat.stored = false;
  23. // 暂存至缓冲区
  24. cacheChats.push(JSON.parse(JSON.stringify(chat)));
  25. // 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间
  26. if (this.chats.length < 15) {
  27. this.chats.push(chat);
  28. }
  29. }
  30. this.privateMsgMaxId = chatsData.privateMsgMaxId || 0;
  31. this.groupMsgMaxId = chatsData.groupMsgMaxId || 0;
  32. },
  33. openChat(chatInfo) {
  34. let chats = this.curChats;
  35. let chat = null;
  36. for (let idx in chats) {
  37. if (chats[idx].type == chatInfo.type &&
  38. chats[idx].targetId === chatInfo.targetId) {
  39. chat = chats[idx];
  40. // 放置头部
  41. this.moveTop(idx)
  42. break;
  43. }
  44. }
  45. // 创建会话
  46. if (chat == null) {
  47. chat = {
  48. targetId: chatInfo.targetId,
  49. type: chatInfo.type,
  50. showName: chatInfo.showName,
  51. headImage: chatInfo.headImage,
  52. isDnd: chatInfo.isDnd,
  53. lastContent: "",
  54. lastSendTime: new Date().getTime(),
  55. unreadCount: 0,
  56. hotMinIdx: 0,
  57. readedMessageIdx: 0,
  58. messages: [],
  59. atMe: false,
  60. atAll: false,
  61. stored: false
  62. };
  63. chats.unshift(chat);
  64. this.saveToStorage();
  65. }
  66. },
  67. activeChat(idx) {
  68. let chats = this.curChats;
  69. if (idx >= 0) {
  70. chats[idx].unreadCount = 0;
  71. }
  72. },
  73. resetUnreadCount(chatInfo) {
  74. let chats = this.curChats;
  75. for (let idx in chats) {
  76. if (chats[idx].type == chatInfo.type &&
  77. chats[idx].targetId == chatInfo.targetId) {
  78. chats[idx].unreadCount = 0;
  79. chats[idx].atMe = false;
  80. chats[idx].atAll = false;
  81. chats[idx].stored = false;
  82. this.saveToStorage();
  83. }
  84. }
  85. },
  86. readedMessage(pos) {
  87. let chat = this.findChatByFriend(pos.friendId);
  88. if (!chat) return;
  89. for (let idx = chat.readedMessageIdx; idx < chat.messages.length; idx++) {
  90. let m = chat.messages[idx];
  91. if (m.id && m.selfSend && m.status < MESSAGE_STATUS.RECALL) {
  92. // pos.maxId为空表示整个会话已读
  93. if (!pos.maxId || m.id <= pos.maxId) {
  94. m.status = MESSAGE_STATUS.READED
  95. chat.readedMessageIdx = idx;
  96. chat.stored = false;
  97. }
  98. }
  99. }
  100. if (!chat.stored) {
  101. this.saveToStorage();
  102. }
  103. },
  104. cleanMessage(idx) {
  105. let chat = this.curChats[idx];
  106. chat.lastContent = '';
  107. chat.hotMinIdx = 0;
  108. chat.unreadCount = 0;
  109. chat.atMe = false;
  110. chat.atAll = false;
  111. chat.stored = false
  112. chat.messages = [];
  113. this.saveToStorage(true);
  114. },
  115. removeChat(idx) {
  116. let chats = this.curChats;
  117. chats[idx].delete = true;
  118. chats[idx].stored = false;
  119. this.saveToStorage();
  120. },
  121. removePrivateChat(userId) {
  122. let chats = this.curChats;
  123. for (let idx in chats) {
  124. if (chats[idx].type == 'PRIVATE' &&
  125. chats[idx].targetId == userId) {
  126. this.removeChat(idx);
  127. }
  128. }
  129. },
  130. removeGroupChat(groupId) {
  131. let chats = this.curChats;
  132. for (let idx in chats) {
  133. if (chats[idx].type == 'GROUP' &&
  134. chats[idx].targetId == groupId) {
  135. this.removeChat(idx);
  136. }
  137. }
  138. },
  139. moveTop(idx) {
  140. if (this.isLoading()) {
  141. return;
  142. }
  143. let chats = this.curChats;
  144. if (idx > 0) {
  145. let chat = chats[idx];
  146. chats.splice(idx, 1);
  147. chats.unshift(chat);
  148. chat.lastSendTime = new Date().getTime();
  149. chat.stored = false;
  150. this.saveToStorage();
  151. }
  152. },
  153. insertMessage(msgInfo, chatInfo) {
  154. // 获取对方id或群id
  155. let type = chatInfo.type;
  156. // 记录消息的最大id
  157. if (msgInfo.id && type == "PRIVATE" && msgInfo.id > this.privateMsgMaxId) {
  158. this.privateMsgMaxId = msgInfo.id;
  159. }
  160. if (msgInfo.id && type == "GROUP" && msgInfo.id > this.groupMsgMaxId) {
  161. this.groupMsgMaxId = msgInfo.id;
  162. }
  163. // 如果是已存在消息,则覆盖旧的消息数据
  164. let chat = this.findChat(chatInfo);
  165. let message = this.findMessage(chat, msgInfo);
  166. if (message) {
  167. Object.assign(message, msgInfo);
  168. chat.stored = false;
  169. this.saveToStorage();
  170. return;
  171. }
  172. // 会话列表内容
  173. if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
  174. chat.lastContent = "[图片]";
  175. } else if (msgInfo.type == MESSAGE_TYPE.FILE) {
  176. chat.lastContent = "[文件]";
  177. } else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
  178. chat.lastContent = "[语音]";
  179. } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VOICE) {
  180. chat.lastContent = "[语音通话]";
  181. } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VIDEO) {
  182. chat.lastContent = "[视频通话]";
  183. } else if (msgInfo.type == MESSAGE_TYPE.TEXT ||
  184. msgInfo.type == MESSAGE_TYPE.RECALL ||
  185. msgInfo.type == MESSAGE_TYPE.TIP_TEXT) {
  186. chat.lastContent = msgInfo.content;
  187. }
  188. chat.lastSendTime = msgInfo.sendTime;
  189. chat.sendNickName = msgInfo.sendNickName;
  190. // 未读加1
  191. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED &&
  192. msgInfo.status != MESSAGE_STATUS.RECALL && msgInfo.type != MESSAGE_TYPE.TIP_TEXT) {
  193. chat.unreadCount++;
  194. }
  195. // 是否有人@我
  196. if (!msgInfo.selfSend && chat.type == "GROUP" && msgInfo.atUserIds &&
  197. msgInfo.status != MESSAGE_STATUS.READED) {
  198. const userStore = useUserStore();
  199. let userId = userStore.userInfo.id;
  200. if (msgInfo.atUserIds.indexOf(userId) >= 0) {
  201. chat.atMe = true;
  202. }
  203. if (msgInfo.atUserIds.indexOf(-1) >= 0) {
  204. chat.atAll = true;
  205. }
  206. }
  207. // 间隔大于10分钟插入时间显示
  208. if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
  209. chat.messages.push({
  210. sendTime: msgInfo.sendTime,
  211. type: MESSAGE_TYPE.TIP_TIME,
  212. });
  213. chat.lastTimeTip = msgInfo.sendTime;
  214. }
  215. // 根据id顺序插入,防止消息乱序
  216. let insertPos = chat.messages.length;
  217. // 防止 图片、文件 在发送方 显示 在顶端 因为还没存库,id=0
  218. if (msgInfo.id && msgInfo.id > 0) {
  219. for (let idx in chat.messages) {
  220. if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
  221. insertPos = idx;
  222. console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`);
  223. break;
  224. }
  225. }
  226. }
  227. if (insertPos == chat.messages.length) {
  228. // 这种赋值效率最高
  229. chat.messages[insertPos] = msgInfo;
  230. } else {
  231. chat.messages.splice(insertPos, 0, msgInfo);
  232. }
  233. chat.stored = false;
  234. this.saveToStorage();
  235. },
  236. updateMessage(msgInfo, chatInfo) {
  237. // 获取对方id或群id
  238. let chat = this.findChat(chatInfo);
  239. let message = this.findMessage(chat, msgInfo);
  240. if (message) {
  241. // 属性拷贝
  242. Object.assign(message, msgInfo);
  243. chat.stored = false;
  244. this.saveToStorage();
  245. }
  246. },
  247. deleteMessage(msgInfo, chatInfo) {
  248. // 获取对方id或群id
  249. let chat = this.findChat(chatInfo);
  250. let isColdMessage = false;
  251. for (let idx in chat.messages) {
  252. // 已经发送成功的,根据id删除
  253. if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
  254. chat.messages.splice(idx, 1);
  255. isColdMessage = idx < chat.hotMinIdx;
  256. break;
  257. }
  258. // 正在发送中的消息可能没有id,只有临时id
  259. if (chat.messages[idx].tmpId && chat.messages[idx].tmpId == msgInfo.tmpId) {
  260. chat.messages.splice(idx, 1);
  261. isColdMessage = idx < chat.hotMinIdx;
  262. break;
  263. }
  264. }
  265. chat.stored = false;
  266. this.saveToStorage(isColdMessage);
  267. },
  268. recallMessage(msgInfo, chatInfo) {
  269. let chat = this.findChat(chatInfo);
  270. if (!chat) return;
  271. let isColdMessage = false;
  272. // 要撤回的消息id
  273. let id = msgInfo.content;
  274. let name = msgInfo.selfSend ? '你' : chat.type == 'PRIVATE' ? '对方' : msgInfo.sendNickName;
  275. for (let idx in chat.messages) {
  276. let m = chat.messages[idx];
  277. if (m.id && m.id == id) {
  278. // 改造成一条提示消息
  279. m.status = MESSAGE_STATUS.RECALL;
  280. m.content = name + "撤回了一条消息";
  281. m.type = MESSAGE_TYPE.TIP_TEXT
  282. // 会话列表
  283. chat.lastContent = m.content;
  284. chat.lastSendTime = msgInfo.sendTime;
  285. chat.sendNickName = '';
  286. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED) {
  287. chat.unreadCount++;
  288. }
  289. isColdMessage = idx < chat.hotMinIdx;
  290. }
  291. // 被引用的消息也要撤回
  292. if (m.quoteMessage && m.quoteMessage.id == msgInfo.id) {
  293. m.quoteMessage.content = "引用内容已撤回";
  294. m.quoteMessage.status = MESSAGE_STATUS.RECALL;
  295. m.quoteMessage.type = MESSAGE_TYPE.TIP_TEXT
  296. }
  297. }
  298. chat.stored = false;
  299. this.saveToStorage(isColdMessage);
  300. },
  301. updateChatFromFriend(friend) {
  302. let chat = this.findChatByFriend(friend.id)
  303. if (chat && (chat.headImage != friend.headImage ||
  304. chat.showName != friend.nickName)) {
  305. // 更新会话中的群名和头像
  306. chat.headImage = friend.headImage;
  307. chat.showName = friend.nickName;
  308. chat.stored = false;
  309. this.saveToStorage();
  310. }
  311. },
  312. updateChatFromUser(user) {
  313. let chat = this.findChatByFriend(user.id);
  314. // 更新会话中的昵称和头像
  315. if (chat && (chat.headImage != user.headImageThumb ||
  316. chat.showName != user.nickName)) {
  317. chat.headImage = user.headImageThumb;
  318. chat.showName = user.nickName;
  319. chat.stored = false;
  320. this.saveToStorage();
  321. }
  322. },
  323. updateChatFromGroup(group) {
  324. let chat = this.findChatByGroup(group.id);
  325. if (chat && (chat.headImage != group.headImageThumb ||
  326. chat.showName != group.showGroupName)) {
  327. // 更新会话中的群名称和头像
  328. chat.headImage = group.headImageThumb;
  329. chat.showName = group.showGroupName;
  330. chat.stored = false;
  331. this.saveToStorage();
  332. }
  333. },
  334. setLoadingPrivateMsg(loading) {
  335. this.loadingPrivateMsg = loading;
  336. if (!this.isLoading()) {
  337. this.refreshChats()
  338. }
  339. },
  340. setLoadingGroupMsg(loading) {
  341. this.loadingGroupMsg = loading;
  342. if (!this.isLoading()) {
  343. this.refreshChats()
  344. }
  345. },
  346. setDnd(chatInfo, isDnd) {
  347. let chat = this.findChat(chatInfo);
  348. if (chat) {
  349. chat.isDnd = isDnd;
  350. }
  351. },
  352. refreshChats() {
  353. if (!cacheChats) return;
  354. // 更新会话免打扰状态
  355. const friendStore = useFriendStore();
  356. const groupStore = useGroupStore();
  357. cacheChats.forEach(chat => {
  358. if (chat.type == 'PRIVATE') {
  359. let friend = friendStore.findFriend(chat.targetId);
  360. if (friend) {
  361. chat.isDnd = friend.isDnd
  362. }
  363. } else if (chat.type == 'GROUP') {
  364. let group = groupStore.findGroup(chat.targetId);
  365. if (group) {
  366. chat.isDnd = group.isDnd
  367. }
  368. }
  369. })
  370. // 排序
  371. cacheChats.sort((chat1, chat2) => chat2.lastSendTime - chat1.lastSendTime);
  372. // #ifndef APP-PLUS
  373. /**
  374. * 由于h5和小程序的stroge只有5m,大约只能存储2w条消息,
  375. * 所以这里每个会话只保留1000条消息,防止溢出
  376. */
  377. cacheChats.forEach(chat => {
  378. if (chat.messages.length > 1000) {
  379. let idx = chat.messages.length - 1000;
  380. chat.messages = chat.messages.slice(idx);
  381. }
  382. })
  383. // #endif
  384. // 记录热数据索引位置
  385. cacheChats.forEach(chat => chat.hotMinIdx = chat.messages.length);
  386. // 将消息一次性装载回来
  387. this.chats = cacheChats;
  388. // 清空缓存,不再使用
  389. cacheChats = null;
  390. // 消息持久化
  391. this.saveToStorage(true);
  392. },
  393. saveToStorage(withColdMessage) {
  394. // 加载中不保存,防止卡顿
  395. if (this.isLoading()) {
  396. return;
  397. }
  398. const userStore = useUserStore();
  399. let userId = userStore.userInfo.id;
  400. let key = "chats-app-" + userId;
  401. let chatKeys = [];
  402. // 按会话为单位存储,只存储有改动的会话
  403. this.chats.forEach((chat) => {
  404. let chatKey = `${key}-${chat.type}-${chat.targetId}`
  405. if (!chat.stored) {
  406. if (chat.delete) {
  407. uni.removeStorageSync(chatKey);
  408. } else {
  409. // 存储冷数据
  410. if (withColdMessage) {
  411. let coldChat = Object.assign({}, chat);
  412. coldChat.messages = chat.messages.slice(0, chat.hotMinIdx);
  413. uni.setStorageSync(chatKey, coldChat)
  414. }
  415. // 存储热消息
  416. let hotKey = chatKey + '-hot';
  417. let hotChat = Object.assign({}, chat);
  418. hotChat.messages = chat.messages.slice(chat.hotMinIdx)
  419. uni.setStorageSync(hotKey, hotChat);
  420. }
  421. chat.stored = true;
  422. }
  423. if (!chat.delete) {
  424. chatKeys.push(chatKey);
  425. }
  426. })
  427. // 会话核心信息
  428. let chatsData = {
  429. privateMsgMaxId: this.privateMsgMaxId,
  430. groupMsgMaxId: this.groupMsgMaxId,
  431. chatKeys: chatKeys
  432. }
  433. uni.setStorageSync(key, chatsData)
  434. // 清理已删除的会话
  435. this.chats = this.chats.filter(chat => !chat.delete)
  436. },
  437. clear(state) {
  438. cacheChats = [];
  439. this.chats = [];
  440. this.privateMsgMaxId = 0;
  441. this.groupMsgMaxId = 0;
  442. this.loadingPrivateMsg = false;
  443. this.loadingGroupMsg = false;
  444. },
  445. loadChat() {
  446. return new Promise((resolve, reject) => {
  447. let userStore = useUserStore();
  448. let userId = userStore.userInfo.id;
  449. let chatsData = uni.getStorageSync("chats-app-" + userId)
  450. if (chatsData) {
  451. if (chatsData.chatKeys) {
  452. chatsData.chats = [];
  453. chatsData.chatKeys.forEach(key => {
  454. let coldChat = uni.getStorageSync(key);
  455. let hotChat = uni.getStorageSync(key + '-hot');
  456. if (!coldChat && !hotChat) {
  457. return;
  458. }
  459. // 防止消息一直处在发送中状态
  460. hotChat && hotChat.messages.forEach(msg => {
  461. if (msg.status == MESSAGE_STATUS.SENDING) {
  462. msg.status = MESSAGE_STATUS.FAILED
  463. }
  464. })
  465. // 冷热消息合并
  466. let chat = Object.assign({}, coldChat, hotChat);
  467. if (hotChat && coldChat) {
  468. chat.messages = coldChat.messages.concat(hotChat.messages)
  469. }
  470. // 历史版本没有readedMessageIdx字段,做兼容一下
  471. chat.readedMessageIdx = chat.readedMessageIdx || 0;
  472. chatsData.chats.push(chat);
  473. })
  474. }
  475. this.initChats(chatsData);
  476. }
  477. resolve()
  478. })
  479. }
  480. },
  481. getters: {
  482. isLoading: (state) => () => {
  483. return state.loadingPrivateMsg || state.loadingGroupMsg
  484. },
  485. curChats: (state) => {
  486. if (cacheChats && state.isLoading()) {
  487. return cacheChats;
  488. }
  489. return state.chats;
  490. },
  491. findChatIdx: (state) => (chat) => {
  492. let chats = state.curChats;
  493. for (let idx in chats) {
  494. if (chats[idx].type == chat.type &&
  495. chats[idx].targetId === chat.targetId) {
  496. chat = state.chats[idx];
  497. return idx;
  498. }
  499. }
  500. },
  501. findChat: (state) => (chat) => {
  502. let chats = state.curChats;
  503. let idx = state.findChatIdx(chat);
  504. return chats[idx];
  505. },
  506. findChatByFriend: (state) => (fid) => {
  507. return state.curChats.find(chat => chat.type == 'PRIVATE' &&
  508. chat.targetId == fid)
  509. },
  510. findChatByGroup: (state) => (gid) => {
  511. return state.curChats.find(chat => chat.type == 'GROUP' &&
  512. chat.targetId == gid)
  513. },
  514. findMessage: (state) => (chat, msgInfo) => {
  515. if (!chat) {
  516. return null;
  517. }
  518. for (let idx in chat.messages) {
  519. // 通过id判断
  520. if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
  521. return chat.messages[idx];
  522. }
  523. // 正在发送中的消息可能没有id,只有tmpId
  524. if (msgInfo.tmpId && chat.messages[idx].tmpId &&
  525. chat.messages[idx].tmpId == msgInfo.tmpId) {
  526. return chat.messages[idx];
  527. }
  528. }
  529. }
  530. }
  531. });