From f2ac871b993f5774ef68510b60704cd376ca7c7e Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 25 Oct 2026 11:57:49 -0700 Subject: [PATCH] Create ArticleThumbnailFinder and ArticleThumbnailTable to find thumbnails. --- Modules/Images/Package.swift | 10 + .../Images/ArticleThumbnailFinder.swift | 188 ++++++++++++++++++ .../Images/ArticleThumbnailTable.swift | 68 +++++++ .../Images/ImageMetadataDatabase.swift | 28 ++- .../ArticleThumbnailFinderTests.swift | 65 ++++++ NetNewsWire.xctestplan | 7 + 6 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 Modules/Images/Sources/Images/ArticleThumbnailFinder.swift create mode 100644 Modules/Images/Sources/Images/ArticleThumbnailTable.swift create mode 100644 Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift diff --git a/Modules/Images/Package.swift b/Modules/Images/Package.swift index 7d9ecd641..95abc0c9e 100644 --- a/Modules/Images/Package.swift +++ b/Modules/Images/Package.swift @@ -13,6 +13,7 @@ let package = Package( dependencies: [ .package(path: "../RSCore"), .package(path: "../RSDatabase"), + .package(path: "../RSParser"), .package(path: "../RSWeb"), .package(path: "../Account"), .package(path: "../Articles"), @@ -25,6 +26,7 @@ let package = Package( dependencies: [ "RSCore", "RSDatabase", + "RSParser", "RSWeb", "Account", "Articles", @@ -36,6 +38,14 @@ let package = Package( .enableUpcomingFeature("InferIsolatedConformances"), .unsafeFlags(["-warnings-as-errors"]) ] + ), + .testTarget( + name: "ImagesTests", + dependencies: ["Images"], + swiftSettings: [ + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + .enableUpcomingFeature("InferIsolatedConformances") + ] ) ] ) diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift new file mode 100644 index 000000000..b101e074a --- /dev/null +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -0,0 +1,188 @@ +// +// ArticleThumbnailFinder.swift +// Images +// +// Created by Brent Simmons on 10/25/26. +// + +import Foundation +import Articles +import RSCore +import RSParser + +extension Notification.Name { + /// Posted when `discoverThumbnailURLs(for:)` finds thumbnails in article HTML. + /// userInfo key: `ArticleThumbnailFinder.articleIDsKey` (`Set`). + public static let articleThumbnailURLsDidBecomeAvailable = Notification.Name("ArticleThumbnailURLsDidBecomeAvailable") +} + +/// Finds the URL of the image that stands for an article in the timeline. +/// +/// Sources: the provided thumbnail, the article’s image, the first significant image +/// attachment, and the first significant image in the article’s HTML. Small mode +/// tries them in that order. Large mode tries the article’s image and attachments +/// before the provided thumbnail, which is usually too small to fill the timeline’s width. +/// +/// The first three sources are property reads. The HTML is parsed off the main thread +/// by `discoverThumbnailURLs(for:)`, and the results are saved in `ImageMetadataDatabase`, +/// so each article’s HTML is parsed once. +/// +/// URLs that recently failed to download are skipped, so a dead or rejected image +/// falls through to the next source. +@MainActor public final class ArticleThumbnailFinder { + + public enum Mode: Sendable { + case small + case large + } + + public static let shared = ArticleThumbnailFinder(metadataDatabase: .shared) + + public static let articleIDsKey = "articleIDs" + + private let metadataDatabase: ImageMetadataDatabase + private var htmlThumbnailURLs = [String: String]() // articleID: thumbnailURL + private var articleIDsWithNoHTMLThumbnail = Set() + private var articleIDsBeingDiscovered = Set() + + init(metadataDatabase: ImageMetadataDatabase) { + self.metadataDatabase = metadataDatabase + } + + /// Nil when the article has no usable image, or when its HTML hasn’t been checked yet. + public func thumbnailURL(for article: Article, mode: Mode) -> String? { + if let providedThumbnailURL = providedThumbnailURL(for: article, mode: mode) { + return providedThumbnailURL + } + guard let htmlThumbnailURL = htmlThumbnailURLs[article.articleID], isUsable(htmlThumbnailURL) else { + return nil + } + return htmlThumbnailURL + } + + /// Looks for thumbnails in the HTML of articles that have no usable provided image. + /// Uses results saved in the database, parses the rest off the main thread, and saves those results. + public func discoverThumbnailURLs(for articles: some Collection
) async { + let articlesToCheck = articles.filter(needsHTMLDiscovery) + guard !articlesToCheck.isEmpty else { + return + } + + let articleIDs = articlesToCheck.map(\.articleID) + articleIDsBeingDiscovered.formUnion(articleIDs) + defer { + articleIDsBeingDiscovered.subtract(articleIDs) + } + + let savedRecords = await metadataDatabase.fetchArticleThumbnails(articleIDs: articleIDs) + cacheRecords(savedRecords) + + let articleHTMLs = articlesToCheck.filter { !isCached($0.articleID) }.compactMap(ArticleHTML.init) + var parsedRecords = [ArticleThumbnailRecord]() + if !articleHTMLs.isEmpty { + parsedRecords = await Self.parseThumbnailURLs(articleHTMLs) + cacheRecords(parsedRecords) + metadataDatabase.saveArticleThumbnails(parsedRecords) + } + + let foundArticleIDs = Set((savedRecords + parsedRecords).filter { $0.thumbnailURL != nil }.map(\.articleID)) + if !foundArticleIDs.isEmpty { + NotificationCenter.default.post(name: .articleThumbnailURLsDidBecomeAvailable, object: self, userInfo: [Self.articleIDsKey: foundArticleIDs]) + } + } +} + +// MARK: - Private + +private extension ArticleThumbnailFinder { + + struct ArticleHTML: Sendable { + let articleID: String + let html: String + let baseURL: String? + + init?(_ article: Article) { + guard let html = article.contentHTML ?? article.summary, !html.isEmpty else { + return nil + } + self.articleID = article.articleID + self.html = html + self.baseURL = article.rawLink ?? article.rawExternalLink + } + } + + func providedThumbnailURL(for article: Article, mode: Mode) -> String? { + let thumbnailURL = Self.normalizedURLString(article.rawThumbnailLink) + let imageURL = Self.normalizedURLString(article.rawImageLink) + let attachmentURL = Self.firstSignificantImageAttachmentURL(article) + + let candidates = switch mode { + case .small: + [thumbnailURL, imageURL, attachmentURL] + case .large: + [imageURL, attachmentURL, thumbnailURL] + } + + for candidate in candidates { + if let candidate, isUsable(candidate) { + return candidate + } + } + return nil + } + + func isUsable(_ urlString: String) -> Bool { + SignificantImageFilter.isSignificant(urlString: urlString, width: nil, height: nil) && !metadataDatabase.recentlyFailed(url: urlString) + } + + func needsHTMLDiscovery(_ article: Article) -> Bool { + let articleID = article.articleID + if isCached(articleID) || articleIDsBeingDiscovered.contains(articleID) { + return false + } + // Which source is chosen depends on mode, but whether there is one doesn’t. + return providedThumbnailURL(for: article, mode: .small) == nil + } + + func isCached(_ articleID: String) -> Bool { + htmlThumbnailURLs[articleID] != nil || articleIDsWithNoHTMLThumbnail.contains(articleID) + } + + func cacheRecords(_ records: [ArticleThumbnailRecord]) { + for record in records { + if let thumbnailURL = record.thumbnailURL { + htmlThumbnailURLs[record.articleID] = thumbnailURL + } else { + articleIDsWithNoHTMLThumbnail.insert(record.articleID) + } + } + } + + @concurrent static func parseThumbnailURLs(_ articleHTMLs: [ArticleHTML]) async -> [ArticleThumbnailRecord] { + articleHTMLs.map { articleHTML in + let parserData = ParserData(url: articleHTML.baseURL ?? "", data: Data(articleHTML.html.utf8)) + let image = HTMLImageParser.firstSignificantImage(with: parserData) + return ArticleThumbnailRecord(articleID: articleHTML.articleID, thumbnailURL: image?.urlString) + } + } + + static func firstSignificantImageAttachmentURL(_ article: Article) -> String? { + guard let attachments = article.attachments else { + return nil + } + for attachment in attachments where attachment.displayMedium == .image { + if SignificantImageFilter.isSignificant(urlString: attachment.url, width: attachment.width, height: attachment.height) { + return attachment.url + } + } + return nil + } + + /// Encodes spaces, as `Article.imageLink` does. + static func normalizedURLString(_ link: String?) -> String? { + guard let link, !link.isEmpty else { + return nil + } + return URL.encodeSpacesIfNeeded(link)?.absoluteString ?? link + } +} diff --git a/Modules/Images/Sources/Images/ArticleThumbnailTable.swift b/Modules/Images/Sources/Images/ArticleThumbnailTable.swift new file mode 100644 index 000000000..b997baa65 --- /dev/null +++ b/Modules/Images/Sources/Images/ArticleThumbnailTable.swift @@ -0,0 +1,68 @@ +// +// ArticleThumbnailTable.swift +// Images +// +// Created by Brent Simmons on 10/25/26. +// + +import Foundation +import RSCore +import RSDatabase +import RSDatabaseObjC + +/// The result of looking for a thumbnail in an article’s HTML. +/// `thumbnailURL` is nil when the HTML has no usable image. +struct ArticleThumbnailRecord: Sendable, Equatable { + let articleID: String + let thumbnailURL: String? +} + +/// Thumbnails found in article HTML. Rows exist only for articles whose HTML was parsed. +struct ArticleThumbnailTable { + + static let name = "articleThumbnail" + + private struct Column { + static let articleID = "articleID" + static let thumbnailURL = "thumbnailURL" + static let lastChecked = "lastChecked" + } + + /// Keeps each query under the database’s limit on parameters. + private static let maximumArticleIDsPerQuery = 500 + + static func fetch(articleIDs: [String], database: FMDatabase) -> [ArticleThumbnailRecord] { + var results = [ArticleThumbnailRecord]() + for articleIDsChunk in articleIDs.chunked(into: maximumArticleIDsPerQuery) { + guard let resultSet = database.selectRowsWhere(key: Column.articleID, equalsAnyValue: articleIDsChunk, tableName: name) else { + continue + } + while resultSet.next() { + guard let articleID = resultSet.string(forColumn: Column.articleID) else { + continue + } + results.append(ArticleThumbnailRecord(articleID: articleID, thumbnailURL: resultSet.string(forColumn: Column.thumbnailURL))) + } + resultSet.close() + } + return results + } + + static func save(_ records: [ArticleThumbnailRecord], database: FMDatabase) { + let lastChecked = Date().timeIntervalSince1970 + for record in records { + let dictionary: DatabaseDictionary = [ + Column.articleID: record.articleID, + Column.thumbnailURL: record.thumbnailURL as Any, + Column.lastChecked: lastChecked + ] + database.insertRow(dictionary, insertType: .orReplace, tableName: name) + } + } + + /// Removes rows whose `lastChecked` predates the cutoff. Cutoff is Unix epoch seconds. + static func removeExpired(olderThan cutoff: TimeInterval, database: FMDatabase) { + let sql = "DELETE FROM \(name) WHERE \(Column.lastChecked) < ?;" + database.executeUpdate(sql, withArgumentsIn: [cutoff]) + } +} diff --git a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift index e9751a82f..a5ed3e4b7 100644 --- a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift +++ b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift @@ -12,6 +12,7 @@ import RSDatabase import RSDatabaseObjC /// Per-URL image metadata: discovered URLs and failure tracking. +/// Also thumbnails found in article HTML, which aren’t loaded into memory at init, since there’s a row per article. @MainActor public final class ImageMetadataDatabase { public static let shared = ImageMetadataDatabase() @@ -34,11 +35,14 @@ import RSDatabaseObjC CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, statusCode INTEGER, 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, lastChecked REAL NOT NULL); + CREATE TABLE IF NOT EXISTS articleThumbnail (articleID TEXT PRIMARY KEY NOT NULL, thumbnailURL TEXT, lastChecked REAL NOT NULL); """ - private init() { - let databasePath = AppConfig.dataFolder - .appendingPathComponent("ImageMetadata.db").path + private convenience init() { + self.init(databasePath: AppConfig.dataFolder.appendingPathComponent("ImageMetadata.db").path) + } + + init(databasePath: String) { self.databasePath = databasePath let queue = DatabaseQueue(databasePath: databasePath) queue.runCreateStatements(Self.tableCreationStatements) @@ -49,6 +53,8 @@ import RSDatabaseObjC let cutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.failureRetentionDays) queue.runInDatabase { database in DownloadFailureTable.removeExpired(olderThan: cutoff, database: database) + // Expiring rows means articles get rechecked, in case their HTML changed. + ArticleThumbnailTable.removeExpired(olderThan: cutoff, database: database) database.vacuumIfNeeded() } } @@ -95,6 +101,22 @@ import RSDatabaseObjC } } + // MARK: - ArticleThumbnail + + func fetchArticleThumbnails(articleIDs: [String]) async -> [ArticleThumbnailRecord] { + await withCheckedContinuation { continuation in + queue.runInDatabase { database in + continuation.resume(returning: ArticleThumbnailTable.fetch(articleIDs: articleIDs, database: database)) + } + } + } + + func saveArticleThumbnails(_ records: [ArticleThumbnailRecord]) { + queue.runInTransaction { database in + ArticleThumbnailTable.save(records, database: database) + } + } + // MARK: - DownloadFailure public func recentlyFailed(url: String) -> Bool { diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift new file mode 100644 index 000000000..54219dbfb --- /dev/null +++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift @@ -0,0 +1,65 @@ +// +// ArticleThumbnailFinderTests.swift +// ImagesTests +// +// Created by Brent Simmons on 10/25/26. +// + +import Foundation +import Testing +import Articles +@testable import Images + +/// Swift Testing also has an `Attachment` type. +private typealias ArticleAttachment = Articles.Attachment + +@MainActor @Suite struct ArticleThumbnailFinderTests { + + @Test func smallModePrefersThumbnailAndLargeModePrefersImage() throws { + let finder = ArticleThumbnailFinder(metadataDatabase: ImageMetadataDatabase(databasePath: ":memory:")) + let attachment = try #require(ArticleAttachment(url: "https://example.com/attachment.jpg", mimeType: "image/jpeg", title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 1200, height: 800, medium: nil)) + let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg", attachments: [attachment]) + + #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg") + #expect(finder.thumbnailURL(for: article, mode: .large) == "https://example.com/image.jpg") + } + + @Test func failedImageFallsThroughToNextSource() { + let metadataDatabase = ImageMetadataDatabase(databasePath: ":memory:") + let finder = ArticleThumbnailFinder(metadataDatabase: metadataDatabase) + let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg") + + metadataDatabase.recordFailure(url: "https://example.com/thumbnail.jpg", statusCode: 404) + + #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg") + } + + @Test func htmlThumbnailIsDiscoveredAndSaved() async { + let metadataDatabase = ImageMetadataDatabase(databasePath: ":memory:") + let finder = ArticleThumbnailFinder(metadataDatabase: metadataDatabase) + let html = """ +

