chatStore.js 14 KB

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