chatStore.js 15 KB

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