chatStore.js 13 KB

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