From cbbd98ae5446b11f2a432dee7ffea291cdf2ee21 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sun, 1 Mar 2026 21:09:04 -0800 Subject: messages --- src/lib/nip17.ts | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) (limited to 'src/lib') diff --git a/src/lib/nip17.ts b/src/lib/nip17.ts index 1400b5a5..69f69464 100644 --- a/src/lib/nip17.ts +++ b/src/lib/nip17.ts @@ -162,10 +162,10 @@ export const decrypt = async (wrapped: any, user: any): Promise => { } }; -// Returns the rumours of the messages the provided user has sent or received. -// If the events have an expiration timestamp, -// that timestamp is added to its rumour object as the property `expiration`. -export const getMessageRumours = async (user: any): Promise => { +// In-memory cache for rumours, keyed by pubkey +let rumourCache = new Map(); + +const fetchMessageRumours = async (user: any): Promise => { const preferredRelays = await getPreferredRelays(user.pubkey); // Always include default relays to catch messages that might be there const relays = Array.from(new Set([...preferredRelays, ...DM_RELAYS_LIST])); @@ -197,9 +197,45 @@ export const getMessageRumours = async (user: any): Promise => { } } + rumourCache.set(user.pubkey, rumours); return rumours; }; +// Returns the rumours of the messages the provided user has sent or received. +// If the events have an expiration timestamp, +// that timestamp is added to its rumour object as the property `expiration`. +// Returns cached results immediately if available, and refreshes in the background. +export const getMessageRumours = async (user: any): Promise => { + const cached = rumourCache.get(user.pubkey); + if (cached) { + fetchMessageRumours(user); + return cached; + } + return fetchMessageRumours(user); +}; + +// Cache for computed chat lists and user info +let chatListCache = new Map(); +let userInfoCache = new Map(); + +export const getCachedChatList = (userPubkey: string) => chatListCache.get(userPubkey); +export const setCachedChatList = (userPubkey: string, chats: any[], rumours: any[]) => { + chatListCache.set(userPubkey, { chats, rumours }); +}; + +export const getCachedUserInfo = (pubkey: string) => userInfoCache.get(pubkey); +export const setCachedUserInfo = (pubkey: string, info: any) => { + userInfoCache.set(pubkey, info); +}; + +// Add a rumour to the cache (used by subscription handlers) +export const cacheRumour = (userPubkey: string, rumour: any) => { + const cached = rumourCache.get(userPubkey); + if (cached && !cached.find((r: any) => r.id === rumour.id)) { + cached.push(rumour); + } +}; + // Returns the preferred relays of the user with the provided pubkey, // according to their kind-10050 event. export const getPreferredRelays = async (pubkey: string): Promise => { -- cgit v1.2.3