chatStore.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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) {
  143. // 获取对方id或群id
  144. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  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(msgInfo);
  154. let message = this.findMessage(chat, msgInfo);
  155. if (message) {
  156. Object.assign(message, msgInfo);
  157. // 撤回消息需要显示
  158. if (msgInfo.type == MESSAGE_TYPE.RECALL) {
  159. chat.lastContent = msgInfo.content;
  160. }
  161. chat.stored = false;
  162. this.saveToStorage();
  163. return;
  164. }
  165. // 会话列表内容
  166. if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
  167. chat.lastContent = "[图片]";
  168. } else if (msgInfo.type == MESSAGE_TYPE.FILE) {
  169. chat.lastContent = "[文件]";
  170. } else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
  171. chat.lastContent = "[语音]";
  172. } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VOICE) {
  173. chat.lastContent = "[语音通话]";
  174. } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VIDEO) {
  175. chat.lastContent = "[视频通话]";
  176. } else if (msgInfo.type == MESSAGE_TYPE.TEXT ||
  177. msgInfo.type == MESSAGE_TYPE.RECALL ||
  178. msgInfo.type == MESSAGE_TYPE.TIP_TEXT) {
  179. chat.lastContent = msgInfo.content;
  180. }
  181. chat.lastSendTime = msgInfo.sendTime;
  182. chat.sendNickName = msgInfo.sendNickName;
  183. // 未读加1
  184. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED &&
  185. msgInfo.type != MESSAGE_TYPE.TIP_TEXT) {
  186. chat.unreadCount++;
  187. }
  188. // 是否有人@我
  189. if (!msgInfo.selfSend && chat.type == "GROUP" && msgInfo.atUserIds &&
  190. msgInfo.status != MESSAGE_STATUS.READED) {
  191. const userStore = useUserStore();
  192. let userId = userStore.userInfo.id;
  193. if (msgInfo.atUserIds.indexOf(userId) >= 0) {
  194. chat.atMe = true;
  195. }
  196. if (msgInfo.atUserIds.indexOf(-1) >= 0) {
  197. chat.atAll = true;
  198. }
  199. }
  200. // 间隔大于10分钟插入时间显示
  201. if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
  202. chat.messages.push({
  203. sendTime: msgInfo.sendTime,
  204. type: MESSAGE_TYPE.TIP_TIME,
  205. });
  206. chat.lastTimeTip = msgInfo.sendTime;
  207. }
  208. // 根据id顺序插入,防止消息乱序
  209. let insertPos = chat.messages.length;
  210. // 防止 图片、文件 在发送方 显示 在顶端 因为还没存库,id=0
  211. if (msgInfo.id && msgInfo.id > 0) {
  212. for (let idx in chat.messages) {
  213. if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
  214. insertPos = idx;
  215. console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`);
  216. break;
  217. }
  218. }
  219. }
  220. if (insertPos == chat.messages.length) {
  221. // 这种赋值效率最高
  222. chat.messages[insertPos] = msgInfo;
  223. } else {
  224. chat.messages.splice(insertPos, 0, msgInfo);
  225. }
  226. chat.stored = false;
  227. this.saveToStorage();
  228. },
  229. updateMessage(msgInfo) {
  230. // 获取对方id或群id
  231. let chat = this.findChat(msgInfo);
  232. let message = this.findMessage(chat, msgInfo);
  233. if (message) {
  234. // 属性拷贝
  235. Object.assign(message, msgInfo);
  236. chat.stored = false;
  237. this.saveToStorage();
  238. }
  239. },
  240. deleteMessage(msgInfo) {
  241. // 获取对方id或群id
  242. let chat = this.findChat(msgInfo);
  243. for (let idx in chat.messages) {
  244. // 已经发送成功的,根据id删除
  245. if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
  246. chat.messages.splice(idx, 1);
  247. break;
  248. }
  249. // 正在发送中的消息可能没有id,根据发送时间删除
  250. if (msgInfo.selfSend && chat.messages[idx].selfSend &&
  251. chat.messages[idx].sendTime == msgInfo.sendTime) {
  252. chat.messages.splice(idx, 1);
  253. break;
  254. }
  255. }
  256. chat.stored = false;
  257. this.saveToStorage();
  258. },
  259. updateChatFromFriend(friend) {
  260. let chat = this.findChatByFriend(friend.id)
  261. if (chat && (chat.headImage != friend.headImageThumb ||
  262. chat.showName != friend.nickName)) {
  263. // 更新会话中的群名和头像
  264. chat.headImage = friend.headImageThumb;
  265. chat.showName = friend.nickName;
  266. chat.stored = false;
  267. this.saveToStorage();
  268. }
  269. },
  270. updateChatFromGroup(group) {
  271. let chat = this.findChatByGroup(group.id);
  272. if (chat && (chat.headImage != group.headImageThumb ||
  273. chat.showName != group.showGroupName)) {
  274. // 更新会话中的群名称和头像
  275. chat.headImage = group.headImageThumb;
  276. chat.showName = group.showGroupName;
  277. chat.stored = false;
  278. this.saveToStorage();
  279. }
  280. },
  281. setLoadingPrivateMsg(loading) {
  282. this.loadingPrivateMsg = loading;
  283. if (!this.isLoading()) {
  284. this.refreshChats()
  285. }
  286. },
  287. setLoadingGroupMsg(loading) {
  288. this.loadingGroupMsg = loading;
  289. if (!this.isLoading()) {
  290. this.refreshChats()
  291. }
  292. },
  293. refreshChats(state) {
  294. // 排序
  295. cacheChats.sort((chat1, chat2) => {
  296. return chat2.lastSendTime - chat1.lastSendTime;
  297. });
  298. // 将消息一次性装载回来
  299. this.chats = cacheChats;
  300. // 断线重连后不能使用缓存模式,否则会导致聊天窗口的消息不刷新
  301. cacheChats = this.chats;
  302. this.saveToStorage();
  303. },
  304. saveToStorage(state) {
  305. // 加载中不保存,防止卡顿
  306. if (this.isLoading()) {
  307. return;
  308. }
  309. const userStore = useUserStore();
  310. let userId = userStore.userInfo.id;
  311. let key = "chats-app-" + userId;
  312. let chatKeys = [];
  313. // 按会话为单位存储,只存储有改动的会话
  314. this.chats.forEach((chat)=>{
  315. let chatKey = `${key}-${chat.type}-${chat.targetId}`
  316. if(!chat.stored){
  317. if(chat.delete){
  318. uni.removeStorageSync(chatKey);
  319. }else{
  320. uni.setStorageSync(chatKey,chat);
  321. }
  322. chat.stored = true;
  323. }
  324. if(!chat.delete){
  325. chatKeys.push(chatKey);
  326. }
  327. })
  328. // 会话核心信息
  329. let chatsData = {
  330. privateMsgMaxId: this.privateMsgMaxId,
  331. groupMsgMaxId: this.groupMsgMaxId,
  332. chatKeys: chatKeys
  333. }
  334. uni.setStorageSync(key, chatsData)
  335. // 清理已删除的会话
  336. this.chats = this.chats.filter(chat => !chat.delete)
  337. },
  338. clear(state) {
  339. cacheChats = [];
  340. this.chats = [];
  341. this.privateMsgMaxId = 0;
  342. this.groupMsgMaxId = 0;
  343. this.loadingPrivateMsg = false;
  344. this.loadingGroupMsg = false;
  345. },
  346. loadChat(context) {
  347. return new Promise((resolve, reject) => {
  348. let userStore = useUserStore();
  349. let userId = userStore.userInfo.id;
  350. let chatsData = uni.getStorageSync("chats-app-" + userId)
  351. if(chatsData){
  352. if(chatsData.chatKeys){
  353. let time = new Date().getTime();
  354. chatsData.chats = [];
  355. chatsData.chatKeys.forEach(key=>{
  356. let chat = uni.getStorageSync(key);
  357. if(chat){
  358. chatsData.chats.push(chat);
  359. }
  360. })
  361. }
  362. this.initChats(chatsData);
  363. }
  364. resolve()
  365. })
  366. }
  367. },
  368. getters: {
  369. isLoading: (state) => () => {
  370. return state.loadingPrivateMsg || state.loadingGroupMsg
  371. },
  372. curChats: (state) => {
  373. return state.isLoading() ? cacheChats : state.chats;
  374. },
  375. findChatIdx: (state) => (chat) => {
  376. let chats = state.curChats;
  377. for (let idx in chats) {
  378. if (chats[idx].type == chat.type &&
  379. chats[idx].targetId === chat.targetId) {
  380. chat = state.chats[idx];
  381. return idx;
  382. }
  383. }
  384. },
  385. findChat: (state) => (msgInfo) => {
  386. let chats = state.curChats;
  387. // 获取对方id或群id
  388. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  389. let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo
  390. .sendId;
  391. let chat = null;
  392. for (let idx in chats) {
  393. if (chats[idx].type == type &&
  394. chats[idx].targetId === targetId) {
  395. chat = chats[idx];
  396. break;
  397. }
  398. }
  399. return chat;
  400. },
  401. findChatByFriend: (state) => (fid) => {
  402. return state.curChats.find(chat => chat.type == 'PRIVATE' &&
  403. chat.targetId == fid)
  404. },
  405. findChatByGroup: (state) => (gid) => {
  406. return state.curChats.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. });