From 9c3bb706ce407d6165192c419e484989eaee7e7a Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 3 Nov 2026 11:30:26 -0800 Subject: [PATCH] Split HomePageIconDownloader from FeedIconDownloader. Save home page icon URLs by home page instead of by feed. --- .../HTMLMetadata/HTMLMetadataRecord.swift | 2 +- .../Sources/Images/FeedIconDownloader.swift | 318 ++---------------- .../Sources/Images/FeedIconURLTable.swift | 46 --- .../Images/HomePageIconDownloader.swift | 166 +++++++++ .../Sources/Images/HomePageIconTable.swift | 56 +++ .../Images/Sources/Images/ImageDatabase.swift | 54 ++- .../Sources/Images/SpecialCase+Icons.swift | 14 + .../ImagesTests/ImageDatabaseTests.swift | 33 +- Shared/IconImageCache.swift | 43 ++- 9 files changed, 376 insertions(+), 356 deletions(-) delete mode 100644 Modules/Images/Sources/Images/FeedIconURLTable.swift create mode 100644 Modules/Images/Sources/Images/HomePageIconDownloader.swift create mode 100644 Modules/Images/Sources/Images/HomePageIconTable.swift create mode 100644 Modules/Images/Sources/Images/SpecialCase+Icons.swift diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift index 364bfdf3b..acc11ae80 100644 --- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift +++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift @@ -101,7 +101,7 @@ public extension HTMLMetadataRecord { public extension HTMLMetadataRecord { - func bestWebsiteIconURL() -> String? { + func bestHomePageIconURL() -> String? { if let appleTouchIcon = largestAppleTouchIcon() { return appleTouchIcon } diff --git a/Modules/Images/Sources/Images/FeedIconDownloader.swift b/Modules/Images/Sources/Images/FeedIconDownloader.swift index 1f872bb6e..7e0009a5b 100644 --- a/Modules/Images/Sources/Images/FeedIconDownloader.swift +++ b/Modules/Images/Sources/Images/FeedIconDownloader.swift @@ -10,254 +10,68 @@ import Foundation import Account import RSCore import RSWeb -import HTMLMetadata import ActivityLog extension Notification.Name { - - public static let feedIconDidBecomeAvailable = Notification.Name("FeedIconDidBecomeAvailable") // userInfo key: "feed" + /// Posted when a feed’s icon loads or fails, or its icon URL changes. + /// userInfo key: `FeedIconDownloader.feedKey`. + public static let feedIconDidChange = Notification.Name("FeedIconDidChange") } +/// Gets the icon a feed specifies in the feed itself. @MainActor public final class FeedIconDownloader { public static let shared = FeedIconDownloader() + public static let feedKey = "feed" - private var homePagesWithNoIconURL = Set() - private var cache = [Feed: CachedIcon]() - private var waitingForFeedURLs = [String: Set]() - private var feedsWaitingForHTMLMetadata = Set() + private var feedsByIconURL = [String: Set]() // icon URL: feeds that looked it up init() { NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared) NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDownloadDidFail(_:)), name: .iconImageDownloadDidFail, object: IconImageDownloader.shared) - NotificationCenter.default.addObserver(self, selector: #selector(handleDownloadedImageDidChange(_:)), name: .downloadedImageDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleFeedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleHTMLMetadataAvailable(_:)), name: .htmlMetadataAvailable, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil) } - @objc func handleLowMemory(_ notification: Notification) { - cache.removeAll() + /// Unavailable when the feed specifies no icon, or its icon isn’t used. + public func feedIcon(for feed: Feed) -> IconLookup { + guard let iconURL = Self.iconURL(for: feed) else { + return .unavailable + } + feedsByIconURL[iconURL, default: Set()].insert(feed) + return IconImageDownloader.shared.iconImage(for: iconURL, activityOwner: .feedImageDownloader, activityKind: .downloadFeedImage(feedURL: iconURL), activityDetail: feed.nameForDisplay) } - @objc func handleAppDidGoToBackground(_ notification: Notification) { - cache.removeAll() - } - - public func icon(for feed: Feed) -> IconImage? { - - if let cachedIcon = cache[feed] { - requestOwnIconIfRetryWaitEnded(feed) - return cachedIcon.iconImage - } - - if Self.shouldSkipDownloadingFeedIcon(feed: feed) { - return nil - } - - @MainActor func checkHomePageURL() { - guard let homePageURL = feed.homePageURL else { - return - } - icon(forHomePageURL: homePageURL, feed: feed) { iconImage, iconURL in - if let iconImage, let iconURL, self.cacheIcon(iconImage, for: feed, isFeedOwnIcon: false) { - self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) - self.postFeedIconDidBecomeAvailableNotification(feed) - } - } - } - - @MainActor func checkSavedHomePageIconURL(_ savedIconURL: String) { - icon(forURL: savedIconURL, feed: feed) { iconImage, isDefinitive in - if let iconImage { - if self.cacheIcon(iconImage, for: feed, isFeedOwnIcon: false) { - self.postFeedIconDidBecomeAvailableNotification(feed) - } - } else if self.cache[feed] == nil, isDefinitive { - // The site may have moved its icon, so the home page is checked again. - checkHomePageURL() - } - } - } - - @MainActor func checkFeedIconURL() { - if let iconURL = feed.iconURL, !Self.shouldIgnoreFeedIconURL(feed) { - icon(forURL: iconURL, feed: feed) { (iconImage, isDefinitive) in - Task { @MainActor in - if let iconImage { - if self.cacheIcon(iconImage, for: feed, isFeedOwnIcon: true) { - self.postFeedIconDidBecomeAvailableNotification(feed) - } - } else if self.cache[feed] == nil, isDefinitive { - // The declared icon failed or isn’t an image. A still-downloading - // icon is no reason to fall back to the home page’s icon. - // - // A home page icon found earlier works without the home page’s metadata. - if let savedIconURL = ImageDatabase.shared.iconURL(forFeedURL: feed.url) { - checkSavedHomePageIconURL(savedIconURL) - } else { - checkHomePageURL() - } - } - } - } - } else { - checkHomePageURL() - } - } - - if let previouslyFoundIconURL = Self.savedHomePageIconURL(for: feed) { - checkSavedHomePageIconURL(previouslyFoundIconURL) - checkForNewHomePageIconURL(feed, savedIconURL: previouslyFoundIconURL) - - return nil - } - - checkFeedIconURL() - - return nil - } + // MARK: - Notifications @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) { - guard let url = notification.userInfo?[IconImageDownloader.urlKey] as? String, let feeds = waitingForFeedURLs[url] else { - return - } - // A single image URL may be shared by multiple feeds. - waitingForFeedURLs[url] = nil - for feed in feeds { - // A waiting feed with an icon is showing its home page icon until its own arrives. - cache[feed] = nil - _ = icon(for: feed) - } + postFeedIconDidChange(iconURL: notification.userInfo?[IconImageDownloader.urlKey] as? String) } - /// Feeds waiting on the failed URL look again, which falls back to the home page icon. @objc func handleIconImageDownloadDidFail(_ notification: Notification) { - guard let url = notification.userInfo?[IconImageDownloader.urlKey] as? String, let feeds = waitingForFeedURLs[url] else { - return - } - waitingForFeedURLs[url] = nil - for feed in feeds { - cache[feed] = nil - _ = icon(for: feed) - } + postFeedIconDidChange(iconURL: notification.userInfo?[IconImageDownloader.urlKey] as? String) } - /// `IconImageDownloader` makes the icon again, and feeds using it get their icon again when it’s ready. - @objc func handleDownloadedImageDidChange(_ notification: Notification) { - guard let url = notification.userInfo?[DownloadedImageCache.urlKey] as? String else { + @objc func handleFeedSettingDidChange(_ notification: Notification) { + guard let feed = notification.object as? Feed, let key = notification.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey, key == .iconURL else { return } - let feeds = cache.keys.filter { Self.iconURLs(for: $0).contains(url) } - for feed in feeds { - cache[feed] = nil - waitingForFeedURLs[url, default: Set()].insert(feed) - } - } - - @objc func handleFeedSettingDidChange(_ note: Notification) { - guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey else { - return - } - if key == .iconURL || key == .homePageURL { - // `IconImageCache` keeps showing the old icon until the new one is ready. - cache[feed] = nil - _ = icon(for: feed) - } - } - - @objc func handleHTMLMetadataAvailable(_ note: Notification) { - guard let url = note.userInfo?[HTMLMetadataUserInfoKey.url] as? String else { - return - } - homePagesWithNoIconURL.remove(url) - // A homepage URL may be shared by multiple feeds. - let feeds = feedsWaitingForHTMLMetadata.filter { $0.homePageURL == url } - feedsWaitingForHTMLMetadata.subtract(feeds) - for feed in feeds { - // A feed already showing its saved home page icon would return it without checking. - if cache[feed] != nil, let savedIconURL = Self.savedHomePageIconURL(for: feed) { - checkForNewHomePageIconURL(feed, savedIconURL: savedIconURL) - } else { - _ = icon(for: feed) - } - } + postFeedIconDidChange(feed) } } private extension FeedIconDownloader { - struct CachedIcon { - let iconImage: IconImage - let isFeedOwnIcon: Bool - } - - /// The feed’s own icon replaces its home page icon, but a home page icon never replaces the feed’s own. - func cacheIcon(_ iconImage: IconImage, for feed: Feed, isFeedOwnIcon: Bool) -> Bool { - if let cachedIcon = cache[feed], cachedIcon.isFeedOwnIcon || !isFeedOwnIcon { - return false - } - cache[feed] = CachedIcon(iconImage: iconImage, isFeedOwnIcon: isFeedOwnIcon) - return true - } - - static let specialCasesToSkip = ["macsparky.com", "xkcd.com", SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName] - - // Substrings matched (case-insensitive) anywhere in the feed URL. A match makes us ignore the - // feed-specified icon URL and fall back to the homepage icon lookup instead. + // Substrings matched (case-insensitive) anywhere in the feed URL. A match means the feed-specified icon isn’t used. static let feedURLSubstringsToIgnoreFeedIconURL: [String] = ["propublica.org", "clubic.com", "comptoir-hardware.com", "cowcotland", "404media.co", "awfulannouncing.com", "michalzelazny.com"] - static func shouldIgnoreFeedIconURL(_ feed: Feed) -> Bool { - SpecialCase.urlStringContainSpecialCase(feed.url, feedURLSubstringsToIgnoreFeedIconURL) - } - - /// The stored icon URL remembers an icon discovered via the home page. A feed - /// that declares its own icon supersedes it. - /// - static func savedHomePageIconURL(for feed: Feed) -> String? { - let feedDeclaresIconURL = feed.iconURL != nil && !shouldIgnoreFeedIconURL(feed) - if feedDeclaresIconURL { + static func iconURL(for feed: Feed) -> String? { + guard let iconURL = feed.iconURL else { return nil } - return ImageDatabase.shared.iconURL(forFeedURL: feed.url) - } - - /// The saved icon keeps working after a site adds a better icon or moves to a new one, - /// so the home page’s metadata is checked too. A different best icon replaces the saved one once it’s ready. - func checkForNewHomePageIconURL(_ feed: Feed, savedIconURL: String) { - guard let homePageURL = feed.homePageURL, !Self.shouldSkipDownloadingFeedIcon(homePageURL) else { - return + if SpecialCase.urlStringContainSpecialCase(feed.url, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) || SpecialCase.urlStringContainSpecialCase(feed.url, feedURLSubstringsToIgnoreFeedIconURL) { + return nil } - guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL) else { - feedsWaitingForHTMLMetadata.insert(feed) - return - } - guard let iconURL = metadata.bestWebsiteIconURL(), iconURL != savedIconURL else { - return - } - icon(forURL: iconURL, feed: feed) { iconImage, _ in - guard let iconImage else { - return - } - // Replaces the saved home page icon, which `cacheIcon` wouldn’t. - self.cache[feed] = CachedIcon(iconImage: iconImage, isFeedOwnIcon: false) - self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) - self.postFeedIconDidBecomeAvailableNotification(feed) - } - } - - static func shouldSkipDownloadingFeedIcon(feed: Feed) -> Bool { - shouldSkipDownloadingFeedIcon(feed.url) - } - - static func shouldSkipDownloadingFeedIcon(_ urlString: String) -> Bool { - SpecialCase.urlStringContainSpecialCase(urlString, specialCasesToSkip) - } - - /// The URLs a feed’s icon may have been made from: its own icon URL and the one found on its home page. - static func iconURLs(for feed: Feed) -> [String] { - [feed.iconURL, ImageDatabase.shared.iconURL(forFeedURL: feed.url)].compactMap { $0 }.map(sanitizedIconURL) + return sanitizedIconURL(iconURL) } static func sanitizedIconURL(_ url: String) -> String { @@ -274,86 +88,16 @@ private extension FeedIconDownloader { return components.string ?? url } - func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping @MainActor (IconImage?, String?) -> Void) { - if Self.shouldSkipDownloadingFeedIcon(homePageURL) { - resultBlock(nil, nil) + func postFeedIconDidChange(iconURL: String?) { + guard let iconURL, let feeds = feedsByIconURL[iconURL] else { return } - - if homePagesWithNoIconURL.contains(homePageURL) { - feedsWaitingForHTMLMetadata.insert(feed) - resultBlock(nil, nil) - return - } - - guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL) else { - feedsWaitingForHTMLMetadata.insert(feed) - resultBlock(nil, nil) - return - } - - if let url = metadata.bestWebsiteIconURL() { - homePagesWithNoIconURL.remove(homePageURL) - icon(forURL: url, feed: feed) { iconImage, _ in - Task { @MainActor in - resultBlock(iconImage, url) - } - } - return - } - - // The feed is checked again when the home page’s metadata refreshes. - homePagesWithNoIconURL.insert(homePageURL) - feedsWaitingForHTMLMetadata.insert(feed) - resultBlock(nil, nil) - } - - /// `isDefinitive` is false when the icon is still loading — `handleIconImageDidBecomeAvailable` - /// re-runs icon(for:) when it arrives. - /// - /// After a transient failure, `isDefinitive` is true, so the caller can fall back to the home page icon, - /// and the feed still waits for this icon, which replaces the fallback when it arrives. - func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @MainActor (IconImage?, _ isDefinitive: Bool) -> Void) { - let url = Self.sanitizedIconURL(url) - switch iconImage(for: url, feed: feed) { - case .found(let iconImage): - imageResultBlock(iconImage, true) - case .loading: - waitingForFeedURLs[url, default: Set()].insert(feed) - imageResultBlock(nil, false) - case .unavailable: - if DownloadedImageCache.shared.isWaitingToRetry(url) { - waitingForFeedURLs[url, default: Set()].insert(feed) - } - imageResultBlock(nil, true) + for feed in feeds { + postFeedIconDidChange(feed) } } - func iconImage(for url: String, feed: Feed) -> IconLookup { - IconImageDownloader.shared.iconImage(for: url, activityOwner: .feedImageDownloader, activityKind: .downloadFeedImage(feedURL: url), activityDetail: feed.nameForDisplay) - } - - /// A feed showing its home page icon while it waits for its own requests it again once the retry wait ends. - func requestOwnIconIfRetryWaitEnded(_ feed: Feed) { - guard let iconURL = feed.iconURL, !Self.shouldIgnoreFeedIconURL(feed) else { - return - } - let url = Self.sanitizedIconURL(iconURL) - guard waitingForFeedURLs[url]?.contains(feed) == true, !DownloadedImageCache.shared.isWaitingToRetry(url) else { - return - } - _ = iconImage(for: url, feed: feed) - } - - func postFeedIconDidBecomeAvailableNotification(_ feed: Feed) { - - DispatchQueue.main.async { - let userInfo: [AnyHashable: Any] = ["feed": feed] - NotificationCenter.default.post(name: .feedIconDidBecomeAvailable, object: self, userInfo: userInfo) - } - } - - func cacheIconURLForFeedURL(iconURL: String, feedURL: String) { - ImageDatabase.shared.saveFeedIconURL(feedURL: feedURL, iconURL: iconURL) + func postFeedIconDidChange(_ feed: Feed) { + NotificationCenter.default.post(name: .feedIconDidChange, object: self, userInfo: [Self.feedKey: feed]) } } diff --git a/Modules/Images/Sources/Images/FeedIconURLTable.swift b/Modules/Images/Sources/Images/FeedIconURLTable.swift deleted file mode 100644 index 200ece492..000000000 --- a/Modules/Images/Sources/Images/FeedIconURLTable.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// FeedIconURLTable.swift -// Images -// -// Created by Brent Simmons on 5/28/26. -// - -import Foundation -import RSDatabase -import RSDatabaseObjC - -struct FeedIconURLTable { - - static let name = "feedIconURL" - - private struct Column { - static let feedURL = "feedURL" - static let iconURL = "iconURL" - } - - static func fetchAll(database: FMDatabase) -> [String: String] { - var results = [String: String]() - guard let resultSet = database.executeQuery("SELECT \(Column.feedURL), \(Column.iconURL) FROM \(name);", withArgumentsIn: []) else { - return results - } - defer { - resultSet.close() - } - while resultSet.next() { - guard let feedURL = resultSet.string(forColumn: Column.feedURL), - let iconURL = resultSet.string(forColumn: Column.iconURL) else { - continue - } - results[feedURL] = iconURL - } - return results - } - - static func save(feedURL: String, iconURL: String, database: FMDatabase) { - let dictionary: DatabaseDictionary = [ - Column.feedURL: feedURL, - Column.iconURL: iconURL - ] - database.insertRow(dictionary, insertType: .orReplace, tableName: name) - } -} diff --git a/Modules/Images/Sources/Images/HomePageIconDownloader.swift b/Modules/Images/Sources/Images/HomePageIconDownloader.swift new file mode 100644 index 000000000..ed8946ff0 --- /dev/null +++ b/Modules/Images/Sources/Images/HomePageIconDownloader.swift @@ -0,0 +1,166 @@ +// +// HomePageIconDownloader.swift +// Images +// +// Created by Brent Simmons on 11/3/26. +// + +import Foundation +import Account +import RSCore +import RSWeb +import HTMLMetadata +import ActivityLog + +extension Notification.Name { + /// Posted when a home page’s icon loads or fails, or its icon URL changes. + /// userInfo key: `HomePageIconDownloader.feedsKey` (`Set`, the feeds that looked up that home page). + public static let homePageIconDidChange = Notification.Name("HomePageIconDidChange") +} + +/// Gets the icon a feed’s home page specifies in its metadata: an apple-touch-icon, og:image, or twitter:image. +/// +/// The icon URL is saved, so it works at launch, before the home page’s metadata is in memory. +/// A site may add, change, or move its icon, so once per session, and whenever the home page’s metadata +/// arrives, a different icon URL in the metadata replaces the saved one once its image loads. +@MainActor public final class HomePageIconDownloader { + + public static let shared = HomePageIconDownloader() + public static let feedsKey = "feeds" + + private var feedsByHomePageURL = [String: Set]() // home page URL: feeds that looked it up + private var homePagesCheckedForNewIconURL = Set() + private var newIconURLs = [String: String]() // home page URL: icon URL that replaces the saved one once its image loads + + init() { + NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared) + NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDownloadDidFail(_:)), name: .iconImageDownloadDidFail, object: IconImageDownloader.shared) + NotificationCenter.default.addObserver(self, selector: #selector(handleHTMLMetadataAvailable(_:)), name: .htmlMetadataAvailable, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil) + } + + /// Unavailable while the home page’s metadata isn’t in memory. `.homePageIconDidChange` follows when it arrives. + public func homePageIcon(for feed: Feed) -> IconLookup { + guard let homePageURL = Self.homePageURL(for: feed) else { + return .unavailable + } + feedsByHomePageURL[homePageURL, default: Set()].insert(feed) + + if let savedIconURL = ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) { + if homePagesCheckedForNewIconURL.insert(homePageURL).inserted { + checkForNewIconURL(homePageURL: homePageURL, savedIconURL: savedIconURL) + } + return iconImage(for: savedIconURL, homePageURL: homePageURL) + } + + if ImageDatabase.shared.homePageHasNoIcon(homePageURL) { + return .unavailable + } + guard let iconURL = iconURLFromMetadata(homePageURL: homePageURL) else { + return .unavailable + } + return iconImage(for: iconURL, homePageURL: homePageURL) + } + + // MARK: - Notifications + + @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) { + guard let iconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String else { + return + } + for (homePageURL, newIconURL) in newIconURLs where newIconURL == iconURL { + newIconURLs[homePageURL] = nil + ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: newIconURL) + } + postHomePageIconDidChange(iconURL: iconURL) + } + + /// Feeds showing this icon look again, which falls back to the next source. + @objc func handleIconImageDownloadDidFail(_ notification: Notification) { + guard let iconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String else { + return + } + newIconURLs = newIconURLs.filter { $0.value != iconURL } + postHomePageIconDidChange(iconURL: iconURL) + } + + @objc func handleHTMLMetadataAvailable(_ notification: Notification) { + guard let homePageURL = notification.userInfo?[HTMLMetadataUserInfoKey.url] as? String, feedsByHomePageURL[homePageURL] != nil else { + return + } + homePagesCheckedForNewIconURL.insert(homePageURL) + if let savedIconURL = ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) { + checkForNewIconURL(homePageURL: homePageURL, savedIconURL: savedIconURL) + } else if iconURLFromMetadata(homePageURL: homePageURL) != nil { + postHomePageIconDidChange(homePageURL: homePageURL) + } + } + + @objc func handleFeedSettingDidChange(_ notification: Notification) { + guard let feed = notification.object as? Feed, let key = notification.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey, key == .homePageURL else { + return + } + NotificationCenter.default.post(name: .homePageIconDidChange, object: self, userInfo: [Self.feedsKey: Set([feed])]) + } +} + +private extension HomePageIconDownloader { + + static func homePageURL(for feed: Feed) -> String? { + guard let homePageURL = feed.homePageURL else { + return nil + } + if SpecialCase.urlStringContainSpecialCase(feed.url, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) || SpecialCase.urlStringContainSpecialCase(homePageURL, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) { + return nil + } + return homePageURL.normalizedURL + } + + /// Saves the icon URL, or that there is none. Nil when the metadata isn’t in memory, + /// in which case this starts loading it, and `.htmlMetadataAvailable` follows. + func iconURLFromMetadata(homePageURL: String) -> String? { + guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL) else { + return nil + } + let iconURL = metadata.bestHomePageIconURL() + ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL) + return iconURL + } + + /// The saved icon keeps working if the new one fails, or if the metadata no longer specifies an icon. + func checkForNewIconURL(homePageURL: String, savedIconURL: String) { + guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL), let iconURL = metadata.bestHomePageIconURL(), iconURL != savedIconURL else { + return + } + switch iconImage(for: iconURL, homePageURL: homePageURL) { + case .found: + ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL) + // Called during a lookup, so the change is posted afterward. + Task { @MainActor in + postHomePageIconDidChange(homePageURL: homePageURL) + } + case .loading: + // When it loads, `handleIconImageDidBecomeAvailable` saves it. + newIconURLs[homePageURL] = iconURL + case .unavailable: + break + } + } + + func iconImage(for iconURL: String, homePageURL: String) -> IconLookup { + IconImageDownloader.shared.iconImage(for: iconURL, activityOwner: .feedImageDownloader, activityKind: .downloadFeedImage(feedURL: iconURL), activityDetail: homePageURL) + } + + func postHomePageIconDidChange(iconURL: String) { + for homePageURL in feedsByHomePageURL.keys where ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) == iconURL { + postHomePageIconDidChange(homePageURL: homePageURL) + } + } + + func postHomePageIconDidChange(homePageURL: String) { + guard let feeds = feedsByHomePageURL[homePageURL] else { + return + } + NotificationCenter.default.post(name: .homePageIconDidChange, object: self, userInfo: [Self.feedsKey: feeds]) + } +} diff --git a/Modules/Images/Sources/Images/HomePageIconTable.swift b/Modules/Images/Sources/Images/HomePageIconTable.swift new file mode 100644 index 000000000..cc91f3ce3 --- /dev/null +++ b/Modules/Images/Sources/Images/HomePageIconTable.swift @@ -0,0 +1,56 @@ +// +// HomePageIconTable.swift +// Images +// +// Created by Brent Simmons on 5/28/26. +// + +import Foundation +import RSDatabase +import RSDatabaseObjC + +/// `iconURL` is `nil` when the home page’s metadata specifies no icon. +struct HomePageIconRecord: Sendable { + let homePageURL: String + let iconURL: String? + let lastChecked: Date +} + +struct HomePageIconTable { + + static let name = "homePageIcon" + + private struct Column { + static let homePageURL = "homePageURL" + static let iconURL = "iconURL" + static let lastChecked = "lastChecked" + } + + static func fetchAll(database: FMDatabase) -> [HomePageIconRecord] { + var results = [HomePageIconRecord]() + guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.iconURL), \(Column.lastChecked) FROM \(name);", withArgumentsIn: []) else { + return results + } + defer { + resultSet.close() + } + while resultSet.next() { + guard let homePageURL = resultSet.string(forColumn: Column.homePageURL) else { + continue + } + let iconURL = resultSet.string(forColumn: Column.iconURL) + let lastChecked = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastChecked)) + results.append(HomePageIconRecord(homePageURL: homePageURL, iconURL: iconURL, lastChecked: lastChecked)) + } + return results + } + + static func save(homePageURL: String, iconURL: String?, database: FMDatabase) { + let dictionary: DatabaseDictionary = [ + Column.homePageURL: homePageURL, + Column.iconURL: iconURL as Any, + Column.lastChecked: Date().timeIntervalSince1970 + ] + database.insertRow(dictionary, insertType: .orReplace, tableName: name) + } +} diff --git a/Modules/Images/Sources/Images/ImageDatabase.swift b/Modules/Images/Sources/Images/ImageDatabase.swift index 67773635f..abdb1d680 100644 --- a/Modules/Images/Sources/Images/ImageDatabase.swift +++ b/Modules/Images/Sources/Images/ImageDatabase.swift @@ -27,14 +27,15 @@ import RSParser private var homePageToFaviconURL = [String: String]() private var noFaviconDates = [String: Date]() // homePageURL: when no favicon was found - private var feedURLToIconURL = [String: String]() + private var homePageToIconURL = [String: String]() + private var noIconDates = [String: Date]() // homePageURL: when no icon was found private var failureDates = [String: Date]() private var urlsUnsuitableForThumbnails = Set() private static let tableCreationStatements = """ CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, lastChecked REAL NOT NULL); CREATE TABLE IF NOT EXISTS homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL); - CREATE TABLE IF NOT EXISTS feedIconURL (feedURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS homePageIcon (homePageURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT, lastChecked REAL NOT NULL); CREATE TABLE IF NOT EXISTS downloadedImage (url TEXT PRIMARY KEY NOT NULL, pixelWidth INTEGER, pixelHeight INTEGER, lastAccessed REAL NOT NULL, etag TEXT, lastModified TEXT, nextCheck REAL NOT NULL, isIcon INTEGER NOT NULL DEFAULT 0); """ @@ -44,8 +45,7 @@ import RSParser /// Tables and columns imported from ImageMetadata.db, which shipped before Images.db replaced it. nonisolated private static let legacyTableColumns = [ (table: "downloadFailure", columns: "url, lastChecked"), - (table: "homePageFavicon", columns: "homePageURL, faviconURL, lastChecked"), - (table: "feedIconURL", columns: "feedURL, iconURL") + (table: "homePageFavicon", columns: "homePageURL, faviconURL, lastChecked") ] private convenience init() { @@ -70,6 +70,8 @@ import RSParser let failureCutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.failureRetryDays) queue.runInDatabase { database in + // Replaced by homePageIcon. Its home page icon URLs are found again from the home pages’ metadata. + database.executeStatements("DROP TABLE IF EXISTS feedIconURL;") DownloadFailureTable.removeExpired(olderThan: failureCutoff, database: database) database.checkpoint() } @@ -113,16 +115,30 @@ import RSParser } } - // MARK: - FeedIconURL + // MARK: - HomePageIcon - public func iconURL(forFeedURL feedURL: String) -> String? { - feedURLToIconURL[feedURL] + public func homePageIconURL(forHomePageURL homePageURL: String) -> String? { + homePageToIconURL[homePageURL] } - public func saveFeedIconURL(feedURL: String, iconURL: String) { - feedURLToIconURL[feedURL] = iconURL + /// A no-icon verdict expires after `failureRetryDays`, so the home page gets checked again. + public func homePageHasNoIcon(_ homePageURL: String) -> Bool { + guard let noIconDate = noIconDates[homePageURL] else { + return false + } + return Date().timeIntervalSince(noIconDate) < TimeInterval(days: Self.failureRetryDays) + } + + public func saveHomePageIcon(homePageURL: String, iconURL: String?) { + if let iconURL { + homePageToIconURL[homePageURL] = iconURL + noIconDates.removeValue(forKey: homePageURL) + } else { + noIconDates[homePageURL] = Date() + homePageToIconURL.removeValue(forKey: homePageURL) + } queue.runInDatabase { database in - FeedIconURLTable.save(feedURL: feedURL, iconURL: iconURL, database: database) + HomePageIconTable.save(homePageURL: homePageURL, iconURL: iconURL, database: database) } } @@ -255,11 +271,11 @@ private extension ImageDatabase { func loadCachesFromDatabase() { nonisolated(unsafe) var homePageRecords = [HomePageFaviconRecord]() - nonisolated(unsafe) var feedIcons = [String: String]() + nonisolated(unsafe) var homePageIconRecords = [HomePageIconRecord]() nonisolated(unsafe) var failures = [String: Date]() nonisolated(unsafe) var pixelSizes = [(url: String, pixelSize: (width: Int, height: Int)?)]() nonisolated(unsafe) var homePageDuration: TimeInterval = 0 - nonisolated(unsafe) var feedIconDuration: TimeInterval = 0 + nonisolated(unsafe) var homePageIconDuration: TimeInterval = 0 nonisolated(unsafe) var failureDuration: TimeInterval = 0 nonisolated(unsafe) var pixelSizeDuration: TimeInterval = 0 @@ -270,8 +286,8 @@ private extension ImageDatabase { homePageDuration = Date().timeIntervalSince(stepStart) stepStart = Date() - feedIcons = FeedIconURLTable.fetchAll(database: database) - feedIconDuration = Date().timeIntervalSince(stepStart) + homePageIconRecords = HomePageIconTable.fetchAll(database: database) + homePageIconDuration = Date().timeIntervalSince(stepStart) stepStart = Date() failures = DownloadFailureTable.fetchAll(database: database) @@ -290,10 +306,16 @@ private extension ImageDatabase { noFaviconDates[record.homePageURL] = record.lastChecked } } - feedURLToIconURL = feedIcons + for record in homePageIconRecords { + if let iconURL = record.iconURL { + homePageToIconURL[record.homePageURL] = iconURL + } else { + noIconDates[record.homePageURL] = record.lastChecked + } + } failureDates = failures urlsUnsuitableForThumbnails = Set(pixelSizes.filter { !Self.isSuitableForThumbnail($0.pixelSize) }.map(\.url)) - Self.logger.info("Initial fetches: homePageFavicon \(homePageRecords.count) rows in \(homePageDuration) seconds, feedIconURL \(feedIcons.count) rows in \(feedIconDuration) seconds, downloadFailure \(failures.count) rows in \(failureDuration) seconds, downloadedImage \(pixelSizes.count) rows in \(pixelSizeDuration) seconds, total \(totalDuration) seconds") + Self.logger.info("Initial fetches: homePageFavicon \(homePageRecords.count) rows in \(homePageDuration) seconds, homePageIcon \(homePageIconRecords.count) rows in \(homePageIconDuration) seconds, downloadFailure \(failures.count) rows in \(failureDuration) seconds, downloadedImage \(pixelSizes.count) rows in \(pixelSizeDuration) seconds, total \(totalDuration) seconds") } } diff --git a/Modules/Images/Sources/Images/SpecialCase+Icons.swift b/Modules/Images/Sources/Images/SpecialCase+Icons.swift new file mode 100644 index 000000000..320eede74 --- /dev/null +++ b/Modules/Images/Sources/Images/SpecialCase+Icons.swift @@ -0,0 +1,14 @@ +// +// SpecialCase+Icons.swift +// Images +// +// Created by Brent Simmons on 11/3/26. +// + +import Foundation +import RSWeb + +extension SpecialCase { + /// Matched anywhere in the feed URL or home page URL. A match means neither the feed icon nor the home page icon is used. + static let hostNamesWithoutFeedOrHomePageIcons = ["macsparky.com", "xkcd.com", SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName] +} diff --git a/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift index 1ecced3d9..0d25a28b4 100644 --- a/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift +++ b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift @@ -27,7 +27,6 @@ import RSWeb let imageDatabase = ImageDatabase(databasePath: databasePath, legacyDatabasePath: legacyDatabasePath) #expect(imageDatabase.faviconURL(forHomePageURL: "https://example.com/") == "https://example.com/favicon.ico") - #expect(imageDatabase.iconURL(forFeedURL: "https://example.com/feed.xml") == "https://example.com/icon.png") #expect(imageDatabase.recentlyFailed(url: "https://example.com/missing.png")) #expect(!FileManager.default.fileExists(atPath: legacyDatabasePath)) @@ -35,6 +34,36 @@ import RSWeb await imageDatabase.vacuum() } + @Test func homePageIconsAreSavedAndReloaded() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { + try? FileManager.default.removeItem(at: folder) + } + let databasePath = folder.appendingPathComponent("Images.db").path + let homePageURL = "https://daringfireball.net/" + let iconURL = "https://daringfireball.net/graphics/apple-touch-icon.png" + let homePageURLWithNoIcon = "https://inessential.com/" + + let imageDatabase = ImageDatabase(databasePath: databasePath) + imageDatabase.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL) + imageDatabase.saveHomePageIcon(homePageURL: homePageURLWithNoIcon, iconURL: nil) + + // Waits for the saves, so the database opened below sees them. + await imageDatabase.vacuum() + + let reopenedImageDatabase = ImageDatabase(databasePath: databasePath) + for database in [imageDatabase, reopenedImageDatabase] { + #expect(database.homePageIconURL(forHomePageURL: homePageURL) == iconURL) + #expect(!database.homePageHasNoIcon(homePageURL)) + #expect(database.homePageIconURL(forHomePageURL: homePageURLWithNoIcon) == nil) + #expect(database.homePageHasNoIcon(homePageURLWithNoIcon)) + } + + // Waits for the cleanup init queues, which would otherwise run after the folder is deleted. + await reopenedImageDatabase.vacuum() + } + @Test func failedUsageQueryReturnsNil() { let database = FMDatabase.openAndSetUpDatabase(path: ":memory:") defer { @@ -92,11 +121,9 @@ private extension ImageDatabaseTests { database.executeStatements(""" CREATE TABLE downloadFailure (url TEXT PRIMARY KEY NOT NULL, statusCode INTEGER, lastChecked REAL NOT NULL); CREATE TABLE homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL); - CREATE TABLE feedIconURL (feedURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT NOT NULL, lastChecked REAL NOT NULL); """) database.executeUpdate("INSERT INTO downloadFailure (url, statusCode, lastChecked) VALUES (?, ?, ?)", withArgumentsIn: ["https://example.com/missing.png", 404, lastChecked]) database.executeUpdate("INSERT INTO homePageFavicon (homePageURL, faviconURL, lastChecked) VALUES (?, ?, ?)", withArgumentsIn: ["https://example.com/", "https://example.com/favicon.ico", lastChecked]) - database.executeUpdate("INSERT INTO feedIconURL (feedURL, iconURL, lastChecked) VALUES (?, ?, ?)", withArgumentsIn: ["https://example.com/feed.xml", "https://example.com/icon.png", lastChecked]) database.close() } } diff --git a/Shared/IconImageCache.swift b/Shared/IconImageCache.swift index ffb3f567d..492f5e8ab 100644 --- a/Shared/IconImageCache.swift +++ b/Shared/IconImageCache.swift @@ -12,6 +12,11 @@ import Articles import RSCore import Images +extension Notification.Name { + /// Posted when a feed’s feed icon or home page icon loads, fails, or changes. userInfo key: `UserInfoKey.feed`. + static let feedIconDidBecomeAvailable = Notification.Name("FeedIconDidBecomeAvailable") +} + @MainActor final class IconImageCache { static var shared = IconImageCache() @@ -24,12 +29,30 @@ import Images init() { NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconDidChange(_:)), name: .feedIconDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleHomePageIconDidChange(_:)), name: .homePageIconDidChange, object: nil) } @objc func handleLowMemory(_ notification: Notification) { emptyCache() } + @objc func handleFeedIconDidChange(_ notification: Notification) { + guard let feed = notification.userInfo?[FeedIconDownloader.feedKey] as? Feed else { + return + } + postFeedIconDidBecomeAvailable(feed) + } + + @objc func handleHomePageIconDidChange(_ notification: Notification) { + guard let feeds = notification.userInfo?[HomePageIconDownloader.feedsKey] as? Set else { + return + } + for feed in feeds { + postFeedIconDidBecomeAvailable(feed) + } + } + func imageFor(_ feedID: SidebarItemIdentifier) -> IconImage? { if let smartFeed = SmartFeedsController.shared.find(by: feedID) { return imageForFeed(smartFeed) @@ -75,7 +98,7 @@ import Images if let feed = article.feed, let feedID = feed.sidebarItemID, !feedsSeen.contains(feedID) { feedsSeen.insert(feedID) - _ = FeedIconDownloader.shared.icon(for: feed) + _ = feedOrHomePageIcon(feed) _ = FaviconDownloader.shared.faviconAsIcon(for: feed) } } @@ -83,7 +106,7 @@ import Images func prefetchImagesForFeeds(_ feeds: [Feed]) { for feed in feeds { - _ = FeedIconDownloader.shared.icon(for: feed) + _ = feedOrHomePageIcon(feed) _ = FaviconDownloader.shared.faviconAsIcon(for: feed) } } @@ -118,6 +141,20 @@ private extension IconImageCache { return feed.url.hasPrefix("https://ranchero.com/downloads/netnewswire") } + /// Precedence: feed icon, then home page icon. + /// A feed icon that’s loading keeps the home page icon from being looked up. + func feedOrHomePageIcon(_ feed: Feed) -> IconLookup { + let feedIcon = FeedIconDownloader.shared.feedIcon(for: feed) + guard case .unavailable = feedIcon else { + return feedIcon + } + return HomePageIconDownloader.shared.homePageIcon(for: feed) + } + + func postFeedIconDidBecomeAvailable(_ feed: Feed) { + NotificationCenter.default.post(name: .feedIconDidBecomeAvailable, object: self, userInfo: [UserInfoKey.feed: feed]) + } + func imageForSmartFeed(_ smartFeed: PseudoFeed, _ feedID: SidebarItemIdentifier) -> IconImage? { if let iconImage = smartFeedIconImageCache[feedID] { return iconImage @@ -139,7 +176,7 @@ private extension IconImageCache { // keep the last known icons across the downloaders’ low-memory and background flushes. // // A miss requests the feed icon, so it comes back after a flush without waiting for a prefetch. - if let iconImage = FeedIconDownloader.shared.icon(for: feed) { + if let iconImage = feedOrHomePageIcon(feed).iconImage { feedIconImageCache[feedID] = iconImage return iconImage }