+

+ """ + let articleWithImage = makeArticle(articleID: "1", contentHTML: html) + let articleWithoutImage = makeArticle(articleID: "2", contentHTML: "

No images.

") + + #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == nil) + + await finder.discoverThumbnailURLs(for: [articleWithImage, articleWithoutImage]) + #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == "https://example.com/uploads/photo.jpg") + #expect(finder.thumbnailURL(for: articleWithoutImage, mode: .small) == nil) + + let records = await metadataDatabase.fetchArticleThumbnails(articleIDs: ["1", "2"]) + #expect(Set(records.map(\.articleID)) == ["1", "2"]) + #expect(records.first { $0.articleID == "1" }?.thumbnailURL == "https://example.com/uploads/photo.jpg") + #expect(records.first { $0.articleID == "2" }?.thumbnailURL == nil) + } +} + +// MARK: - Helpers + +private func makeArticle(articleID: String = "1", contentHTML: String? = nil, imageURL: String? = nil, thumbnailURL: String? = nil, attachments: [ArticleAttachment]? = nil) -> Article { + let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date()) + return Article(accountID: "account", articleID: articleID, feedID: "feed", uniqueID: articleID, title: nil, contentHTML: contentHTML, contentText: nil, markdown: nil, url: "https://example.com/posts/\(articleID)", externalURL: nil, summary: nil, imageURL: imageURL, thumbnailURL: thumbnailURL, datePublished: nil, dateModified: nil, authors: nil, attachments: attachments, status: status) +} diff --git a/NetNewsWire.xctestplan b/NetNewsWire.xctestplan index 510c27962..b159bb8bc 100644 --- a/NetNewsWire.xctestplan +++ b/NetNewsWire.xctestplan @@ -100,6 +100,13 @@ "identifier" : "FeedFinderTests", "name" : "FeedFinderTests" } + }, + { + "target" : { + "containerPath" : "container:Modules\/Images", + "identifier" : "ImagesTests", + "name" : "ImagesTests" + } } ], "version" : 1