Merge branch '7.1.3-pre' of https://github.com/Ranchero-Software/NetNewsWire into 7.1.3-pre

This commit is contained in:
Brent Simmons committed 2026-07-29 10:23:34 -07:00
commit 3b8ebc6bc1
17 files changed
+186 -78

No files matched your search

+1
View File
@@ -164,6 +164,7 @@ let appName = "NetNewsWire"
func applicationDidFinishLaunching(_ note: Notification) {
WebViewConfiguration.resolveBrowserUserAgent()
Task {
await WebViewConfiguration.compileContentBlockingRules()
}
+1 -15
View File
@@ -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
}
@@ -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
@@ -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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4868>
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
}
@@ -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
}
@@ -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)
@@ -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)
}
}
@@ -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)
+18 -6
View File
@@ -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
@@ -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.
/// <https://github.com/Ranchero-Software/NetNewsWire/issues/4868>
@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
+21
View File
@@ -22,6 +22,7 @@ import Images
private var selectingActivity: NSUserActivity?
private var readingActivity: NSUserActivity?
private var readingArticle: Article?
private var browsingActivity: NSUserActivity?
#if os(macOS)
var stateRestorationActivity: NSUserActivity {
@@ -54,11 +55,30 @@ import Images
}
func invalidateCurrentActivities() {
invalidateBrowsing()
invalidateReading()
invalidateSelecting()
invalidateNextUnread()
}
// Handoff advertises the in-app browser's page, not the article behind it.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5369>
func browsing(url: URL) {
browsingActivity?.invalidate()
let activity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
activity.webpageURL = url
activity.isEligibleForHandoff = true
browsingActivity = activity
activity.becomeCurrent()
}
func invalidateBrowsing() {
browsingActivity?.invalidate()
browsingActivity = nil
readingActivity?.becomeCurrent()
}
func selecting(sidebarItem: SidebarItem) {
invalidateCurrentActivities()
@@ -98,6 +118,7 @@ import Images
}
func reading(feed: SidebarItem?, article: Article?) {
invalidateBrowsing()
invalidateReading()
invalidateNextUnread()
@@ -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<WKUserContentController>.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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4453>
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 {
@@ -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)
+1
View File
@@ -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()
}
+12 -1
View File
@@ -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
@@ -888,10 +888,21 @@ private extension WebViewController {
guard let viewController = SFSafariViewController.safeSafariViewController(url) else {
return
}
viewController.delegate = self
coordinator?.beganBrowsing(url: url)
present(viewController, animated: true)
}
}
// MARK: SFSafariViewControllerDelegate
extension WebViewController: @preconcurrency SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
coordinator?.endedBrowsing()
}
}
// MARK: Find in Article
private struct FindInArticleOptions: Codable {
+8
View File
@@ -1528,6 +1528,14 @@ struct SidebarItemNode: Hashable, Sendable {
}
}
func beganBrowsing(url: URL) {
activityManager.browsing(url: url)
}
func endedBrowsing() {
activityManager.invalidateBrowsing()
}
func navigateToFeeds() {
mainFeedCollectionViewController?.focus()
selectArticle(nil)
+3 -26
View File
@@ -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)
}
}
}