chatHistoryService.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * 聊天历史服务
  3. * 用于在本地记录用户与谁聊过天,并在新会话登录时获取历史记录
  4. */
  5. import {logger} from '../logger';
  6. import rootScope from '../rootScope';
  7. /**
  8. * 聊天对象记录
  9. */
  10. interface ChatPeer {
  11. peerId: string; // 聊天对象ID
  12. lastChatTime: number; // 最后聊天时间戳
  13. }
  14. /**
  15. * 聊天历史服务类
  16. */
  17. export class ChatHistoryService {
  18. private log = logger('chat-history-service');
  19. private readonly STORAGE_KEY = 'chat_history_peers';
  20. private readonly MAX_PEERS = 50;
  21. /**
  22. * 记录聊天对象ID
  23. * @param peerId 聊天对象ID
  24. */
  25. public recordChatPeer(peerId: string | number): void {
  26. try {
  27. const peerIdStr = peerId.toString();
  28. const now = Date.now();
  29. // 获取现有记录
  30. const existingPeers = this.getChatPeers();
  31. // 检查是否已存在该peerId
  32. const existingIndex = existingPeers.findIndex(p => p.peerId === peerIdStr);
  33. if(existingIndex !== -1) {
  34. // 更新最后聊天时间
  35. existingPeers[existingIndex].lastChatTime = now;
  36. } else {
  37. // 添加新记录
  38. existingPeers.push({
  39. peerId: peerIdStr,
  40. lastChatTime: now
  41. });
  42. }
  43. // 按最后聊天时间排序(降序)
  44. existingPeers.sort((a, b) => b.lastChatTime - a.lastChatTime);
  45. // 限制记录数量
  46. const limitedPeers = existingPeers.slice(0, this.MAX_PEERS);
  47. // 保存回localStorage
  48. this.saveChatPeers(limitedPeers);
  49. } catch(error) {
  50. this.log('记录聊天对象ID失败:', error);
  51. }
  52. }
  53. /**
  54. * 聊天对象ID是否存在
  55. * @param peerId 聊天对象ID
  56. * @returns 是否存在
  57. */
  58. public hasChatPeer(peerId: string | number): boolean {
  59. const chatPeers = this.getChatPeers();
  60. const hasPeer = chatPeers.find(peer => peer.peerId === peerId.toString()) !== undefined;
  61. this.log(`${peerId} exists: ${hasPeer}`);
  62. return hasPeer;
  63. }
  64. /**
  65. * 获取所有记录的聊天对象
  66. */
  67. public getChatPeers(): ChatPeer[] {
  68. try {
  69. const peersJson = localStorage.getItem(this.STORAGE_KEY);
  70. if(!peersJson) return [];
  71. return JSON.parse(peersJson);
  72. } catch(error) {
  73. this.log('获取聊天对象记录失败:', error);
  74. return [];
  75. }
  76. }
  77. /**
  78. * 保存聊天对象记录
  79. */
  80. private saveChatPeers(peers: ChatPeer[]): void {
  81. try {
  82. localStorage.setItem(this.STORAGE_KEY, JSON.stringify(peers));
  83. } catch(error) {
  84. this.log('保存聊天对象记录失败:', error);
  85. }
  86. }
  87. /**
  88. * 清除所有聊天对象记录
  89. */
  90. public clearChatPeers(): void {
  91. try {
  92. localStorage.removeItem(this.STORAGE_KEY);
  93. } catch(error) {
  94. this.log('清除聊天对象记录失败:', error);
  95. }
  96. }
  97. }
  98. // 导出单例实例
  99. export const chatHistoryService = new ChatHistoryService();