From 49c23da9e09759a7804c0b521e07063b198cf7cd Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Thu, 28 May 2026 09:28:06 -0700 Subject: [PATCH] Do icon prefetch instead of on demand by cell, add activity reporting for downloading images, add CloudKit no change back-off, and remove backslashes from HTMLMetadata JSON encoding. --- .../ActivityLogWindowController.swift | 10 +++++- Mac/Activity/ActivityWindowController.swift | 24 ++++++++++++-- .../Timeline/TimelineViewController.swift | 1 + .../CloudKit/CloudKitAccountDelegate.swift | 32 +++++++++++++++++++ .../CloudKitAccountZoneDelegate.swift | 7 ++++ .../CloudKitArticlesZoneDelegate.swift | 7 ++++ .../Sources/ActivityLog/ActivityKind.swift | 2 ++ .../Sources/ActivityLog/ActivityOwner.swift | 2 ++ .../HTMLMetadata/HTMLMetadataTable.swift | 9 ++++-- Shared/Favicons/FaviconDownloader.swift | 6 ++++ Shared/Favicons/SingleFaviconDownloader.swift | 9 ++++++ Shared/IconImageCache.swift | 29 +++++++++++++++-- Shared/Images/AuthorAvatarDownloader.swift | 23 +++++++++++++ Shared/Images/FeedIconDownloader.swift | 30 +++++++++++++++++ iOS/SceneCoordinator.swift | 1 + 15 files changed, 184 insertions(+), 8 deletions(-) diff --git a/Mac/Activity/ActivityLogWindowController.swift b/Mac/Activity/ActivityLogWindowController.swift index 541b13579..1d66d39e0 100644 --- a/Mac/Activity/ActivityLogWindowController.swift +++ b/Mac/Activity/ActivityLogWindowController.swift @@ -461,6 +461,10 @@ private extension ActivityLogWindowController { return "Feed Finder" case .feedImageDownloader: return "Feed Images" + case .faviconDownloader: + return "Favicons" + case .avatarDownloader: + return "Avatars" case .htmlMetadataDownloader: return "HTML Metadata" } @@ -489,6 +493,10 @@ private extension ActivityLogWindowController { return "Finding feed \(urlString)" case .downloadFeedImage(let feedURL): return "Downloading image \(feedURL)" + case .downloadFavicon(let faviconURL): + return "Downloading favicon \(faviconURL)" + case .downloadAvatar(let avatarURL): + return "Downloading avatar \(avatarURL)" case .downloadHTMLMetadata(let urlString): return "Downloading metadata \(urlString)" } @@ -501,7 +509,7 @@ private extension ActivityLogWindowController { return .secondaryLabelColor } return account.type.logColor - case .app, .feedFinder, .feedImageDownloader, .htmlMetadataDownloader: + case .app, .feedFinder, .feedImageDownloader, .faviconDownloader, .avatarDownloader, .htmlMetadataDownloader: return .secondaryLabelColor } } diff --git a/Mac/Activity/ActivityWindowController.swift b/Mac/Activity/ActivityWindowController.swift index 82e497ebc..463041909 100644 --- a/Mac/Activity/ActivityWindowController.swift +++ b/Mac/Activity/ActivityWindowController.swift @@ -385,6 +385,10 @@ private extension ActivityWindowController { return NSLocalizedString("Feed Finder", comment: "Activity owner name") case .feedImageDownloader: return NSLocalizedString("Feed Images", comment: "Activity owner name") + case .faviconDownloader: + return NSLocalizedString("Favicons", comment: "Activity owner name") + case .avatarDownloader: + return NSLocalizedString("Avatars", comment: "Activity owner name") case .htmlMetadataDownloader: return NSLocalizedString("HTML Metadata", comment: "Activity owner name") } @@ -416,13 +420,29 @@ private extension ActivityWindowController { let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes) result.append(NSAttributedString(string: feedURL, attributes: secondaryAttributes)) return result + case .downloadFavicon(let faviconURL): + let prefix = NSLocalizedString("Downloading favicon", comment: "Activity kind — downloading favicon") + let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes) + result.append(NSAttributedString(string: faviconURL, attributes: secondaryAttributes)) + return result + case .downloadAvatar(let avatarURL): + let prefix = NSLocalizedString("Downloading avatar", comment: "Activity kind — downloading avatar") + let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes) + result.append(NSAttributedString(string: avatarURL, attributes: secondaryAttributes)) + return result case .downloadHTMLMetadata(let urlString): let prefix = NSLocalizedString("Downloading metadata", comment: "Activity kind — downloading HTML metadata") let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes) result.append(NSAttributedString(string: urlString, attributes: secondaryAttributes)) return result default: - return NSAttributedString(string: plainDisplayName(for: activity.kind), attributes: primaryAttributes) + let name = plainDisplayName(for: activity.kind) + if let detail = activity.detail { + let result = NSMutableAttributedString(string: name, attributes: primaryAttributes) + result.append(NSAttributedString(string: " \(detail)", attributes: secondaryAttributes)) + return result + } + return NSAttributedString(string: name, attributes: primaryAttributes) } } @@ -440,7 +460,7 @@ private extension ActivityWindowController { return NSLocalizedString("Refreshing missing articles", comment: "Activity kind") case .importOPML: return NSLocalizedString("Importing OPML", comment: "Activity kind") - case .refreshFeedContent, .findFeed, .downloadFeedImage, .downloadHTMLMetadata: + case .refreshFeedContent, .findFeed, .downloadFeedImage, .downloadFavicon, .downloadAvatar, .downloadHTMLMetadata: return "" } } diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index d7ac791f1..62c1e79eb 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -147,6 +147,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr articleRowMap = [String: [Int]]() tableView.reloadData() + IconImageCache.shared.prefetchImagesForArticles(articles) } } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 7be224f63..ac7424443 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -52,6 +52,9 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { private let refresher: LocalAccountRefresher private var syncErrorHandler: CloudKitSyncErrorHandler? + private var lastNoChangeSyncDate: Date? + private static let noChangeBackoffInterval: TimeInterval = 30 * 60 + weak var account: Account? let behaviors: AccountBehaviors = [] @@ -103,6 +106,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async { + lastNoChangeSyncDate = nil Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") await withCheckedContinuation { continuation in let op = CloudKitRemoteNotificationOperation(accountZone: accountZone, articlesZone: articlesZone, accountID: account.accountID, userInfo: userInfo) @@ -132,12 +136,39 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { func syncArticleStatus(for account: Account) async throws { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") + + if let lastNoChangeSyncDate, Date().timeIntervalSince(lastNoChangeSyncDate) < Self.noChangeBackoffInterval { + Self.logger.debug("CloudKitAccountDelegate: Skipping sync — no changes on last check, backing off") + return + } + try await sendArticleStatus(for: account) try await refreshArticleStatus(for: account) + + if articlesZoneHasNoChanges && accountZoneHasNoChanges { + lastNoChangeSyncDate = Date() + } else { + lastNoChangeSyncDate = nil + } + await cleanUpContentRecordsIfNeeded() Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } + private var articlesZoneHasNoChanges: Bool { + guard let delegate = articlesZone.delegate as? CloudKitArticlesZoneDelegate else { + return true + } + return delegate.lastChangedCount == 0 && delegate.lastDeletedCount == 0 + } + + private var accountZoneHasNoChanges: Bool { + guard let delegate = accountZone.delegate as? CloudKitAcountZoneDelegate else { + return true + } + return delegate.lastChangedCount == 0 && delegate.lastDeletedCount == 0 + } + func sendArticleStatus(for account: Account) async throws { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try await sendArticleStatus(account: account, showProgress: false) @@ -573,6 +604,7 @@ private extension CloudKitAccountDelegate { } func performRefreshAll(for account: Account, sendArticleStatus: Bool) async throws { + lastNoChangeSyncDate = nil Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) sendArticleStatus: \(sendArticleStatus ? "true" : "false")") defer { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift index 2ad54ca7c..0f2318341 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift @@ -23,12 +23,19 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { weak var account: Account? weak var articlesZone: CloudKitArticlesZone? + /// Number of records changed in the most recent sync. + private(set) var lastChangedCount = 0 + /// Number of records deleted in the most recent sync. + private(set) var lastDeletedCount = 0 + init(account: Account, articlesZone: CloudKitArticlesZone) { self.account = account self.articlesZone = articlesZone } @MainActor func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey]) async throws { + lastChangedCount = changed.count + lastDeletedCount = deleted.count for deletedRecordKey in deleted { switch deletedRecordKey.recordType { case CloudKitAccountZone.CloudKitFeed.recordType: diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index de733137a..5bc8a5723 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -26,6 +26,11 @@ final class CloudKitArticlesZoneDelegate: CloudKitZoneDelegate { weak var articlesZone: CloudKitArticlesZone? let syncErrorHandler: CloudKitSyncErrorHandler? + /// Number of records changed in the most recent sync. + private(set) var lastChangedCount = 0 + /// Number of records deleted in the most recent sync. + private(set) var lastDeletedCount = 0 + init(account: Account, database: SyncDatabase, articlesZone: CloudKitArticlesZone, syncErrorHandler: CloudKitSyncErrorHandler?) { self.account = account self.syncDatabase = database @@ -34,6 +39,8 @@ final class CloudKitArticlesZoneDelegate: CloudKitZoneDelegate { } func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey]) async throws { + lastChangedCount = changed.count + lastDeletedCount = deleted.count do { let pendingReadStatusArticleIDs = try await syncDatabase.selectPendingReadStatusArticleIDs() ?? Set() let pendingStarredStatusArticleIDs = try await syncDatabase.selectPendingStarredStatusArticleIDs() ?? Set() diff --git a/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift b/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift index 190982682..06db3ab9f 100644 --- a/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift +++ b/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift @@ -26,5 +26,7 @@ public enum ActivityKind: Sendable, Hashable { case findFeed(urlString: String) case downloadFeedImage(feedURL: String) + case downloadFavicon(faviconURL: String) + case downloadAvatar(avatarURL: String) case downloadHTMLMetadata(urlString: String) } diff --git a/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift b/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift index e8f4e1387..0e54b4a88 100644 --- a/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift +++ b/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift @@ -11,5 +11,7 @@ public enum ActivityOwner: Sendable, Hashable { case account(String) // accountID case feedFinder case feedImageDownloader + case faviconDownloader + case avatarDownloader case htmlMetadataDownloader } diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataTable.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataTable.swift index 24648ed2e..a3b937616 100644 --- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataTable.swift +++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataTable.swift @@ -99,8 +99,13 @@ private extension HTMLMetadataTable { ) } - static func jsonString(_ value: T) -> String? { - guard let data = try? JSONEncoder().encode(value) else { + static func jsonString(_ values: [T]) -> String? { + if values.isEmpty { + return nil + } + let encoder = JSONEncoder() + encoder.outputFormatting = .withoutEscapingSlashes + guard let data = try? encoder.encode(values) else { return nil } return String(data: data, encoding: .utf8) diff --git a/Shared/Favicons/FaviconDownloader.swift b/Shared/Favicons/FaviconDownloader.swift index 91065862f..c04afba5c 100644 --- a/Shared/Favicons/FaviconDownloader.swift +++ b/Shared/Favicons/FaviconDownloader.swift @@ -123,6 +123,12 @@ extension Notification.Name { return nil } + /// Returns the in-memory favicon for `feed` without triggering a download. + /// Used by `IconImageCache` for read-only lookups and prefetch paths. + func cachedFaviconAsIcon(for feed: Feed) -> IconImage? { + cache[feed] + } + func favicon(with faviconURL: String, homePageURL: String?) -> IconImage? { let downloader = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL) return downloader.iconImage diff --git a/Shared/Favicons/SingleFaviconDownloader.swift b/Shared/Favicons/SingleFaviconDownloader.swift index ce4e59118..fdf07d173 100644 --- a/Shared/Favicons/SingleFaviconDownloader.swift +++ b/Shared/Favicons/SingleFaviconDownloader.swift @@ -8,6 +8,7 @@ import Foundation import os +import ActivityLog import RSCore import RSWeb @@ -132,17 +133,25 @@ private extension SingleFaviconDownloader { return nil } + let activityLog = ActivityLog.shared + let kind = ActivityKind.downloadFavicon(faviconURL: faviconURL) + activityLog.createActivity(owner: .faviconDownloader, kind: kind) + activityLog.didStart(.faviconDownloader, kind: kind) + do { let (data, response) = try await Downloader.shared.download(url) if let data, !data.isEmpty, let response, response.statusIsOK { let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data saveToDisk(scaledData) let image = await RSImage.image(data: scaledData) + activityLog.didComplete(.faviconDownloader, kind: kind) return image } + activityLog.didComplete(.faviconDownloader, kind: kind, durationIsSignificant: false) } catch { Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)") + activityLog.didFail(.faviconDownloader, kind: kind, error: error) } return nil diff --git a/Shared/IconImageCache.swift b/Shared/IconImageCache.swift index 8ee527e8c..68afd2fda 100644 --- a/Shared/IconImageCache.swift +++ b/Shared/IconImageCache.swift @@ -57,6 +57,29 @@ import RSCore return nil } + func prefetchImagesForArticles(_ articles: ArticleArray) { + + var feedsSeen = Set() + var authorsSeen = Set() + + for article in articles { + if let authors = article.authors { + for author in authors { + if let avatarURL = author.avatarURL, !authorsSeen.contains(avatarURL) { + authorsSeen.insert(avatarURL) + _ = AuthorAvatarDownloader.shared.image(for: author) + } + } + } + + if let feed = article.feed, let feedID = feed.sidebarItemID, !feedsSeen.contains(feedID) { + feedsSeen.insert(feedID) + _ = FeedIconDownloader.shared.icon(for: feed) + _ = FaviconDownloader.shared.faviconAsIcon(for: feed) + } + } + } + func imageForArticle(_ article: Article) -> IconImage? { if let iconImage = imageForAuthors(article.authors) { return iconImage @@ -93,14 +116,14 @@ private extension IconImageCache { if let iconImage = feedIconImageCache[feedID] { return iconImage } - if let iconImage = FeedIconDownloader.shared.icon(for: feed) { + if let iconImage = FeedIconDownloader.shared.cachedIcon(for: feed) { feedIconImageCache[feedID] = iconImage return iconImage } if let faviconImage = faviconImageCache[feedID] { return faviconImage } - if let faviconImage = FaviconDownloader.shared.faviconAsIcon(for: feed) { + if let faviconImage = FaviconDownloader.shared.cachedFaviconAsIcon(for: feed) { faviconImageCache[feedID] = faviconImage return faviconImage } @@ -129,7 +152,7 @@ private extension IconImageCache { if let iconImage = authorIconImageCache[author] { return iconImage } - if let iconImage = AuthorAvatarDownloader.shared.image(for: author) { + if let iconImage = AuthorAvatarDownloader.shared.cachedImage(for: author) { authorIconImageCache[author] = iconImage return iconImage } diff --git a/Shared/Images/AuthorAvatarDownloader.swift b/Shared/Images/AuthorAvatarDownloader.swift index 8c57303fa..d5c6fe528 100644 --- a/Shared/Images/AuthorAvatarDownloader.swift +++ b/Shared/Images/AuthorAvatarDownloader.swift @@ -9,6 +9,7 @@ import Foundation import Articles import RSCore +import ActivityLog extension Notification.Name { static let AvatarDidBecomeAvailable = Notification.Name("AvatarDidBecomeAvailableNotification") // UserInfoKey.imageURL (which is an avatarURL) @@ -48,12 +49,31 @@ extension Notification.Name { if let imageData = imageDownloader.image(for: avatarURL) { scaleAndCacheImageData(imageData, avatarURL) } else { + // Multiple authors can share the same avatar URL. Only produce the + // activity once per URL — the imageDidBecomeAvailable notification + // will complete the single in-flight activity. + if !waitingForAvatarURLs.contains(avatarURL) { + let activityLog = ActivityLog.shared + let kind = ActivityKind.downloadAvatar(avatarURL: avatarURL) + activityLog.createActivity(owner: .avatarDownloader, kind: kind) + activityLog.didStart(.avatarDownloader, kind: kind) + } + waitingForAvatarURLs.insert(avatarURL) } return nil } + /// Returns the in-memory avatar for `author` without triggering a download. + /// Used by `IconImageCache.prefetchImagesForArticles` and read-only lookups. + func cachedImage(for author: Author) -> IconImage? { + guard let avatarURL = author.avatarURL else { + return nil + } + return cache[avatarURL] + } + @objc func imageDidBecomeAvailable(_ note: Notification) { guard let avatarURL = note.userInfo?[UserInfoKey.url] as? String else { return @@ -65,6 +85,9 @@ extension Notification.Name { return } scaleAndCacheImageData(imageData, avatarURL) + + let kind = ActivityKind.downloadAvatar(avatarURL: avatarURL) + ActivityLog.shared.didComplete(.avatarDownloader, kind: kind) } } diff --git a/Shared/Images/FeedIconDownloader.swift b/Shared/Images/FeedIconDownloader.swift index 0a99caa06..9a32c12b2 100644 --- a/Shared/Images/FeedIconDownloader.swift +++ b/Shared/Images/FeedIconDownloader.swift @@ -11,6 +11,7 @@ import Account import RSCore import RSWeb import HTMLMetadata +import ActivityLog extension Notification.Name { @@ -139,8 +140,18 @@ extension Notification.Name { return } waitingForFeedURLs[url] = nil + + let kind = ActivityKind.downloadFeedImage(feedURL: url) + ActivityLog.shared.didComplete(.feedImageDownloader, kind: kind) + _ = icon(for: feed) } + + /// Returns the in-memory icon for `feed` without triggering a download. + /// Used by `IconImageCache.prefetchImagesForArticles` and read-only lookups. + func cachedIcon(for feed: Feed) -> IconImage? { + cache[feed] + } } private extension FeedIconDownloader { @@ -210,11 +221,30 @@ private extension FeedIconDownloader { func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping ImageResultBlock) { let url = Self.sanitizedIconURL(url) + + // Multiple feeds can share the same icon URL. Only produce the activity + // once per URL — the imageDidBecomeAvailable notification will complete + // the single in-flight activity. + let alreadyInFlight = waitingForFeedURLs[url] != nil + let kind = ActivityKind.downloadFeedImage(feedURL: url) + let activityLog = ActivityLog.shared + + if !alreadyInFlight { + activityLog.createActivity(owner: .feedImageDownloader, kind: kind, detail: feed.nameForDisplay) + activityLog.didStart(.feedImageDownloader, kind: kind) + } + waitingForFeedURLs[url] = feed guard let imageData = imageDownloader.image(for: url) else { + // Download dispatched — completion comes via imageDidBecomeAvailable. imageResultBlock(nil) return } + + // Image was already on disk — no actual download. + if !alreadyInFlight { + activityLog.didComplete(.feedImageDownloader, kind: kind, durationIsSignificant: false) + } RSImage.image(with: imageData, imageResultBlock: imageResultBlock) } diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index f542f10d7..aecad769a 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -2127,6 +2127,7 @@ private extension SceneCoordinator { } updateShowNamesAndIcons() + IconImageCache.shared.prefetchImagesForArticles(articles) updateUnreadCount() mainTimelineViewController?.reloadArticles(animated: animated) }