chatStore.js 15 KB

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