diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 9d7d496f8..f6249d554 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -164,6 +164,7 @@ let appName = "NetNewsWire" func applicationDidFinishLaunching(_ note: Notification) { + WebViewConfiguration.resolveBrowserUserAgent() Task { await WebViewConfiguration.compileContentBlockingRules() } diff --git a/Mac/Scripting/AppDelegate+Scriptability.swift b/Mac/Scripting/AppDelegate+Scriptability.swift index 439a86878..e3433a1dc 100644 --- a/Mac/Scripting/AppDelegate+Scriptability.swift +++ b/Mac/Scripting/AppDelegate+Scriptability.swift @@ -61,21 +61,7 @@ extension AppDelegate: AppDelegateAppleEvents { } if let themeURL = URL(string: themeURLString) { - let request = URLRequest(url: themeURL) - let task = URLSession.shared.downloadTask(with: request) { location, _, error in - guard let location = location else { - return - } - - Task { @MainActor in - do { - try ArticleThemeDownloader.shared.handleFile(at: location) - } catch { - NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) - } - } - } - task.resume() + ArticleThemeDownloader.shared.downloadTheme(from: themeURL) } return } diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift index 6fe321e00..a0353b8b6 100644 --- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift +++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift @@ -117,7 +117,7 @@ nonisolated private extension HTMLMetadataDownloader { activityLog.didStart(.htmlMetadataDownloader, kind: kind) do { - let downloadResponse = try await Downloader.shared.download(actualURL) + let downloadResponse = try await Downloader.shared.download(actualURL, userAgentStyle: .browser) if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { let urlToUse = response.url ?? actualURL diff --git a/Modules/Images/Sources/Images/FaviconDownloader.swift b/Modules/Images/Sources/Images/FaviconDownloader.swift index f99f7e5ee..322fc7891 100644 --- a/Modules/Images/Sources/Images/FaviconDownloader.swift +++ b/Modules/Images/Sources/Images/FaviconDownloader.swift @@ -131,12 +131,7 @@ extension Notification.Name { } public func favicon(with faviconURL: String, homePageURL: String?) -> IconImage? { - if !faviconURL.hasPrefix("http://") && !faviconURL.hasPrefix("https://") { - Self.logger.debug("Skipping non-http(s) URL: \(faviconURL)") - return nil - } - if ImageMetadataDatabase.shared.recentlyFailed(url: faviconURL) { - Self.logger.debug("Skipping recently-failed URL: \(faviconURL)") + guard canAttemptDownload(faviconURL) else { return nil } let downloader = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL) @@ -158,11 +153,8 @@ extension Notification.Name { if let faviconURLs = findFaviconURLs(with: url) { // If the site explicitly specifies favicon.ico, it will appear twice. self.currentHomePageHasOnlyFaviconICO = faviconURLs.count == 1 - - if let firstIconURL = faviconURLs.first { - _ = self.favicon(with: firstIconURL, homePageURL: url) - self.remainingFaviconURLs[url] = faviconURLs.dropFirst() - } + self.remainingFaviconURLs[url] = faviconURLs[...] + downloadNextFavicon(forHomePageURL: url) } return nil @@ -187,17 +179,8 @@ extension Notification.Name { return } guard singleFaviconDownloader.iconImage != nil else { - if let faviconURLs = remainingFaviconURLs[homePageURL] { - if let nextIconURL = faviconURLs.first { - _ = favicon(with: nextIconURL, homePageURL: singleFaviconDownloader.homePageURL) - remainingFaviconURLs[homePageURL] = faviconURLs.dropFirst() - } else { - remainingFaviconURLs[homePageURL] = nil - - if currentHomePageHasOnlyFaviconICO { - ImageMetadataDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: nil) - } - } + if remainingFaviconURLs[homePageURL] != nil { + downloadNextFavicon(forHomePageURL: homePageURL) } return } @@ -248,6 +231,36 @@ private extension FaviconDownloader { return faviconURLs + [defaultFaviconURL] } + func canAttemptDownload(_ faviconURL: String) -> Bool { + if !faviconURL.hasPrefix("http://") && !faviconURL.hasPrefix("https://") { + Self.logger.debug("Skipping non-http(s) URL: \(faviconURL)") + return false + } + if ImageMetadataDatabase.shared.recentlyFailed(url: faviconURL) { + Self.logger.debug("Skipping recently-failed URL: \(faviconURL)") + return false + } + return true + } + + // A skipped candidate advances to the next one — otherwise the queue + // would stall and the remaining candidates would never be tried. + // + func downloadNextFavicon(forHomePageURL homePageURL: String) { + while let faviconURL = remainingFaviconURLs[homePageURL]?.first { + remainingFaviconURLs[homePageURL] = remainingFaviconURLs[homePageURL]?.dropFirst() + if canAttemptDownload(faviconURL) { + _ = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL) + return + } + } + + remainingFaviconURLs[homePageURL] = nil + if currentHomePageHasOnlyFaviconICO { + ImageMetadataDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: nil) + } + } + func faviconDownloader(withURL faviconURL: String, homePageURL: String?) -> SingleFaviconDownloader { var firstTimeSeeingHomepageURL = false @@ -295,6 +308,12 @@ private extension HTMLMetadataRecord { private func shouldAllowFavicon(_ favicon: HTMLMetadataRecord.Favicon) -> Bool { + // Only http(s) — a data: or other non-web URL can't be downloaded as a favicon. + guard let urlString = favicon.urlString, + urlString.hasPrefix("http://") || urlString.hasPrefix("https://") else { + return false + } + // Check mime type. if let mimeType = favicon.type, let utType = UTType(mimeType: mimeType) { if Self.ignoredTypes.contains(utType) { @@ -303,7 +322,7 @@ private extension HTMLMetadataRecord { } // Check file extension. - if let urlString = favicon.urlString, let url = URL(string: urlString), let utType = UTType(filenameExtension: url.pathExtension) { + if let url = URL(string: urlString), let utType = UTType(filenameExtension: url.pathExtension) { if Self.ignoredTypes.contains(utType) { return false } diff --git a/Modules/Images/Sources/Images/HomePageFaviconTable.swift b/Modules/Images/Sources/Images/HomePageFaviconTable.swift index 98b113de2..f69980905 100644 --- a/Modules/Images/Sources/Images/HomePageFaviconTable.swift +++ b/Modules/Images/Sources/Images/HomePageFaviconTable.swift @@ -13,6 +13,7 @@ import RSDatabaseObjC public struct HomePageFaviconRecord: Sendable { public let homePageURL: String public let faviconURL: String? + public let lastChecked: Date } struct HomePageFaviconTable { @@ -27,7 +28,7 @@ struct HomePageFaviconTable { static func fetchAll(database: FMDatabase) -> [HomePageFaviconRecord] { var results = [HomePageFaviconRecord]() - guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.faviconURL) FROM \(name);", withArgumentsIn: []) else { + guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.faviconURL), \(Column.lastChecked) FROM \(name);", withArgumentsIn: []) else { return results } defer { @@ -38,7 +39,8 @@ struct HomePageFaviconTable { continue } let faviconURL = resultSet.string(forColumn: Column.faviconURL) - results.append(HomePageFaviconRecord(homePageURL: homePageURL, faviconURL: faviconURL)) + let lastChecked = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastChecked)) + results.append(HomePageFaviconRecord(homePageURL: homePageURL, faviconURL: faviconURL, lastChecked: lastChecked)) } return results } diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift index 2b6e0d4b8..503111474 100644 --- a/Modules/Images/Sources/Images/ImageDownloader.swift +++ b/Modules/Images/Sources/Images/ImageDownloader.swift @@ -164,7 +164,7 @@ private extension ImageDownloader { let downloadResponse: DownloadResponse do { - downloadResponse = try await Downloader.shared.download(imageURL) + 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) diff --git a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift index 25cbb7393..3ef3af06d 100644 --- a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift +++ b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift @@ -150,7 +150,8 @@ private extension ImageMetadataDatabase { for record in homePageRecords { if let faviconURL = record.faviconURL { homePageToFaviconURL[record.homePageURL] = faviconURL - } else { + } else if Date().timeIntervalSince(record.lastChecked) < TimeInterval(days: Self.failureRetryDays) { + // A no-favicon verdict expires after failureRetryDays, so the homepage gets rechecked. homePagesWithNoFavicon.insert(record.homePageURL) } } diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index 643315b33..2b380a186 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -147,7 +147,7 @@ private extension SingleFaviconDownloader { let downloadResponse: DownloadResponse do { - downloadResponse = try await Downloader.shared.download(url) + downloadResponse = try await Downloader.shared.download(url, userAgentStyle: .browser) } catch { Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)") activityLog.didFail(.faviconDownloader, kind: kind, error: error) diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index dac4fad84..fe855261f 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -42,9 +42,13 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi urlSession.invalidateAndCancel() } - public func download(_ url: URL) async throws -> DownloadResponse { + public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { + try await download(URLRequest(url: url), userAgentStyle: userAgentStyle) + } + + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { try await withCheckedThrowingContinuation { continuation in - download(url) { downloadResponse, error in + download(urlRequest, userAgentStyle: userAgentStyle) { downloadResponse, error in if let error { continuation.resume(throwing: error) } else { @@ -54,12 +58,12 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi } } - public func download(_ url: URL, _ callback: @escaping DownloadCallback) { + public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed, _ callback: @escaping DownloadCallback) { assert(Thread.isMainThread) - download(URLRequest(url: url), callback) + download(URLRequest(url: url), userAgentStyle: userAgentStyle, callback) } - public func download(_ urlRequest: URLRequest, _ callback: @escaping DownloadCallback) { + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, _ callback: @escaping DownloadCallback) { assert(Thread.isMainThread) guard let url = urlRequest.url else { @@ -98,7 +102,15 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi } var urlRequestToUse = urlRequest - urlRequestToUse.addSpecialCaseUserAgentIfNeeded() + switch userAgentStyle { + case .feed: + break // the session's user agent + case .specialCaseFeed: + urlRequestToUse.setValue(UserAgent.extendedUserAgent, forHTTPHeaderField: HTTPRequestHeader.userAgent) + case .browser: + urlRequestToUse.setValue(UserAgent.browserUserAgent, forHTTPHeaderField: HTTPRequestHeader.userAgent) + } + urlRequestToUse.addSpecialCaseUserAgentIfNeeded() // Host requirements win over the requested style. let task = urlSession.dataTask(with: urlRequestToUse) { (data, response, error) in diff --git a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift index 8b1942cfa..14d597e12 100755 --- a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift +++ b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift @@ -8,8 +8,28 @@ import Foundation +/// Which User-Agent a download sends. +public enum UserAgentStyle: Sendable { + + /// The app's normal feed-reader user agent — the session default. + case feed + + /// The extended feed-reader user agent that some hosts require. + case specialCaseFeed + + /// The browser-style user agent that matches the article web view. + case browser +} + nonisolated public struct UserAgent { + /// Browser-style user agent for favicon and homepage-HTML downloads — + /// some servers reject requests without a browser-like user agent. + /// The app replaces this at startup with the article web view's actual + /// user agent, so the two match. This value is the fallback. + /// + @MainActor public static var browserUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) NetNewsWire" + public static func fromInfoPlist() -> String? { return Bundle.main.object(forInfoDictionaryKey: "UserAgent") as? String diff --git a/Shared/Article Rendering/WebViewConfiguration.swift b/Shared/Article Rendering/WebViewConfiguration.swift index 963ab4fd9..d2dbb55db 100644 --- a/Shared/Article Rendering/WebViewConfiguration.swift +++ b/Shared/Article Rendering/WebViewConfiguration.swift @@ -9,6 +9,7 @@ import Foundation import os import WebKit +import RSWeb @MainActor final class WebViewConfiguration { @@ -16,6 +17,10 @@ import WebKit private static var contentBlockingRuleList: WKContentRuleList? private static var configuredContentControllers = NSHashTable.weakObjects() + private static let applicationNameForUserAgent = "NetNewsWire" + + // Keeps the web view alive while resolveBrowserUserAgent() waits for its answer. + private static var userAgentWebView: WKWebView? static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { assert(Thread.isMainThread) @@ -30,7 +35,7 @@ import WebKit // Present article content as NetNewsWire on top of WebKit's default browser UA, rather than a non-browser string. // - configuration.applicationNameForUserAgent = "NetNewsWire" + configuration.applicationNameForUserAgent = applicationNameForUserAgent #if os(iOS) configuration.allowsInlineMediaPlayback = true @@ -51,6 +56,23 @@ import WebKit } } + /// Ask WebKit for the article web view's user agent and use it for favicon + /// and homepage-HTML downloads, so the two match. Call early at app startup. + /// Until it resolves — or if it fails — UserAgent.browserUserAgent's fallback value applies. + static func resolveBrowserUserAgent() { + let configuration = WKWebViewConfiguration() + configuration.applicationNameForUserAgent = applicationNameForUserAgent + let webView = WKWebView(frame: .zero, configuration: configuration) + userAgentWebView = webView + + webView.evaluateJavaScript("navigator.userAgent") { result, _ in + if let userAgent = result as? String, userAgent.hasPrefix("Mozilla/") { + UserAgent.browserUserAgent = userAgent + } + userAgentWebView = nil + } + } + /// Compile content blocking rules. Call early at app startup. static func compileContentBlockingRules() async { diff --git a/Shared/ArticleStyles/ArticleThemeDownloader.swift b/Shared/ArticleStyles/ArticleThemeDownloader.swift index 4f4503553..47097c8a7 100644 --- a/Shared/ArticleStyles/ArticleThemeDownloader.swift +++ b/Shared/ArticleStyles/ArticleThemeDownloader.swift @@ -8,15 +8,19 @@ import Foundation import Zip +import RSWeb public final class ArticleThemeDownloader: Sendable { public static let shared = ArticleThemeDownloader() public enum ArticleThemeDownloaderError: LocalizedError { + case downloadFailed case noThemeFile public var errorDescription: String? { switch self { + case .downloadFailed: + return "The NetNewsWire theme could not be downloaded." case .noThemeFile: return "There is no NetNewsWire theme available." } @@ -25,6 +29,29 @@ public final class ArticleThemeDownloader: Sendable { private init() {} + @MainActor public func downloadTheme(from url: URL) { + NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil) + + Task { @MainActor in + do { + let downloadResponse = try await Downloader.shared.download(url, userAgentStyle: .browser) + guard let data = downloadResponse.data, !data.isEmpty, + let response = downloadResponse.response, response.statusIsOK else { + throw ArticleThemeDownloaderError.downloadFailed + } + + // handleFile expects a file whose .tmp name becomes the .zip name. + let temporaryFileURL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString) + .appendingPathExtension("tmp") + try data.write(to: temporaryFileURL) + try handleFile(at: temporaryFileURL) + } catch { + NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) + } + } + } + public func handleFile(at location: URL) throws { createDownloadDirectoryIfRequired() let movedFileLocation = try moveTheme(from: location) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 3af2bfa2c..e954203d6 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -63,6 +63,7 @@ import Images func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FaviconGenerator.templateImage = Assets.Images.faviconTemplate + WebViewConfiguration.resolveBrowserUserAgent() Task { await WebViewConfiguration.compileContentBlockingRules() } diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index fbbbfeb67..04b077a5f 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -703,7 +703,7 @@ private extension WebViewController { guard let imageURL = URL(string: clickMessage.imageURL) else { return } - Downloader.shared.download(imageURL) { [weak self] downloadResponse, error in + Downloader.shared.download(imageURL, userAgentStyle: .browser) { [weak self] downloadResponse, error in guard let self, let data = downloadResponse.data, error == nil, !data.isEmpty, let image = UIImage(data: data) else { return diff --git a/iOS/SceneDelegate.swift b/iOS/SceneDelegate.swift index c66d7cdc2..26f4825f3 100644 --- a/iOS/SceneDelegate.swift +++ b/iOS/SceneDelegate.swift @@ -192,32 +192,9 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - if let providedThemeURL = queryItems.first(where: { $0.name == "url" })?.value { - if let themeURL = URL(string: providedThemeURL) { - let request = URLRequest(url: themeURL) - - DispatchQueue.main.async { - NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil) - } - let task = URLSession.shared.downloadTask(with: request) { location, _, error in - guard - let location = location else { return } - - Task { @MainActor in - do { - try ArticleThemeDownloader.shared.handleFile(at: location) - } catch { - NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) - } - } - } - task.resume() - } else { - print("No theme URL") - return - } - } else { - return + if let providedThemeURL = queryItems.first(where: { $0.name == "url" })?.value, + let themeURL = URL(string: providedThemeURL) { + ArticleThemeDownloader.shared.downloadTheme(from: themeURL) } } }