chatStore.js 12 KB

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