From 03d4fbcc48f1db4c49fc2c9a99ff6de242d620eb Mon Sep 17 00:00:00 2001 From: Igor Sirotin Date: Fri, 17 Nov 2023 15:42:24 +0000 Subject: [PATCH] fix: avoid duplicating UnfurlURLs requests (#12687) --- .../chat_content/input_area/controller.nim | 1 + .../chat_content/input_area/link_preview_cache.nim | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/app/modules/main/chat_section/chat_content/input_area/controller.nim b/src/app/modules/main/chat_section/chat_content/input_area/controller.nim index c59dd4b7e5..1c932ab85d 100644 --- a/src/app/modules/main/chat_section/chat_content/input_area/controller.nim +++ b/src/app/modules/main/chat_section/chat_content/input_area/controller.nim @@ -219,6 +219,7 @@ proc setText*(self: Controller, text: string, unfurlNewUrls: bool) = if self.getLinkPreviewEnabled() and len(newUrls) > 0: self.messageService.asyncUnfurlUrls(newUrls) + self.linkPreviewCache.markAsRequested(newUrls) proc linkPreviewsFromCache*(self: Controller, urls: seq[string]): Table[string, LinkPreview] = return self.linkPreviewCache.linkPreviews(urls) diff --git a/src/app/modules/main/chat_section/chat_content/input_area/link_preview_cache.nim b/src/app/modules/main/chat_section/chat_content/input_area/link_preview_cache.nim index 03bd950924..9e9df8351a 100644 --- a/src/app/modules/main/chat_section/chat_content/input_area/link_preview_cache.nim +++ b/src/app/modules/main/chat_section/chat_content/input_area/link_preview_cache.nim @@ -1,13 +1,15 @@ -import tables +import tables, sets import ../../../../../../app_service/service/message/dto/link_preview type LinkPreviewCache* = ref object cache: Table[string, LinkPreview] + requests: HashSet[string] proc newLinkPreiewCache*(): LinkPreviewCache = result = LinkPreviewCache() result.cache = initTable[string, LinkPreview]() + result.requests = initHashSet[string]() # Returns a table of link previews for given `urls`. # If url is not found in cache, it's skipped @@ -31,14 +33,22 @@ proc add*(self: LinkPreviewCache, linkPreviews: Table[string, LinkPreview]): seq for key, value in pairs(linkPreviews): result.add(key) self.cache[key] = value + self.requests.excl(key) + +# Marks the URL as requested. +# This should be used to avoid duplicating unfurl requests. +proc markAsRequested*(self: LinkPreviewCache, urls: seq[string]) = + for url in urls: + self.requests.incl(url) # Goes though given `urls` and returns a list # of urls not found in cache. proc unknownUrls*(self: LinkPreviewCache, urls: seq[string]): seq[string] = for url in urls: - if not self.cache.hasKey(url): + if not self.cache.hasKey(url) and not self.requests.contains(url): result.add(url) # Clears link preview cache proc clear*(self: LinkPreviewCache) = self.cache.clear() + self.requests.clear()