From 6831d31fc911c1b13a2ebf49a537eeaee8fff8af Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 26 Oct 2026 21:05:41 -0700 Subject: [PATCH] Create DownloadedImageCache. --- Mac/AppDelegate.swift | 13 -- .../Sources/Images/DownloadedImageCache.swift | 156 ++++++++++++++++++ .../Sources/Images/ImageDownloader.swift | 150 +++-------------- .../Images/SingleFaviconDownloader.swift | 5 +- .../ImagesTests/ImageDownloaderTests.swift | 4 +- Modules/RSWeb/Sources/RSWeb/Downloader.swift | 14 +- Shared/Extensions/CacheCleaner.swift | 33 +++- iOS/AppDelegate.swift | 7 - 8 files changed, 219 insertions(+), 163 deletions(-) create mode 100644 Modules/Images/Sources/Images/DownloadedImageCache.swift diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 4cf3d753a..287b9132a 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -149,19 +149,6 @@ let appName = "NetNewsWire" installAppleEventHandlers() CacheCleaner.purgeIfNecessary() - - // Try to establish a cache in the Caches folder, but if it fails for some reason fall back to a temporary dir - let cacheFolder: String - if let userCacheFolder = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).path { - cacheFolder = userCacheFolder - } else { - let bundleIdentifier = (Bundle.main.infoDictionary!["CFBundleIdentifier"]! as! String) - cacheFolder = (NSTemporaryDirectory() as NSString).appendingPathComponent(bundleIdentifier) - } - - let imagesFolder = (cacheFolder as NSString).appendingPathComponent("Images") - let imagesFolderURL = URL(fileURLWithPath: imagesFolder) - try! FileManager.default.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil) } func applicationDidFinishLaunching(_ note: Notification) { diff --git a/Modules/Images/Sources/Images/DownloadedImageCache.swift b/Modules/Images/Sources/Images/DownloadedImageCache.swift new file mode 100644 index 000000000..3807aad92 --- /dev/null +++ b/Modules/Images/Sources/Images/DownloadedImageCache.swift @@ -0,0 +1,156 @@ +// +// DownloadedImageCache.swift +// Images +// +// Created by Brent Simmons on 10/26/26. +// + +import Foundation +import os +import RSCore +import RSWeb +import ActivityLog + +/// Downloads each image URL once and keeps one copy on disk, shared by every `ImageDownloader`. +/// +/// The copy is scaled down to `maxPixelSize`, the largest size anything displays, +/// or kept as is when it’s already smaller. Each `ImageDownloader` makes its own size from it. +/// Requests for a URL that’s already being read or downloaded share that work. +@MainActor final class DownloadedImageCache { + + static let shared = DownloadedImageCache() + + /// The size of large thumbnails, the largest images displayed. + nonisolated static let maxPixelSize = 1200 + + private static let folderName = "DownloadedImages" + nonisolated private static let compressionQuality = 0.8 + private static let maximumConcurrentLimitedDownloads = 4 + + nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DownloadedImageCache") + + private let diskCache: BinaryDiskCache + private let downloadLimiter = DownloadLimiter(maximumConcurrentDownloads: maximumConcurrentLimitedDownloads) + private var tasks = [String: Task, Never>]() // url: task + + private init() { + let folder = AppConfig.cacheSubfolder(named: Self.folderName) + self.diskCache = BinaryDiskCache(folder: folder.path) + } + + /// The stored copy, read from disk or downloaded. Downloads that use the download limiter + /// wait their turn, and don’t start when offline or in Low Data Mode. + /// Activity log fires only when the request reaches the network. + func imageData(for url: String, usesDownloadLimiter: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async throws(ImageDownloadError) -> Data { + if let task = tasks[url] { + return try await task.value.get() + } + + let task = Task { + await findImage(url, usesDownloadLimiter: usesDownloadLimiter, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) + } + tasks[url] = task + let result = await task.value + tasks[url] = nil + return try result.get() + } +} + +private extension DownloadedImageCache { + + func findImage(_ url: String, usesDownloadLimiter: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result { + if let data = await Self.readFromDisk(diskCache, key: Self.diskKey(url)) { + return .success(data) + } + + if usesDownloadLimiter { + guard downloadLimiter.networkAllowsDownloads else { + return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) + } + await downloadLimiter.waitForTurn() + } + let result = await downloadImageFromNetwork(url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) + if usesDownloadLimiter { + downloadLimiter.downloadDidFinish() + } + return result + } + + func downloadImageFromNetwork(_ url: String, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result { + let activityLog = ActivityLog.shared + if let activityOwner, let activityKind { + activityLog.createActivity(owner: activityOwner, kind: activityKind, detail: activityDetail) + activityLog.didStart(activityOwner, kind: activityKind) + } + + do { + let (data, downloadResponse) = try await downloadImage(url) + if let activityOwner, let activityKind { + let message = downloadResponse.data.map(ActivityLog.dataSizeMessage) + activityLog.didComplete(activityOwner, kind: activityKind, message: message, returnedFromCache: downloadResponse.returnedFromCache) + } + ImageMetadataDatabase.shared.clearFailure(url: url) + return .success(data) + } catch { + if let activityOwner, let activityKind { + activityLog.didFail(activityOwner, kind: activityKind, error: error) + } + if !error.isTransient { + ImageMetadataDatabase.shared.recordFailure(url: url, statusCode: error.statusCode) + } + return .failure(error) + } + } + + func downloadImage(_ url: String) async throws(ImageDownloadError) -> (Data, DownloadResponse) { + guard let imageURL = URL(string: url) else { + throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false) + } + + let downloadResponse: DownloadResponse + do { + // Not cached by Downloader, since the copy on disk is the cache. + downloadResponse = try await Downloader.shared.download(imageURL, userAgentStyle: .browser, cachesResponse: false) + } catch { + Self.logger.error("Error downloading image at \(url) \(error.localizedDescription)") + throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true) + } + + let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode + if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { + let storedData = await Self.scaledImageData(data) + await Self.saveToDisk(diskCache, key: Self.diskKey(url), data: storedData) + return (storedData, downloadResponse) + } + + // 2xx with empty / missing body — server said OK but gave us no image bytes. + if let response = downloadResponse.response, response.statusIsOK { + throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false) + } + var isTransient = true + if let statusCode { + isTransient = statusCode >= 500 && statusCode <= 599 + } + throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient) + } + + static func diskKey(_ url: String) -> String { + url.md5String + } + + /// Data that ImageIO can’t read, such as SVG, is kept as is, since `RSImage` may still read it. + @concurrent static func scaledImageData(_ data: Data) async -> Data { + RSImage.scaledImageData(data, maxPixelSize: maxPixelSize, format: .jpeg(compressionQuality: compressionQuality)) ?? data + } + + @concurrent static func readFromDisk(_ diskCache: BinaryDiskCache, key: String) async -> Data? { + guard let data = diskCache[key], !data.isEmpty else { + return nil + } + return data + } + + @concurrent static func saveToDisk(_ diskCache: BinaryDiskCache, key: String, data: Data) async { + diskCache[key] = data + } +} diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift index 607dc61c1..cf46f06be 100644 --- a/Modules/Images/Sources/Images/ImageDownloader.swift +++ b/Modules/Images/Sources/Images/ImageDownloader.swift @@ -10,7 +10,6 @@ import Foundation import os import RSCore import RSParser -import RSWeb import ActivityLog extension Notification.Name { @@ -50,50 +49,39 @@ extension ImageDownloadError: LocalizedError { } } -/// Downloads images, resizes them, and caches them in memory and on disk. -/// Each instance has its own disk cache folder, since the disk key is the URL alone. +/// Makes images at one size from `DownloadedImageCache`’s copy, and caches them in memory. +/// The public API is the same whether the copy is on disk or has to be downloaded. @MainActor public final class ImageDownloader { /// Feed icons, favicons, and avatars. - public static let shared = ImageDownloader(configuration: Configuration(cacheFolderName: "Images", maxPixelSize: RSImage.maxIconPixelSize, format: .png, memoryCacheByteLimit: 0, requiresSignificantDimensions: false, downloadLimiter: nil)) + public static let shared = ImageDownloader(configuration: Configuration(maxPixelSize: RSImage.maxIconPixelSize, format: .png, memoryCacheByteLimit: 0, requiresSignificantDimensions: false, usesDownloadLimiter: false)) /// Timeline thumbnails, sized for aspect-fill cropping into a small square. - public static let thumbnails = ImageDownloader(configuration: Configuration(cacheFolderName: "Thumbnails", maxPixelSize: thumbnailMaxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, downloadLimiter: thumbnailDownloadLimiter)) + public static let thumbnails = ImageDownloader(configuration: Configuration(maxPixelSize: thumbnailMaxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, usesDownloadLimiter: true)) /// Timeline thumbnails, sized to span the timeline’s width. - public static let largeThumbnails = ImageDownloader(configuration: Configuration(cacheFolderName: "LargeThumbnails", maxPixelSize: largeThumbnailMaxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, downloadLimiter: thumbnailDownloadLimiter)) + public static let largeThumbnails = ImageDownloader(configuration: Configuration(maxPixelSize: DownloadedImageCache.maxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, usesDownloadLimiter: true)) struct Configuration: Sendable { - let cacheFolderName: String let maxPixelSize: Int let format: ScaledImageFormat let memoryCacheByteLimit: Int // 0 means no limit - let requiresSignificantDimensions: Bool // Checked against the downloaded image’s real pixel dimensions - let downloadLimiter: DownloadLimiter? + let requiresSignificantDimensions: Bool // Checked against the stored image’s pixel dimensions + let usesDownloadLimiter: Bool } private static let thumbnailMaxPixelSize = 512 - private static let largeThumbnailMaxPixelSize = 1200 private static let thumbnailCompressionQuality = 0.8 private static let thumbnailMemoryCacheByteLimit = 32 * 1024 * 1024 - private static let maximumConcurrentThumbnailDownloads = 4 - - /// Shared by both thumbnail downloaders. - private static let thumbnailDownloadLimiter = DownloadLimiter(maximumConcurrentDownloads: maximumConcurrentThumbnailDownloads) nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageDownloader") private let configuration: Configuration - nonisolated private let diskCache: BinaryDiskCache - private let queue: DispatchQueue private let imageCache = NSCache() // url: image private var urlsInProgress = Set() init(configuration: Configuration) { self.configuration = configuration - let folder = AppConfig.cacheSubfolder(named: configuration.cacheFolderName) - self.diskCache = BinaryDiskCache(folder: folder.path) - self.queue = DispatchQueue(label: "ImageDownloader serial queue - \(folder.path)") self.imageCache.totalCostLimit = configuration.memoryCacheByteLimit NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil) @@ -108,7 +96,8 @@ extension ImageDownloadError: LocalizedError { imageCache.removeAllObjects() } - /// Returns the data if in memory, else dispatches a disk-then-network fetch and returns nil. + /// Returns the data if in memory, else makes it from `DownloadedImageCache`’s copy and returns nil. + /// Posts `.imageDidBecomeAvailable` when it’s ready. /// Activity log fires only when the fetch reaches the network. @discardableResult public func image(for url: String, activityOwner: ActivityOwner? = nil, activityKind: ActivityKind? = nil, activityDetail: String? = nil) -> Data? { @@ -139,129 +128,32 @@ extension ImageDownloadError: LocalizedError { private extension ImageDownloader { - func cacheImage(_ url: String, _ image: Data) { - assert(Thread.isMainThread) - imageCache.setObject(image as NSData, forKey: url as NSString, cost: image.count) - postImageDidBecomeAvailableNotification(url) - } - func findImage(_ url: String, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async { guard !urlsInProgress.contains(url) else { return } urlsInProgress.insert(url) - - if let image = await readFromDisk(url: url) { - cacheImage(url, image) + defer { urlsInProgress.remove(url) - return - } - - if let downloadLimiter = configuration.downloadLimiter { - guard downloadLimiter.networkAllowsDownloads else { - urlsInProgress.remove(url) - return - } - await downloadLimiter.waitForTurn() - } - await downloadImageFromNetwork(url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) - configuration.downloadLimiter?.downloadDidFinish() - urlsInProgress.remove(url) - } - - func downloadImageFromNetwork(_ url: String, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async { - let activityLog = ActivityLog.shared - if let activityOwner, let activityKind { - activityLog.createActivity(owner: activityOwner, kind: activityKind, detail: activityDetail) - activityLog.didStart(activityOwner, kind: activityKind) } do { - let (image, downloadResponse) = try await downloadImage(url) - if let activityOwner, let activityKind { - let message = downloadResponse.data.map(ActivityLog.dataSizeMessage) - activityLog.didComplete(activityOwner, kind: activityKind, message: message, returnedFromCache: downloadResponse.returnedFromCache) - } - cacheImage(url, image) - ImageMetadataDatabase.shared.clearFailure(url: url) + let storedData = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadLimiter: configuration.usesDownloadLimiter, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) + let data = try await Self.scaledImageData(storedData, configuration: configuration) + cacheImage(url, data) } catch { - if let activityOwner, let activityKind { - activityLog.didFail(activityOwner, kind: activityKind, error: error) + if error.rejectedPixelSize != nil { + ImageMetadataDatabase.shared.recordInsignificantDimensions(url: url) } if !error.isTransient { - if error.rejectedPixelSize != nil { - ImageMetadataDatabase.shared.recordInsignificantDimensions(url: url) - } else { - ImageMetadataDatabase.shared.recordFailure(url: url, statusCode: error.statusCode) - } NotificationCenter.default.post(name: .imageDownloadDidFail, object: self, userInfo: ["url": url]) } } } - func readFromDisk(url: String) async -> Data? { - await withCheckedContinuation { continuation in - readFromDisk(url) { data in - continuation.resume(returning: data) - } - } - } - - func readFromDisk(_ url: String, _ completion: @escaping @MainActor (Data?) -> Void) { - queue.async { - if let data = self.diskCache[self.diskKey(url)], !data.isEmpty { - DispatchQueue.main.async { - completion(data) - } - return - } - - DispatchQueue.main.async { - completion(nil) - } - } - } - - func downloadImage(_ url: String) async throws(ImageDownloadError) -> (Data, DownloadResponse) { - guard let imageURL = URL(string: url) else { - throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false) - } - - let downloadResponse: DownloadResponse - do { - downloadResponse = try await Downloader.shared.download(imageURL, userAgentStyle: .browser) - } catch { - Self.logger.error("Error downloading image at \(url) \(error.localizedDescription)") - throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true) - } - - let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode - if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { - let scaledData = try await Self.scaledImageData(data, statusCode: statusCode, configuration: configuration) - saveToDisk(url, scaledData) - return (scaledData, downloadResponse) - } - - // 2xx with empty / missing body — server said OK but gave us no image bytes. - if let response = downloadResponse.response, response.statusIsOK { - throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false) - } - let isTransient = statusCode.map { (500...599).contains($0) } ?? true - throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient) - } - - func saveToDisk(_ url: String, _ data: Data) { - queue.async { - self.diskCache[self.diskKey(url)] = data - } - } - - nonisolated func diskKey(_ url: String) -> String { - url.md5String - } - - func postImageDidBecomeAvailableNotification(_ url: String) { + func cacheImage(_ url: String, _ image: Data) { assert(Thread.isMainThread) + imageCache.setObject(image as NSData, forKey: url as NSString, cost: image.count) NotificationCenter.default.post(name: .imageDidBecomeAvailable, object: self, userInfo: ["url": url]) } } @@ -271,14 +163,14 @@ private extension ImageDownloader { extension ImageDownloader { /// Resizes off the main thread. Throws when `requiresSignificantDimensions` and the image is - /// unreadable, too small, or too narrow, so it’s recorded as a failure, as a 404 would be. - @concurrent static func scaledImageData(_ data: Data, statusCode: Int?, configuration: Configuration) async throws(ImageDownloadError) -> Data { + /// unreadable, too small, or too narrow. + @concurrent static func scaledImageData(_ data: Data, configuration: Configuration) async throws(ImageDownloadError) -> Data { if configuration.requiresSignificantDimensions { guard let pixelSize = RSImage.largestFramePixelSize(data) else { - throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false) + throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false) } guard SignificantImageFilter.hasSignificantDimensions(width: pixelSize.width, height: pixelSize.height) else { - throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: false, rejectedPixelSize: pixelSize) + throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false, rejectedPixelSize: pixelSize) } } return RSImage.scaledImageData(data, maxPixelSize: configuration.maxPixelSize, format: configuration.format) ?? data diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index 49b2ebe46..cef5bfb6c 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -175,7 +175,10 @@ private extension SingleFaviconDownloader { activityLog.didFail(.faviconDownloader, kind: kind, error: error) throw error } - let isTransient = statusCode.map { (500...599).contains($0) } ?? true + var isTransient = true + if let statusCode { + isTransient = statusCode >= 500 && statusCode <= 599 + } let error = ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient) activityLog.didFail(.faviconDownloader, kind: kind, error: error) throw error diff --git a/Modules/Images/Tests/ImagesTests/ImageDownloaderTests.swift b/Modules/Images/Tests/ImagesTests/ImageDownloaderTests.swift index 578eb604f..25ff2b98c 100644 --- a/Modules/Images/Tests/ImagesTests/ImageDownloaderTests.swift +++ b/Modules/Images/Tests/ImagesTests/ImageDownloaderTests.swift @@ -15,11 +15,11 @@ import UniformTypeIdentifiers @Suite struct ImageDownloaderTests { @Test func thumbnailTooSmallIsRejected() async throws { - let configuration = ImageDownloader.Configuration(cacheFolderName: "Test", maxPixelSize: 512, format: .jpeg(compressionQuality: 0.8), memoryCacheByteLimit: 0, requiresSignificantDimensions: true, downloadLimiter: nil) + let configuration = ImageDownloader.Configuration(maxPixelSize: 512, format: .jpeg(compressionQuality: 0.8), memoryCacheByteLimit: 0, requiresSignificantDimensions: true, usesDownloadLimiter: false) let smallImageData = try #require(pngData(width: 48, height: 48)) await #expect { - _ = try await ImageDownloader.scaledImageData(smallImageData, statusCode: 200, configuration: configuration) + _ = try await ImageDownloader.scaledImageData(smallImageData, configuration: configuration) } throws: { error in (error as? ImageDownloadError)?.rejectedPixelSize?.width == 48 } diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index 7a9a74c7e..612770ed9 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -14,7 +14,7 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi /// Simple downloader, for a one-shot download like an image /// or a web page. For a download-feeds session, see DownloadSession. -/// Caches response for a short time for GET requests. May return cached response. +/// Caches response for a short time for GET requests, unless `cachesResponse` is false. May return cached response. @MainActor public final class Downloader { public static let shared = Downloader() private let urlSession: URLSession @@ -42,13 +42,13 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi urlSession.invalidateAndCancel() } - public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { - try await download(URLRequest(url: url), userAgentStyle: userAgentStyle) + public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true) async throws -> DownloadResponse { + try await download(URLRequest(url: url), userAgentStyle: userAgentStyle, cachesResponse: cachesResponse) } - public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true) async throws -> DownloadResponse { try await withCheckedThrowingContinuation { continuation in - download(urlRequest, userAgentStyle: userAgentStyle) { downloadResponse, error in + download(urlRequest, userAgentStyle: userAgentStyle, cachesResponse: cachesResponse) { downloadResponse, error in if let error { continuation.resume(throwing: error) } else { @@ -63,7 +63,7 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi download(URLRequest(url: url), userAgentStyle: userAgentStyle, callback) } - public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, _ callback: @escaping DownloadCallback) { + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true, _ callback: @escaping DownloadCallback) { assert(Thread.isMainThread) guard let url = urlRequest.url else { @@ -115,7 +115,7 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi let task = urlSession.dataTask(with: urlRequestToUse) { (data, response, error) in // Don’t cache errors — a retry should hit the network. - if isCacheableRequest && error == nil { + if isCacheableRequest && cachesResponse && error == nil { Self.logger.debug("Downloader: caching response for \(url)") self.cache.add(url.absoluteString, data: data, response: response) } diff --git a/Shared/Extensions/CacheCleaner.swift b/Shared/Extensions/CacheCleaner.swift index b8022b50c..d7d2ef7c0 100644 --- a/Shared/Extensions/CacheCleaner.swift +++ b/Shared/Extensions/CacheCleaner.swift @@ -15,10 +15,12 @@ struct CacheCleaner { static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "CacheCleaner") private static let didPurgeImageCachesForResizingKey = "didPurgeImageCachesForResizing-2026-03-30" + private static let didRemoveFoldersReplacedByDownloadedImageCacheKey = "didRemoveFoldersReplacedByDownloadedImageCache-2026-10-26" static func purgeIfNecessary() { purgeImageCachesForResizingIfNeeded() + removeFoldersReplacedByDownloadedImageCacheIfNeeded() guard let flushDate = AppDefaults.lastImageCacheFlushDate else { AppDefaults.lastImageCacheFlushDate = Date() @@ -29,14 +31,12 @@ struct CacheCleaner { if flushDate.addingTimeInterval(3600 * 24 * 3) < Date() { let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! let faviconsFolderURL = tempDir.appendingPathComponent("Favicons") - let imagesFolderURL = tempDir.appendingPathComponent("Images") - let thumbnailsFolderURL = tempDir.appendingPathComponent("Thumbnails") - let largeThumbnailsFolderURL = tempDir.appendingPathComponent("LargeThumbnails") + let downloadedImagesFolderURL = tempDir.appendingPathComponent("DownloadedImages") let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist") let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist") let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist") - for tempItem in [faviconsFolderURL, imagesFolderURL, thumbnailsFolderURL, largeThumbnailsFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] { + for tempItem in [faviconsFolderURL, downloadedImagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] { do { logger.info("Removing cache file: \(tempItem.absoluteString)") try FileManager.default.removeItem(at: tempItem) @@ -77,4 +77,29 @@ private extension CacheCleaner { UserDefaults.standard.set(true, forKey: didPurgeImageCachesForResizingKey) } + + /// One-time removal of the image folders that DownloadedImageCache’s DownloadedImages folder replaces. + static func removeFoldersReplacedByDownloadedImageCacheIfNeeded() { + guard !UserDefaults.standard.bool(forKey: didRemoveFoldersReplacedByDownloadedImageCacheKey) else { + return + } + + let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! + let foldersToRemove = [ + cacheDir.appendingPathComponent("Images"), + cacheDir.appendingPathComponent("Thumbnails"), + cacheDir.appendingPathComponent("LargeThumbnails") + ] + + for folder in foldersToRemove { + do { + try FileManager.default.removeItem(at: folder) + logger.info("Removed image folder replaced by DownloadedImageCache: \(folder.lastPathComponent, privacy: .public)") + } catch { + // Folder may not exist — that's fine + } + } + + UserDefaults.standard.set(true, forKey: didRemoveFoldersReplacedByDownloadedImageCacheKey) + } } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 5c145d73b..e8d5e7a41 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -80,7 +80,6 @@ import Images registerBackgroundTasks() CacheCleaner.purgeIfNecessary() - initializeDownloaders() initializeHomeScreenQuickActions() DispatchQueue.main.async { @@ -251,12 +250,6 @@ import Images private extension AppDelegate { - private func initializeDownloaders() { - let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! - let imagesFolderURL = tempDir.appendingPathComponent("Images") - try! FileManager.default.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil) - } - private func initializeHomeScreenQuickActions() { let unreadTitle = NSLocalizedString("First Unread", comment: "First Unread") let unreadIcon = UIApplicationShortcutIcon(systemImageName: "chevron.down.circle")