chatStore.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.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. chat.unreadCount++;
  272. }
  273. // 被引用的消息也要撤回
  274. if (m.quoteMessage && m.quoteMessage.id == msgInfo.id) {
  275. m.quoteMessage.content = "引用内容已撤回";
  276. m.quoteMessage.status = MESSAGE_STATUS.RECALL;
  277. m.quoteMessage.type = MESSAGE_TYPE.TIP_TEXT
  278. }
  279. }
  280. chat.stored = false;
  281. this.saveToStorage();
  282. },
  283. updateChatFromFriend(friend) {
  284. let chat = this.findChatByFriend(friend.id)
  285. if (chat && (chat.headImage != friend.headImageThumb ||
  286. chat.showName != friend.nickName)) {
  287. // 更新会话中的群名和头像
  288. chat.headImage = friend.headImageThumb;
  289. chat.showName = friend.nickName;
  290. chat.stored = false;
  291. this.saveToStorage();
  292. }
  293. },
  294. updateChatFromGroup(group) {
  295. let chat = this.findChatByGroup(group.id);
  296. if (chat && (chat.headImage != group.headImageThumb ||
  297. chat.showName != group.showGroupName)) {
  298. // 更新会话中的群名称和头像
  299. chat.headImage = group.headImageThumb;
  300. chat.showName = group.showGroupName;
  301. chat.stored = false;
  302. this.saveToStorage();
  303. }
  304. },
  305. setLoadingPrivateMsg(loading) {
  306. this.loadingPrivateMsg = loading;
  307. if (!this.isLoading()) {
  308. this.refreshChats()
  309. }
  310. },
  311. setLoadingGroupMsg(loading) {
  312. this.loadingGroupMsg = loading;
  313. if (!this.isLoading()) {
  314. this.refreshChats()
  315. }
  316. },
  317. refreshChats() {
  318. if (!cacheChats) {
  319. return;
  320. }
  321. // 排序
  322. cacheChats.sort((chat1, chat2) => {
  323. return chat2.lastSendTime - chat1.lastSendTime;
  324. });
  325. // 将消息一次性装载回来
  326. this.chats = cacheChats;
  327. // 清空缓存,不再使用
  328. cacheChats = null;
  329. this.saveToStorage();
  330. },
  331. saveToStorage(state) {
  332. // 加载中不保存,防止卡顿
  333. if (this.isLoading()) {
  334. return;
  335. }
  336. const userStore = useUserStore();
  337. let userId = userStore.userInfo.id;
  338. let key = "chats-app-" + userId;
  339. let chatKeys = [];
  340. // 按会话为单位存储,只存储有改动的会话
  341. this.chats.forEach((chat) => {
  342. let chatKey = `${key}-${chat.type}-${chat.targetId}`
  343. if (!chat.stored) {
  344. if (chat.delete) {
  345. uni.removeStorageSync(chatKey);
  346. } else {
  347. uni.setStorageSync(chatKey, chat);
  348. }
  349. chat.stored = true;
  350. }
  351. if (!chat.delete) {
  352. chatKeys.push(chatKey);
  353. }
  354. })
  355. // 会话核心信息
  356. let chatsData = {
  357. privateMsgMaxId: this.privateMsgMaxId,
  358. groupMsgMaxId: this.groupMsgMaxId,
  359. chatKeys: chatKeys
  360. }
  361. uni.setStorageSync(key, chatsData)
  362. // 清理已删除的会话
  363. this.chats = this.chats.filter(chat => !chat.delete)
  364. },
  365. clear(state) {
  366. cacheChats = [];
  367. this.chats = [];
  368. this.privateMsgMaxId = 0;
  369. this.groupMsgMaxId = 0;
  370. this.loadingPrivateMsg = false;
  371. this.loadingGroupMsg = false;
  372. },
  373. loadChat(context) {
  374. return new Promise((resolve, reject) => {
  375. let userStore = useUserStore();
  376. let userId = userStore.userInfo.id;
  377. let chatsData = uni.getStorageSync("chats-app-" + userId)
  378. if (chatsData) {
  379. if (chatsData.chatKeys) {
  380. let time = new Date().getTime();
  381. chatsData.chats = [];
  382. chatsData.chatKeys.forEach(key => {
  383. let chat = uni.getStorageSync(key);
  384. if (chat) {
  385. chatsData.chats.push(chat);
  386. }
  387. })
  388. }
  389. this.initChats(chatsData);
  390. }
  391. resolve()
  392. })
  393. }
  394. },
  395. getters: {
  396. isLoading: (state) => () => {
  397. return state.loadingPrivateMsg || state.loadingGroupMsg
  398. },
  399. curChats: (state) => {
  400. if (cacheChats && state.isLoading()) {
  401. return cacheChats;
  402. }
  403. return state.chats;
  404. },
  405. findChatIdx: (state) => (chat) => {
  406. let chats = state.curChats;
  407. for (let idx in chats) {
  408. if (chats[idx].type == chat.type &&
  409. chats[idx].targetId === chat.targetId) {
  410. chat = state.chats[idx];
  411. return idx;
  412. }
  413. }
  414. },
  415. findChat: (state) => (chat) => {
  416. let chats = state.curChats;
  417. let idx = state.findChatIdx(chat);
  418. return chats[idx];
  419. },
  420. findChatByFriend: (state) => (fid) => {
  421. return state.curChats.find(chat => chat.type == 'PRIVATE' &&
  422. chat.targetId == fid)
  423. },
  424. findChatByGroup: (state) => (gid) => {
  425. return state.curChats.find(chat => chat.type == 'GROUP' &&
  426. chat.targetId == gid)
  427. },
  428. findMessage: (state) => (chat, msgInfo) => {
  429. if (!chat) {
  430. return null;
  431. }
  432. for (let idx in chat.messages) {
  433. // 通过id判断
  434. if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
  435. return chat.messages[idx];
  436. }
  437. // 正在发送中的消息可能没有id,只有tmpId
  438. if (msgInfo.tmpId && chat.messages[idx].tmpId &&
  439. chat.messages[idx].tmpId == msgInfo.tmpId) {
  440. return chat.messages[idx];
  441. }
  442. }
  443. }
  444. }
  445. });