chatStore.js 16 KB

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