chatStore.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. let isColdMessage = false;
  249. let chat = this.findChat(chatInfo);
  250. let delIdx = -1;
  251. for (let idx in chat.messages) {
  252. // 已经发送成功的,根据id删除
  253. if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
  254. delIdx = idx;
  255. break;
  256. }
  257. // 正在发送中的消息可能没有id,只有临时id
  258. if (chat.messages[idx].tmpId && chat.messages[idx].tmpId == msgInfo.tmpId) {
  259. delIdx = idx;
  260. break;
  261. }
  262. }
  263. if (delIdx >= 0) {
  264. chat.messages.splice(delIdx, 1);
  265. if( delIdx < chat.hotMinIdx){
  266. isColdMessage = true;
  267. chat.hotMinIdx--;
  268. }
  269. if (delIdx < chat.readedMessageIdx) {
  270. chat.readedMessageIdx--;
  271. }
  272. chat.stored = false;
  273. this.saveToStorage(isColdMessage);
  274. }
  275. },
  276. recallMessage(msgInfo, chatInfo) {
  277. let chat = this.findChat(chatInfo);
  278. if (!chat) return;
  279. let isColdMessage = false;
  280. // 要撤回的消息id
  281. let id = msgInfo.content;
  282. let name = msgInfo.selfSend ? '你' : chat.type == 'PRIVATE' ? '对方' : msgInfo.sendNickName;
  283. for (let idx in chat.messages) {
  284. let m = chat.messages[idx];
  285. if (m.id && m.id == id) {
  286. // 改造成一条提示消息
  287. m.status = MESSAGE_STATUS.RECALL;
  288. m.content = name + "撤回了一条消息";
  289. m.type = MESSAGE_TYPE.TIP_TEXT
  290. // 会话列表
  291. chat.lastContent = m.content;
  292. chat.lastSendTime = msgInfo.sendTime;
  293. chat.sendNickName = '';
  294. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED) {
  295. chat.unreadCount++;
  296. }
  297. isColdMessage = idx < chat.hotMinIdx;
  298. }
  299. // 被引用的消息也要撤回
  300. if (m.quoteMessage && m.quoteMessage.id == msgInfo.id) {
  301. m.quoteMessage.content = "引用内容已撤回";
  302. m.quoteMessage.status = MESSAGE_STATUS.RECALL;
  303. m.quoteMessage.type = MESSAGE_TYPE.TIP_TEXT
  304. }
  305. }
  306. chat.stored = false;
  307. this.saveToStorage(isColdMessage);
  308. },
  309. updateChatFromFriend(friend) {
  310. let chat = this.findChatByFriend(friend.id)
  311. if (chat && (chat.headImage != friend.headImage ||
  312. chat.showName != friend.nickName)) {
  313. // 更新会话中的群名和头像
  314. chat.headImage = friend.headImage;
  315. chat.showName = friend.nickName;
  316. chat.stored = false;
  317. this.saveToStorage();
  318. }
  319. },
  320. updateChatFromUser(user) {
  321. let chat = this.findChatByFriend(user.id);
  322. // 更新会话中的昵称和头像
  323. if (chat && (chat.headImage != user.headImageThumb ||
  324. chat.showName != user.nickName)) {
  325. chat.headImage = user.headImageThumb;
  326. chat.showName = user.nickName;
  327. chat.stored = false;
  328. this.saveToStorage();
  329. }
  330. },
  331. updateChatFromGroup(group) {
  332. let chat = this.findChatByGroup(group.id);
  333. if (chat && (chat.headImage != group.headImageThumb ||
  334. chat.showName != group.showGroupName)) {
  335. // 更新会话中的群名称和头像
  336. chat.headImage = group.headImageThumb;
  337. chat.showName = group.showGroupName;
  338. chat.stored = false;
  339. this.saveToStorage();
  340. }
  341. },
  342. setLoadingPrivateMsg(loading) {
  343. this.loadingPrivateMsg = loading;
  344. if (!this.isLoading()) {
  345. this.refreshChats()
  346. }
  347. },
  348. setLoadingGroupMsg(loading) {
  349. this.loadingGroupMsg = loading;
  350. if (!this.isLoading()) {
  351. this.refreshChats()
  352. }
  353. },
  354. setDnd(chatInfo, isDnd) {
  355. let chat = this.findChat(chatInfo);
  356. if (chat) {
  357. chat.isDnd = isDnd;
  358. }
  359. },
  360. refreshChats() {
  361. if (!cacheChats) return;
  362. // 更新会话免打扰状态
  363. const friendStore = useFriendStore();
  364. const groupStore = useGroupStore();
  365. cacheChats.forEach(chat => {
  366. if (chat.type == 'PRIVATE') {
  367. let friend = friendStore.findFriend(chat.targetId);
  368. if (friend) {
  369. chat.isDnd = friend.isDnd
  370. }
  371. } else if (chat.type == 'GROUP') {
  372. let group = groupStore.findGroup(chat.targetId);
  373. if (group) {
  374. chat.isDnd = group.isDnd
  375. }
  376. }
  377. })
  378. // 排序
  379. cacheChats.sort((chat1, chat2) => chat2.lastSendTime - chat1.lastSendTime);
  380. // #ifndef APP-PLUS
  381. /**
  382. * 由于h5和小程序的stroge只有5m,大约只能存储2w条消息,
  383. * 所以这里每个会话只保留1000条消息,防止溢出
  384. */
  385. cacheChats.forEach(chat => {
  386. if (chat.messages.length > 1000) {
  387. let idx = chat.messages.length - 1000;
  388. chat.messages = chat.messages.slice(idx);
  389. }
  390. })
  391. // #endif
  392. // 记录热数据索引位置
  393. cacheChats.forEach(chat => chat.hotMinIdx = chat.messages.length);
  394. // 将消息一次性装载回来
  395. this.chats = cacheChats;
  396. // 清空缓存,不再使用
  397. cacheChats = null;
  398. // 消息持久化
  399. this.saveToStorage(true);
  400. },
  401. saveToStorage(withColdMessage) {
  402. // 加载中不保存,防止卡顿
  403. if (this.isLoading()) {
  404. return;
  405. }
  406. const userStore = useUserStore();
  407. let userId = userStore.userInfo.id;
  408. let key = "chats-app-" + userId;
  409. let chatKeys = [];
  410. // 按会话为单位存储,只存储有改动的会话
  411. this.chats.forEach((chat) => {
  412. let chatKey = `${key}-${chat.type}-${chat.targetId}`
  413. if (!chat.stored) {
  414. if (chat.delete) {
  415. uni.removeStorageSync(chatKey);
  416. } else {
  417. // 存储冷数据
  418. if (withColdMessage) {
  419. let coldChat = Object.assign({}, chat);
  420. coldChat.messages = chat.messages.slice(0, chat.hotMinIdx);
  421. uni.setStorageSync(chatKey, coldChat)
  422. }
  423. // 存储热消息
  424. let hotKey = chatKey + '-hot';
  425. let hotChat = Object.assign({}, chat);
  426. hotChat.messages = chat.messages.slice(chat.hotMinIdx)
  427. uni.setStorageSync(hotKey, hotChat);
  428. }
  429. chat.stored = true;
  430. }
  431. if (!chat.delete) {
  432. chatKeys.push(chatKey);
  433. }
  434. })
  435. // 会话核心信息
  436. let chatsData = {
  437. privateMsgMaxId: this.privateMsgMaxId,
  438. groupMsgMaxId: this.groupMsgMaxId,
  439. chatKeys: chatKeys
  440. }
  441. uni.setStorageSync(key, chatsData)
  442. // 清理已删除的会话
  443. this.chats = this.chats.filter(chat => !chat.delete)
  444. },
  445. clear(state) {
  446. cacheChats = [];
  447. this.chats = [];
  448. this.privateMsgMaxId = 0;
  449. this.groupMsgMaxId = 0;
  450. this.loadingPrivateMsg = false;
  451. this.loadingGroupMsg = false;
  452. },
  453. loadChat() {
  454. return new Promise((resolve, reject) => {
  455. let userStore = useUserStore();
  456. let userId = userStore.userInfo.id;
  457. let chatsData = uni.getStorageSync("chats-app-" + userId)
  458. if (chatsData) {
  459. if (chatsData.chatKeys) {
  460. chatsData.chats = [];
  461. chatsData.chatKeys.forEach(key => {
  462. let coldChat = uni.getStorageSync(key);
  463. let hotChat = uni.getStorageSync(key + '-hot');
  464. if (!coldChat && !hotChat) {
  465. return;
  466. }
  467. // 防止消息一直处在发送中状态
  468. hotChat && hotChat.messages.forEach(msg => {
  469. if (msg.status == MESSAGE_STATUS.SENDING) {
  470. msg.status = MESSAGE_STATUS.FAILED
  471. }
  472. })
  473. // 冷热消息合并
  474. let chat = Object.assign({}, coldChat, hotChat);
  475. if (hotChat && coldChat) {
  476. chat.messages = coldChat.messages.concat(hotChat.messages)
  477. }
  478. // 历史版本没有readedMessageIdx字段,做兼容一下
  479. chat.readedMessageIdx = chat.readedMessageIdx || 0;
  480. chatsData.chats.push(chat);
  481. })
  482. }
  483. this.initChats(chatsData);
  484. }
  485. resolve()
  486. })
  487. }
  488. },
  489. getters: {
  490. isLoading: (state) => () => {
  491. return state.loadingPrivateMsg || state.loadingGroupMsg
  492. },
  493. curChats: (state) => {
  494. if (cacheChats && state.isLoading()) {
  495. return cacheChats;
  496. }
  497. return state.chats;
  498. },
  499. findChatIdx: (state) => (chat) => {
  500. let chats = state.curChats;
  501. for (let idx in chats) {
  502. if (chats[idx].type == chat.type &&
  503. chats[idx].targetId === chat.targetId) {
  504. chat = state.chats[idx];
  505. return idx;
  506. }
  507. }
  508. },
  509. findChat: (state) => (chat) => {
  510. let chats = state.curChats;
  511. let idx = state.findChatIdx(chat);
  512. return chats[idx];
  513. },
  514. findChatByFriend: (state) => (fid) => {
  515. return state.curChats.find(chat => chat.type == 'PRIVATE' &&
  516. chat.targetId == fid)
  517. },
  518. findChatByGroup: (state) => (gid) => {
  519. return state.curChats.find(chat => chat.type == 'GROUP' &&
  520. chat.targetId == gid)
  521. },
  522. findMessage: (state) => (chat, msgInfo) => {
  523. if (!chat) {
  524. return null;
  525. }
  526. for (let idx in chat.messages) {
  527. // 通过id判断
  528. if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
  529. return chat.messages[idx];
  530. }
  531. // 正在发送中的消息可能没有id,只有tmpId
  532. if (msgInfo.tmpId && chat.messages[idx].tmpId &&
  533. chat.messages[idx].tmpId == msgInfo.tmpId) {
  534. return chat.messages[idx];
  535. }
  536. }
  537. }
  538. }
  539. });