chatStore.js 13 KB

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