chatStore.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. cacheChats.push(JSON.parse(JSON.stringify(chat)));
  22. // 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间
  23. if (this.chats.length < 15) {
  24. chat.messages = [];
  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. chat.delete = false;
  47. // 放置头部
  48. this.moveTop(idx)
  49. break;
  50. }
  51. }
  52. // 创建会话
  53. if (chat == null) {
  54. chat = {
  55. targetId: chatInfo.targetId,
  56. type: chatInfo.type,
  57. showName: chatInfo.showName,
  58. headImage: chatInfo.headImage,
  59. lastContent: "",
  60. lastSendTime: new Date().getTime(),
  61. unreadCount: 0,
  62. messages: [],
  63. atMe: false,
  64. atAll: false,
  65. delete: false
  66. };
  67. chats.unshift(chat);
  68. this.saveToStorage();
  69. }
  70. },
  71. activeChat(idx) {
  72. let chats = this.curChats;
  73. if (idx >= 0) {
  74. chats[idx].unreadCount = 0;
  75. }
  76. },
  77. resetUnreadCount(chatInfo) {
  78. console.log("resetUnreadCount")
  79. let chats = this.curChats;
  80. for (let idx in chats) {
  81. if (chats[idx].type == chatInfo.type &&
  82. chats[idx].targetId == chatInfo.targetId) {
  83. chats[idx].unreadCount = 0;
  84. chats[idx].atMe = false;
  85. chats[idx].atAll = false;
  86. }
  87. }
  88. this.saveToStorage();
  89. },
  90. readedMessage(pos) {
  91. let chats = this.curChats;
  92. for (let idx in chats) {
  93. if (chats[idx].type == 'PRIVATE' &&
  94. chats[idx].targetId == pos.friendId) {
  95. chats[idx].messages.forEach((m) => {
  96. if (m.selfSend && m.status != MESSAGE_STATUS.RECALL) {
  97. // pos.maxId为空表示整个会话已读
  98. if (!pos.maxId || m.id <= pos.maxId) {
  99. m.status = MESSAGE_STATUS.READED
  100. }
  101. }
  102. })
  103. }
  104. }
  105. this.saveToStorage();
  106. },
  107. removeChat(idx) {
  108. let chats = this.curChats;
  109. chats.splice(idx, 1);
  110. this.saveToStorage();
  111. },
  112. removePrivateChat(userId) {
  113. let chats = this.curChats;
  114. for (let idx in chats) {
  115. if (chats[idx].type == 'PRIVATE' &&
  116. chats[idx].targetId == userId) {
  117. this.removeChat(idx);
  118. }
  119. }
  120. },
  121. removeGroupChat(groupId) {
  122. let chats = this.curChats;
  123. for (let idx in chats) {
  124. if (chats[idx].type == 'GROUP' &&
  125. chats[idx].targetId == groupId) {
  126. this.removeChat(idx);
  127. }
  128. }
  129. },
  130. moveTop(idx) {
  131. console.log("moveTop")
  132. if (this.isLoading()) {
  133. return;
  134. }
  135. let chats = this.curChats;
  136. if (idx > 0) {
  137. let chat = chats[idx];
  138. chats.splice(idx, 1);
  139. chats.unshift(chat);
  140. this.saveToStorage();
  141. }
  142. },
  143. insertMessage(msgInfo) {
  144. // 获取对方id或群id
  145. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  146. // 记录消息的最大id
  147. if (msgInfo.id && type == "PRIVATE" && msgInfo.id > this.privateMsgMaxId) {
  148. this.privateMsgMaxId = msgInfo.id;
  149. }
  150. if (msgInfo.id && type == "GROUP" && msgInfo.id > this.groupMsgMaxId) {
  151. this.groupMsgMaxId = msgInfo.id;
  152. }
  153. // 如果是已存在消息,则覆盖旧的消息数据
  154. let chat = this.findChat(msgInfo);
  155. let message = this.findMessage(chat, msgInfo);
  156. if (message) {
  157. Object.assign(message, msgInfo);
  158. // 撤回消息需要显示
  159. if (msgInfo.type == MESSAGE_TYPE.RECALL) {
  160. chat.lastContent = msgInfo.content;
  161. }
  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.TEXT || msgInfo.type == MESSAGE_TYPE.RECALL) {
  173. chat.lastContent = msgInfo.content;
  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. }
  179. chat.lastSendTime = msgInfo.sendTime;
  180. chat.sendNickName = msgInfo.sendNickName;
  181. // 未读加1
  182. if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED &&
  183. msgInfo.type != MESSAGE_TYPE.TIP_TEXT) {
  184. chat.unreadCount++;
  185. }
  186. // 是否有人@我
  187. if (!msgInfo.selfSend && chat.type == "GROUP" && msgInfo.atUserIds &&
  188. msgInfo.status != MESSAGE_STATUS.READED) {
  189. const userStore = useUserStore();
  190. let userId = userStore.userInfo.id;
  191. if (msgInfo.atUserIds.indexOf(userId) >= 0) {
  192. chat.atMe = true;
  193. }
  194. if (msgInfo.atUserIds.indexOf(-1) >= 0) {
  195. chat.atAll = true;
  196. }
  197. }
  198. // 间隔大于10分钟插入时间显示
  199. if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
  200. chat.messages.push({
  201. sendTime: msgInfo.sendTime,
  202. type: MESSAGE_TYPE.TIP_TIME,
  203. });
  204. chat.lastTimeTip = msgInfo.sendTime;
  205. }
  206. // 根据id顺序插入,防止消息乱序
  207. let insertPos = chat.messages.length;
  208. // 防止 图片、文件 在发送方 显示 在顶端 因为还没存库,id=0
  209. if (msgInfo.id && msgInfo.id > 0) {
  210. for (let idx in chat.messages) {
  211. if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
  212. insertPos = idx;
  213. console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`);
  214. break;
  215. }
  216. }
  217. }
  218. if (insertPos == chat.messages.length) {
  219. // 这种赋值效率最高
  220. chat.messages[insertPos] = msgInfo;
  221. } else {
  222. chat.messages.splice(insertPos, 0, msgInfo);
  223. }
  224. this.saveToStorage();
  225. },
  226. updateMessage(msgInfo) {
  227. // 获取对方id或群id
  228. let chat = this.findChat(msgInfo);
  229. let message = this.findMessage(chat, msgInfo);
  230. if (message) {
  231. // 属性拷贝
  232. Object.assign(message, msgInfo);
  233. this.saveToStorage();
  234. }
  235. },
  236. deleteMessage(msgInfo) {
  237. // 获取对方id或群id
  238. let chat = this.findChat(msgInfo);
  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,根据发送时间删除
  246. if (msgInfo.selfSend && chat.messages[idx].selfSend &&
  247. chat.messages[idx].sendTime == msgInfo.sendTime) {
  248. chat.messages.splice(idx, 1);
  249. break;
  250. }
  251. }
  252. this.saveToStorage();
  253. },
  254. updateChatFromFriend(friend) {
  255. let chat = this.findChatByFriend(friend.id)
  256. if (chat.headImage != friend.headImageThumb ||
  257. chat.showName != friend.nickName) {
  258. // 更新会话中的群名和头像
  259. chat.headImage = friend.headImageThumb;
  260. chat.showName = friend.nickName;
  261. this.saveToStorage();
  262. }
  263. },
  264. updateChatFromGroup(group) {
  265. let chat = this.findChatByGroup(group.id);
  266. if (chat.headImage != group.headImageThumb ||
  267. chat.showName != group.showGroupName) {
  268. // 更新会话中的群名称和头像
  269. chat.headImage = group.headImageThumb;
  270. chat.showName = group.showGroupName;
  271. this.saveToStorage();
  272. }
  273. },
  274. setLoadingPrivateMsg(loading) {
  275. this.loadingPrivateMsg = loading;
  276. if (!this.isLoading()) {
  277. this.refreshChats()
  278. }
  279. },
  280. setLoadingGroupMsg(loading) {
  281. this.loadingGroupMsg = loading;
  282. if (!this.isLoading()) {
  283. this.refreshChats()
  284. }
  285. },
  286. refreshChats(state) {
  287. console.log("refreshChats")
  288. // 排序
  289. cacheChats.sort((chat1, chat2) => {
  290. return chat2.lastSendTime - chat1.lastSendTime;
  291. });
  292. // 将消息一次性装载回来
  293. this.chats = cacheChats;
  294. // 断线重连后不能使用缓存模式,否则会导致聊天窗口的消息不刷新
  295. cacheChats = this.chats;
  296. this.saveToStorage();
  297. },
  298. saveToStorage(state) {
  299. console.log("saveToStorage")
  300. // 加载中不保存,防止卡顿
  301. if (this.isLoading()) {
  302. return;
  303. }
  304. const timeStamp = new Date().getTime();
  305. const userStore = useUserStore();
  306. let userId = userStore.userInfo.id;
  307. let key = "chats-app-" + userId;
  308. let chatsData = {
  309. privateMsgMaxId: this.privateMsgMaxId,
  310. groupMsgMaxId: this.groupMsgMaxId,
  311. chats: this.chats
  312. }
  313. uni.setStorageSync(key, chatsData)
  314. console.log("耗时:", new Date().getTime() - timeStamp);
  315. },
  316. clear(state) {
  317. cacheChats = [];
  318. this.chats = [];
  319. this.privateMsgMaxId = 0;
  320. this.groupMsgMaxId = 0;
  321. this.loadingPrivateMsg = false;
  322. this.loadingGroupMsg = false;
  323. },
  324. loadChat(context) {
  325. return new Promise((resolve, reject) => {
  326. const userStore = useUserStore();
  327. let userId = userStore.userInfo.id;
  328. uni.getStorage({
  329. key: "chats-app-" + userId,
  330. success: (res) => {
  331. this.initChats(res.data);
  332. resolve()
  333. },
  334. fail: (e) => {
  335. resolve()
  336. }
  337. });
  338. })
  339. }
  340. },
  341. getters: {
  342. isLoading: (state) => () => {
  343. return state.loadingPrivateMsg || state.loadingGroupMsg
  344. },
  345. curChats: (state) => {
  346. return state.isLoading() ? cacheChats : state.chats;
  347. },
  348. findChatIdx: (state) => (chat) => {
  349. let chats = state.curChats;
  350. for (let idx in chats) {
  351. if (chats[idx].type == chat.type &&
  352. chats[idx].targetId === chat.targetId) {
  353. chat = state.chats[idx];
  354. return idx;
  355. }
  356. }
  357. },
  358. findChat: (state) => (msgInfo) => {
  359. let chats = state.curChats;
  360. // 获取对方id或群id
  361. let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
  362. let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo
  363. .sendId;
  364. let chat = null;
  365. for (let idx in chats) {
  366. if (chats[idx].type == type &&
  367. chats[idx].targetId === targetId) {
  368. chat = chats[idx];
  369. break;
  370. }
  371. }
  372. return chat;
  373. },
  374. findChatByFriend: (state) => (fid) => {
  375. return state.curChats.find(chat => chat.type == 'PRIVATE' &&
  376. chat.targetId == fid)
  377. },
  378. findChatByGroup: (state) => (gid) => {
  379. return state.curChats.find(chat => chat.type == 'GROUP' &&
  380. chat.targetId == gid)
  381. },
  382. findMessage: (state) => (chat, msgInfo) => {
  383. if (!chat) {
  384. return null;
  385. }
  386. for (let idx in chat.messages) {
  387. // 通过id判断
  388. if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
  389. return chat.messages[idx];
  390. }
  391. // 正在发送中的消息可能没有id,只有tmpId
  392. if (msgInfo.tmpId && chat.messages[idx].tmpId &&
  393. chat.messages[idx].tmpId == msgInfo.tmpId) {
  394. return chat.messages[idx];
  395. }
  396. }
  397. }
  398. }
  399. });