chatStore.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import {defineStore} from 'pinia'
  2. import type Chat from '@/mode/Chat'
  3. import type Message from '@/mode/Message'
  4. import ChatType from '@/utils/ChatType'
  5. import GroupApi from '@/api/GroupApi'
  6. import UserApi from '../api/UserApi'
  7. import MessageType from '@/utils/MessageType'
  8. import FetchRequest from '@/api/FetchRequest'
  9. import {useSettingStore} from '@/store/settingStore'
  10. import DictUtils from '@/utils/DictUtils'
  11. import {useUserStore} from '@/store/userStore'
  12. import {useImmunityStore} from '@/store/immunityStore'
  13. import type Extend from '@/mode/Extend'
  14. import {useSysStore} from "@/store/sysStore";
  15. import type Receipt from "@/mode/Receipt";
  16. import {useWsStore} from "@/store/WsStore";
  17. import ChatApi from "@/api/ChatApi";
  18. import VimConfig from "@/config/VimConfig";
  19. import {decryptLong2 } from '@/store/cryptoAES';
  20. import dbApi from '@/api/DBactApi';
  21. export interface IState {
  22. chats: Array<Chat>;
  23. openChatId: string | null;
  24. last: number;
  25. quoteMessage: Message | undefined
  26. chatMessage: Map<string, Message[]>;
  27. chatLastTime: Map<string, number>;
  28. chatLastMessage: Map<string, string>;
  29. //未读消息id
  30. chatUnreadId: Map<string, Array<string>>
  31. }
  32. export const useChatStore = defineStore({
  33. id: 'chat_store',
  34. state: (): IState => ({
  35. chats: new Array<Chat>(),
  36. //当前打开的聊天室id
  37. openChatId: null,
  38. //消息声音提醒时间(限流作用)
  39. last: 0,
  40. //引用消息的id
  41. quoteMessage: undefined,
  42. chatMessage: new Map<string, Message[]>(),
  43. chatLastTime: new Map<string,number>(),
  44. chatLastMessage: new Map<string,string>(),
  45. chatUnreadId: new Map<string, []>()
  46. }),
  47. // // 开启数据缓存
  48. persist: {
  49. enabled: true,
  50. strategies: [
  51. {
  52. key: 'chat',
  53. storage: localStorage,
  54. paths: ['chatLastTime','chatLastMessage','chatUnreadId']
  55. }
  56. ]
  57. },
  58. getters: {
  59. allUnReadCount(): number {
  60. //console.log('allUnReadCount',this.chats)
  61. return this.chats.reduce((accumulator, currentValue) => accumulator + currentValue.unreadCount, 0)
  62. }
  63. },
  64. actions: {
  65. /**
  66. * 去重
  67. * @param chatArr 聊天室数组
  68. */
  69. removeDuplicateChats(chatArr: Chat[]) {
  70. return chatArr.reduce((prev: Chat[], cur: Chat) => {
  71. const has = prev.some((item) => item.id === cur.id)
  72. return has ? prev : [...prev, cur]
  73. }, [])
  74. },
  75. /**
  76. * 插入数据库
  77. * @param chatArr 聊天室数组
  78. */
  79. insertChats(chatArr: Chat[]){
  80. chatArr.forEach((item) => {
  81. dbApi.insertchat(item);
  82. })
  83. },
  84. /**
  85. * 重新加载聊历史记录
  86. */
  87. reloadChats() {
  88. var locatList=[];
  89. dbApi.selectchats().then((sres:any)=>{
  90. if(sres){
  91. //console.log('selectchats',sres);
  92. locatList=sres;
  93. }
  94. });
  95. return Promise.all([ChatApi.topList(), ChatApi.list()])
  96. .then((res) => {
  97. //console.log('reloadChats',res)
  98. this.chats = []
  99. const topChats = res[0].data
  100. topChats.forEach((item) => {
  101. item.top = true
  102. })
  103. const list = topChats.concat(res[1].data)
  104. list.forEach((item) => {
  105. item.unreadCount = (this.chatUnreadId[item.id]??[]).length
  106. })
  107. const rlist=list.concat(locatList);
  108. //console.log(rlist);
  109. //去重
  110. this.chats = this.removeDuplicateChats(rlist);
  111. //插入数据库
  112. this.insertChats(this.chats);
  113. return Promise.resolve()
  114. })
  115. },
  116. setQuoteMessage(quoteMessage: Message | undefined) {
  117. this.quoteMessage = quoteMessage
  118. },
  119. /**
  120. * 把一个消息推送到对应的聊天记录里面
  121. * @param message 消息
  122. */
  123. pushMessage(message: Message) {
  124. //console.log('pushMessage',message);
  125. const hideIndex = 10
  126. const chat = this.getChat(message.chatId)
  127. //所在的位置
  128. const chatIndex = this.getChatIndex(message.chatId)
  129. //消息是在队列的后面,用户可能看不到,需要把消息移到队列的前面
  130. if (chatIndex > hideIndex) {
  131. const topList = this.chats.filter((item) => !!item.top) // 查找已置顶元素的位置
  132. const topIndex = topList.length
  133. if (topIndex < hideIndex) {
  134. const temp = this.chats.splice(chatIndex, 1)[0];
  135. this.chats.splice(topIndex, 0, temp)
  136. //把消息列表更新到服务端
  137. ChatApi.move(message.chatId)
  138. }
  139. }
  140. //说明该聊天对话框已经存在
  141. if (chat) {
  142. this.addToMessageList(message, chat, true)
  143. } else {
  144. this.createChatRoom(message)
  145. const chat = this.getChat(message.chatId);
  146. if (chat) {
  147. this.addToMessageList(message, chat, true)
  148. }
  149. }
  150. if (message.chatId === this.openChatId && !message.mine) {
  151. const user = useUserStore().getUser();
  152. if (chat && user) {
  153. const receipt: Receipt = {
  154. chatId: chat.id,
  155. userId: user?.id,
  156. timestamp: new Date().getTime(),
  157. type: chat.type
  158. }
  159. useWsStore().sendRead(receipt)
  160. }
  161. }
  162. },
  163. /**
  164. * 收到后端返回的用户自己发送数据,删除本地临时数据
  165. * @param message 消息
  166. * @param chat 聊天室
  167. * @param addTips 仅仅添加,不做其他操作(true:提醒 false:不提醒)
  168. */
  169. delLocalMessageList(message: Message) {
  170. const chat = this.getChat(message.chatId)
  171. if (chat) {
  172. const messageList = this.getChatMessage(chat.id)
  173. //执行清除操作
  174. const len = messageList.findIndex((n:Message) => {
  175. // @ts-ignore
  176. return n.localtime > message.localtime
  177. })
  178. messageList.splice(len,1);
  179. this.chatMessage.set(chat.id, messageList)
  180. }
  181. },
  182. /**
  183. * 把数据插入到消息的列表,有序插入
  184. * @param list list
  185. * @param message 消息
  186. * @param chat 聊天室
  187. * @param addTips 仅仅添加,不做其他操作(true:提醒 false:不提醒)
  188. */
  189. insertMessage(list: Message[], message: Message, chat: Chat, addTips: boolean = true): void {
  190. //重复数据,不予处理
  191. const repeat = list.findIndex((item) => {
  192. return item.id === message.id
  193. })
  194. if (repeat > -1) {
  195. return
  196. }
  197. //console.log('insertMessage',message)
  198. var content=decryptLong2(message.content);
  199. if(content){
  200. message.content=content;
  201. }
  202. var extend=message.extend;
  203. if((typeof extend)=='string'){
  204. //console.log('typeof extend==string');
  205. try {
  206. message.extend=JSON.parse(extend);
  207. } catch (e) {
  208. message.extend=undefined; // 如果 jsonString 不是有效的 JSON,会进入这里
  209. }
  210. }
  211. else{
  212. //console.log('typeof extend!=string');
  213. }
  214. //console.log('insertMessage1',message)
  215. if (addTips && !message.mine && this.openChatId !== chat.id && ((message.fromId != useUserStore().getUser()?.id &&
  216. useImmunityStore().immunityList.indexOf(message.chatId) === -1) ||
  217. (message.type === ChatType.GROUP && this.isAtMine(message.extend)))) {
  218. // @ts-ignore
  219. this.chatLastMessage[chat.id] = message.content
  220. // @ts-ignore
  221. this.chatLastTime[chat.id] = message.timestamp
  222. if (!this.chatUnreadId[chat.id]) {
  223. this.chatUnreadId[chat.id] = []
  224. }
  225. if(!this.chatUnreadId[chat.id].includes(message.id)){
  226. this.chatUnreadId[chat.id].push(message.id)
  227. }
  228. chat.unreadCount = this.chatUnreadId[chat.id].length
  229. //console.log('chat.unreadCount',chat.unreadCount)
  230. this.messageTips(message)
  231. } else if (message.fromId == useUserStore().getUser()?.id) {
  232. // @ts-ignore
  233. this.chatLastMessage[chat.id] = message.content
  234. // @ts-ignore
  235. this.chatLastTime[chat.id] = message.timestamp
  236. }
  237. //如果新消息的时间比历史数据的时间小
  238. const len = list.findIndex((n) => {
  239. // @ts-ignore
  240. return n.timestamp > message.timestamp
  241. })
  242. //消息是在队列的中间,不在最后
  243. if (len > -1) {
  244. list.splice(len, 0, message)
  245. } else {
  246. list.push(message)
  247. }
  248. },
  249. /**
  250. * 当前用户是否被@
  251. * @param extend 扩展信息
  252. */
  253. isAtMine(extend: Extend | undefined): boolean {
  254. const user = useUserStore().getUser()
  255. //@所有人
  256. if (extend && extend.atAll && user) {
  257. return true
  258. }
  259. //@指定用户
  260. if (extend && extend.atUserIds && user) {
  261. return extend.atUserIds.indexOf(user.id) > -1
  262. }
  263. return false
  264. },
  265. /**
  266. * 创建一个新聊天室
  267. * @param message message
  268. * @private 私有方法
  269. */
  270. createChatRoom(message: Message) {
  271. //先占位,后加载
  272. const chat: Chat = {
  273. id: message.chatId,
  274. name: '加载中...',
  275. avatar: '',
  276. type: message.type,
  277. unreadCount: 0,
  278. isLoading: false,
  279. loaded: true
  280. }
  281. // @ts-ignore
  282. this.chatLastMessage[chat.id] = message.content
  283. // @ts-ignore
  284. this.chatLastTime[chat.id] = message.timestamp
  285. this.newChat(chat)
  286. if (message.type === ChatType.GROUP) {
  287. GroupApi.get(message.chatId).then((res) => {
  288. this.updateChat(chat.id, res.data.name, res.data.avatar, false)
  289. })
  290. } else {
  291. UserApi.getUser(message.mine ? message.chatId : message.fromId).then((res) => {
  292. this.updateChat(chat.id, res.data.name, res.data.avatar, false)
  293. })
  294. }
  295. },
  296. /**
  297. * 重置未读消息计数
  298. */
  299. reset() {
  300. this.chats.forEach((item: Chat) => {
  301. item.unreadCount = 0
  302. this.chatUnreadId[item.id] = []
  303. })
  304. },
  305. /**
  306. * 打开一个聊天对话框
  307. * @param chat chat
  308. */
  309. openChat(chat: Chat) {
  310. let hasChat = false
  311. this.chats.forEach((item: Chat) => {
  312. //聊天对话框已经存在
  313. if (item.id === chat.id) {
  314. item.unreadCount = 0
  315. this.chatUnreadId[item.id] = []
  316. hasChat = true
  317. }
  318. })
  319. //新增一个新聊天对话框
  320. if (!hasChat) {
  321. chat.unreadCount = 0
  322. this.chatUnreadId[chat.id] = []
  323. //添加到聊天列表第一个
  324. this.newChat(chat)
  325. }
  326. },
  327. /**
  328. * 根据聊天室的ID 获取他的index
  329. * @param id 聊天室的ID
  330. */
  331. getChatIndex(id: string) {
  332. let i = -1
  333. this.chats.forEach((item: Chat, index: number) => {
  334. if (item.id === id) {
  335. i = index
  336. }
  337. })
  338. return i
  339. },
  340. /**
  341. * 根据聊天室的ID 获取聊天室
  342. * @param id 聊天室的ID
  343. */
  344. getChat(id: string): null | Chat {
  345. let chat: null | Chat = null
  346. this.chats.forEach((item: Chat) => {
  347. if (item.id === id) {
  348. chat = item
  349. }
  350. })
  351. return chat
  352. },
  353. /**
  354. * 退出清除chatMessage
  355. */
  356. clearMessage(): void {
  357. this.chatMessage = new Map<string, Message[]>()
  358. },
  359. /**
  360. * 设置打开的chatId
  361. */
  362. setOpenChatId(id: string | null) {
  363. this.openChatId = id
  364. },
  365. /**
  366. * 限制聊天记录的数组的长度
  367. * @param message 新增的聊天消息
  368. * @param chat 聊天室
  369. * @param addTips 是否提醒
  370. */
  371. addToMessageList(message: Message, chat: Chat, addTips: boolean = true) {
  372. const messageList = this.getChatMessage(chat.id)
  373. this.insertMessage(messageList, message, chat, addTips)
  374. this.chatMessage.set(chat.id, messageList)
  375. },
  376. /**
  377. * 获取聊天消息
  378. */
  379. getChatMessage(chatId: string) {
  380. return this.chatMessage.get(chatId) ?? []
  381. },
  382. /**
  383. * 删除聊天
  384. * @param id 聊天室的ID
  385. */
  386. delChat(id: string) {
  387. this.chats.splice(this.getChatIndex(id), 1)
  388. ChatApi.delete(id)
  389. },
  390. /**
  391. * 更新聊天室信息
  392. * @param id 聊天室id
  393. * @param name 名称
  394. * @param avatar 头像
  395. * @param updateUnreadCount 是否更新未读消息数
  396. * @param updateServer 是否更新服务器
  397. */
  398. updateChat(id: string, name: string, avatar: string, updateUnreadCount: boolean = true, updateServer: boolean = true) {
  399. this.chats.forEach((item: Chat) => {
  400. if (item.id === id) {
  401. item.name = name
  402. item.avatar = avatar
  403. if (updateUnreadCount) {
  404. item.unreadCount = 0
  405. this.chatUnreadId[item.id] = []
  406. }
  407. if (updateServer) {
  408. ChatApi.update(item)
  409. }
  410. }
  411. })
  412. },
  413. /**
  414. * 新增聊天室
  415. * @param chat 聊天室
  416. */
  417. newChat(chat: Chat) {
  418. const items = this.chats
  419. const topList = items.filter((item) => item.top) // 查找已置顶元素的位置
  420. const topIndex = topList.length
  421. if (this.chats.findIndex((item) => item.id === chat.id) === -1) {
  422. items.splice(topIndex, 0, chat) // 将该元素插入已置顶元素的后面
  423. ChatApi.add(chat)
  424. }
  425. },
  426. /**
  427. * 撤回消息
  428. * @param message 消息
  429. */
  430. backMessage(message: Message) {
  431. this.chatMessage.get(message.chatId)?.forEach((item) => {
  432. if (item.id === message.id) {
  433. item.content = '该消息已被撤回'
  434. item.messageType = MessageType.event
  435. }
  436. })
  437. },
  438. /**
  439. * 撤回消息
  440. * @param message 消息
  441. */
  442. deMessage(message: Message) {
  443. let dechatId='';
  444. if(message.mine){
  445. dechatId = message.chatId
  446. }
  447. else{
  448. dechatId = message.fromId
  449. }
  450. const messages = this.chatMessage.get(dechatId)
  451. console.log('deMessage',message)
  452. messages?.forEach((item) => {
  453. //删除id 一样的消息
  454. if (item.id === message.id) {
  455. console.log(item)
  456. messages?.splice(messages?.indexOf(item), 1);
  457. dbApi.deleteLocalmsg(message);
  458. if(this.chatLastTime[message.chatId]==message.timestamp){
  459. this.chatLastMessage[message.chatId]='';
  460. }
  461. }
  462. })
  463. },
  464. /**
  465. * 置顶聊天室
  466. * @param id 聊天室的ID
  467. */
  468. topChat(id: string) {
  469. const items = this.chats
  470. const itemIndex = this.getChatIndex(id) // 查找对应元素的索引
  471. const chat = JSON.parse(JSON.stringify(this.chats[itemIndex]))
  472. if (itemIndex !== -1) {
  473. items.splice(itemIndex, 1) // 先从原数组中删除该元素
  474. const topIndex = items.findIndex((item) => !!item.top) // 查找已置顶元素的位置
  475. if (topIndex !== -1) {
  476. items.splice(topIndex, 0, chat) // 将该元素插入已置顶元素的前面
  477. } else {
  478. items.unshift(chat) // 如果不存在已置顶元素,则将该元素插入数组最前面
  479. }
  480. chat.top = true // 标记该元素已置顶
  481. }
  482. ChatApi.top(id)
  483. },
  484. /**
  485. * 实现取消置顶功能
  486. * @param id 聊天室的ID
  487. */
  488. cancelTop(id: string) {
  489. const items = this.chats
  490. const itemIndex = this.getChatIndex(id) // 查找对应元素的索引
  491. const chat = JSON.parse(JSON.stringify(this.chats[itemIndex]))
  492. if (itemIndex !== -1 && chat.top) {
  493. chat.top = false // 标记该元素已取消置顶
  494. const topList = items.filter((item) => !!item.top) // 查找已置顶元素的位置
  495. const topIndex = topList.length
  496. if (topIndex !== 0) {
  497. items.splice(topIndex, 0, chat) // 将该元素插入已置顶元素的后面
  498. } else {
  499. items.push(chat) // 如果不存在已置顶元素,则将该元素插入数组末尾
  500. }
  501. items.splice(itemIndex, 1) // 最后从原位置删除该元素
  502. }
  503. ChatApi.cancelTop(id)
  504. },
  505. /**
  506. * 消息提醒,限流2秒
  507. */
  508. messageTips: function (message: Message) {
  509. const now = Date.now()
  510. if (now - this.last >= 1000) {
  511. this.last = now
  512. if (useSettingStore().setting?.canSoundRemind === DictUtils.YES) {
  513. // 创建音频对象并播放
  514. // const innerAudioContext = uni.createInnerAudioContext();
  515. // innerAudioContext.src = `${FetchRequest.getHost()}${VimConfig.soundPath}`;
  516. // innerAudioContext.play()
  517. //#ifdef APP-PLUS
  518. //只提醒友聊,如果想提示群聊,去掉 && message.type === ChatType.FRIEND
  519. if (VimConfig.openUniPush && !useSysStore().show && message.type === ChatType.FRIEND) {
  520. let content = MessageType.text === message.messageType ? message.content : ''
  521. uni.createPushMessage({
  522. title: '您有一条新消息',
  523. content: content,
  524. sound: 'system',
  525. fail: fail => {
  526. console.log(fail);
  527. }
  528. })
  529. }
  530. // #endif
  531. }
  532. }
  533. },
  534. /**
  535. * 设置已读读消息时间
  536. */
  537. setLastReadTime(receipt: Receipt) {
  538. this.chats.forEach((item: Chat) => {
  539. if (receipt.userId === item.id) {
  540. item.lastReadTime = receipt.timestamp
  541. }
  542. })
  543. },
  544. /**
  545. * 设置当前聊天室的对方 已读时间
  546. */
  547. setCurrentChatLastReadTime(time: number) {
  548. if (this.openChatId && this.getChat(this.openChatId)) {
  549. const chat = this.getChat(this.openChatId);
  550. //console.log('setCurrentChatLastReadTime',chat);
  551. if (chat) {
  552. chat.lastReadTime = time
  553. }
  554. }
  555. },
  556. }
  557. })