Merge branch '7.1.3-pre'

# Conflicts:
#	xcconfig/common/NetNewsWire_mac_target_common.xcconfig
#	xcconfig/common/NetNewsWire_version.xcconfig
This commit is contained in:
Brent Simmons committed 2026-08-02 16:26:42 -07:00
commit 057b56ff73
137 files changed
+3686 -1486

No files matched your search

-126
View File
@@ -1,126 +0,0 @@
//
// AddWebFeedIntentHandler.swift
// NetNewsWire
//
// Created by Maurice Parker on 10/18/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Intents
public enum AddWebFeedIntentHandlerError: LocalizedError, Sendable {
case communicationFailure
public var errorDescription: String? {
switch self {
case .communicationFailure:
return NSLocalizedString("Unable to communicate with NetNewsWire.", comment: "Communication failure")
}
}
}
public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling {
override init() {
super.init()
}
public func resolveUrl(for intent: AddWebFeedIntent) async -> AddWebFeedUrlResolutionResult {
guard let url = intent.url else {
return .unsupported(forReason: .required)
}
return .success(with: url)
}
public func provideAccountNameOptions(for intent: AddWebFeedIntent) async throws -> [String] {
guard let extensionContainers = await ExtensionContainersFile.read() else {
throw AddWebFeedIntentHandlerError.communicationFailure
}
let accountNames = extensionContainers.accounts.map { $0.name }
return accountNames
}
public func resolveAccountName(for intent: AddWebFeedIntent) async -> AddWebFeedAccountNameResolutionResult {
guard let accountName = intent.accountName else {
return .notRequired()
}
guard let extensionContainers = await ExtensionContainersFile.read() else {
return .unsupported(forReason: .communication)
}
if extensionContainers.findAccount(forName: accountName) == nil {
return .unsupported(forReason: .invalid)
}
return .success(with: accountName)
}
public func provideFolderNameOptions(for intent: AddWebFeedIntent) async throws -> [String] {
guard let extensionContainers = await ExtensionContainersFile.read() else {
throw AddWebFeedIntentHandlerError.communicationFailure
}
guard let accountName = intent.accountName, let account = extensionContainers.findAccount(forName: accountName) else {
return [String]()
}
let folderNames = account.folders.map { $0.name }
return folderNames
}
public func resolveFolderName(for intent: AddWebFeedIntent) async -> AddWebFeedFolderNameResolutionResult {
guard let accountName = intent.accountName, let folderName = intent.folderName else {
return .notRequired()
}
guard let extensionContainers = await ExtensionContainersFile.read() else {
return .unsupported(forReason: .communication)
}
guard let account = extensionContainers.findAccount(forName: accountName) else {
return .unsupported(forReason: .invalid)
}
let folder = account.findFolder(forName: folderName)
if folder == nil {
return .unsupported(forReason: .invalid)
}
return .success(with: folderName)
}
public func handle(intent: AddWebFeedIntent) async -> AddWebFeedIntentResponse {
guard let url = intent.url, let extensionContainers = await ExtensionContainersFile.read() else {
return AddWebFeedIntentResponse(code: .failure, userActivity: nil)
}
let account: ExtensionAccount? = {
if let accountName = intent.accountName {
return extensionContainers.findAccount(forName: accountName)
} else {
return extensionContainers.accounts.first
}
}()
guard let validAccount = account else {
return AddWebFeedIntentResponse(code: .failure, userActivity: nil)
}
let container: ExtensionContainer? = {
if let folderName = intent.folderName {
return validAccount.findFolder(forName: folderName)
} else {
return validAccount
}
}()
guard let validContainer = container, let containerID = validContainer.containerID else {
return AddWebFeedIntentResponse(code: .failure, userActivity: nil)
}
let request = ExtensionFeedAddRequest(name: nil, feedURL: url, destinationContainerID: containerID)
ExtensionFeedAddRequestFile.save(request)
return AddWebFeedIntentResponse(code: .success, userActivity: nil)
}
}
-314
View File
@@ -1,314 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>INEnums</key>
<array/>
<key>INIntentDefinitionModelVersion</key>
<string>1.1</string>
<key>INIntentDefinitionNamespace</key>
<string>U6u7RF</string>
<key>INIntentDefinitionSystemVersion</key>
<string>19D76</string>
<key>INIntentDefinitionToolsBuildVersion</key>
<string>11B53</string>
<key>INIntentDefinitionToolsVersion</key>
<string>11.2.1</string>
<key>INIntents</key>
<array>
<dict>
<key>INIntentCategory</key>
<string>create</string>
<key>INIntentConfigurable</key>
<true/>
<key>INIntentDescription</key>
<string>Add a web feed</string>
<key>INIntentDescriptionID</key>
<string>IuAbef</string>
<key>INIntentIneligibleForSuggestions</key>
<true/>
<key>INIntentInput</key>
<string>url</string>
<key>INIntentKeyParameter</key>
<string>url</string>
<key>INIntentLastParameterTag</key>
<integer>4</integer>
<key>INIntentManagedParameterCombinations</key>
<dict>
<key>url,accountName</key>
<dict>
<key>INIntentParameterCombinationSupportsBackgroundExecution</key>
<true/>
<key>INIntentParameterCombinationTitle</key>
<string>Add ${url} to ${accountName}</string>
<key>INIntentParameterCombinationTitleID</key>
<string>kaKsEY</string>
<key>INIntentParameterCombinationUpdatesLinked</key>
<true/>
</dict>
<key>url,accountName,folderName</key>
<dict>
<key>INIntentParameterCombinationSupportsBackgroundExecution</key>
<true/>
<key>INIntentParameterCombinationTitle</key>
<string>Add ${url} to ${folderName} in ${accountName}</string>
<key>INIntentParameterCombinationTitleID</key>
<string>dkSFD2</string>
<key>INIntentParameterCombinationUpdatesLinked</key>
<true/>
</dict>
</dict>
<key>INIntentName</key>
<string>AddWebFeed</string>
<key>INIntentParameters</key>
<array>
<dict>
<key>INIntentParameterDisplayName</key>
<string>URL</string>
<key>INIntentParameterDisplayNameID</key>
<string>BCHr23</string>
<key>INIntentParameterDisplayPriority</key>
<integer>1</integer>
<key>INIntentParameterName</key>
<string>url</string>
<key>INIntentParameterPromptDialogs</key>
<array>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogFormatString</key>
<string>What is the ${url} you would like add?</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>jLLidQ</string>
<key>INIntentParameterPromptDialogType</key>
<string>Primary</string>
</dict>
</array>
<key>INIntentParameterSupportsResolution</key>
<true/>
<key>INIntentParameterTag</key>
<integer>2</integer>
<key>INIntentParameterType</key>
<string>URL</string>
<key>INIntentParameterUnsupportedReasons</key>
<array>
<dict>
<key>INIntentParameterUnsupportedReasonCode</key>
<string>required</string>
<key>INIntentParameterUnsupportedReasonCustom</key>
<true/>
<key>INIntentParameterUnsupportedReasonFormatString</key>
<string>You must supply a URL.</string>
<key>INIntentParameterUnsupportedReasonFormatStringID</key>
<string>4xjRes</string>
</dict>
</array>
</dict>
<dict>
<key>INIntentParameterCustomDisambiguation</key>
<true/>
<key>INIntentParameterDisplayName</key>
<string>Account Name</string>
<key>INIntentParameterDisplayNameID</key>
<string>CSrgUY</string>
<key>INIntentParameterDisplayPriority</key>
<integer>2</integer>
<key>INIntentParameterMetadata</key>
<dict>
<key>INIntentParameterMetadataCapitalization</key>
<string>Sentences</string>
</dict>
<key>INIntentParameterName</key>
<string>accountName</string>
<key>INIntentParameterPromptDialogs</key>
<array>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogType</key>
<string>Primary</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogFormatString</key>
<string>There are ${count} options matching ‘${accountName}’.</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>IbqUVS</string>
<key>INIntentParameterPromptDialogType</key>
<string>DisambiguationIntroduction</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogFormatString</key>
<string>Which one?</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>fWs3li</string>
<key>INIntentParameterPromptDialogType</key>
<string>DisambiguationSelection</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogFormatString</key>
<string>Just to confirm, you wanted ‘${accountName}’?</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>HHiZUh</string>
<key>INIntentParameterPromptDialogType</key>
<string>Confirmation</string>
</dict>
</array>
<key>INIntentParameterSupportsDynamicEnumeration</key>
<true/>
<key>INIntentParameterSupportsResolution</key>
<true/>
<key>INIntentParameterTag</key>
<integer>3</integer>
<key>INIntentParameterType</key>
<string>String</string>
<key>INIntentParameterUnsupportedReasons</key>
<array>
<dict>
<key>INIntentParameterUnsupportedReasonCode</key>
<string>invalid</string>
<key>INIntentParameterUnsupportedReasonCustom</key>
<true/>
<key>INIntentParameterUnsupportedReasonFormatString</key>
<string>A valid Account Name is required.</string>
<key>INIntentParameterUnsupportedReasonFormatStringID</key>
<string>JGkCuS</string>
</dict>
<dict>
<key>INIntentParameterUnsupportedReasonCode</key>
<string>communication</string>
<key>INIntentParameterUnsupportedReasonCustom</key>
<true/>
<key>INIntentParameterUnsupportedReasonFormatString</key>
<string>Unable to communicate with NetNewsWire.</string>
<key>INIntentParameterUnsupportedReasonFormatStringID</key>
<string>uSfloN</string>
</dict>
</array>
</dict>
<dict>
<key>INIntentParameterCustomDisambiguation</key>
<true/>
<key>INIntentParameterDisplayName</key>
<string>Folder Name</string>
<key>INIntentParameterDisplayNameID</key>
<string>zXhMPF</string>
<key>INIntentParameterDisplayPriority</key>
<integer>3</integer>
<key>INIntentParameterMetadata</key>
<dict>
<key>INIntentParameterMetadataCapitalization</key>
<string>Sentences</string>
</dict>
<key>INIntentParameterName</key>
<string>folderName</string>
<key>INIntentParameterPromptDialogs</key>
<array>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogType</key>
<string>Primary</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogFormatString</key>
<string>There are ${count} options matching ‘${folderName}’.</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>5CYbGL</string>
<key>INIntentParameterPromptDialogType</key>
<string>DisambiguationIntroduction</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogFormatString</key>
<string>Which one?</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>gEzXaM</string>
<key>INIntentParameterPromptDialogType</key>
<string>DisambiguationSelection</string>
</dict>
<dict>
<key>INIntentParameterPromptDialogCustom</key>
<true/>
<key>INIntentParameterPromptDialogFormatString</key>
<string>Just to confirm, you wanted ‘${folderName}’?</string>
<key>INIntentParameterPromptDialogFormatStringID</key>
<string>k5GTo0</string>
<key>INIntentParameterPromptDialogType</key>
<string>Confirmation</string>
</dict>
</array>
<key>INIntentParameterRelationship</key>
<dict>
<key>INIntentParameterRelationshipParentName</key>
<string>accountName</string>
<key>INIntentParameterRelationshipPredicateName</key>
<string>HasAnyValue</string>
</dict>
<key>INIntentParameterSupportsDynamicEnumeration</key>
<true/>
<key>INIntentParameterSupportsResolution</key>
<true/>
<key>INIntentParameterTag</key>
<integer>4</integer>
<key>INIntentParameterType</key>
<string>String</string>
<key>INIntentParameterUnsupportedReasons</key>
<array>
<dict>
<key>INIntentParameterUnsupportedReasonCode</key>
<string>invalid</string>
<key>INIntentParameterUnsupportedReasonCustom</key>
<true/>
<key>INIntentParameterUnsupportedReasonFormatString</key>
<string>A valid Folder Name is required.</string>
<key>INIntentParameterUnsupportedReasonFormatStringID</key>
<string>ef5kBt</string>
</dict>
<dict>
<key>INIntentParameterUnsupportedReasonCode</key>
<string>communication</string>
<key>INIntentParameterUnsupportedReasonCustom</key>
<true/>
<key>INIntentParameterUnsupportedReasonFormatString</key>
<string>Unable to communicate with NetNewsWire.</string>
<key>INIntentParameterUnsupportedReasonFormatStringID</key>
<string>ExjqcE</string>
</dict>
</array>
</dict>
</array>
<key>INIntentResponse</key>
<dict>
<key>INIntentResponseCodes</key>
<array>
<dict>
<key>INIntentResponseCodeName</key>
<string>success</string>
<key>INIntentResponseCodeSuccess</key>
<true/>
</dict>
<dict>
<key>INIntentResponseCodeName</key>
<string>failure</string>
</dict>
</array>
</dict>
<key>INIntentTitle</key>
<string>Add Web Feed</string>
<key>INIntentTitleID</key>
<string>oV681v</string>
<key>INIntentType</key>
<string>Custom</string>
<key>INIntentVerb</key>
<string>Add</string>
</dict>
</array>
<key>INTypes</key>
<array/>
</dict>
</plist>
-30
View File
@@ -1,30 +0,0 @@
"4xjRes" = "You must supply a URL.";
"8Dh9Yy" = "No feed was found at the specified URL.";
"BCHr23" = "URL";
"CSrgUY" = "Account Name";
"HHiZUh" = "Just to confirm, you wanted ‘${accountName}’?";
"IbqUVS" = "There are ${count} options matching ‘${accountName}’.";
"IuAbef" = "Add a feed";
"JGkCuS" = "An account name is required.";
"UGGPkp" = "You are already subscribed to this feed in this account.";
"dkSFD2" = "Add${url}to ${accountName}";
"drQfaI" = "No feed was found at the specified URL.";
"fWs3li" = "Which one?";
"jLLidQ" = "What is the ${url}you would like add?";
"oV681v" = "Add Feed";
"srME8b" = "You are already subscribed to this feed in this account.";
+4 -28
View File
@@ -30,7 +30,7 @@ let appName = "NetNewsWire"
@main
@MainActor final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidations, UNUserNotificationCenterDelegate, UnreadCountProvider, SPUStandardUserDriverDelegate, SPUUpdaterDelegate {
static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppDelegate")
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "AppDelegate")
private struct WindowRestorationIdentifiers {
static let mainWindow = "mainWindow"
@@ -164,6 +164,7 @@ let appName = "NetNewsWire"
func applicationDidFinishLaunching(_ note: Notification) {
WebViewConfiguration.resolveBrowserUserAgent()
Task {
await WebViewConfiguration.compileContentBlockingRules()
}
@@ -327,6 +328,7 @@ let appName = "NetNewsWire"
func applicationDidBecomeActive(_ notification: Notification) {
fireOldTimers()
AppNotification.postAppDidBecomeActive()
}
func applicationDidResignActive(_ notification: Notification) {
@@ -991,33 +993,7 @@ extension AppDelegate {
return
}
themeImportPath = userInfo["path"] as? String
var informativeText: String = ""
if let decodingError = error as? DecodingError {
switch decodingError {
case .typeMismatch(let type, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the type—“%@”—is mismatched in the Info.plist", comment: "Type mismatch")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, type as! CVarArg) as String
case .valueNotFound(let value, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the value—“%@”—is not found in the Info.plist.", comment: "Decoding value missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, value as! CVarArg) as String
case .keyNotFound(let codingKey, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the key—“%@”—is not found in the Info.plist.", comment: "Decoding key missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, codingKey.stringValue) as String
case .dataCorrupted(let context):
guard let underlyingError = context.underlyingError as NSError?,
let debugDescription = underlyingError.userInfo["NSDebugDescription"] as? String else {
informativeText = error.localizedDescription
break
}
let localizedError = NSLocalizedString("This theme cannot be used because of data corruption in the Info.plist: %@.", comment: "Decoding key missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, debugDescription) as String
default:
informativeText = error.localizedDescription
}
} else {
informativeText = error.localizedDescription
}
let informativeText = ArticleThemesManager.importErrorMessage(for: error)
DispatchQueue.main.async {
let alert = NSAlert()
+15 -2
View File
@@ -6,21 +6,34 @@
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import RSCore
import AppKit
import Account
import os
struct ErrorHandler: Sendable {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ErrorHandler")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ErrorHandler")
@Sendable public static func present(_ error: Error) {
Task { @MainActor in
NSApplication.shared.presentError(error)
NSApplication.shared.presentError(errorForPresentation(error))
}
}
public static func log(_ error: Error) {
logger.error("\(error.localizedDescription)")
}
// Drop a recovery suggestion when there are no recovery options to act on it.
private static func errorForPresentation(_ error: Error) -> NSError {
let nsError = error as NSError
guard nsError.localizedRecoverySuggestion != nil, nsError.localizedRecoveryOptions == nil else {
return nsError
}
var userInfo = nsError.userInfo
userInfo[NSLocalizedDescriptionKey] = nsError.localizedDescription
userInfo[NSLocalizedRecoverySuggestionErrorKey] = nil
return NSError(domain: nsError.domain, code: nsError.code, userInfo: userInfo)
}
}
@@ -91,6 +91,10 @@ final class DetailViewController: NSViewController, WKUIDelegate {
currentWebViewController.stopMediaPlayback()
}
func fetchSelectedHTML(_ completion: @escaping (String?) -> Void) {
currentWebViewController.fetchSelectedHTML(completion)
}
func canScrollDown() async -> Bool {
await currentWebViewController.canScrollDown()
}
@@ -8,6 +8,7 @@
import AppKit
@preconcurrency import WebKit
import os
import RSCore
import Articles
import Images
@@ -19,6 +20,8 @@ import Images
final class DetailWebViewController: NSViewController {
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DetailWebViewController")
weak var delegate: DetailWebViewControllerDelegate?
var webView: DetailWebView!
var state: DetailState = .noSelection {
@@ -27,6 +30,7 @@ final class DetailWebViewController: NSViewController {
switch state {
case .article(_, let scrollY), .extracted(_, _, let scrollY):
windowScrollY = scrollY
pendingScrollRestorationY = scrollY
default:
break
}
@@ -67,6 +71,21 @@ final class DetailWebViewController: NSViewController {
private let keyboardDelegate = DetailKeyboardDelegate()
private var windowScrollY: CGFloat?
// The scroll offset to apply to the next-loaded article. Kept separate from windowScrollY,
// which windowDidScroll messages still arriving from the previous article can overwrite.
private var pendingScrollRestorationY: CGFloat?
// The page posts windowDidScroll continuously while scrolling, including during momentum.
private var lastWindowDidScrollMessageDate: Date?
private static let recentScrollInterval: TimeInterval = 0.2
private var webViewMayStillBeScrolling: Bool {
guard let lastWindowDidScrollMessageDate else {
return false
}
return Date().timeIntervalSince(lastWindowDidScrollMessageDate) < Self.recentScrollInterval
}
private var isShowingExtractedArticle: Bool {
switch state {
case .extracted:
@@ -84,26 +103,16 @@ final class DetailWebViewController: NSViewController {
override func loadView() {
let configuration = WebViewConfiguration.configuration(with: detailIconSchemeHandler)
view = NSView()
configuration.userContentController.add(self, name: MessageName.windowDidScroll)
configuration.userContentController.add(self, name: MessageName.mouseDidEnter)
configuration.userContentController.add(self, name: MessageName.mouseDidExit)
webView = DetailWebView(frame: NSRect.zero, configuration: configuration)
webView.uiDelegate = self
webView.navigationDelegate = self
webView.keyboardDelegate = keyboardDelegate
webView.translatesAutoresizingMaskIntoConstraints = false
view = webView
webView = createWebView()
view.addSubview(webView)
// Hide the web view until the first reload (navigation) is committed (plus some delay) to avoid the white flash that happens on initial display in dark mode.
// See bug #901.
webView.isHidden = true
waitingForFirstReload = true
webInspectorEnabled = AppDefaults.shared.webInspectorEnabled
NotificationCenter.default.addObserver(self, selector: #selector(webInspectorEnabledDidChange(_:)), name: .WebInspectorEnabledDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
@@ -150,6 +159,18 @@ final class DetailWebViewController: NSViewController {
webView.evaluateJavaScript("stopMediaPlayback();")
}
// MARK: Selection
func fetchSelectedHTML(_ completion: @escaping (String?) -> Void) {
webView.evaluateJavaScript("selectedHTML()") { result, _ in
guard let selectedHTML = (result as? String)?.trimmingWhitespace, !selectedHTML.isEmpty else {
completion(nil)
return
}
completion(selectedHTML)
}
}
// MARK: Scrolling
func canScrollDown() async -> Bool {
@@ -178,6 +199,7 @@ extension DetailWebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == MessageName.windowDidScroll {
windowScrollY = message.body as? CGFloat
lastWindowDidScrollMessageDate = Date()
} else if message.name == MessageName.mouseDidEnter, let link = message.body as? String {
delegate?.mouseDidEnter(self, link: link)
} else if message.name == MessageName.mouseDidExit {
@@ -228,11 +250,16 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate {
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let windowScrollY else {
guard webView === self.webView else {
return
}
webView.evaluateJavaScript("window.scrollTo(0, \(windowScrollY));")
self.windowScrollY = nil
removeOldWebViews()
if let pendingScrollRestorationY {
webView.evaluateJavaScript("window.scrollTo(0, \(pendingScrollRestorationY));")
self.pendingScrollRestorationY = nil
}
}
// WKUIDelegate
@@ -266,9 +293,39 @@ private extension DetailWebViewController {
}
}
func createWebView() -> DetailWebView {
let configuration = WebViewConfiguration.configuration(with: detailIconSchemeHandler)
configuration.userContentController.add(self, name: MessageName.windowDidScroll)
configuration.userContentController.add(self, name: MessageName.mouseDidEnter)
configuration.userContentController.add(self, name: MessageName.mouseDidExit)
let webView = DetailWebView(frame: view.bounds, configuration: configuration)
webView.uiDelegate = self
webView.navigationDelegate = self
webView.keyboardDelegate = keyboardDelegate
webView.autoresizingMask = [.width, .height]
webView.configuration.preferences._developerExtrasEnabled = AppDefaults.shared.webInspectorEnabled
return webView
}
// Old web views stay on top until the new one finishes loading — see reloadHTML().
func removeOldWebViews() {
for subview in view.subviews {
guard let oldWebView = subview as? DetailWebView, oldWebView !== webView else {
continue
}
if let window = view.window, let responder = window.firstResponder as? NSView, responder.isDescendant(of: oldWebView) {
window.makeFirstResponder(webView)
}
oldWebView.removeFromSuperview()
}
}
func reloadHTMLMaintainingScrollPosition() {
fetchScrollInfo { scrollInfo in
self.windowScrollY = scrollInfo?.offsetY
self.pendingScrollRestorationY = scrollInfo?.offsetY
self.reloadHTML()
}
}
@@ -312,6 +369,20 @@ private extension DetailWebViewController {
var html = try! MacroProcessor.renderedText(withTemplate: ArticleRenderer.page.html, substitutions: substitutions)
html = ArticleRenderingSpecialCases.filterHTMLIfNeeded(baseURL: rendering.baseURL, html: html)
// When the old article may still be scrolling, swap in a fresh web view for the
// new content. Scrolling momentum lives in the web content process and survives
// loading new HTML — replacing the web view is what keeps a flick on the old
// article from scrolling the new one.
// The old web view stays on top until the new one finishes loading, which also
// covers the new web view's first paint.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/901>
if !webView.isHidden && webViewMayStillBeScrolling {
Self.logger.debug("DetailWebViewController: swapping in a fresh web view because the old one may still be scrolling")
let newWebView = createWebView()
view.addSubview(newWebView, positioned: .below, relativeTo: webView)
webView = newWebView
}
WebViewConfiguration.addContentBlockingRules(to: webView)
webView.loadHTMLString(html, baseURL: URL(string: rendering.baseURL))
}
+18
View File
@@ -19,6 +19,24 @@ function linkHover() {
}
}
// The selection as an HTML fragment — links, bold, and so on included.
function selectedHTML() {
var selection = window.getSelection();
var container = document.createElement("div");
for (var i = 0; i < selection.rangeCount; i++) {
container.appendChild(selection.getRangeAt(i).cloneContents());
}
// Relative URLs would break outside this page.
container.querySelectorAll("a[href]").forEach(function(anchor) {
anchor.setAttribute("href", anchor.href);
});
// A single-paragraph selection doesn't need its <p> wrapper.
if (container.childNodes.length === 1 && container.firstChild.nodeName === "P") {
return container.firstChild.innerHTML;
}
return container.innerHTML;
}
function postRenderProcessing() {
scrollDetection();
linkHover();
+47 -9
View File
@@ -18,7 +18,7 @@ enum TimelineSourceMode {
}
final class MainWindowController: NSWindowController, NSUserInterfaceValidations {
static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainWindowController")
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "MainWindowController")
@IBOutlet var articleThemePopUpButton: NSPopUpButton?
@@ -26,7 +26,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
private var isShowingExtractedArticle = false
private var articleExtractor: ArticleExtractor?
private var sharingServicePickerDelegate: NSSharingServicePickerDelegate?
private var sharingServicePickerDelegate: SharingServicePickerDelegate?
private let windowAutosaveName = NSWindow.FrameAutosaveName("MainWindow")
private static let mainWindowWidthsStateKey = "mainWindowWidthsStateKey"
@@ -149,7 +149,10 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
Self.logger.debug("MainWindowController: Saving state to UserDefaults: \(state)")
let data = try? NSKeyedArchiver.archivedData(withRootObject: state, requiringSecureCoding: true)
AppDefaults.shared.secureWindowState = data
window?.saveFrame(usingName: windowAutosaveName)
// Don't save the frame in full screen — it would replace the saved windowed frame with the screen's frame.
if let window, !window.styleMask.contains(.fullScreen) {
window.saveFrame(usingName: windowAutosaveName)
}
}
func restoreStateFromUserDefaults() {
@@ -536,19 +539,36 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
assertionFailure("Expected toolbarShowShareMenu to be called only by the Share item in the toolbar.")
return
}
guard let view = shareToolbarItem.view else {
// TODO: handle menu form representation
// In the toolbar's Text Only mode or overflow menu the item's view isn't on-window, so anchor the picker to the window instead.
let anchorView: NSView
let anchorRect: NSRect
if let view = shareToolbarItem.view, view.window != nil {
anchorView = view
anchorRect = view.bounds
} else if let contentView = window?.contentView {
anchorView = contentView
anchorRect = NSRect(x: contentView.frame.width / 2.0, y: contentView.frame.height - 4, width: 1, height: 1)
} else {
return
}
let sortedArticles = selectedArticles.sortedByDate(.orderedAscending)
let items = sortedArticles.map { ArticlePasteboardWriter(article: $0) }
let sharingServicePicker = NSSharingServicePicker(items: items)
sharingServicePicker.delegate = sharingServicePickerDelegate
sharingServicePicker.show(relativeTo: view.bounds, of: view, preferredEdge: .minY)
detailViewController?.fetchSelectedHTML { selectedHTML in
self.sharingServicePickerDelegate?.selectedHTML = selectedHTML
let sharingServicePicker = NSSharingServicePicker(items: items)
sharingServicePicker.delegate = self.sharingServicePickerDelegate
sharingServicePicker.show(relativeTo: anchorRect, of: anchorView, preferredEdge: .minY)
}
}
@IBAction func moveFocusToSearchField(_ sender: Any?) {
// The search field lives in the toolbar — show it if hidden.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4896>
if let toolbar = window?.toolbar, !toolbar.isVisible {
toolbar.isVisible = true
}
guard let searchField = currentSearchField else {
return
}
@@ -855,6 +875,7 @@ extension MainWindowController: NSToolbarDelegate {
let button = ArticleExtractorButton()
button.action = #selector(toggleArticleExtractor(_:))
toolbarItem.view = button
toolbarItem.menuFormRepresentation = NSMenuItem(title: description, action: #selector(toggleArticleExtractor(_:)), keyEquivalent: "")
return toolbarItem
case .share:
@@ -1047,7 +1068,14 @@ private extension MainWindowController {
func restoreState(from state: MainWindowState) {
if state.isFullScreen {
window?.toggleFullScreen(self)
// Defer the toggle — during launch the window isn't on screen yet,
// and AppKit ignores toggleFullScreen for windows not yet on screen.
Task { @MainActor in
guard let window = self.window, !window.styleMask.contains(.fullScreen) else {
return
}
window.toggleFullScreen(nil)
}
}
restoreSplitViewState(from: state)
@@ -1160,6 +1188,10 @@ private extension MainWindowController {
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
// Text Only toolbar mode shows the label and menu form representation, so they need to track state too.
let shortName = markingRead ? NSLocalizedString("Mark Read", comment: "command") : NSLocalizedString("Mark Unread", comment: "command")
toolbarItem.label = shortName
toolbarItem.menuFormRepresentation?.title = shortName
}
if let menuItem = item as? NSMenuItem {
@@ -1244,6 +1276,10 @@ private extension MainWindowController {
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
// Text Only toolbar mode shows the label and menu form representation, so they need to track state too.
let shortName = starring ? NSLocalizedString("Star", comment: "Star") : NSLocalizedString("Unstar", comment: "Unstar")
toolbarItem.label = shortName
toolbarItem.menuFormRepresentation?.title = shortName
}
if let menuItem = item as? NSMenuItem {
@@ -1438,6 +1474,8 @@ private extension MainWindowController {
toolbarItem.view = button
toolbarItem.toolTip = title
toolbarItem.label = title
// A menu form representation keeps view-based items working in the toolbar's Text Only mode and overflow menu.
toolbarItem.menuFormRepresentation = NSMenuItem(title: title, action: Selector((selector)), keyEquivalent: "")
return toolbarItem
}
@@ -11,6 +11,8 @@ import RSCore
@objc final class SharingServicePickerDelegate: NSObject, @MainActor NSSharingServicePickerDelegate {
var selectedHTML: String?
private let sharingServiceDelegate: SharingServiceDelegate
init(_ window: NSWindow?) {
@@ -19,14 +21,14 @@ import RSCore
@MainActor func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, sharingServicesForItems items: [Any], proposedSharingServices proposedServices: [NSSharingService]) -> [NSSharingService] {
let filteredServices = proposedServices.filter { $0.menuItemTitle != "NetNewsWire" }
return filteredServices + SharingServicePickerDelegate.customSharingServices(for: items)
return filteredServices + SharingServicePickerDelegate.customSharingServices(for: items, selectedHTML: selectedHTML)
}
func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, delegateFor sharingService: NSSharingService) -> NSSharingServiceDelegate? {
return sharingServiceDelegate
}
@MainActor static func customSharingServices(for items: [Any]) -> [NSSharingService] {
@MainActor static func customSharingServices(for items: [Any], selectedHTML: String? = nil) -> [NSSharingService] {
let customServices: [SendToCommand] = [SendToMarsEditCommand(), SendToMicroBlogCommand()]
return customServices.compactMap { (sendToCommand) -> NSSharingService? in
@@ -35,13 +37,13 @@ import RSCore
return nil
}
guard sendToCommand.canSendObject(object, selectedText: nil) else {
guard sendToCommand.canSendObject(object, selectedText: selectedHTML) else {
return nil
}
let image = sendToCommand.image ?? NSImage()
return NSSharingService(title: sendToCommand.title, image: image, alternateImage: nil) {
sendToCommand.sendObject(object, selectedText: nil)
sendToCommand.sendObject(object, selectedText: selectedHTML)
}
}
}
+19 -1
View File
@@ -108,7 +108,7 @@ final class SidebarCell: NSTableCellView {
guard let cellAppearance = cellAppearance else {
return
}
let layout = SidebarCellLayout(appearance: cellAppearance, cellSize: bounds.size, shouldShowImage: shouldShowImage, textField: titleView, unreadCountView: unreadCountView)
let layout = SidebarCellLayout(appearance: cellAppearance, cellSize: bounds.size, trailingEdge: trailingEdge(), shouldShowImage: shouldShowImage, textField: titleView, unreadCountView: unreadCountView)
layoutWith(layout)
}
@@ -135,6 +135,24 @@ private extension SidebarCell {
view.translatesAutoresizingMaskIntoConstraints = false
}
// Ask the outline view for the cell frame instead of trusting
// the cell's own width, which can be stale while the outline view is tiling.
func trailingEdge() -> CGFloat {
var view = superview
while let currentView = view {
if let outlineView = currentView as? NSOutlineView {
let row = outlineView.row(for: self)
if row < 0 {
return bounds.maxX
}
let cellFrame = outlineView.frameOfCell(atColumn: 0, row: row)
return convert(NSPoint(x: cellFrame.maxX, y: 0), from: outlineView).x
}
view = currentView.superview
}
return bounds.maxX
}
func layoutWith(_ layout: SidebarCellLayout) {
faviconImageView.setFrameIfNotEqual(layout.faviconRect)
titleView.setFrameIfNotEqual(layout.titleRect)
@@ -16,8 +16,9 @@ import RSCore
let titleRect: CGRect
let unreadCountRect: CGRect
init(appearance: SidebarCellAppearance, cellSize: NSSize, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) {
init(appearance: SidebarCellAppearance, cellSize: NSSize, trailingEdge: CGFloat, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) {
let bounds = NSRect(x: 0.0, y: 0.0, width: floor(cellSize.width), height: floor(cellSize.height))
let maxX = floor(trailingEdge)
var rFavicon = NSRect.zero
if shouldShowImage {
@@ -40,7 +41,7 @@ import RSCore
var rUnread = NSRect.zero
if !unreadCountIsHidden {
rUnread.size = unreadCountSize
rUnread.origin.x = bounds.maxX - unreadCountSize.width
rUnread.origin.x = maxX - unreadCountSize.width
rUnread = rUnread.centeredVertically(in: bounds)
let textFieldMaxX = rUnread.minX - appearance.unreadCountMarginLeft
if rTextField.maxX > textFieldMaxX {
@@ -49,8 +50,8 @@ import RSCore
}
self.unreadCountRect = rUnread
if rTextField.maxX > bounds.maxX {
rTextField.size.width = bounds.maxX - rTextField.minX
if rTextField.maxX > maxX {
rTextField.size.width = maxX - rTextField.minX
}
self.titleRect = rTextField
}
@@ -12,6 +12,10 @@ import Articles
import RSCore
import Account
extension Notification.Name {
static let SidebarDidAcceptDrop = Notification.Name("SidebarDidAcceptDropNotification")
}
@objc @MainActor final class SidebarOutlineDataSource: NSObject, NSOutlineViewDataSource {
let treeController: TreeController
@@ -98,6 +102,14 @@ import Account
}
func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
let accepted = acceptDrop(outlineView, info, item, index)
if accepted {
NotificationCenter.default.post(name: .SidebarDidAcceptDrop, object: nil)
}
return accepted
}
private func acceptDrop(_ outlineView: NSOutlineView, _ info: NSDraggingInfo, _ item: Any?, _ index: Int) -> Bool {
let draggedFolders = PasteboardFolder.pasteboardFolders(with: info.draggingPasteboard)
let draggedFeeds = PasteboardFeed.pasteboardFeeds(with: info.draggingPasteboard)
if (draggedFolders == nil && draggedFeeds == nil) || (draggedFolders != nil && draggedFeeds != nil) {
@@ -753,11 +753,9 @@ private extension SidebarViewController {
}
func shouldSkipRow(_ row: Int) -> Bool {
let skipExpandedFolders = UserDefaults.standard.bool(forKey: "JalkutRespectFolderExpansionOnNextUnread")
// Skip group items, because they should never be selected.
// Skip expanded folders only if Jalkut's pref is enabled.
if rowIsGroupItem(row) || (skipExpandedFolders && rowIsExpandedFolder(row)) {
// Skip expanded folders — go to the feeds inside instead.
if rowIsGroupItem(row) || rowIsExpandedFolder(row) {
return true
}
return false
@@ -215,7 +215,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
private let keyboardDelegate = TimelineKeyboardDelegate()
private var timelineShowsSeparatorsObserver: NSKeyValueObservation?
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "TimelineViewController")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "TimelineViewController")
convenience init(delegate: TimelineDelegate) {
self.init(nibName: "TimelineTableView", bundle: nil)
@@ -244,6 +244,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarDidAcceptDrop(_:)), name: .SidebarDidAcceptDrop, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in
@@ -722,26 +723,35 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
@objc func accountStateDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() {
fetchAndReplaceArticlesAsync()
fetchAndReplacePreservingSelectionAsync()
}
}
@objc func accountsDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() {
fetchAndReplaceArticlesAsync()
fetchAndReplacePreservingSelectionAsync()
}
}
@objc func userDidDeleteAccount(_ note: Notification) {
undoManager?.removeAllActions() // Undo stack may contain actions for the deleted account.
if representedObjectsContainsAnyPseudoFeed() {
fetchAndReplaceArticlesAsync()
fetchAndReplacePreservingSelectionAsync()
}
}
@objc func handleSidebarDidAcceptDrop(_ note: Notification) {
// Drops aren't undoable — without this, ⌘Z could silently undo an older, unrelated action.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3583>
undoManager?.removeAllActions()
}
@objc func containerChildrenDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() || representedObjectsContainAnyFolder() {
fetchAndReplaceArticlesAsync()
// Merge, don't replace — replacing drops articles read this session
// from All Unread. Matches iOS.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3832>
queueFetchAndMergeArticles()
}
}
@@ -1043,6 +1053,19 @@ private extension TimelineViewController {
}
}
// The current article should stay in the timeline, and stay selected,
// when the timeline updates and the sidebar selection hasn't changed —
// even if the new fetch wouldn't otherwise include it.
func fetchAndReplacePreservingSelectionAsync() {
if let article = oneSelectedArticle, let account = article.account {
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID)
}
let savedSelection = selectedArticleIDs()
fetchAndReplaceArticlesAsync { [weak self] in
self?.restoreSelection(savedSelection)
}
}
func updateUnreadCount() {
var count = 0
for article in articles {
@@ -1190,7 +1213,7 @@ private extension TimelineViewController {
replaceArticles(with: fetchedArticles)
}
func fetchAndReplaceArticlesAsync() {
func fetchAndReplaceArticlesAsync(completion: (() -> Void)? = nil) {
// To be called when we need to do an entire fetch, but an async delay is okay.
// Example: we have the Today feed selected, and the calendar day just changed.
cancelPendingAsyncFetches()
@@ -1206,6 +1229,7 @@ private extension TimelineViewController {
fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (articles) in
self?.replaceArticles(with: articles)
completion?()
}
}
@@ -108,11 +108,6 @@ final class AccountsReaderAPIWindowController: NSWindowController {
let trimmedUsername = usernameTextField.stringValue.trimmingWhitespace
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: accountType, username: trimmedUsername) else {
self.errorMessageLabel.stringValue = NSLocalizedString("There is already an account of this type with that username created.", comment: "Duplicate Error")
return
}
let apiURL: URL
switch accountType {
case .freshRSS:
@@ -132,6 +127,11 @@ final class AccountsReaderAPIWindowController: NSWindowController {
return
}
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: accountType, username: trimmedUsername, endpoint: apiURL) else {
self.errorMessageLabel.stringValue = NSLocalizedString("There is already an account of this type with that username created.", comment: "Duplicate Error")
return
}
Task { @MainActor in
actionButton.isEnabled = false
progressIndicator.isHidden = false
@@ -1,6 +1,24 @@
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.000",
"green" : "0.631",
"red" : "0.922"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
@@ -54,7 +54,11 @@ final class SafariExtensionHandler: SFSafariExtensionHandler {
}
if openInDefaultBrowser == false {
feedURLString = feedURLString.replacingOccurrences(of: "feed:", with: "x-netnewswire-feed:")
if feedURLString.hasPrefix("feeds:") {
feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feeds:".count)
} else if feedURLString.hasPrefix("feed:") {
feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feed:".count)
}
}
if let feedURL = URL(string: feedURLString) {
@@ -1,72 +1,9 @@
var thisPageLinkObjects = null;
// The button is enabled on every web page. Clicking sends the page URL to the app,
// whose FeedFinder module does all feed discovery — head links, page scanning,
// URL guessing, special cases — so the logic lives in exactly one place.
// I convert the native "link" node into an object that I can pass out to the global page
function objectFromLink(theLink) {
var linkObject = new Object();
linkObject.href = theLink.href;
linkObject.type = theLink.type;
linkObject.title = theLink.title;
return linkObject;
}
// Some sites will list feeds with inappropriate or at least less-than-ideal information
// in the MIME type attribute. We cover some edge cases here that allow to be passed through,
// where they will successfully open as "feed://" URLs in the browser.
function isValidFeedLink(theLink) {
var isValid = false;
switch (theLink.type)
{
case "application/atom+xml":
case "application/x.atom+xml":
case "application/rss+xml":
// These types do not require other criteria.
isValid = (theLink.href != null);
case "text/xml":
case "application/rdf+xml":
// These types require a title that has "RSS" in it.
if (theLink.title && theLink.title.search(/RSS/i) != -1)
{
isValid = (theLink.href != null);
}
}
return isValid;
}
function scanForSyndicationFeeds() {
// In case we don't find any, we establish that we have at least tried by setting the
// variables to empty instead of null.
thisPageLinkObjects = []
thisPageLinks = document.querySelectorAll("link[href][rel~='alternate'][type]");
for (thisLinkIndex = 0; thisLinkIndex < thisPageLinks.length; thisLinkIndex++)
{
var thisLink = thisPageLinks[thisLinkIndex];
if (isValidFeedLink(thisLink))
{
thisPageLinkObjects.push(objectFromLink(thisLink));
}
}
}
function subscribeToFeed(theFeed) {
// Convert the URL to a feed:// scheme because Safari
// will refuse to load e.g. a feed that is listed merely
// as "text/xml". We do some preflighting of the link rel
// in the PageLoadEnd.js so we can be more confident it's a
// good feed: URL.
var feedURL = theFeed.href;
if (!feedURL.startsWith('feed:'))
{
feedURL = 'feed:' + feedURL;
}
safari.extension.dispatchMessage("subscribeToFeed", { "url": feedURL });
function subscribeToPage() {
safari.extension.dispatchMessage("subscribeToFeed", { "url": "feed:" + document.location.href });
}
function messageHandler(event) {
@@ -77,10 +14,9 @@ function messageHandler(event) {
// causing multiple responses to broadcast message about toolbar
// button being clicked. In the case of the "extra" injections,
// the document location is null, so we can avoid doing on anything.
if ((document.location != null) && (thisPageLinkObjects.length > 0))
if (document.location != null)
{
feedToOpen = thisPageLinkObjects[0];
subscribeToFeed(feedToOpen);
subscribeToPage();
}
}
else if (event.name === "ping")
@@ -93,7 +29,7 @@ function messageHandler(event) {
// succeed even if its been disabled and the page reloaded. Checking for the existence of
// document.location seems to ensure we have enough of a handle still on the document that
// we can do something useful with it.
var shouldValidate = (document.location != null) && (thisPageLinkObjects.length > 0);
var shouldValidate = (document.location != null);
// Pass back the same validationID we were handed so they can look up the correlated validationHandler
safari.extension.dispatchMessage("pong", { "validationID": event.message.validationID, "shouldValidate": shouldValidate });
@@ -105,6 +41,5 @@ document.addEventListener("DOMContentLoaded", function(event) {
if ((window.top === window) && (typeof safari != 'undefined') && (document.location != null))
{
safari.self.addEventListener("message", messageHandler, false)
scanForSyndicationFeeds();
}
});
+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
}
+16 -5
View File
@@ -91,7 +91,7 @@ public enum FetchType {
@MainActor public final class Account: ProgressInfoReporter, DisplayNameProvider, UnreadCountProvider, Container, Hashable {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Account")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Account")
public struct UserInfoKey {
public static let account = "account" // UserDidAddAccount, UserDidDeleteAccount
@@ -650,8 +650,9 @@ public enum FetchType {
let settings = feedSettings(feedURL: feedURL, feedID: feedURL)
let feed = Feed(account: self, url: opmlFeedSpecifier.feedURL, settings: settings)
if let feedTitle = opmlFeedSpecifier.title {
if feed.name == nil {
feed.name = feedTitle
// Store as editedName so the imported title survives the next refresh, which overwrites name with the feed's own title.
if feed.editedName == nil {
feed.editedName = feedTitle
}
}
return feed
@@ -685,6 +686,14 @@ public enum FetchType {
func createFeed(with name: String?, url: String, feedID: String, homePageURL: String?) -> Feed {
let settings = feedSettings(feedURL: url, feedID: feedID)
// The caller’s feedID is authoritative — repair a stored feedID that disagrees.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4172>
if settings.feedID != feedID {
Self.logger.info("Account: repairing feedID for \(url, privacy: .public): \(settings.feedID, privacy: .public) is now \(feedID, privacy: .public)")
settings.feedID = feedID
}
let feed = Feed(account: self, url: url, settings: settings)
feed.name = name
feed.homePageURL = homePageURL
@@ -913,16 +922,18 @@ public enum FetchType {
return articleChanges
}
func updateAsync(feedIDsAndItems: [String: Set<ParsedItem>], defaultRead: Bool) async {
@discardableResult
func updateAsync(feedIDsAndItems: [String: Set<ParsedItem>], defaultRead: Bool) async -> ArticleChanges {
// Used only by syncing systems.
precondition(Thread.isMainThread)
precondition(type != .onMyMac && type != .cloudKit)
guard !feedIDsAndItems.isEmpty else {
return
return ArticleChanges()
}
let newAndUpdatedArticles = await database.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead)
sendNotificationAbout(newAndUpdatedArticles)
return newAndUpdatedArticles
}
/// Mark statuses for articleIDs. Returns the articleIDs whose status actually changed.
@@ -18,10 +18,10 @@ public enum AccountError: LocalizedError {
case invalidResponse
case urlNotFound
case unknown
case wrappedError(error: Error, accountID: String, accountName: String)
case wrappedError(error: Error, accountID: String, accountName: String, accountType: AccountType)
public var isCredentialsError: Bool {
if case .wrappedError(let error, _, _) = self {
if case .wrappedError(let error, _, _, _) = self {
if case WebserviceError.httpError(let status) = error {
return isCredentialsError(status: status)
}
@@ -30,11 +30,11 @@ public enum AccountError: LocalizedError {
}
@MainActor static func wrapped(_ error: Error, _ account: Account) -> AccountError {
AccountError.wrappedError(error: error, accountID: account.accountID, accountName: account.nameForDisplay)
AccountError.wrappedError(error: error, accountID: account.accountID, accountName: account.nameForDisplay, accountType: account.type)
}
@MainActor public static func account(from error: AccountError?) -> Account? {
if case let .wrappedError(_, accountID, _) = error {
if case let .wrappedError(_, accountID, _, _) = error {
return AccountManager.shared.existingAccount(accountID: accountID)
}
return nil
@@ -56,17 +56,17 @@ public enum AccountError: LocalizedError {
return NSLocalizedString("The URL request resulted in a not found error.", comment: "URL not found")
case .unknown:
return NSLocalizedString("Unknown error", comment: "Unknown error")
case .wrappedError(let error, _, let accountName):
case .wrappedError(let error, _, let accountName, let accountType):
switch error {
case WebserviceError.httpError(let status):
if isCredentialsError(status: status) {
let localizedText = NSLocalizedString("Your “%@” credentials are invalid or expired.", comment: "Invalid or expired")
return NSString.localizedStringWithFormat(localizedText as NSString, accountName) as String
} else {
return unknownError(error, accountName)
return syncError(error, accountName, accountType)
}
default:
return unknownError(error, accountName)
return syncError(error, accountName, accountType)
}
}
}
@@ -77,7 +77,7 @@ public enum AccountError: LocalizedError {
return nil
case .createErrorAlreadySubscribed:
return nil
case .wrappedError(let error, _, _):
case .wrappedError(let error, _, _, _):
switch error {
case WebserviceError.httpError(let status):
if isCredentialsError(status: status) {
@@ -100,6 +100,12 @@ extension AccountError {
/// Returns a description that includes the error domain, code, and any underlying error.
static func detailedErrorMessage(_ error: Error) -> String {
// A parser diagnostic wouldn't help anybody — this usually means the
// service is down and returning an error page.
if error is DecodingError {
return NSLocalizedString("The service returned an invalid response.", comment: "Invalid response from service")
}
let nsError = error as NSError
var message = error.localizedDescription
if !nsError.domain.isEmpty {
@@ -117,9 +123,9 @@ extension AccountError {
private extension AccountError {
func unknownError(_ error: Error, _ accountName: String) -> String {
let localizedText = NSLocalizedString("An error occurred while processing the “%@” account: %@", comment: "Unknown error")
return NSString.localizedStringWithFormat(localizedText as NSString, accountName, AccountError.detailedErrorMessage(error)) as String
func syncError(_ error: Error, _ accountName: String, _ accountType: AccountType) -> String {
let localizedText = NSLocalizedString("An error occurred while syncing the %1$@ account “%2$@”: %3$@", comment: "Account sync error — account type, account name, error details")
return NSString.localizedStringWithFormat(localizedText as NSString, accountType.displayName, accountName, AccountError.detailedErrorMessage(error)) as String
}
func isCredentialsError(status: Int) -> Bool {
@@ -49,7 +49,7 @@ import ActivityLog
}
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AccountManager")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "AccountManager")
public var areUnreadCountsInitialized: Bool {
for account in activeAccounts {
@@ -221,12 +221,16 @@ import ActivityLog
NotificationCenter.default.post(name: .UserDidDeleteAccount, object: self, userInfo: userInfo)
}
public func duplicateServiceAccount(type: AccountType, username: String?) -> Bool {
public func duplicateServiceAccount(type: AccountType, username: String?, endpoint: URL? = nil) -> Bool {
guard type != .onMyMac else {
return false
}
for account in accounts {
if account.type == type && username == account.username {
// Self-hosted services can have the same username on different servers.
if let endpoint, let existingEndpoint = account.endpointURL, endpoint != existingEndpoint {
continue
}
return true
}
}
@@ -633,7 +637,7 @@ private extension AccountManager {
}
func duplicateServiceAccount(_ account: Account) -> Bool {
duplicateServiceAccount(type: account.type, username: account.username)
duplicateServiceAccount(type: account.type, username: account.username, endpoint: account.endpointURL)
}
func sortByName(_ accounts: [Account]) -> [Account] {
@@ -6,6 +6,7 @@
//
import Foundation
import RSCore
import os
import RSWeb
@@ -23,7 +24,7 @@ import RSWeb
let conditionalGetInfo: [String: HTTPConditionalGetInfo]?
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AccountSettingsImporter")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "AccountSettingsImporter")
/// Returns ImportedSettings if there is a Settings.plist to read.
/// Returns nil if there is no plist or it can't be read.
@@ -456,7 +456,9 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
account.removeFolderFromTree(folder)
try await account.logActivity(kind: .removeFolder, detail: folderName) {
syncProgress.addTask()
// Two tasks: finding the folder's feed externalIDs, removing the folder record.
// Every path below completes exactly two.
syncProgress.addTasks(2)
let feedExternalIDs: [String]
do {
@@ -570,7 +572,9 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
account.addFolderToTree(folder)
}
} catch {
syncProgress.completeTask()
// Only reachable when createFolder throws, before any of the
// 1 + feedsToRestore.count tasks completed — complete them all.
syncProgress.completeTasks(1 + feedsToRestore.count)
postSyncError(error, account: account, operation: "Restoring folder")
throw error
}
@@ -893,7 +897,9 @@ private extension CloudKitAccountDelegate {
editedName: editedName,
container: container)
} catch {
syncProgress.completeTasks(3)
// When FeedFinder.find is what threw, none of the five tasks have completed yet —
// four here plus one more from the validateFeed path or addDeadFeed.
syncProgress.completeTasks(4)
if validateFeed {
syncProgress.completeTask()
throw AccountError.createErrorNotFound
@@ -991,6 +997,11 @@ private extension CloudKitAccountDelegate {
func sendNewArticlesToTheCloud(_ account: Account, _ feed: Feed) {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
Task {
// Completes createRSSFeed's fifth task.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4538>
defer {
syncProgress.completeTask()
}
do {
let articles = await account.fetchArticlesAsync(.feed(feed))
@@ -126,6 +126,8 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate {
if let existingUnclaimedFeeds = existingUnclaimedFeeds[containerExternalID] {
for existingUnclaimedFeed in existingUnclaimedFeeds {
// Clear the top-level safety-net fallback (no-op if not there) so we don't leave a duplicate.
account.removeFeedFromTreeAtTopLevel(existingUnclaimedFeed)
container.addFeedToTreeAtTopLevel(existingUnclaimedFeed)
}
self.existingUnclaimedFeeds.removeValue(forKey: containerExternalID)
@@ -168,6 +170,13 @@ private extension CloudKitAcountZoneDelegate {
}
}
}
// Never leave a moved feed invisible: if its destination container(s) aren't known locally yet,
// keep it visible at the top level. addOrUpdateContainer relocates it when the folder record arrives.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5124>
if account.existingContainers(withFeed: feed).isEmpty {
account.addFeedToTreeAtTopLevel(feed)
}
}
@MainActor func createFeedIfNecessary(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, container: Container) {
@@ -11,10 +11,19 @@ import Articles
@MainActor final class FeedSettings {
private let feedURL: String
let feedID: String
private let database: FeedSettingsDatabase
weak var feed: Feed?
// Reassign only before a Feed is created from these settings — Feed copies feedID at init and hashes on it.
var feedID: String {
didSet {
if feedID != oldValue {
database.setString(feedID, for: feedURL, column: .feedID)
postSettingDidChange(.feedID)
}
}
}
var homePageURL: String? {
didSet {
if homePageURL != oldValue {
@@ -6,6 +6,7 @@
//
import Foundation
import RSCore
import os
import RSDatabase
import RSDatabaseObjC
@@ -57,7 +58,7 @@ final class FeedSettingsDatabase: Sendable {
nonisolated(unsafe) private let database: FMDatabase // Used on serial dispatch queue only
private let serialDispatchQueue: DispatchQueue
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedSettingsDatabase")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FeedSettingsDatabase")
init(databasePath: String) {
self.databasePath = databasePath
@@ -6,12 +6,13 @@
//
import Foundation
import RSCore
import os
import Articles
/// One-time import from FeedMetadata.plist into FeedSettingsDatabase.
@MainActor struct FeedSettingsImporter {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedSettingsImporter")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FeedSettingsImporter")
static func importIfNeeded(dataFolder: String, database: FeedSettingsDatabase) {
let plistPath = (dataFolder as NSString).appendingPathComponent("FeedMetadata.plist")
@@ -6,9 +6,10 @@
//
import Foundation
import RSCore
import os
struct Feedbin {
// Convention with this logger is to put "Feedbin: " at the beginning of each message.
static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Feedbin")
static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Feedbin")
}
@@ -752,7 +752,7 @@ private extension FeedbinAccountDelegate {
}
func sendArticleStatuses(_ statuses: [SyncStatus], apiCall: ([Int]) async throws -> Void) async throws -> Int {
guard !statuses.isEmpty else {
guard let key = statuses.first?.key else {
return 0
}
@@ -764,12 +764,12 @@ private extension FeedbinAccountDelegate {
for articleIDGroup in articleIDGroups {
do {
try await apiCall(articleIDGroup)
await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) }))
await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) }), key: key)
sentCount += articleIDGroup.count
} catch {
savedError = error
Self.logger.error("Feedbin: Article status sync call failed: \(error.localizedDescription)")
await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) }))
await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) }), key: key)
}
}
@@ -964,16 +964,16 @@ private extension FeedbinAccountDelegate {
}
let feedbinUnreadArticleIDs = Set(articleIDs.map { String($0) })
let updatableFeedbinUnreadArticleIDs = feedbinUnreadArticleIDs.subtracting(pendingArticleIDs)
let currentUnreadArticleIDs = await account.fetchUnreadArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Mark articles as unread
let deltaUnreadArticleIDs = updatableFeedbinUnreadArticleIDs.subtracting(currentUnreadArticleIDs)
let deltaUnreadArticleIDs = feedbinUnreadArticleIDs.subtracting(currentUnreadArticleIDs).subtracting(pendingArticleIDs)
let markedUnread = await account.markAsUnreadAsync(articleIDs: deltaUnreadArticleIDs)
// Mark articles as read
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableFeedbinUnreadArticleIDs)
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(feedbinUnreadArticleIDs).subtracting(pendingArticleIDs)
let markedRead = await account.markAsReadAsync(articleIDs: deltaReadArticleIDs)
return markedUnread.count + markedRead.count
@@ -989,16 +989,16 @@ private extension FeedbinAccountDelegate {
}
let feedbinStarredArticleIDs = Set(articleIDs.map { String($0) })
let updatableFeedbinStarredArticleIDs = feedbinStarredArticleIDs.subtracting(pendingArticleIDs)
let currentStarredArticleIDs = await account.fetchStarredArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Mark articles as starred
let deltaStarredArticleIDs = updatableFeedbinStarredArticleIDs.subtracting(currentStarredArticleIDs)
let deltaStarredArticleIDs = feedbinStarredArticleIDs.subtracting(currentStarredArticleIDs).subtracting(pendingArticleIDs)
let markedStarred = await account.markAsStarredAsync(articleIDs: deltaStarredArticleIDs)
// Mark articles as unstarred
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableFeedbinStarredArticleIDs)
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(feedbinStarredArticleIDs).subtracting(pendingArticleIDs)
let markedUnstarred = await account.markAsUnstarredAsync(articleIDs: deltaUnstarredArticleIDs)
return markedStarred.count + markedUnstarred.count
@@ -6,8 +6,9 @@
//
import Foundation
import RSCore
import os
struct Feedly: Sendable {
static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Feedly")
static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Feedly")
}
@@ -74,6 +74,10 @@ import Secrets
private static let markChunkSize = 300 // Feedly /v3/markers limit
private static let pendingStatusSendThreshold = 100
private static let feedsToRefreshPerSync = 5
// Slightly over a day so each feed's schedule drifts, rather than hitting the server at the same time daily.
private static let minimumFeedRefreshInterval: TimeInterval = 24.5 * 60 * 60
private var lastNoChangeSyncDate: Date?
private static let noChangeBackoffInterval: TimeInterval = 30 * 60
@@ -116,7 +120,7 @@ import Secrets
}
refreshProgress.reset()
refreshProgress.addTasks(6)
refreshProgress.addTasks(7)
progressInfo = ProgressInfo()
let startDate = Date()
@@ -140,6 +144,8 @@ import Secrets
refreshProgress.completeTask()
summary.articlesDownloaded = try await downloadEntries(for: account, articleIDs: missingIDs.union(updatedIDs))
refreshProgress.completeTask()
summary.newArticlesFromFeedRefresh = await refreshIndividualFeeds(for: account)
refreshProgress.completeTask()
return summary
}
accountSettings?.lastArticleFetchStartTime = startDate
@@ -233,11 +239,11 @@ import Secrets
let chunkIDs = Set(chunk)
try await logRefreshPage(for: account, kind: .sendArticleStatuses, message: { _ in "\(chunkIDs.count) \(pairing.action.rawValue)" }, { try await caller.mark(chunkIDs, as: pairing.action) })
}
await syncDatabase.deleteSelectedForProcessing(articleIDs)
await syncDatabase.deleteSelectedForProcessing(articleIDs, key: pairing.key)
sentCount += articleIDs.count
} catch {
Self.logger.error("Feedly: Article status sync call failed: \(error.localizedDescription)")
await syncDatabase.resetSelectedForProcessing(articleIDs)
await syncDatabase.resetSelectedForProcessing(articleIDs, key: pairing.key)
savedError = error
}
}
@@ -520,6 +526,12 @@ import Secrets
try await account.logActivity(kind: .removeFeed, detail: feed.url) {
try await caller.removeFeed(feed.feedID, fromCollectionWith: collectionID)
}
} catch WebserviceError.httpError(let status) where status == HTTPResponseCode.badRequest || status == HTTPResponseCode.notFound {
// Feedly doesn’t recognize this subscription — most likely a stale or malformed feedID.
// Let the local removal stand, since otherwise the feed could never be deleted.
// If Feedly still has the feed, the next sync will bring it back.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4172>
Self.logger.info("FeedlyAccountDelegate: Feedly returned \(status) when removing \(feed.url) — removing the feed locally anyway")
} catch {
folder.addFeedToTreeAtTopLevel(feed)
throw error
@@ -796,13 +808,16 @@ private extension FeedlyAccountDelegate {
let resource = FeedlyCategoryResourceID.Global.all(for: userID)
let remoteUnreadIDs = try await collectStreamIDs(for: account, resource: resource, kind: .refreshArticleStatuses, unreadOnly: true)
let pendingArticleIDs = (await syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set<String>()
// A failed pending-statuses read must not be treated as “nothing pending” — that would revert pending changes.
guard let pendingArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() else {
return (added: 0, removed: 0)
}
let adjustedRemoteUnreadIDs = remoteUnreadIDs.subtracting(pendingArticleIDs)
let localUnreadIDs = await account.fetchUnreadArticleIDsAsync()
let newlyUnread = adjustedRemoteUnreadIDs.subtracting(localUnreadIDs)
let toMarkRead = localUnreadIDs.subtracting(adjustedRemoteUnreadIDs)
let toMarkRead = localUnreadIDs.subtracting(adjustedRemoteUnreadIDs).subtracting(pendingArticleIDs)
await account.markAsUnreadAsync(articleIDs: adjustedRemoteUnreadIDs)
await account.markAsReadAsync(articleIDs: toMarkRead)
@@ -818,13 +833,16 @@ private extension FeedlyAccountDelegate {
let resource = FeedlyTagResourceID.Global.saved(for: userID)
let remoteStarredIDs = try await collectStreamIDs(for: account, resource: resource, kind: .refreshArticleStatuses, unreadOnly: nil)
let pendingArticleIDs = (await syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set<String>()
// A failed pending-statuses read must not be treated as “nothing pending” — that would revert pending changes.
guard let pendingArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() else {
return (added: 0, removed: 0)
}
let adjustedRemoteStarredIDs = remoteStarredIDs.subtracting(pendingArticleIDs)
let localStarredIDs = await account.fetchStarredArticleIDsAsync()
let newlyStarred = adjustedRemoteStarredIDs.subtracting(localStarredIDs)
let toUnstar = localStarredIDs.subtracting(adjustedRemoteStarredIDs)
let toUnstar = localStarredIDs.subtracting(adjustedRemoteStarredIDs).subtracting(pendingArticleIDs)
await account.markAsStarredAsync(articleIDs: adjustedRemoteStarredIDs)
await account.markAsUnstarredAsync(articleIDs: toUnstar)
@@ -893,20 +911,76 @@ private extension FeedlyAccountDelegate {
}
}
/// Directly refresh a few of the least-recently-checked feeds each sync, fetching each feed's own
/// Feedly stream. Backfills articles that the aggregate global.all stream doesn't return.
/// <https://github.com/Ranchero-Software/NetNewsWire/issues/4635>
/// Returns the total number of new articles ingested across the refreshed feeds.
func refreshIndividualFeeds(for account: Account) async -> Int {
let now = Date()
let due = account.flattenedFeeds()
.filter { feed in
guard let lastCheckDate = feed.lastCheckDate else {
return true // never checked — most overdue
}
return now.timeIntervalSince(lastCheckDate) >= Self.minimumFeedRefreshInterval
}
.sorted { ($0.lastCheckDate ?? .distantPast) < ($1.lastCheckDate ?? .distantPast) }
.prefix(Self.feedsToRefreshPerSync)
var newArticleCount = 0
for feed in due {
feed.lastCheckDate = now // mark the attempt; a failed feed retries next rotation, not immediately
do {
let successMessage: (IngestResult) -> String? = { "\($0.newArticleCount) new article\($0.newArticleCount == 1 ? "" : "s")" }
let result = try await account.logActivity(kind: .refreshFeedContent(feedURL: feed.url), detail: feed.nameForDisplay, successMessage: successMessage) {
let resource = FeedlyFeedResourceID(id: feed.feedID)
return try await self.syncStreamContents(for: account, resource: resource, paginated: false, newerThan: nil)
}
newArticleCount += result.newArticleCount
// ingest marks new articles read by default; restore the server's unread state for the ones that are unread.
if !result.newUnreadArticleIDs.isEmpty {
await account.markAsUnreadAsync(articleIDs: result.newUnreadArticleIDs)
}
} catch {
postSyncError(error, account: account, operation: "Refreshing feed \(feed.nameForDisplay)")
}
}
return newArticleCount
}
/// Pull stream contents for `resource`, optionally paginated, and update the account.
func syncStreamContents(for account: Account, resource: FeedlyResourceID, paginated: Bool, newerThan: Date?) async throws {
/// Returns the aggregate ingest result across pages.
@discardableResult
func syncStreamContents(for account: Account, resource: FeedlyResourceID, paginated: Bool, newerThan: Date?) async throws -> IngestResult {
var result = IngestResult()
var continuation: String?
repeat {
let stream = try await logRefreshPage(for: account, kind: .refreshArticles, message: { "\($0.items.count) articles" }, { try await caller.getStreamContents(for: resource, continuation: continuation, newerThan: newerThan, unreadOnly: nil) })
await ingest(entries: stream.items, into: account)
let pageResult = await ingest(entries: stream.items, into: account)
result.newArticleCount += pageResult.newArticleCount
result.newUnreadArticleIDs.formUnion(pageResult.newUnreadArticleIDs)
continuation = paginated ? stream.continuation : nil
} while continuation != nil
return result
}
func ingest(entries: [FeedlyEntry], into account: Account) async {
/// The outcome of ingesting a batch of Feedly entries.
struct IngestResult {
var newArticleCount = 0
/// New (not previously in the database) article IDs that are unread on the server.
var newUnreadArticleIDs = Set<String>()
}
/// Ingest entries, reporting the new-article count and which of the new articles are unread on the server.
@discardableResult
func ingest(entries: [FeedlyEntry], into account: Account) async -> IngestResult {
let parsedItems = entries.compactMap { FeedlyEntryParser(entry: $0).parsedItemRepresentation }
let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { $0.feedURL }).mapValues { Set($0) }
await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true)
let changes = await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true)
let newArticleIDs = Set(changes.new?.map { $0.articleID } ?? [])
let unreadEntryIDs = Set(entries.lazy.filter { $0.unread }.map { $0.id })
return IngestResult(newArticleCount: newArticleIDs.count, newUnreadArticleIDs: newArticleIDs.intersection(unreadEntryIDs))
}
}
@@ -998,6 +1072,7 @@ extension FeedlyAccountDelegate {
var feedListChanges = FeedListChanges()
var statusRefreshCounts = StatusRefreshCounts()
var articlesDownloaded = 0
var newArticlesFromFeedRefresh = 0
}
static func sendStatusMessage(count: Int) -> String {
@@ -1055,6 +1130,9 @@ extension FeedlyAccountDelegate {
if summary.articlesDownloaded > 0 {
parts.append("\(summary.articlesDownloaded) article\(summary.articlesDownloaded == 1 ? "" : "s") downloaded")
}
if summary.newArticlesFromFeedRefresh > 0 {
parts.append("\(summary.newArticlesFromFeedRefresh) new from feed refresh")
}
let refresh = summary.statusRefreshCounts
if refresh.unreadAdded > 0 {
parts.append("\(refresh.unreadAdded) marked unread")
@@ -68,7 +68,7 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
nonisolated(unsafe) private var session: ASWebAuthenticationSession?
private var error: Error?
private var activityID: Int?
nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "OAuthAccountAuthorizationOperation")
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "OAuthAccountAuthorizationOperation")
public init(accountType: AccountType) {
self.accountType = accountType
@@ -245,4 +245,3 @@ private extension OAuthAccountAuthorizationOperation {
didComplete()
}
}
@@ -73,7 +73,7 @@ import os
private var urlToFeedDictionary = [String: Feed]()
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "LocalAccountRefresher")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "LocalAccountRefresher")
@MainActor public func refreshFeeds(_ feeds: Set<Feed>) async {
await withCheckedContinuation { continuation in
@@ -112,25 +112,27 @@ import os
// Add any feeds we don't have and update any we do
var feedsToAdd = Set<NewsBlurFeed>()
feeds.forEach { feed in
let subFeedId = String(feed.feedID)
feeds.forEach { newsBlurFeed in
let subFeedId = String(newsBlurFeed.feedID)
if let feed = account.existingFeed(withFeedID: subFeedId) {
feed.name = feed.name
// If the name has been changed on the server remove the locally edited name
feed.editedName = nil
feed.homePageURL = feed.homePageURL
feed.externalID = String(feed.feedID)
feed.faviconURL = feed.faviconURL
// If the name has been changed on the server, remove the locally edited name.
if feed.name != newsBlurFeed.name {
feed.editedName = nil
}
feed.name = newsBlurFeed.name
feed.homePageURL = newsBlurFeed.homePageURL
feed.externalID = String(newsBlurFeed.feedID)
feed.faviconURL = newsBlurFeed.faviconURL
} else {
feedsToAdd.insert(feed)
feedsToAdd.insert(newsBlurFeed)
}
}
// Actually add feeds all in one go, so we don’t trigger various rebuilding things that Account does.
for feed in feedsToAdd {
let feed = account.createFeed(with: feed.name, url: feed.feedURL, feedID: String(feed.feedID), homePageURL: feed.homePageURL)
feed.externalID = String(feed.feedID)
for newsBlurFeed in feedsToAdd {
let feed = account.createFeed(with: newsBlurFeed.name, url: newsBlurFeed.feedURL, feedID: String(newsBlurFeed.feedID), homePageURL: newsBlurFeed.homePageURL)
feed.externalID = String(newsBlurFeed.feedID)
account.addFeedToTreeAtTopLevel(feed)
}
}
@@ -163,7 +165,10 @@ import os
let newsBlurFolderFeedIDs = folderRelationships.map { String($0.feedID) }
guard let folder = folderDict[folderName] else { return }
// A missing folder must not abort the rest of the relationship sync.
guard let folder = folderDict[folderName] else {
continue
}
// Move any feeds not in the folder to the account
for feed in folder.topLevelFeeds {
@@ -275,7 +280,7 @@ import os
throttle: Bool,
apiCall: (Set<String>) async throws -> Void)
async throws -> Int {
guard !statuses.isEmpty else {
guard let key = statuses.first?.key else {
return 0
}
@@ -287,12 +292,12 @@ import os
for storyHashGroup in storyHashGroups {
do {
try await apiCall(Set(storyHashGroup))
await syncDatabase.deleteSelectedForProcessing(Set(storyHashGroup))
await syncDatabase.deleteSelectedForProcessing(Set(storyHashGroup), key: key)
sentCount += storyHashGroup.count
} catch {
savedError = error
Self.logger.error("NewsBlur: Story status sync call failed: \(error.localizedDescription)")
await syncDatabase.resetSelectedForProcessing(Set(storyHashGroup))
await syncDatabase.resetSelectedForProcessing(Set(storyHashGroup), key: key)
}
}
@@ -312,16 +317,16 @@ import os
}
let newsBlurUnreadStoryHashes = Set(hashes.map { $0.hash })
let updatableNewsBlurUnreadStoryHashes = newsBlurUnreadStoryHashes.subtracting(pendingStoryHashes)
let currentUnreadArticleIDs = await account.fetchUnreadArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Mark articles as unread
let deltaUnreadArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs)
let deltaUnreadArticleIDs = newsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs).subtracting(pendingStoryHashes)
let markedUnread = await account.markAsUnreadAsync(articleIDs: deltaUnreadArticleIDs)
// Mark articles as read
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes)
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(newsBlurUnreadStoryHashes).subtracting(pendingStoryHashes)
let markedRead = await account.markAsReadAsync(articleIDs: deltaReadArticleIDs)
return markedUnread.count + markedRead.count
@@ -336,16 +341,16 @@ import os
}
let newsBlurStarredStoryHashes = Set(hashes.map { $0.hash })
let updatableNewsBlurUnreadStoryHashes = newsBlurStarredStoryHashes.subtracting(pendingStoryHashes)
let currentStarredArticleIDs = await account.fetchStarredArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Mark articles as starred
let deltaStarredArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentStarredArticleIDs)
let deltaStarredArticleIDs = newsBlurStarredStoryHashes.subtracting(currentStarredArticleIDs).subtracting(pendingStoryHashes)
let markedStarred = await account.markAsStarredAsync(articleIDs: deltaStarredArticleIDs)
// Mark articles as unstarred
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes)
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(newsBlurStarredStoryHashes).subtracting(pendingStoryHashes)
let markedUnstarred = await account.markAsUnstarredAsync(articleIDs: deltaUnstarredArticleIDs)
return markedStarred.count + markedUnstarred.count
@@ -21,7 +21,7 @@ import RSParser
}
}
private let saveQueue = CoalescingQueue(name: "Save Queue", interval: 0.5)
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "OPMLFile")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "OPMLFile")
init(filename: String, account: Account) {
self.fileURL = URL(fileURLWithPath: filename)
@@ -23,6 +23,7 @@ public enum ReaderAPIAccountDelegateError: LocalizedError {
case invalidParameter
case invalidResponse
case urlNotFound
case unsendableStatuses(Int)
public var errorDescription: String? {
switch self {
@@ -34,6 +35,8 @@ public enum ReaderAPIAccountDelegateError: LocalizedError {
return NSLocalizedString("There was an invalid response from the server.", comment: "Invalid response")
case .urlNotFound:
return NSLocalizedString("The API URL wasn't found.", comment: "The API URL wasn't found.")
case .unsendableStatuses(let count):
return String(format: NSLocalizedString("Dropped %d article status changes that can’t be encoded for this service.", comment: "Dropped unsendable article status changes"), count)
}
}
}
@@ -47,7 +50,14 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
private let syncDatabase: SyncDatabase
private let caller: ReaderAPICaller
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ReaderAPI")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ReaderAPI")
// Set on a 429 Too Many Requests response. Refreshing and status syncing are skipped
// until this date so we don’t keep burning the shared per-application API quota.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3001>
private var rateLimitResumeDate: Date?
private static let defaultRetryAfter: TimeInterval = 60 * 60
private static let zone1UsageThreshold = 0.9
var progressInfo = ProgressInfo() {
didSet {
@@ -103,6 +113,9 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
guard let account else {
return
}
if shouldSkipBecauseRateLimited() {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: refreshAll")
retrieveCredentialsIfNeeded(account)
@@ -118,18 +131,29 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
try? await sendArticleStatus()
refreshProgress.completeTask()
let articleIDs = try await account.logActivity(kind: .fetchArticleIDs, detail: "All articles", successMessage: { "\($0.count) article IDs" }, {
try await caller.retrieveItemIDs(type: .allForAccount, pageHandler: articleIDPageHandler(for: account, kind: .fetchArticleIDs))
})
refreshProgress.completeTask()
// The mark-as-read of all fetched article IDs and the unread download that
// corrects it are a pair — skipping just the second half would leave new
// articles wrongly marked read. Skip or run the whole reconcile together.
if shouldSkipStatusDownloadsToConserveQuota() {
refreshProgress.completeTask()
refreshProgress.completeTask()
} else {
let articleIDs = try await account.logActivity(kind: .fetchArticleIDs, detail: "All articles", successMessage: { "\($0.count) article IDs" }, {
try await caller.retrieveItemIDs(type: .allForAccount, pageHandler: articleIDPageHandler(for: account, kind: .fetchArticleIDs))
})
refreshProgress.completeTask()
_ = await account.markAsReadAsync(articleIDs: Set(articleIDs))
try? await refreshArticleStatus()
refreshProgress.completeTask()
_ = await account.markAsReadAsync(articleIDs: Set(articleIDs))
try? await refreshArticleStatus()
refreshProgress.completeTask()
}
await refreshMissingArticles(account)
refreshProgress.reset()
}
} catch WebserviceError.tooManyRequests(let retryAfter) {
refreshProgress.reset()
noteRateLimited(retryAfter: retryAfter, account: account, operation: "Refreshing account")
} catch {
Self.logger.error("ReaderAPIAccountDelegate: refreshAll 1 — error \(error.localizedDescription)")
refreshProgress.reset()
@@ -162,23 +186,42 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
guard let account else {
return false
}
guard variant != .inoreader else {
// Inoreader: no-op for this delegate.
if shouldSkipBecauseRateLimited() {
return false
}
Self.logger.debug("ReaderAPIAccountDelegate: syncArticleStatus")
let sentCount = try await sendArticleStatusReturningCount(for: account)
let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account)
return sentCount > 0 || refreshChangedCount > 0
do {
let sentCount = try await sendArticleStatusReturningCount(for: account)
// Inoreader: skip downloading statuses, to conserve its API rate limits — but do send,
// since a send is a single cheap request and skipping it loses stars.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4476>
if variant == .inoreader {
return sentCount > 0
}
let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account)
return sentCount > 0 || refreshChangedCount > 0
} catch WebserviceError.tooManyRequests(let retryAfter) {
noteRateLimited(retryAfter: retryAfter, account: account, operation: "Syncing article status")
return false
}
}
public func sendArticleStatus() async throws {
guard let account else {
return
}
_ = try await sendArticleStatusReturningCount(for: account)
if shouldSkipBecauseRateLimited() {
return
}
do {
_ = try await sendArticleStatusReturningCount(for: account)
} catch WebserviceError.tooManyRequests(let retryAfter) {
noteRateLimited(retryAfter: retryAfter, account: account, operation: "Sending article status")
}
}
/// Sends queued local status changes upstream. Returns the count successfully sent.
@@ -221,7 +264,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
if let savedError {
postSyncError(savedError, account: account, operation: "Sending article status")
// A 429 gets one Error Log entry from noteRateLimited, not one per send.
if !isTooManyRequests(savedError) {
postSyncError(savedError, account: account, operation: "Sending article status")
}
throw savedError
}
return sentCount
@@ -232,7 +278,14 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
guard let account else {
return
}
_ = try await refreshArticleStatusReturningCount(for: account)
if shouldSkipBecauseRateLimited() {
return
}
do {
_ = try await refreshArticleStatusReturningCount(for: account)
} catch WebserviceError.tooManyRequests(let retryAfter) {
noteRateLimited(retryAfter: retryAfter, account: account, operation: "Refreshing article status")
}
}
/// Brings local read/starred statuses in line with the server. Returns the count
@@ -240,25 +293,38 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
@MainActor private func refreshArticleStatusReturningCount(for account: Account) async throws -> Int {
Self.logger.debug("ReaderAPIAccountDelegate: refreshArticleStatus")
if shouldSkipStatusDownloadsToConserveQuota() {
return 0
}
return try await account.logActivity(kind: .refreshArticleStatuses) { () -> Int in
var changedCount = 0
var errorOccurred = false
var savedError: Error?
let articleIDs = try await caller.retrieveItemIDs(type: .unread, pageHandler: articleIDPageHandler(for: account, kind: .refreshArticleStatuses))
changedCount += await syncArticleReadState(account: account, articleIDs: articleIDs)
do {
let articleIDs = try await caller.retrieveItemIDs(type: .unread, pageHandler: articleIDPageHandler(for: account, kind: .refreshArticleStatuses))
changedCount += await syncArticleReadState(account: account, articleIDs: articleIDs)
} catch {
savedError = error
Self.logger.error("ReaderAPIAccountDelegate: refreshArticleStatus — retrieving unread entries failed: \(error.localizedDescription)")
}
do {
let articleIDs = try await caller.retrieveItemIDs(type: .starred, pageHandler: articleIDPageHandler(for: account, kind: .refreshArticleStatuses))
changedCount += await syncArticleStarredState(account: account, articleIDs: articleIDs)
} catch {
errorOccurred = true
if savedError == nil {
savedError = error
}
Self.logger.error("ReaderAPIAccountDelegate: refreshArticleStatus — retrieving starred entries failed: \(error.localizedDescription)")
}
if errorOccurred {
let error = AccountError.unknown
postSyncError(error, account: account, operation: "Refreshing article status")
throw error
if let savedError {
// A 429 gets one Error Log entry from noteRateLimited, not one per refresh.
if !isTooManyRequests(savedError) {
postSyncError(savedError, account: account, operation: "Refreshing article status")
}
throw savedError
}
return changedCount
}
@@ -869,7 +935,7 @@ private extension ReaderAPIAccountDelegate {
func sendArticleStatuses(_ statuses: Set<SyncStatus>, account: Account, label: String, apiCall: ([String]) async throws -> Void) async throws -> Int {
Self.logger.debug("ReaderAPIAccountDelegate: sendArticleStatuses")
guard !statuses.isEmpty else {
guard let key = statuses.first?.key else {
return 0
}
@@ -880,7 +946,8 @@ private extension ReaderAPIAccountDelegate {
let unsendableArticleIDs = Set(articleIDs.filter { !articleIDIsSendable($0) })
if !unsendableArticleIDs.isEmpty {
Self.logger.error("ReaderAPIAccountDelegate: dropping \(unsendableArticleIDs.count) unsendable article IDs from the status queue")
await syncDatabase.deleteSelectedForProcessing(unsendableArticleIDs)
postSyncError(ReaderAPIAccountDelegateError.unsendableStatuses(unsendableArticleIDs.count), account: account, operation: "Sending article status")
await syncDatabase.deleteSelectedForProcessing(unsendableArticleIDs, key: key)
}
let sendableArticleIDs = articleIDs.filter { articleIDIsSendable($0) }
@@ -891,12 +958,12 @@ private extension ReaderAPIAccountDelegate {
do {
try await logRefreshPage(for: account, kind: .sendArticleStatuses, message: { _ in "\(articleIDGroup.count) \(label)" }, { try await apiCall(articleIDGroup) })
await syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup))
await syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup), key: key)
sentCount += articleIDGroup.count
} catch {
savedError = error
Self.logger.error("ReaderAPIAccountDelegate: sendArticleStatuses — error \(error.localizedDescription)")
await syncDatabase.resetSelectedForProcessing(Set(articleIDGroup))
await syncDatabase.resetSelectedForProcessing(Set(articleIDGroup), key: key)
}
}
@@ -1067,18 +1134,21 @@ private extension ReaderAPIAccountDelegate {
return 0
}
let pendingArticleIDs = (await self.syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set<String>()
let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs)
// A failed pending-statuses read must not be treated as “nothing pending” — that would revert pending changes.
guard let pendingArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() else {
return 0
}
let serverUnreadArticleIDs = Set(articleIDs)
let currentUnreadArticleIDs = await account.fetchUnreadArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Mark articles as unread
let deltaUnreadArticleIDs = updatableReaderUnreadArticleIDs.subtracting(currentUnreadArticleIDs)
let deltaUnreadArticleIDs = serverUnreadArticleIDs.subtracting(currentUnreadArticleIDs).subtracting(pendingArticleIDs)
let markedUnread = await account.markAsUnreadAsync(articleIDs: deltaUnreadArticleIDs)
// Mark articles as read
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableReaderUnreadArticleIDs)
let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(serverUnreadArticleIDs).subtracting(pendingArticleIDs)
let markedRead = await account.markAsReadAsync(articleIDs: deltaReadArticleIDs)
return markedUnread.count + markedRead.count
@@ -1091,21 +1161,78 @@ private extension ReaderAPIAccountDelegate {
return 0
}
let pendingArticleIDs = (await self.syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set<String>()
let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs)
// A failed pending-statuses read must not be treated as “nothing pending” — that would revert pending changes.
guard let pendingArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() else {
return 0
}
let serverStarredArticleIDs = Set(articleIDs)
let currentStarredArticleIDs = await account.fetchStarredArticleIDsAsync()
// Skip articles with pending local changes in both directions — the pending send is the truth.
// Previously a pending unsent star landed in the unstarred delta and got visibly reverted.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4476>
// Mark articles as starred
let deltaStarredArticleIDs = updatableReaderUnreadArticleIDs.subtracting(currentStarredArticleIDs)
let deltaStarredArticleIDs = serverStarredArticleIDs.subtracting(currentStarredArticleIDs).subtracting(pendingArticleIDs)
let markedStarred = await account.markAsStarredAsync(articleIDs: deltaStarredArticleIDs)
// Mark articles as unstarred
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableReaderUnreadArticleIDs)
let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(serverStarredArticleIDs).subtracting(pendingArticleIDs)
let markedUnstarred = await account.markAsUnstarredAsync(articleIDs: deltaUnstarredArticleIDs)
return markedStarred.count + markedUnstarred.count
}
// MARK: - Rate Limiting
/// True when a 429 response has paused syncing and the pause hasn’t expired.
private func shouldSkipBecauseRateLimited() -> Bool {
guard let rateLimitResumeDate else {
return false
}
guard rateLimitResumeDate > Date() else {
self.rateLimitResumeDate = nil
return false
}
Self.logger.info("ReaderAPIAccountDelegate: skipping — rate limited until \(rateLimitResumeDate)")
return true
}
/// Pause syncing until the server’s Retry-After (or a default) and post one Error Log entry.
private func noteRateLimited(retryAfter: TimeInterval?, account: Account, operation: String) {
let alreadyRateLimited = (rateLimitResumeDate ?? .distantPast) > Date()
rateLimitResumeDate = Date().addingTimeInterval(retryAfter ?? Self.defaultRetryAfter)
Self.logger.error("ReaderAPIAccountDelegate: rate limited — pausing syncing until \(self.rateLimitResumeDate ?? .distantPast)")
if !alreadyRateLimited {
postSyncError(WebserviceError.tooManyRequests(retryAfter: retryAfter), account: account, operation: operation)
}
}
private func isTooManyRequests(_ error: Error) -> Bool {
if case WebserviceError.tooManyRequests = error {
return true
}
return false
}
/// True when the reported Zone 1 (read) usage is close enough to the daily limit
/// that the full status downloads should be skipped until the limits reset.
private func shouldSkipStatusDownloadsToConserveQuota() -> Bool {
guard let usageLimits = caller.usageLimits else {
return false
}
guard usageLimits.resetDate > Date() else {
return false
}
guard Double(usageLimits.zone1Usage) >= Double(usageLimits.zone1Limit) * Self.zone1UsageThreshold else {
return false
}
Self.logger.info("ReaderAPIAccountDelegate: skipping status downloads — Zone 1 API usage is \(usageLimits.zone1Usage) of \(usageLimits.zone1Limit)")
return true
}
func postSyncError(_ error: Error, account: Account, operation: String, fileName: String = #fileID, functionName: String = #function, lineNumber: Int = #line) {
let errorLogUserInfo = ErrorLogUserInfoKey.userInfo(sourceName: account.nameForDisplay, sourceID: account.type.rawValue, operation: operation, errorMessage: AccountError.detailedErrorMessage(error), fileName: fileName, functionName: functionName, lineNumber: lineNumber)
NotificationCenter.default.post(name: .appDidEncounterError, object: self, userInfo: errorLogUserInfo)
@@ -16,6 +16,14 @@ enum CreateReaderAPISubscriptionResult {
case notFound
}
/// Inoreader’s per-zone API usage, reported on every response. Zone 1 is reads.
/// <https://www.inoreader.com/developers/rate-limiting>
struct ReaderAPIUsageLimits {
let zone1Usage: Int
let zone1Limit: Int
let resetDate: Date
}
@MainActor final class ReaderAPICaller {
enum ItemIDType {
case unread
@@ -33,6 +41,11 @@ enum CreateReaderAPISubscriptionResult {
case readingList = "user/-/state/com.google/reading-list"
}
private struct ConditionalGetKeys {
static let subscriptions = "subscriptions"
static let tags = "tags"
}
private enum ReaderAPIEndpoints: String {
case login = "/accounts/ClientLogin"
case token = "/reader/api/0/token"
@@ -58,6 +71,9 @@ enum CreateReaderAPISubscriptionResult {
var variant: ReaderAPIVariant = .generic
var credentials: Credentials?
/// Most recent usage report. Nil for services that don’t send the headers.
private(set) var usageLimits: ReaderAPIUsageLimits?
@MainActor var server: String? {
apiBaseURL?.host
}
@@ -192,10 +208,13 @@ enum CreateReaderAPISubscriptionResult {
throw WebserviceError.noURL
}
var request = URLRequest(url: callURL, readerAPICredentials: credentials)
let conditionalGet = accountSettings?.conditionalGetInfo(for: ConditionalGetKeys.tags)
var request = URLRequest(url: callURL, readerAPICredentials: credentials, conditionalGet: conditionalGet)
addVariantHeaders(&request)
let (_, wrapper) = try await session.send(request: request, resultType: ReaderAPITagContainer.self)
// A 304 Not Modified comes back with an empty body, so this returns nil — callers skip syncing.
let (response, wrapper) = try await session.send(request: request, resultType: ReaderAPITagContainer.self)
storeConditionalGet(key: ConditionalGetKeys.tags, headers: response.allHeaderFields)
return wrapper?.tags
}
@@ -257,11 +276,14 @@ enum CreateReaderAPISubscriptionResult {
throw WebserviceError.noURL
}
var request = URLRequest(url: callURL, readerAPICredentials: credentials)
let conditionalGet = accountSettings?.conditionalGetInfo(for: ConditionalGetKeys.subscriptions)
var request = URLRequest(url: callURL, readerAPICredentials: credentials, conditionalGet: conditionalGet)
addVariantHeaders(&request)
do {
let (_, container) = try await session.send(request: request, resultType: ReaderAPISubscriptionContainer.self)
// A 304 Not Modified comes back with an empty body, so this returns nil — callers skip syncing.
let (response, container) = try await session.send(request: request, resultType: ReaderAPISubscriptionContainer.self)
storeConditionalGet(key: ConditionalGetKeys.subscriptions, headers: response.allHeaderFields)
return container?.subscriptions
} catch {
logger.error("ReaderAPICaller: retrieveSubscriptions — error calling API: \(error.localizedDescription)")
@@ -410,26 +432,15 @@ enum CreateReaderAPISubscriptionResult {
request.setValue(MimeType.formURLEncoded, forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
// Get ids from above into hex representation of value
let idsToFetch = articleIDs.compactMap({ articleID -> String? in
if self.variant == .theOldReader {
return "i=tag:google.com,2005:reader/item/\(articleID)"
} else {
if let idValue = Int(articleID) {
let idHexString = String(idValue, radix: 16, uppercase: false)
return "i=tag:google.com,2005:reader/item/\(idHexString)"
} else {
return nil
}
}
}).joined(separator: "&")
let idsToFetch = articleIDs.compactMap(itemIDParameter).joined(separator: "&")
if idsToFetch.isEmpty {
return nil
}
let entryWrapper = try await withWriteToken(endpoint: baseURL) { token -> ReaderAPIEntryWrapper? in
let postData = Data("T=\(token)&output=json&\(idsToFetch)".utf8)
let (_, wrapper) = try await session.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIEntryWrapper.self)
let (response, wrapper) = try await session.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIEntryWrapper.self)
noteUsageLimits(from: response)
return wrapper
}
@@ -490,6 +501,7 @@ enum CreateReaderAPISubscriptionResult {
addVariantHeaders(&request)
let (response, entries) = try await session.send(request: request, resultType: ReaderAPIReferenceWrapper.self)
noteUsageLimits(from: response)
guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else {
return [String]()
@@ -527,7 +539,8 @@ enum CreateReaderAPISubscriptionResult {
var request: URLRequest = URLRequest(url: callURL, readerAPICredentials: credentials)
addVariantHeaders(&request)
let (_, entries) = try await self.session.send(request: request, resultType: ReaderAPIReferenceWrapper.self)
let (response, entries) = try await self.session.send(request: request, resultType: ReaderAPIReferenceWrapper.self)
noteUsageLimits(from: response)
guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else {
return try await retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: itemIDs, continuation: entries?.continuation, pageHandler: pageHandler)
@@ -611,22 +624,49 @@ private extension ReaderAPICaller {
request.setValue(MimeType.formURLEncoded, forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
// Get ids from above into hex representation of value
let idsToFetch = entries.compactMap({ idValue -> String? in
if self.variant == .theOldReader {
return "i=tag:google.com,2005:reader/item/\(idValue)"
} else {
guard let intValue = Int(idValue) else { return nil }
let idHexString = String(format: "%.16llx", intValue)
return "i=tag:google.com,2005:reader/item/\(idHexString)"
}
}).joined(separator: "&")
let idsToFetch = entries.compactMap(itemIDParameter).joined(separator: "&")
let actionIndicator = add ? "a" : "r"
try await withWriteToken(endpoint: baseURL) { token in
let postData = Data("T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".utf8)
_ = try await session.send(request: request, method: HTTPMethod.post, payload: postData)
let (response, _) = try await session.send(request: request, method: HTTPMethod.post, payload: postData)
noteUsageLimits(from: response)
}
}
private enum UsageLimitHeader {
static let zone1Usage = "X-Reader-Zone1-Usage"
static let zone1Limit = "X-Reader-Zone1-Limit"
static let resetAfter = "X-Reader-Limits-Reset-After"
}
private static let defaultUsageLimitsResetAfter: TimeInterval = 60 * 60 * 24
private func storeConditionalGet(key: String, headers: [AnyHashable: Any]) {
accountSettings?.setConditionalGetInfo(HTTPConditionalGetInfo(headers: headers), for: key)
}
private func noteUsageLimits(from response: HTTPURLResponse) {
guard let usageValue = response.value(forHTTPHeaderField: UsageLimitHeader.zone1Usage), let usage = Int(usageValue),
let limitValue = response.value(forHTTPHeaderField: UsageLimitHeader.zone1Limit), let limit = Int(limitValue), limit > 0 else {
return
}
let resetAfter = response.value(forHTTPHeaderField: UsageLimitHeader.resetAfter).flatMap { TimeInterval($0) } ?? Self.defaultUsageLimitsResetAfter
usageLimits = ReaderAPIUsageLimits(zone1Usage: usage, zone1Limit: limit, resetDate: Date().addingTimeInterval(resetAfter))
}
/// Long-form item parameter for an articleID — i=tag:google.com,2005:reader/item/000000000004c608.
/// The long form is zero-padded 16-digit hex, two’s-complement for negative IDs.
/// Returns nil for an articleID that can’t be encoded for this server.
private func itemIDParameter(_ articleID: String) -> String? {
if variant == .theOldReader {
return "i=tag:google.com,2005:reader/item/\(articleID)"
}
guard let idValue = Int(articleID) else {
return nil
}
let idHexString = String(format: "%.16llx", idValue)
return "i=tag:google.com,2005:reader/item/\(idHexString)"
}
}
@@ -0,0 +1,39 @@
//
// FeedSettingsDatabaseTests.swift
// AccountTests
//
// Created by Brent Simmons on 8/2/26.
//
import Foundation
import Testing
@testable import Account
struct FeedSettingsDatabaseTests {
@Test func feedIDColumnIsUpdatable() {
let database = makeDatabase()
let feedURL = "https://example.com/feed.xml"
let canonicalFeedID = "feed/\(feedURL)"
database.ensureFeedExists(feedURL, feedID: feedURL)
database.setString(canonicalFeedID, for: feedURL, column: .feedID)
#expect(database.allRows()[feedURL]?.feedID == canonicalFeedID)
}
@Test func ensureFeedExistsDoesNotReplaceFeedID() {
let database = makeDatabase()
let feedURL = "https://example.com/feed.xml"
let canonicalFeedID = "feed/\(feedURL)"
database.ensureFeedExists(feedURL, feedID: canonicalFeedID)
database.ensureFeedExists(feedURL, feedID: feedURL)
#expect(database.allRows()[feedURL]?.feedID == canonicalFeedID)
}
private func makeDatabase() -> FeedSettingsDatabase {
FeedSettingsDatabase(databasePath: ":memory:")
}
}
@@ -160,6 +160,53 @@ import XCTest
XCTAssertTrue(originalFeed === updatedFeed, "Renaming a feed should reuse the existing Feed instance.")
}
func testSyncFeedsForCollectionFoldersRepairsStaleFeedID() {
let url = "https://example.com/feed.xml"
let canonicalFeedID = "feed/\(url)"
let folder = makeFolder(name: "Folder", externalID: "folder/1")
// A feed created from OPML before its settings row existed gets the bare URL as its feedID.
let staleFeed = account.createFeed(with: "Example", url: url, feedID: url, homePageURL: nil)
staleFeed.newArticleNotificationsEnabled = true
folder.addFeedToTreeAtTopLevel(staleFeed)
syncFeedsForCollectionFolders([
([FeedlyFeed(id: canonicalFeedID, title: "Example", updated: nil, website: nil)], folder)
], in: account)
let feeds = account.flattenedFeeds()
XCTAssertEqual(feeds.count, 1)
let repairedFeed = feeds.first
XCTAssertEqual(repairedFeed?.feedID, canonicalFeedID)
XCTAssertEqual(repairedFeed?.url, url)
assertFolder(folder, contains: [canonicalFeedID])
XCTAssertEqual(repairedFeed?.newArticleNotificationsEnabled, true, "Settings should survive a feedID repair.")
}
func testSyncFeedsForCollectionFoldersAfterRepairReusesFeedInstance() {
let url = "https://example.com/feed.xml"
let canonicalFeedID = "feed/\(url)"
let folder = makeFolder(name: "Folder", externalID: "folder/1")
let staleFeed = account.createFeed(with: "Example", url: url, feedID: url, homePageURL: nil)
folder.addFeedToTreeAtTopLevel(staleFeed)
let collectionFeeds = [FeedlyFeed(id: canonicalFeedID, title: "Example", updated: nil, website: nil)]
syncFeedsForCollectionFolders([(collectionFeeds, folder)], in: account)
let repairedFeed = folder.existingFeed(withFeedID: canonicalFeedID)
XCTAssertNotNil(repairedFeed)
// A second pass must not remove and recreate the feed — that was the pre-repair flapping.
syncFeedsForCollectionFolders([(collectionFeeds, folder)], in: account)
let secondPassFeed = folder.existingFeed(withFeedID: canonicalFeedID)
XCTAssertTrue(repairedFeed === secondPassFeed, "A repaired feed should be reused on subsequent syncs.")
XCTAssertEqual(account.flattenedFeeds().count, 1)
}
// MARK: - Combined behavior
func testMirrorThenRemoveAllRemovesFeedsToo() {
@@ -58,7 +58,7 @@ public struct ArticleCounts: Sendable {
private let retentionStyle: RetentionStyle
private let accountID: String
nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ArticlesDatabase")
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ArticlesDatabase")
public init(databaseFilePath: String, accountID: String, retentionStyle: RetentionStyle) {
Self.logger.debug("Articles Database init \(accountID, privacy: .public)")
@@ -24,8 +24,8 @@ final class ArticlesTable: DatabaseTable, Sendable {
private let retentionStyle: ArticlesDatabase.RetentionStyle
private let articlesCache = OSAllocatedUnfairLock(initialState: [String: Article]())
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ArticlesTable")
private static let signposter = OSSignposter(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ArticlesTable")
private static let signposter = OSSignposter(subsystem: Logger.nnwSubsystem, category: .pointsOfInterest)
// TODO: update articleCutoffDate as time passes and based on user preferences.
let articleCutoffDate = Date().bySubtracting(days: 90)
@@ -6,6 +6,7 @@
//
import Foundation
import RSCore
import os
import RSDatabase
import RSDatabaseObjC
@@ -25,7 +26,7 @@ struct AuthorsSchemaMigration: Sendable {
let accountID: String
let queue: DatabaseQueue
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AuthorsSchemaMigration")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "AuthorsSchemaMigration")
func run() async {
let startTime = Date()
@@ -16,6 +16,7 @@ import RSParser
final class ArticleSearchInfo: Hashable, Sendable {
let articleID: String
let title: String?
let titleForIndex: String
let contentHTML: String?
let contentText: String?
let summary: String?
@@ -26,6 +27,7 @@ final class ArticleSearchInfo: Hashable, Sendable {
init(articleID: String, title: String?, contentHTML: String?, contentText: String?, summary: String?, authorsNames: String?, searchRowID: Int?) {
self.articleID = articleID
self.title = title
self.titleForIndex = (title ?? "").normalizedForSearchIndex
self.authorsNames = authorsNames
self.contentHTML = contentHTML
self.contentText = contentText
@@ -51,7 +53,7 @@ final class ArticleSearchInfo: Hashable, Sendable {
} else {
return sanitizedBody
}
}()
}().normalizedForSearchIndex
}
convenience init(article: Article) {
@@ -139,7 +141,7 @@ private extension SearchTable {
}
func insert(_ article: ArticleSearchInfo, _ database: FMDatabase) -> Int {
let rowDictionary: DatabaseDictionary = [DatabaseKey.body: article.bodyForIndex, DatabaseKey.title: article.title ?? ""]
let rowDictionary: DatabaseDictionary = [DatabaseKey.body: article.bodyForIndex, DatabaseKey.title: article.titleForIndex]
insertRow(rowDictionary, insertType: .normal, in: database)
return Int(database.lastInsertRowId())
}
@@ -192,7 +194,7 @@ private extension SearchTable {
return
}
let title = article.title ?? ""
let title = article.titleForIndex
if title == searchInfo.title && article.bodyForIndex == searchInfo.body {
return
}
@@ -220,3 +222,26 @@ private extension SearchTable {
return resultSet.mapToSet { SearchInfo(row: $0) }
}
}
private extension String {
static let searchIndexCharactersToReplace = CharacterSet.punctuationCharacters.union(.symbols)
/// The search table's tokenizer treats non-ASCII punctuation and symbols as
/// word characters — “‘BeReal’” would index as a token that a search for
/// “bereal” can’t match. Replace them with spaces before indexing.
/// Collapsing afterward keeps the replacements from growing the stored text.
/// <https://github.com/Ranchero-Software/NetNewsWire/issues/3531>
var normalizedForSearchIndex: String {
guard rangeOfCharacter(from: Self.searchIndexCharactersToReplace) != nil else {
return self
}
var scalars = [Unicode.Scalar]()
scalars.reserveCapacity(unicodeScalars.count)
for scalar in unicodeScalars {
scalars.append(Self.searchIndexCharactersToReplace.contains(scalar) ? " " : scalar)
}
return String(String.UnicodeScalarView(scalars)).collapsingWhitespace
}
}
@@ -6,6 +6,7 @@
//
import Foundation
import RSCore
import os
public let cloudKitLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "CloudKit")
public let cloudKitLogger = Logger(subsystem: Logger.nnwSubsystem, category: "CloudKit")
@@ -25,7 +25,7 @@ public enum FeedFinderError: LocalizedError {
}
public final class FeedFinder {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedFinder")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FeedFinder")
/// Which discovery path produced the result. Used to write a more useful
/// completion message on the parent `findFeed` activity.
@@ -40,6 +40,13 @@ public struct FeedSpecifier: Hashable, Sendable {
return FeedSpecifier(title: "writing - rachelbythebay", urlString: feedURLString, source: .userEntered, orderFound: 0)
}
// The blog page only advertises the master podcast feed in its <head>, so the finder would
// otherwise miss the blog feed. <https://github.com/Ranchero-Software/NetNewsWire/issues/5299>
if url.isRelayFMBlogURL {
let feedURLString = "https://www.relay.fm/blog/feed"
return FeedSpecifier(title: "Relay FM Blog", urlString: feedURLString, source: .userEntered, orderFound: 0)
}
return nil
}
@@ -15,4 +15,13 @@ final class FeedFinderTests: XCTestCase {
let feedFinder = FeedFinder()
XCTAssertNotNil(feedFinder)
}
func testKnownFeedSpecifierForRelayFMBlog() throws {
let specifier = FeedSpecifier.knownFeedSpecifier(url: URL(string: "https://www.relay.fm/blog")!)
XCTAssertEqual(specifier?.urlString, "https://www.relay.fm/blog/feed")
}
func testKnownFeedSpecifierIgnoresRelayFMRoot() throws {
XCTAssertNil(FeedSpecifier.knownFeedSpecifier(url: URL(string: "https://www.relay.fm")!))
}
}
@@ -17,7 +17,7 @@ nonisolated public final class HTMLMetadataDownloader: Sendable {
public static let shared = HTMLMetadataDownloader()
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "HTMLMetadataDownloader")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "HTMLMetadataDownloader")
private static let hoursBetweenAttempts = 3
@@ -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
@@ -24,7 +24,7 @@ extension Notification.Name {
@MainActor public final class FaviconDownloader {
public static let shared = FaviconDownloader()
nonisolated static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FaviconDownloader")
nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FaviconDownloader")
private let folder: String
private let diskCache: BinaryDiskCache
@@ -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
}
@@ -40,7 +40,7 @@ extension ImageDownloadError: LocalizedError {
@MainActor public final class ImageDownloader {
public static let shared = ImageDownloader()
nonisolated static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader")
nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageDownloader")
nonisolated private let diskCache: BinaryDiskCache
private let queue: DispatchQueue
@@ -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)
@@ -21,7 +21,7 @@ import RSDatabaseObjC
public let databasePath: String
nonisolated static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ImageMetadataDatabase")
nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageMetadataDatabase")
private let queue: DatabaseQueue
@@ -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)
}
}
@@ -31,7 +31,7 @@ extension Notification.Name {
/// The persistent failure, if any. Nil after success or for transient failures.
public private(set) var error: ImageDownloadError?
static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SingleFaviconDownloader")
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "SingleFaviconDownloader")
private let diskCache: BinaryDiskCache
private let queue: DispatchQueue
@@ -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)
@@ -6,9 +6,10 @@
//
import Foundation
import RSCore
import os
public struct NewsBlur {
// Convention with this logger is to put "NewsBlur: " at the beginning of each message.
public static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "NewsBlur")
public static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "NewsBlur")
}
@@ -12,10 +12,6 @@ import AppKit
public class RSToolbarItem: NSToolbarItem {
override public func validate() {
guard let view = view, view.window != nil else {
isEnabled = false
return
}
isEnabled = isValidAsUserInterfaceItem()
}
}
@@ -29,7 +25,9 @@ private extension RSToolbarItem {
return validateWithResponder(target) ?? false
}
var responder = view?.window?.firstResponder
// view.window is nil when the item is shown as its menu form representation (the toolbar's
// Text Only mode or overflow menu), so fall back to the main window's responder chain.
var responder = view?.window?.firstResponder ?? NSApp.mainWindow?.firstResponder
if responder == nil {
return false
}
@@ -8,18 +8,17 @@
import Foundation
import os
// These are all posted on the main thread.
public extension Notification.Name {
/// Posted on actual low memory condition. Main thread.
static let lowMemory = Notification.Name("LowMemoryNotification")
/// Posted when the app goes to background. Main thread.
static let appDidGoToBackground = Notification.Name("AppDidGoToBackgroundNotification")
static let appDidBecomeActive = Notification.Name("AppDidBecomeActiveNotification")
}
public struct AppNotification {
private static let notificationLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppNotification")
private static let notificationLogger = Logger(subsystem: Logger.nnwSubsystem, category: "AppNotification")
public static func postLowMemory() {
notificationLogger.info("Posting low memory notification.")
@@ -30,4 +29,9 @@ public struct AppNotification {
notificationLogger.info("Posting app did go to background notification.")
NotificationCenter.default.postOnMainThread(name: .appDidGoToBackground, object: nil)
}
public static func postAppDidBecomeActive() {
notificationLogger.info("Posting app did become active notification.")
NotificationCenter.default.postOnMainThread(name: .appDidBecomeActive, object: nil)
}
}
@@ -0,0 +1,19 @@
//
// Logging.swift
// RSCore
//
// Created by Brent Simmons on 8/2/26.
//
import Foundation
import os
public extension Logger {
/// Subsystem for all NetNewsWire logging.
///
/// A constant rather than Bundle.main.bundleIdentifier so that logging works
/// in processes without a bundle identifier (the Swift Testing runner, for instance)
/// and so that one Console filter covers the apps and the extensions.
static let nnwSubsystem = "com.ranchero.NetNewsWire"
}
+1 -1
View File
@@ -11,7 +11,7 @@ import os
public struct Platform {
nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.ranchero.Platform", category: "Platform")
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Platform")
nonisolated public static var deviceHasiCloudAccount: Bool {
FileManager.default.ubiquityIdentityToken != nil
+1 -1
View File
@@ -22,7 +22,7 @@ public typealias RSImage = UIImage
public typealias RSColor = UIColor
#endif
private let RSImageLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "RSImage")
private let RSImageLogger = Logger(subsystem: Logger.nnwSubsystem, category: "RSImage")
public extension RSImage {
@@ -24,9 +24,14 @@ extension UICollectionView {
selectItem(at: indexPath, animated: true, scrollPosition: [])
if !indexPathsForVisibleItems.contains(indexPath) {
scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
// indexPathsForVisibleItems includes cells hidden under the bars —
// check the unobscured region instead.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5107>
let unobscuredBounds = bounds.inset(by: adjustedContentInset)
if let itemFrame = layoutAttributesForItem(at: indexPath)?.frame, unobscuredBounds.contains(itemFrame) {
return
}
scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
}
public func middleVisibleRow() -> IndexPath? {
@@ -14,7 +14,7 @@ public extension URL {
guard scheme == "mailto" else {
return nil
}
guard let urlString = absoluteString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
guard let urlString = absoluteString.addingPercentEncoding(withAllowedCharacters: .mailtoAllowed) else {
return nil
}
return URL(string: urlString)
@@ -30,3 +30,9 @@ public extension URL {
return URL(string: link.replacingOccurrences(of: " ", with: "%20"))
}
}
private extension CharacterSet {
// Includes % so existing percent escapes don't get encoded a second time.
static let mailtoAllowed = CharacterSet.urlQueryAllowed.union(CharacterSet(charactersIn: "%"))
}
@@ -0,0 +1,44 @@
//
// URL+RSCoreTests.swift
// RSCore
//
// Created by Brent Simmons on 7/27/26.
//
import Foundation
import Testing
import RSCore
struct URLRSCoreTests {
// An already-encoded mailto URL must pass through unchanged — re-encoding
// turned %20 into %2520, showing literal "%20" in Mail.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3719>
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4380>
@Test func percentEncodedEmailAddressDoesNotDoubleEncode() throws {
let url = try #require(URL(string: "mailto:test@example.com?subject=Hello%20World"))
#expect(url.percentEncodedEmailAddress?.absoluteString == "mailto:test@example.com?subject=Hello%20World")
}
@Test func percentEncodedEmailAddressPreservesMultipleEscapes() throws {
let url = try #require(URL(string: "mailto:test@example.com?subject=One%20Two%20Three&body=Hi%2C%20there"))
#expect(url.percentEncodedEmailAddress?.absoluteString == "mailto:test@example.com?subject=One%20Two%20Three&body=Hi%2C%20there")
}
@Test func percentEncodedEmailAddressIsIdempotent() throws {
let url = try #require(URL(string: "mailto:test@example.com?subject=Hello%20World"))
let once = url.percentEncodedEmailAddress
let twice = once?.percentEncodedEmailAddress
#expect(once == twice)
}
@Test func percentEncodedEmailAddressRequiresMailto() throws {
let url = try #require(URL(string: "https://example.com/"))
#expect(url.percentEncodedEmailAddress == nil)
}
@Test func percentEncodedEmailAddressPlainAddress() throws {
let url = try #require(URL(string: "mailto:test@example.com"))
#expect(url.percentEncodedEmailAddress?.absoluteString == "mailto:test@example.com")
}
}
@@ -26,7 +26,7 @@ public final class DatabaseQueue: Sendable {
private let databasePath: String
private let serialDispatchQueue: DispatchQueue
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "DatabaseQueue")
private static let logger = Logger(subsystem: logSubsystem, category: "DatabaseQueue")
public init(databasePath: String) {
Self.logger.debug("DatabaseQueue: creating with database path \(databasePath)")
@@ -33,7 +33,7 @@ public extension FMDatabase {
commit()
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FMDatabase")
private static let logger = Logger(subsystem: logSubsystem, category: "FMDatabase")
func vacuum() {
let path = databasePath() ?? "unknown"
@@ -0,0 +1,11 @@
//
// Logging.swift
// RSDatabase
//
// Created by Brent Simmons on 8/2/26.
//
import Foundation
// Matches Logger.nnwSubsystem in RSCore, which RSDatabase doesn’t depend on.
let logSubsystem = "com.ranchero.NetNewsWire"
@@ -49,6 +49,15 @@ private final class AtomDelegate: XMLSAXParserDelegate {
// Attributes per open element.
private var attributesStack: [XMLAttributes] = []
// Effective xml:base per open element — kept exactly parallel to attributesStack.
private var baseURLStack: [URL?] = []
private lazy var documentURL: URL? = URL(string: feedURLString)
private var effectiveBaseURL: URL? {
baseURLStack.last ?? nil
}
init(urlString: String) {
self.feedURLString = urlString
self.isDaringFireball = urlString.contains("daringfireball.net/")
@@ -106,6 +115,7 @@ private final class AtomDelegate: XMLSAXParserDelegate {
}
attributesStack.append(attributes)
pushBaseURL(attributes)
if namespaceElementDepth > 0 {
namespaceElementDepth += 1
@@ -172,7 +182,17 @@ private final class AtomDelegate: XMLSAXParserDelegate {
guard let article = currentArticle else {
return
}
let html = String(decoding: bytes, as: UTF8.self)
// The content element is still on the stacks here, so effectiveBaseURL
// includes its own xml:base. An xml:base on an element inside the captured
// content is invisible (pass-through emits no events) and unsupported.
let html: String
if let base = effectiveBaseURL {
html = HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: bytes, baseURL: base)
} else {
html = String(decoding: bytes, as: UTF8.self)
}
if localName.equals("content") {
article.body = html
} else if localName.equals("summary") {
@@ -189,6 +209,9 @@ private final class AtomDelegate: XMLSAXParserDelegate {
if !attributesStack.isEmpty {
attributesStack.removeLast()
}
if !baseURLStack.isEmpty {
baseURLStack.removeLast()
}
}
if localName.equals("feed") {
@@ -250,13 +273,13 @@ private final class AtomDelegate: XMLSAXParserDelegate {
// Overwrite only if there are characters —
// may have been set by didCaptureRawInnerContent for raw XHTML.
if let s = parser.currentStringWithTrimmedWhitespace {
article.body = s
article.body = resolvedHTMLBody(s)
}
} else if localName.equals("summary") {
// Overwrite only if there are characters —
// may have been set by didCaptureRawInnerContent for raw XHTML.
if let s = parser.currentStringWithTrimmedWhitespace {
article.summary = s
article.summary = resolvedHTMLBody(s)
}
} else if localName.equals("link") {
handleArticleLink()
@@ -352,7 +375,9 @@ private final class AtomDelegate: XMLSAXParserDelegate {
} else if localName.equals("email") {
author.emailAddress = parser.currentStringWithTrimmedWhitespace
} else if localName.equals("uri") {
author.url = parser.currentStringWithTrimmedWhitespace
if let s = parser.currentStringWithTrimmedWhitespace {
author.url = resolvedURLString(s) ?? s
}
}
}
@@ -368,11 +393,11 @@ private final class AtomDelegate: XMLSAXParserDelegate {
}
} else if localName.equals("icon") {
if let s = parser.currentStringWithTrimmedWhitespace, !s.isEmpty {
iconURLString = s
iconURLString = resolvedURLString(s) ?? s
}
} else if localName.equals("logo") {
if logoURLString == nil, let s = parser.currentStringWithTrimmedWhitespace, !s.isEmpty {
logoURLString = s
logoURLString = resolvedURLString(s) ?? s
}
}
}
@@ -401,10 +426,45 @@ private final class AtomDelegate: XMLSAXParserDelegate {
// MARK: - URL resolution
// RFC 4287: xml:base applies to its element and everything below it,
// and a relative xml:base resolves against the nearest enclosing base —
// the document (feed) URL when there is none.
private func pushBaseURL(_ attributes: XMLAttributes) {
let inherited = baseURLStack.last ?? nil
guard !attributes.isEmpty, let xmlBase = attributes["xml:base"], !xmlBase.isEmpty else {
baseURLStack.append(inherited)
return
}
let outerBase = inherited ?? documentURL
guard let resolved = URL(string: xmlBase, relativeTo: outerBase)?.absoluteURL,
let scheme = resolved.scheme?.lowercased(), scheme == "http" || scheme == "https" else {
// A garbage or non-http base (tag:, urn:) would poison resolution — inherit instead.
baseURLStack.append(inherited)
return
}
baseURLStack.append(resolved)
}
// Rewrite relative URLs in an escaped-HTML body when an xml:base is in effect.
// RFC 4287 allows a MIME type as well as the "html" keyword.
// type="text" (and absent type, which means text) is never rewritten.
private func resolvedHTMLBody(_ html: String) -> String {
let type = currentAttributes["type"]
guard type == "html" || type == "text/html", let base = effectiveBaseURL else {
return html
}
return HTMLRelativeURLResolver.resolvingRelativeURLs(in: html, baseURL: base)
}
private func resolvedURLString(_ s: String) -> String? {
if isValidURLString(s) {
return s
}
if let base = effectiveBaseURL,
let resolved = URL(string: s, relativeTo: base)?.absoluteString,
isValidURLString(resolved) {
return resolved
}
var base: String? = homepageURLString
if base?.isEmpty ?? true {
base = feedURLString
@@ -0,0 +1,408 @@
//
// HTMLRelativeURLResolver.swift
// RSParser
//
// Created by Brent Simmons on 7/28/26.
//
import Foundation
/// Resolves relative URLs in HTML attribute values (href, src, poster, srcset)
/// against a base URL — used for Atom xml:base support.
///
/// Replacement is surgical: everything outside a rewritten attribute value is
/// byte-identical to the input. Values are left alone when they are empty,
/// fragment-only (`#…` — same-document references), or already have a scheme
/// (http:, data:, mailto:, and so on). Protocol-relative values (`//…`) do get
/// resolved, taking the base URL's scheme.
///
/// Attribute values are not entity-decoded — `URL(string:relativeTo:)` passes
/// characters like `&` through untouched, so an `&amp;` in a relative URL
/// survives resolution byte-for-byte.
public enum HTMLRelativeURLResolver {
public static func resolvingRelativeURLs(in html: String, baseURL: URL) -> String {
let bytes = Array(html.utf8)
guard let rewritten = rewrittenBytes(bytes[...], baseURL: baseURL) else {
return html
}
return String(decoding: rewritten, as: UTF8.self)
}
public static func resolvingRelativeURLs(inBytes bytes: ArraySlice<UInt8>, baseURL: URL) -> String {
guard let rewritten = rewrittenBytes(bytes, baseURL: baseURL) else {
return String(decoding: bytes, as: UTF8.self)
}
return String(decoding: rewritten, as: UTF8.self)
}
}
// MARK: - Private
private extension HTMLRelativeURLResolver {
/// Returns nil when nothing needs resolving, so callers can keep the input verbatim.
static func rewrittenBytes(_ bytes: ArraySlice<UInt8>, baseURL: URL) -> [UInt8]? {
var scanner = URLReplacementScanner(bytes: bytes, baseURL: baseURL)
let replacements = scanner.scan()
if replacements.isEmpty {
return nil
}
let sizeDelta = replacements.reduce(0) { $0 + $1.bytes.count - $1.range.count }
var result = [UInt8]()
result.reserveCapacity(bytes.count + sizeDelta)
var copyStart = bytes.startIndex
for replacement in replacements {
result.append(contentsOf: bytes[copyStart..<replacement.range.lowerBound])
result.append(contentsOf: replacement.bytes)
copyStart = replacement.range.upperBound
}
result.append(contentsOf: bytes[copyStart...])
return result
}
struct Replacement {
let range: Range<Int>
let bytes: [UInt8]
}
/// Scans HTML bytes and collects the URL attribute-value replacements to make.
struct URLReplacementScanner {
private let bytes: ArraySlice<UInt8>
private let baseURL: URL
private var pos: Int
private var replacements: [Replacement] = []
private var end: Int {
bytes.endIndex
}
init(bytes: ArraySlice<UInt8>, baseURL: URL) {
self.bytes = bytes
self.baseURL = baseURL
self.pos = bytes.startIndex
}
mutating func scan() -> [Replacement] {
while pos < end {
if bytes[pos] == .asciiLessThan {
handleLessThan()
} else {
pos += 1
}
}
return replacements
}
// MARK: Markup dispatch
private mutating func handleLessThan() {
guard pos + 1 < end else {
pos = end
return
}
let next = bytes[pos + 1]
if next == .asciiExclamation {
handleDeclaration()
} else if next == .asciiQuestion {
skipPast("?>")
} else if next == .asciiSlash {
skipPastGreaterThan()
} else if next.isASCIILetter {
scanStartTag()
} else {
pos += 1
}
}
private mutating func handleDeclaration() {
if matches("<!--") {
skipPast("-->")
} else if matches("<![CDATA[") {
skipPast("]]>")
} else {
skipPastGreaterThan()
}
}
// MARK: Start tags
private mutating func scanStartTag() {
let nameStart = pos + 1
var i = nameStart
while i < end && bytes[i].isXMLNameChar {
i += 1
}
let tagName = bytes[nameStart..<i]
pos = i
var selfClosing = false
while pos < end {
skipWhitespace()
guard pos < end else {
return
}
let b = bytes[pos]
if b == .asciiGreaterThan {
pos += 1
break
}
if b == .asciiSlash {
if pos + 1 < end && bytes[pos + 1] == .asciiGreaterThan {
selfClosing = true
pos += 2
break
}
pos += 1
continue
}
if b.isXMLNameStart {
scanAttribute()
} else {
pos += 1
}
}
// Nothing inside script or style elements is a URL to resolve.
if !selfClosing {
if tagName.equalsASCIICaseInsensitive(lowercaseLiteral: "script") {
skipRawText(lowercaseCloseTagName: "script")
} else if tagName.equalsASCIICaseInsensitive(lowercaseLiteral: "style") {
skipRawText(lowercaseCloseTagName: "style")
}
}
}
private mutating func scanAttribute() {
let nameStart = pos
while pos < end {
let b = bytes[pos]
if b.isASCIIWhitespace || b == .asciiEquals || b == .asciiGreaterThan || b == .asciiSlash {
break
}
pos += 1
}
let name = bytes[nameStart..<pos]
skipWhitespace()
guard pos < end, bytes[pos] == .asciiEquals else {
return // valueless attribute
}
pos += 1
skipWhitespace()
guard pos < end else {
return
}
let valueRange: Range<Int>
let quote = bytes[pos]
if quote == .asciiDoubleQuote || quote == .asciiSingleQuote {
let valueStart = pos + 1
var i = valueStart
while i < end && bytes[i] != quote {
i += 1
}
guard i < end else {
// Unterminated quote — abandon the rest of the scan.
// Replacements recorded so far were well-formed and stay.
pos = end
return
}
valueRange = valueStart..<i
pos = i + 1
} else {
// Unquoted value: ends at whitespace or `>` (the WHATWG rule).
// Deliberately not at `/`, so href=/foo/bar isn't truncated.
let valueStart = pos
var i = pos
while i < end && !bytes[i].isASCIIWhitespace && bytes[i] != .asciiGreaterThan {
i += 1
}
valueRange = valueStart..<i
pos = i
}
handleAttributeValue(name: name, valueRange: valueRange)
}
private mutating func handleAttributeValue(name: ArraySlice<UInt8>, valueRange: Range<Int>) {
if name.equalsASCIICaseInsensitive(lowercaseLiteral: "href") ||
name.equalsASCIICaseInsensitive(lowercaseLiteral: "src") ||
name.equalsASCIICaseInsensitive(lowercaseLiteral: "poster") {
addReplacementIfNeeded(valueRange)
} else if name.equalsASCIICaseInsensitive(lowercaseLiteral: "srcset") {
handleSrcsetValue(valueRange)
}
}
// MARK: srcset
private mutating func handleSrcsetValue(_ valueRange: Range<Int>) {
var i = valueRange.lowerBound
let valueEnd = valueRange.upperBound
while i < valueEnd {
while i < valueEnd && (bytes[i].isASCIIWhitespace || bytes[i] == .asciiComma) {
i += 1
}
guard i < valueEnd else {
return
}
// URL token: up to whitespace. Trailing commas are separators, not URL.
let urlStart = i
while i < valueEnd && !bytes[i].isASCIIWhitespace {
i += 1
}
var urlEnd = i
while urlEnd > urlStart && bytes[urlEnd - 1] == .asciiComma {
urlEnd -= 1
}
let tokenEndedWithComma = urlEnd < i
if urlEnd > urlStart {
addReplacementIfNeeded(urlStart..<urlEnd)
}
// A trailing comma already ended this candidate. Otherwise skip
// the descriptor — everything up to the next comma.
if !tokenEndedWithComma {
while i < valueEnd && bytes[i] != .asciiComma {
i += 1
}
}
}
}
// MARK: URL classification and resolution
private mutating func addReplacementIfNeeded(_ range: Range<Int>) {
// Browsers strip surrounding whitespace before processing a URL value.
// Classify and replace only the trimmed part — the whitespace stays.
let trimmed = trimmingASCIIWhitespace(range)
guard let resolved = resolvedURLBytes(bytes[trimmed]) else {
return
}
replacements.append(Replacement(range: trimmed, bytes: resolved))
}
private func trimmingASCIIWhitespace(_ range: Range<Int>) -> Range<Int> {
var lower = range.lowerBound
var upper = range.upperBound
while lower < upper && bytes[lower].isASCIIWhitespace {
lower += 1
}
while upper > lower && bytes[upper - 1].isASCIIWhitespace {
upper -= 1
}
return lower..<upper
}
private func resolvedURLBytes(_ value: ArraySlice<UInt8>) -> [UInt8]? {
guard shouldResolve(value) else {
return nil
}
let s = String(decoding: value, as: UTF8.self)
guard let resolved = URL(string: s, relativeTo: baseURL)?.absoluteString, resolved != s else {
return nil
}
return Array(resolved.utf8)
}
private func shouldResolve(_ value: ArraySlice<UInt8>) -> Bool {
guard let first = value.first else {
return false // empty
}
if first == .asciiHash {
return false // same-document reference
}
return !hasScheme(value)
}
/// True when the value starts with a URL scheme (`[A-Za-z][A-Za-z0-9+.-]*:`).
private func hasScheme(_ value: ArraySlice<UInt8>) -> Bool {
guard let first = value.first, first.isASCIILetter else {
return false
}
var i = value.startIndex + 1
while i < value.endIndex {
let b = value[i]
if b == .asciiColon {
return true
}
if !(b.isASCIILetter || b.isASCIIDigit || b == .asciiPlus || b == .asciiHyphen || b == .asciiDot) {
return false
}
i += 1
}
return false
}
// MARK: Scanning helpers
private mutating func skipWhitespace() {
while pos < end && bytes[pos].isASCIIWhitespace {
pos += 1
}
}
private mutating func skipPastGreaterThan() {
while pos < end && bytes[pos] != .asciiGreaterThan {
pos += 1
}
if pos < end {
pos += 1
}
}
private func matches(_ literal: StaticString) -> Bool {
let count = literal.utf8CodeUnitCount
guard pos + count <= end else {
return false
}
return bytes[pos..<pos + count].equals(literal)
}
private mutating func skipPast(_ literal: StaticString) {
let count = literal.utf8CodeUnitCount
while pos + count <= end {
if bytes[pos..<pos + count].equals(literal) {
pos += count
return
}
pos += 1
}
pos = end
}
private mutating func skipRawText(lowercaseCloseTagName: StaticString) {
let nameCount = lowercaseCloseTagName.utf8CodeUnitCount
while pos < end {
if bytes[pos] == .asciiLessThan && pos + 1 < end && bytes[pos + 1] == .asciiSlash {
let nameStart = pos + 2
let nameEnd = nameStart + nameCount
if nameEnd <= end && bytes[nameStart..<nameEnd].equalsASCIICaseInsensitive(lowercaseLiteral: lowercaseCloseTagName)
&& isCloseTagNameBoundary(at: nameEnd) {
pos = nameEnd
skipPastGreaterThan()
return
}
}
pos += 1
}
}
// Keeps </scripty> from being mistaken for </script>.
private func isCloseTagNameBoundary(at index: Int) -> Bool {
guard index < end else {
return true
}
let b = bytes[index]
return b == .asciiGreaterThan || b == .asciiSlash || b.isASCIIWhitespace
}
}
}
@@ -220,13 +220,14 @@ private extension HTMLScanner {
return String(decoding: out, as: UTF8.self)
}
// Unquoted — consume until whitespace, `>`, or `/`.
// Unquoted — consume until whitespace or `>`. A `/` is part of the value,
// as in `href=https://example.com/feed` (HTML5 tokenizer behavior).
let start = pos
var out = [UInt8]()
var expanded = false
while pos < input.count {
let b = input[pos]
if b.isASCIIWhitespace || b == .asciiGreaterThan || b == .asciiSlash {
if b.isASCIIWhitespace || b == .asciiGreaterThan {
break
}
if b == .asciiAmpersand {
@@ -21,6 +21,8 @@ extension UInt8 {
static let asciiHash = UInt8(ascii: "#")
static let asciiAmpersand = UInt8(ascii: "&")
static let asciiSingleQuote = UInt8(ascii: "'")
static let asciiPlus = UInt8(ascii: "+")
static let asciiComma = UInt8(ascii: ",")
static let asciiHyphen = UInt8(ascii: "-")
static let asciiDot = UInt8(ascii: ".")
static let asciiSlash = UInt8(ascii: "/")
@@ -67,6 +67,189 @@ import RSParser
#expect(foundTestArticle)
}
// MARK: - xml:base
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5088>
@Test func xmlBaseResolvesRelativeURLsInXHTMLContent() throws {
let d = parserData("pappacoda", "atom", "https://andrea.pappacoda.it/blog/feed.atom")
let parsedFeed = try #require(try FeedParser.parse(d))
// Root-relative <icon> and <logo> resolve against the feed-level xml:base.
// iconURL prefers the logo, faviconURL is the icon.
#expect(parsedFeed.iconURL == "https://andrea.pappacoda.it/assets/debian-button.gif")
#expect(parsedFeed.faviconURL == "https://andrea.pappacoda.it/andrea_pappacoda.jpg")
let item = try #require(parsedFeed.items.first(where: { $0.title == "C su Windows" }))
// <id> is never resolved, even though it looks nothing like the base.
#expect(item.uniqueID == "tag:andrea.pappacoda.it,2023-06-09:c_su_windows")
#expect(item.url == "https://andrea.pappacoda.it/blog/c_su_windows/")
let html = try #require(item.contentHTML)
#expect(html.contains("src=\"https://andrea.pappacoda.it/blog/c_su_windows/c_su_windows_visual_studio_componenti.png\""))
#expect(html.contains("srcset=\"https://andrea.pappacoda.it/blog/c_su_windows/c_su_windows_visual_studio_componenti_light.png\""))
#expect(html.contains("src=\"https://andrea.pappacoda.it/blog/c_su_windows/clangd_path.png\""))
#expect(!html.contains("src=\"clangd_path.png\""))
// The xhtml wrapper still comes through verbatim.
#expect(html.contains("xmlns=\"http://www.w3.org/1999/xhtml\""))
}
@Test func nestedRelativeXMLBase() throws {
// A feed-level base and a relative content-level base compose,
// a relative entry link resolves against xml:base rather than
// the homepage fallback, and an xml:base on the link element itself wins.
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="https://example.com/blog/">
<title>t</title><id>urn:t</id>
<link rel="alternate" href="https://homepage.example.org/"/>
<entry>
<id>urn:t:1</id>
<title>nested base</title>
<updated>2020-05-01T00:00:00Z</updated>
<link rel="alternate" href="post1/"/>
<link rel="related" xml:base="https://elsewhere.example.net/dir/" href="related.html"/>
<content type="html" xml:base="post1/">&lt;a href="pic.png"&gt;pic&lt;/a&gt;</content>
</entry>
</feed>
"""
let d = ParserData(url: "https://example.com/blog/feed.atom", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
#expect(item.url == "https://example.com/blog/post1/")
#expect(item.externalURL == "https://elsewhere.example.net/dir/related.html")
let html = try #require(item.contentHTML)
#expect(html.contains("href=\"https://example.com/blog/post1/pic.png\""))
}
@Test func mimeTypeHTMLContentWithXMLBaseResolved() throws {
// RFC 4287 allows type="text/html" as well as type="html".
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>t</title><id>urn:t</id>
<entry>
<id>urn:t:1</id>
<title>mime type html</title>
<updated>2020-05-01T00:00:00Z</updated>
<content type="text/html" xml:base="https://example.com/post/">&lt;img src="pic.png"&gt;</content>
</entry>
</feed>
"""
let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
let html = try #require(item.contentHTML)
#expect(html.contains("src=\"https://example.com/post/pic.png\""))
}
@Test func relativeXMLBaseResolvesAgainstFeedURL() throws {
// qemu-style: a root-relative xml:base with no enclosing base
// resolves against the document (feed) URL.
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>t</title><id>urn:t</id>
<entry>
<id>/2024/04/23/qemu-9-0-0</id>
<title>release</title>
<updated>2024-04-23T23:02:00Z</updated>
<content type="html" xml:base="/2024/04/23/qemu-9-0-0/">&lt;a href="changelog.html"&gt;changelog&lt;/a&gt;</content>
</entry>
</feed>
"""
let d = ParserData(url: "https://www.qemu.org/feed.xml", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
// The relative-looking <id> stays verbatim.
#expect(item.uniqueID == "/2024/04/23/qemu-9-0-0")
let html = try #require(item.contentHTML)
#expect(html.contains("href=\"https://www.qemu.org/2024/04/23/qemu-9-0-0/changelog.html\""))
}
@Test func fragmentAndEmptyHrefsSurviveXMLBase() throws {
// One Foot Tsunami has per-entry xml:base plus footnote links like
// href="#fn…" in bodies — those must stay untouched (the footnote JS
// in the app depends on fragment-only hrefs). Some entries also have
// empty link hrefs, which must not resolve to the base URL itself.
let d = parserData("OneFootTsunami", "atom", "http://onefoottsunami.com/feed/atom/")
let parsedFeed = try #require(try FeedParser.parse(d))
let bodies = parsedFeed.items.compactMap { $0.contentHTML }
let fragmentHrefs = bodies.filter { $0.contains("href=\"#fn") }
#expect(!fragmentHrefs.isEmpty, "fragment-only hrefs must stay fragment-only")
#expect(!parsedFeed.items.contains { $0.url?.hasSuffix("wp-atom.php") ?? false }, "empty link hrefs must not resolve to the base")
}
@Test func summaryWithXMLBaseResolved() throws {
// A summary promoted to the body (no content element) is resolved
// against its own element's base at parse time.
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>t</title><id>urn:t</id>
<entry>
<id>urn:t:1</id>
<title>summary only</title>
<updated>2020-05-01T00:00:00Z</updated>
<summary type="html" xml:base="https://example.com/post/">&lt;img src="pic.png"&gt;</summary>
</entry>
</feed>
"""
let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
let html = try #require(item.contentHTML)
#expect(html.contains("src=\"https://example.com/post/pic.png\""))
}
@Test func relativeAuthorURIResolvesAgainstXMLBase() throws {
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="https://example.com/blog/">
<title>t</title><id>urn:t</id>
<entry>
<id>urn:t:1</id>
<title>relative author uri</title>
<updated>2020-05-01T00:00:00Z</updated>
<author><name>Alice</name><uri>about/</uri></author>
</entry>
</feed>
"""
let d = ParserData(url: "https://example.com/blog/feed.atom", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
let author = try #require(item.authors?.first)
#expect(author.url == "https://example.com/blog/about/")
}
@Test func textContentWithXMLBaseUntouched() throws {
let xml = """
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>t</title><id>urn:t</id>
<entry>
<id>urn:t:1</id>
<title>text content</title>
<updated>2020-05-01T00:00:00Z</updated>
<content type="text" xml:base="https://example.com/post/">See src="pic.png" for details.</content>
</entry>
</feed>
"""
let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8))
let parsedFeed = try #require(try FeedParser.parse(d))
let item = try #require(parsedFeed.items.first)
let html = try #require(item.contentHTML)
#expect(html.contains("src=\"pic.png\""))
}
@Test func articleExternalLinks() throws {
var d = parserData("DaringFireball", "atom", "https://daringfireball.net/feeds/main")
var parsedFeed = try #require(try FeedParser.parse(d))
@@ -185,4 +185,23 @@ import RSParser
let metadata = HTMLMetadataParser.htmlMetadata(with: d)
#expect(metadata.feedLinks.isEmpty)
}
@Test func unquotedAttributeValues() throws {
// Unquoted attribute values are valid HTML5, and a `/` is part of the
// value — `type=application/rss+xml` and full URLs must survive.
// ranchero.com writes its feed links this way.
let html = """
<html><head>
<link rel=alternate type=application/rss+xml title="ranchero.com RSS feed" href=https://ranchero.com/xml/rss.xml>
<link rel=alternate type=application/json title="ranchero.com JSON feed" href=https://ranchero.com/feed.json>
</head><body></body></html>
"""
let d = ParserData(url: "https://ranchero.com/", data: Data(html.utf8))
let metadata = HTMLMetadataParser.htmlMetadata(with: d)
#expect(metadata.feedLinks.count == 2)
let rssLink = try #require(metadata.feedLinks.first(where: { $0.type == "application/rss+xml" }))
#expect(rssLink.urlString == "https://ranchero.com/xml/rss.xml")
#expect(rssLink.title == "ranchero.com RSS feed")
}
}
@@ -0,0 +1,187 @@
//
// HTMLRelativeURLResolverTests.swift
// RSParser
//
// Created by Brent Simmons on 7/28/26.
//
import Foundation
import Testing
import RSParser
@Suite struct HTMLRelativeURLResolverTests {
private let base = URL(string: "https://example.com/blog/post1/")!
private func resolved(_ html: String) -> String {
HTMLRelativeURLResolver.resolvingRelativeURLs(in: html, baseURL: base)
}
// MARK: - Values that resolve
@Test func relativeValuesResolve() {
let cases: [(input: String, expected: String)] = [
("<a href=\"page.html\">x</a>", "<a href=\"https://example.com/blog/post1/page.html\">x</a>"),
("<img src=\"img.png\">", "<img src=\"https://example.com/blog/post1/img.png\">"),
("<video poster=\"p.jpg\"></video>", "<video poster=\"https://example.com/blog/post1/p.jpg\"></video>"),
("<a href=\"/root\">x</a>", "<a href=\"https://example.com/root\">x</a>"),
("<a href=\"../up/\">x</a>", "<a href=\"https://example.com/blog/up/\">x</a>"),
("<a href=\"?q=1\">x</a>", "<a href=\"https://example.com/blog/post1/?q=1\">x</a>"),
("<a href=\"//cdn.example.com/x\">x</a>", "<a href=\"https://cdn.example.com/x\">x</a>")
]
for c in cases {
#expect(resolved(c.input) == c.expected, "mismatch for \(c.input)")
}
}
@Test func ampersandEntityInRelativeURLSurvives() {
let html = "<a href=\"page?a=1&amp;b=2\">x</a>"
#expect(resolved(html) == "<a href=\"https://example.com/blog/post1/page?a=1&amp;b=2\">x</a>")
}
@Test func attributeNamesAreCaseInsensitive() {
#expect(resolved("<a HREF=\"x\">y</a>") == "<a HREF=\"https://example.com/blog/post1/x\">y</a>")
#expect(resolved("<img SrcSet=\"x 1x\">") == "<img SrcSet=\"https://example.com/blog/post1/x 1x\">")
}
@Test func unquotedAndSingleQuotedValuesResolve() {
#expect(resolved("<a href=foo/bar>x</a>") == "<a href=https://example.com/blog/post1/foo/bar>x</a>")
#expect(resolved("<a href='x'>y</a>") == "<a href='https://example.com/blog/post1/x'>y</a>")
}
// MARK: - Values left alone
@Test func untouchedValues() {
let cases = [
"<a href=\"#fn1\">x</a>",
"<a href=\"\">x</a>",
"<a href=\"https://other.example.com/a\">x</a>",
"<a href=\"http://other.example.com/a\">x</a>",
"<img src=\"data:image/png;base64,AAAA\">",
"<a href=\"mailto:x@example.com\">x</a>",
"<a href=\"javascript:void(0)\">x</a>",
"<a title=\"foo.png\" data-src=\"x\">not URL attributes</a>"
]
for html in cases {
#expect(resolved(html) == html, "expected no change for \(html)")
}
}
@Test func scriptStyleCommentsAndCDATAUntouched() {
let cases = [
"<script>var a = \"<img src=foo>\";</script>",
"<style>.x { background: url(foo.png); }</style>",
"<!-- <a href=\"x\">commented out</a> -->",
"<![CDATA[<a href=\"x\">]]>"
]
for html in cases {
#expect(resolved(html) == html, "expected no change for \(html)")
}
}
@Test func scriptSrcAttributeStillResolves() {
// The script element's own attributes are scanned — only its text content is skipped.
let html = "<script src=\"app.js\">var s = \"<img src=x>\";</script>"
#expect(resolved(html) == "<script src=\"https://example.com/blog/post1/app.js\">var s = \"<img src=x>\";</script>")
}
// MARK: - srcset
@Test func srcsetCandidatesResolve() {
let cases: [(input: String, expected: String)] = [
("<img srcset=\"a.png\">",
"<img srcset=\"https://example.com/blog/post1/a.png\">"),
("<img srcset=\"a.png 1x, b.png 2x\">",
"<img srcset=\"https://example.com/blog/post1/a.png 1x, https://example.com/blog/post1/b.png 2x\">"),
("<img srcset=\"a.png, b.png 2x\">",
"<img srcset=\"https://example.com/blog/post1/a.png, https://example.com/blog/post1/b.png 2x\">"),
("<img srcset=\"a.png 1x,b.png 2x\">",
"<img srcset=\"https://example.com/blog/post1/a.png 1x,https://example.com/blog/post1/b.png 2x\">"),
("<img srcset=\"https://other.example.com/a.png 1x, b.png 2x\">",
"<img srcset=\"https://other.example.com/a.png 1x, https://example.com/blog/post1/b.png 2x\">")
]
for c in cases {
#expect(resolved(c.input) == c.expected, "mismatch for \(c.input)")
}
}
@Test func surroundingWhitespaceInValuesIsIgnoredAndPreserved() {
// Whitespace can't hide a fragment-only href from the skip rule.
#expect(resolved("<a href=\" #fn1\">x</a>") == "<a href=\" #fn1\">x</a>")
// A padded relative value resolves — the padding stays in place.
#expect(resolved("<a href=\" page.html \">x</a>") == "<a href=\" https://example.com/blog/post1/page.html \">x</a>")
}
@Test func similarlyNamedCloseTagDoesNotEndRawText() {
// </scripty> is not </script> — everything inside stays untouched.
let html = "<script>if (a</scripty>b) { s = '<img src=\"x.png\">'; }</script>"
#expect(resolved(html) == html)
}
// MARK: - Malformed input
@Test func malformedInputIsSafe() {
// Unterminated quote: scanning stops, input preserved.
let unterminated = "<a href=\"never closed"
#expect(resolved(unterminated) == unterminated)
// Well-formed replacement before the malformed tag still happens.
let mixed = "<img src=\"a.png\"><a href=\"never closed"
#expect(resolved(mixed) == "<img src=\"https://example.com/blog/post1/a.png\"><a href=\"never closed")
let atEOF = "<a href="
#expect(resolved(atEOF) == atEOF)
let strayLessThan = "1 < 2 and <a href=\"x\">y</a>"
#expect(resolved(strayLessThan) == "1 < 2 and <a href=\"https://example.com/blog/post1/x\">y</a>")
}
// MARK: - No-op guarantee
@Test func allAbsoluteDocumentIsUnchanged() {
let html = """
<p>Intro text with an <a href="https://example.org/a">absolute link</a>.</p>
<img src="https://example.org/img.png" srcset="https://example.org/img.png 1x">
<p>More text, an <a href="#fn1">footnote</a>, and an <a href="">empty href</a>.</p>
"""
#expect(resolved(html) == html)
}
@Test func mixedDocumentIsSurgical() {
// Everything outside the two rewritten values is byte-identical —
// whitespace, attribute order, quoting, the non-URL attributes.
let html = """
<figure class='pic'>
<picture>
<source srcset="shot_light.png" media="(prefers-color-scheme: light)" width="1280" height="720"/>
<img src="shot.png" width="1280" height="720" alt="A screenshot"/>
</picture>
<figcaption>Caption &amp; more</figcaption>
</figure>
"""
let expected = """
<figure class='pic'>
<picture>
<source srcset="https://example.com/blog/post1/shot_light.png" media="(prefers-color-scheme: light)" width="1280" height="720"/>
<img src="https://example.com/blog/post1/shot.png" width="1280" height="720" alt="A screenshot"/>
</picture>
<figcaption>Caption &amp; more</figcaption>
</figure>
"""
#expect(resolved(html) == expected)
}
// MARK: - Bytes entry point
@Test func bytesEntryPointMatchesStringEntryPoint() {
let html = "<img src=\"img.png\">"
let bytes = Array(html.utf8)[...]
let fromBytes = HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: bytes, baseURL: base)
#expect(fromBytes == resolved(html))
let absolute = "<img src=\"https://example.org/img.png\">"
let absoluteBytes = Array(absolute.utf8)[...]
#expect(HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: absoluteBytes, baseURL: base) == absolute)
}
}
@@ -0,0 +1,586 @@
<?xml-stylesheet type="text/xsl" href="atom-to-xhtml.xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="it" xml:base="https://andrea.pappacoda.it/blog/">
<id>https://andrea.pappacoda.it/blog/feed.atom</id>
<link rel="self" type="application/atom+xml" href="https://andrea.pappacoda.it/blog/feed.atom"/>
<link rel="alternate" type="application/xhtml+xml" href="https://andrea.pappacoda.it/blog/"/>
<link rel="hub" href="https://websubhub.com/hub"/>
<title>Andrea Pappacoda - Blog</title>
<updated>2026-05-24T13:02:30+02:00</updated>
<author>
<name>Andrea Pappacoda</name>
<uri>https://andrea.pappacoda.it</uri>
</author>
<generator uri="https://www.vim.org" version="9.0">Vim</generator>
<icon>/andrea_pappacoda.jpg</icon>
<logo>/assets/debian-button.gif</logo>
<rights>© 2026 Andrea Pappacoda</rights>
<subtitle>Faccio cose</subtitle>
<entry>
<id>tag:andrea.pappacoda.it,2026-05-24:favicon_2026</id>
<title>Le favicon non sono difficili</title>
<published>2026-05-24T13:02:30+02:00</published>
<updated>2026-05-24T13:02:30+02:00</updated>
<summary>Una guida ragionata alle favicon (e non solo)</summary>
<link rel="alternate" type="application/xhtml+xml" href="https://andrea.pappacoda.it/blog/favicon_2026/"/>
<content type="xhtml" xml:base="https://andrea.pappacoda.it/blog/favicon_2026/"><div xmlns="http://www.w3.org/1999/xhtml">
<h1>Le favicon non sono difficili</h1>
<p>
Sembra che nel mondo della creazione dei siti web ci sia una enorme confusione
su come specificare le
<a href="https://it.wikipedia.org/wiki/Favicon">Favicon</a>, ovvero l'icona di
un particolare sito web.
</p>
<p>
Il mio sito al momento in cui sto scrivendo non ha nessuna favicon, ma in
questi giorni ho impostato quella del
<a href="https://hackinpovo.it">sito di HackInPovo</a>, un hacklab locale
di cui faccio parte. Doveva essere una cosa semplicissima, ma se ci sto
scrivendo un articolo a riguardo significa che qualcosa è andato storto.
</p>
<p>
Il web, infatti, ha fatto un casino. Gente confusa che fa domande, "guru" che
danno risposte approssimative, soluzioni che "a me funzionano" sparate un po'
qua e là. Ma qual è la causa di questo caos?
</p>
<h2>Il problema</h2>
<p>
In breve, il problema è che il web è vecchio. Mi spiego meglio.
</p>
<p>
Esistono tantissimi web browser, da tantissimi anni, e se oggi la situazione è
abbastanza standardizzata, con gruppi di persone che lavorano insieme per far
sì che diverse implementazioni funzionino in maniera simile, non è sempre stato
così.
</p>
<p>
In passato i vari autori di browser web hanno aggiunto, ognuno a modo
loro, la possibilità per un sito web di comunicare al browser una sua icona
"preferita", per dare un riferimento simbolico e visuale al sito. Nonostante
l'idea sia generica, le risposte alle domande implementative erano diverse:
quali formati immagine supportiamo? Come troviamo l'icona? Di che dimensione
dev'essere? Ma se tipo voglio aggiungere un collegamento del sito alla
<span xml:lang="en">home page</span> del mio telefono che icona uso? E come
facciamo per i temi chiaro/scuro? E così via.
</p>
<p>
È quindi naturale che in un ecosistema dove chi sviluppa dà risposte diverse a
domande che cambiano nel tempo, ogni risposta di un "guru" pubblicata da
qualche parte nell'internet lascia il tempo che trova.
</p>
<h2>La soluzione</h2>
<p>
La soluzione è non ascoltare quello che dicono i guru. Sì, questo articolo
compreso.
</p>
<p>
O meglio: dobbiamo farci dare le risposte da chi sviluppa le tecnologie del
web, in quanto sono loro davvero gli unici che conoscono la verità. A questo,
non fa mai male aggiungere un po' di buon senso proprio, più un occhio di
riguardo per chi utilizza browser vecchi o alternativi.
</p>
<p>
Ma dove le dobbiamo cercare, quindi, queste risposte? Ci basta sapere chi
sviluppa le tecnologie del web come l'HTML, e dove vengono da loro pubblicate
le informazioni per noi comuni mortali.
</p>
<p>
Lo standard HTML viene sviluppato principalmente da un gruppo di persone
chiamato "<a href="https://whatwg.org">WHATWG</a>", e pubblicato come una
grossa specifica nota come
"<cite><a href="https://html.spec.whatwg.org/dev/">HTML Living Standard</a></cite>".
Potete spulciarvi tutto il documento se siete curiosi e avete abbastanza tempo
libero, ma se volete semplicemente sapere come cavolo impostare 'ste benedette
icone vi rimando direttamente alla pagina che descrive il comportamento
dell'elemento <code>link</code>, in particolare la sezione
<a href="https://html.spec.whatwg.org/dev/links.html#rel-icon">4.6.6.9 Link type "icon"</a>.
</p>
<p>
Lo standard mostra come per specificare una icona sia necessario creare
un elemento <code>link</code> con l'attributo <code>rel</code> impostato a
<code>icon</code>, l'attributo <code>type</code> che specifichi il
<a href="https://www.iana.org/assignments/media-types/media-types.xhtml#image">media type</a>
dell'immagine, l'attributo <code>sizes</code> che specifichi le dimensioni
in pixel dell'immagine e infine l'attributo <code>href</code> che contenga il
percorso all'immagine da usare come icona.
</p>
<p>
Tutte queste informazioni vengono usate dal web browser per capire quale icona
scegliere a seconda del contesto. Una immagine vettoriale SVG verrà
probabilmente preferita a un PNG, a meno che il PNG non abbia una dimensione in
pixel che sia esattamente quella necessaria al browser.
</p>
<p>
O forse no.
</p>
<p>
Non ci importa sapere che cosa un determinato browser faccia <em>oggi</em>,
perché probabilmente domani agirà in maniera diversa. Quello che ci interessa
sapere è come comunicare al browser in maniera efficace tutto quello che gli
serve per fare la scelta che questo reputi più giusta.
</p>
<h2>Il buon senso</h2>
<p>
Arriviamo quindi alle mie raccomandazioni personali, basate su quello che credo
sia un po' di ragionamento e buon senso.
</p>
<p>
Storicamente i browser web hanno usato una immagine in
<a href="https://www.iana.org/assignments/media-types/image/vnd.microsoft.icon">formato ICO</a>
chiamata "favicon.ico" e disponibile nella cartella primaria del sito web.
Quindi, se il nostro sito è <i>blog.example.org</i>, dovrebbe essere
accessibile dall'URL <code>https://blog.example.org/favicon.ico</code>.
</p>
<p>
È importante assicurarsi che l'immagine sia effettivamente in formato ICO, e
non semplicemente chiamata "favicon.ico". Creare una icona in questo formato è
abbastanza semplice usando il programma
<a href="https://imagemagick.org">ImageMagick</a>:
</p>
<pre><samp><span class="prompt">$ </span><kbd>magick immagine.png -resize 256x -define icon:auto-resize favicon.ico</kbd></samp></pre>
<p>
L'opzione
<code>
<a href="https://imagemagick.org/script/defines.php">-define</a>
icon:auto-resize
</code> ci permette di sfruttare una utile funzionalità dei file ICO, ovvero
quella di inserire più dimensioni della stessa immagine all'interno di un unico
file. Possiamo averne conferma sempre con ImageMagick usando il suo
sotto-comando <code>identify</code>:
</p>
<pre><samp><span class="prompt">$ </span><kbd>magick identify favicon.ico</kbd>
favicon.ico[0] ICO 256x256 256x256+0+0 8-bit sRGB 0.010u 0:00.003
favicon.ico[1] ICO 192x192 192x192+0+0 8-bit sRGB 0.010u 0:00.001
favicon.ico[2] ICO 128x128 128x128+0+0 8-bit sRGB 0.010u 0:00.001
favicon.ico[3] ICO 96x96 96x96+0+0 8-bit sRGB 0.010u 0:00.000
favicon.ico[4] ICO 64x64 64x64+0+0 8-bit sRGB 0.010u 0:00.000
favicon.ico[5] ICO 48x48 48x48+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[6] ICO 40x40 40x40+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[7] ICO 32x32 32x32+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[8] ICO 24x24 24x24+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[9] ICO 16x16 16x16+0+0 8-bit sRGB 569494B 0.000u 0:00.000</samp></pre>
<p>
Essendo che il formato ICO non fa uso di compressione, l'avere così tante
immagini di diverse dimensioni può portare a un file di dimensioni eccessive.
Il problema è evitabile specificando quali risoluzioni ci interessano
all'opzione <code>-define icon:auto-resize</code>, ad esempio con
<code>-define icon:auto-resize=128,96,64,48,40,32,24,16</code>.
</p>
<p>
Infine, questa immagine dovrà essere aggiunta all'intestazione del documento
HTML del nostro sito con un elemento <code>link</code>:
</p>
<pre><code class="language-html">&lt;link
rel="icon"
type="image/vnd.microsoft.icon"
sizes="128x128 96x96 64x64 48x48 40x40 32x32 24x24 16x16"
href="/favicon.ico"
/&gt;</code></pre>
<p>
Una icona di più alta risoluzione può essere aggiunta usando una immagine di
tipo PNG, che è un formato un po' più moderno ed efficiente dei file ICO di
Microsoft. Il mio consiglio è di usare una immagine che abbia una risoluzione
maggiore dell'immagine ICO, come 256x256 o 512x512 pixel, ma non più di
1024x1024 pixel.
</p>
<p>
Il motivo è che tipicamente le favicon vengono rappresentate come piccolissime
immagini sul nostro schermo, e diventano più grandi in condizioni particolari
(tipo quando aggiungiamo un sito alla pagina iniziale del browser). Non serve
quindi che l'immagine abbia risoluzione estremamente elevata. Per i curiosi,
i dettagli sul perché del limite di 1024 pixel sono discussi più sotto.
</p>
<p>
Il secondo elemento <code>link</code> che quindi consiglio è questo qui:
</p>
<pre><code class="language-html">&lt;link
rel="icon"
type="image/png"
sizes="256x256"
href="/favicon.png"
/&gt;</code></pre>
<p>
Ma tutte queste chiacchiere sulle dimensioni sono inutili. La vera soluzione è
quella di usare una immagine vettoriale in formato SVG, così che i siano i
browser stessi a poter scegliere la dimensione che vogliono, senza dover star
lì a impazzire creando mille mila PNG di dimensioni diverse. L'unico motivo per
cui non consiglio di usare <em>solo</em> un SVG è che non tutti i browser li
supportano.
</p>
<p>
Il terzo e ultimo elemento <code>link</code> da aggiungere è quindi questo:
</p>
<pre><code class="language-html">&lt;link
rel="icon"
type="image/svg+xml"
sizes="any"
href="/favicon.svg"
/&gt;</code></pre>
<h2>La mela</h2>
<p>
E anche oggi mi tocca parlar di Apple...
</p>
<p>
Anche se questo articolo parla delle favicon, non posso fare a meno di parlare
anche della icona assegnata alle Web Clip su iOS, meglio nota come "Apple touch
icon".
</p>
<p>
Nonostante Safari di Apple utilizzi le icone specificate con
<code>rel="icon"</code> come iconcine dei siti all'interno del browser stesso,
quando andiamo ad aggiungere il sito alla schermata Home del telefono (creando
quindi una Web Clip) quell'immagine viene totalmente ignorata.
</p>
<p>
Al suo posto viene invece usata l'immagine specificata attraverso il valore
<code>apple-touch-icon</code> dell'attributo <code>rel</code>. Questa immagine
ha dei requisiti particolari imposti da Apple, sparsi in diverse pagine di
documentazione ufficiale.
L'<a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html">originale</a>
(e ormai obsoleto) documento mostra diverse dimensioni come esempi,
raccomandando di leggere le <i xml:lang="en">iOS Human Interface Guidelines</i> per i valori effettivi.
Queste, nella
<a href="https://developer.apple.com/design/human-interface-guidelines/app-icons#Specifications">sezione dedicata alle icone</a>
raccomandano che le icone siano quadrati di 1024 pixel. E, ancora, in una
<a href="https://developer.apple.com/documentation/devicemanagement/webclip">pagina
di documentazione per sviluppatori</a> riguardante le API di gestione del dispositivo,
viene raccomandato che l'immagine non superi i 400x400 pixel.
</p>
<p>
Insomma, un casino.
</p>
<p>
Per capire effettivamente cosa fare bisogna fare un passo indietro nel tempo,
quando la documentazione di Apple conteneva ancora informazioni precise.
<a href="https://archive.is/VBAJs">Nel 2023</a>, infatti, le
<abbr title="Human Interface Guidelines">HIG</abbr> spiegavano che i dispositivi
iOS usano icone a multipli di 60 pixel, a seconda della loro dimensione.
Il mio vecchio iPhone SE, ad esempio, usa un fattore di scala "@2x", quindi
vuole le icone di 120x120 pixel, mentre l'ultimissimo iPhone 17 Pro Max ha un
fattore di scala @3x, con icone della Home screen a 180x180 pixel.
</p>
<p>
Potremmo quindi voler usare due immagini, una scalata @2x e una @3x.
Se proprio sentite che 180 pixel sembrano troppo pochi, potete anche inventarvi
un fattore di scala @4x con una immagine di 240x240 pixel, così da essere pronti
anche all'iPhone 28 con Diplay Retina Hyper-Dense™.
</p>
<!--
In realtà l'icona 120x120 l'ho esclusa di proposito perché per qualche motivo
viene sempre preferita anche dagli iPhone scalati @3x, nonostante esista anche
l'icona 180x180. E, di fatti, comporta che l'icona della web clip sia leggermente
sgranata.
Ho riportato questo problema a Apple, ma senza ricevere risposta:
> Hello,
>
> The Safari browser always prefers a @2x scaled Web Clip icon
> (apple-touch-icon-120x120.png) even for devices which use @3x scaled app
> icons (like all the most recent iPhones).
>
> Safari should instead only use the 120x120 image on the devices which perform
> @2x scaling, as described in the Layout chapter of the Human Interface
> Guidelines, while using the 180x180 images on the @3x-scaled devices.
>
> For instance, Safari should not unconditionally perform a
> GET /apple-touch-icon-120x120.png, but make it conditional on
> what I showed above.
>
> Thank you. Have a nice day.
Poi vabbè, ci sono altri problemi. Tipo che Safari su iOS 26 sembra ignorare
completamente l'attributo link, e faccia due GET hardcoded su
apple-touch-icon.png e apple-touch-icon-120x120.png. A caso. Completamente. Boh.
E la roba crazy è che su iOS 15 invece i link rel funzionano!!! Ma che cazzzz
Se stai leggendo questo, sei curioso next level :)
-->
<p>
Ma in termini pratici, questa distinzione non è davvero necessaria.
L'icona infatti verrà infatti riadattata automaticamente dal dispositivo se
troppo grande o troppo piccola. Per semplicità consiglio quindi di usare un
singolo PNG di 180x180 pixel chiamato <code>apple-touch-icon.png</code>.
Inoltre, l'immagine dev'essere quadrata, non circolare (così come le icone di iOS).
</p>
<p>
Ed ecco quindi il vero ultimo elemento <code>link</code> da aggiungere alla
nostra pagina HTML:
</p>
<pre><code class="language-html">&lt;link
rel="apple-touch-icon"
type="image/png"
sizes="180x180"
href="/apple-touch-icon.png"
/&gt;</code></pre>
<h2>Trick extra</h2>
<p>
Se proprio vi piace fare tutto preciso per filo e per segno allora vi consiglio
anche l'uso di tre programmini per ottimizzare e semplificare le vostre favicon:
<a href="https://pngquant.org">pngquant</a>,
<a href="https://github.com/oxipng/oxipng">oxipng</a> e
<a href="https://github.com/linebender/resvg/tree/main/crates/usvg">usvg</a>.
</p>
<p>
I primi due servono per ridurre drasticamente le dimensioni dei file PNG. Il
primo ricodifica i PNG in un formato più efficiente, riducendo il numero di
colori usati per esprimere l'icona (talvolta con una minima, seppur
impercettibile, perdita di dettagli), mentre il secondo rimuove metadati non
necessari e ri-comprime l'immagine senza perdita di qualità.
</p>
<p>
Ad esempio, per creare la favicon di tipo PNG che ho descritto prima potete
usare una combo di ImageMagick + pngquant + oxipng in questo modo:
</p>
<pre><code>$ magick immagine.png -resize 256x png:- \
| pngquant --speed 1 - \
| oxipng --opt max --strip all --out favicon.png -</code></pre>
<p>
usvg, invece, semplifica drasticamente la struttura dei file SVG così che
risultino più facilmente gestibili dai vari visualizzatori, risolvendo così
eventuali problemi di visualizzazione che alcuni utenti potrebbero incontrare,
specialmente su browser vecchi o alternativi. Usarlo è molto semplice:
</p>
<pre><code>$ usvg immagine.svg favicon.svg</code></pre>
<h2>Conclusioni</h2>
<p>
Spero che questo articolo abbia fatto un po' di chiarezza!
</p>
<p>
Non solo: il messaggio più importante che voglio far passare è che
<em>importantissimo</em> sviluppare la capacità di individuare <em>da chi</em>
andare a prendere le risposte alle nostre domande. Il web, come ogni altra
parte del mondo, è pieno di contenuto che ci viene sparato addosso da ogni
lato. Spendere un po' di tempo ed energie per andare alla radice della
questione e trovare la <em>vera</em> risposta è l'unico modo per trovare quale,
tra il mare di dati, è l'informazione corretta.
</p>
<p>
E se siete dei nerd come me, è anche divertente :D
</p>
<p><small>Dedicato a viirginiax</small></p>
</div></content>
</entry>
<entry>
<id>tag:andrea.pappacoda.it,2024-12-12:tesi</id>
<title>Una nuova primitiva di creazione dei processi per sistemi Unix</title>
<published>2024-12-12T15:30:00+01:00</published>
<updated>2026-06-02T15:14:31+02:00</updated>
<summary>
Nei sistemi Unix la creazione dei processi è stata storicamente effettuata
attraverso la famiglia di funzioni fork() ed exec(). In questa tesi verrà
introdotta e analizzata la funzione spawn(), una nuova primitiva
fondamentalmente diversa che, con un design più semplice, mira a risolvere
le problematiche legate alla natura di fork()
</summary>
<link rel="alternate" type="application/pdf" href="https://andrea.pappacoda.it/blog/tesi.pdf"/>
</entry>
<entry>
<id>tag:andrea.pappacoda.it,2023-06-09:c_su_windows</id>
<title>C su Windows</title>
<published>2023-06-09T16:00:00+01:00</published>
<updated>2025-12-26T20:30:00+01:00</updated>
<summary>Come installare un ambiente di sviluppo flessibile e moderno per C su Windows</summary>
<link rel="alternate" type="application/xhtml+xml" href="https://andrea.pappacoda.it/blog/c_su_windows/"/>
<content type="xhtml" xml:base="https://andrea.pappacoda.it/blog/c_su_windows/"><div xmlns="http://www.w3.org/1999/xhtml">
<h1>C su Windows</h1>
<p>Installare un compilatore C su Windows può essere semplice quanto complesso, a
seconda della procedura scelta. Ci sono due modi principali per farlo, uno più
immediato e uno più flessibile. Si può decidere di installare l'IDE Visual
Studio e lasciar fare tutto a lui, ma si sarà praticamente obbligati ad usare
l'IDE per tutte le interazioni con gli strumenti di sviluppo C, oppure si può
andare a installare gli strumenti di sviluppo manualmente senza l'IDE e andare a
configurare il nostro editor di codice per fare uso degli strumenti scaricati.</p>
<p>Qui andrò a spiegare i dettagli della seconda procedura, dato che la prima è
abbastanza semplice; basta cercare Visual Studio sul web, scaricare l'installer
e seguire le istruzioni a schermo.</p>
<p>Potrei partire subito con la lista di cose da fare, ma preferisco prima spiegare
un attimo cosa e soprattutto perché stiamo facendo le cose in questo modo. C e
C++, a differenza di altri linguaggi, sono solo &quot;standard&quot;, documenti che
descrivono come C dovrebbe funzionare, ed esistono quindi diverse
implementazioni di questi standard, di queste specifiche. Ogni implementazione è
divisa in due componenti principali: il compilatore C, che prende il nostro
codice sorgente e lo trasforma in codice macchina eseguibile, e la libreria
standard C che contiene tutte le funzioni, appunto, &quot;di libreria&quot;, come
<code>printf()</code>, <code>scanf()</code>, e insomma tutte le funzioni che possiamo includere nel
nostro codice con direttive come <code>#include &lt;stdlib.h&gt;</code> eccetera.</p>
<p>Dovrebbe essere ora un po' più chiaro cosa dobbiamo fare, ovvero installare un
compilatore e una libreria standard. Su Windows esistono diversi compilatori C,
ma solo una libreria standard. Questi fanno parte di &quot;MSVC&quot;, che sta per
&quot;Microsoft Visual C&quot;, che come dice il nome sono parte della suite di Visual
Studio. Per installarli è necessario scaricare i &quot;Visual Studio Build Tools&quot;,
che sono gli stessi strumenti installati con l'IDE ma senza l'IDE. I Build Tools
sono sul sito di Visual Studio; basta cercarli sul web e andare in fondo alla
pagina (oppure andare direttamente su
<a href="https://visualstudio.microsoft.com/it/downloads/#build-tools-for-visual-studio-2022">https://visualstudio.microsoft.com/it/downloads/#build-tools-for-visual-studio-2022</a>).
Una volta scaricato ed avviato l'installer ci ritroveremo davanti a una sezione
che permette di selezionare tanti workload diversi; a noi servono solo una
manciata di componenti, quindi bisogna spostarsi nella sezione &quot;Singoli
componenti&quot; selezionare &quot;Funzionalità di base per C++ Build Tools&quot;, la versione
più recente di MSVC (nel mio caso &quot;MSVC v143 - VS 2022 C++ Build Tools x64/x86
(più recente)&quot;), l'ultimo Windows SDK (nel mio caso &quot;Windows 11 SDK
(10.0.22621.0)&quot;), e &quot;Windows Universal C Runtime&quot;. Una volta selezionati,
possiamo procedere con l'installazione. Il tutto andrà a occupare un paio di GB
di spazio di archiviazione.</p>
<figure>
<picture>
<source srcset="c_su_windows_visual_studio_componenti_light.png" media="(prefers-color-scheme: light)" width="1280" height="720"/>
<img src="c_su_windows_visual_studio_componenti.png" width="1280" height="720" alt="Screenshot del Visual Studio Installer"/>
</picture>
<figcaption>Componenti da selezionare dal Visual Studio Installer</figcaption>
</figure>
<p>A questo punto abbiamo già un ambiente di sviluppo C, benché molto minimale.
Possiamo accedere al compilatore aprendo il &quot;Prompt dei comandi di sviluppo
nativo x64&quot;, e dando il comando <code>cl</code>. Per compilare un file si può dare <code>cl nomefile.c</code>, ed eseguire il .exe generato.</p>
<p>Per come Microsoft ha sviluppato i suoi compilatori, l'uso di questo prompt di
comandi di sviluppo, a volte installato in inglese come &quot;x64 Native Tools
Command Prompt&quot;, è obbligatorio per avere accesso al compilatore C. Quindi ogni
volta che vorremo andare a sviluppare codice C o C++ dovremo lanciare prima di
tutto uno di quei <code>cmd</code>, e da lì tutti i programmi (ad esempio, se vogliamo
usare VSCode, dovremo aprire un developer command prompt e digitare <code>code</code> per
lanciarlo direttamente dal <code>cmd</code> di sviluppo).</p>
<p>Con questo set up, però, aprendo un editor di codice come VSCode non ci saranno
funzionalità &quot;smart&quot; come segnalazione di errori, warning, suggerimenti,
eccetera. Anche qui, abbiamo due opzioni: la prima è specifica a VSCode, di
qualità relativamente bassa, (e ho visto che è un po' buggata, ma non avendola
usata molto personalmente non ne sono sicuro), mentre la seconda è utilizzabile
da pressoché tutti gli editor di codice, è più usata, dà suggerimenti migliori,
ma vanno fatti dei passaggi a mano. Ovviamente, sceglieremo la seconda opzione.</p>
<p>La seconda opzione consiste nell'usare clangd, un <em>Language Server</em> basato sul
compilatore Clang, che parla il <em>Language Server Protocol</em> (LSP). In pratica è
un programmino che parla con un qualsiasi editor di codice che supporta l'LSP e
gli dice se e cosa non va bene del codice presente nell'editor. Clang invece è
un ottimo compilatore basato sul progetto LLVM, ed è naturale che abbia
suggerimenti molto utili.</p>
<p>Per ottenere clangd è sufficiente scaricare l'ultima release pubblicata sulla
sua pagina GitHub, disponibile al link
<a href="https://github.com/clangd/clangd/releases/latest">https://github.com/clangd/clangd/releases/latest</a> nella sezione &quot;Assets&quot;. Una
volta scaricato lo zip, possiamo estrarlo in una cartella a piacere e informare
Windows della sua esistenza, così che possa essere eseguito dal nostro editor di
testo; in altri termini, dobbiamo aggiungere l'eseguibile <code>clangd</code> alla variabile
d'ambiente <code>PATH</code>. Per fare ciò ci basta cercare &quot;Variabili d'ambiente&quot; nella
casella di ricerca di sistema, aprire la pagina delle impostazioni, e andare a
modificare la variabile <code>Path</code> per l'utente corrente. Una volta schiacciato
&quot;Modifica&quot;, andiamo a schiacciare &quot;Nuovo&quot; nella finestra di dialogo appena
aperta e incolliamo il percorso completo alla cartella <code>bin</code> contenuta nello zip
di clangd appena estratto. Fatto ciò, possiamo schiacciare &quot;Ok&quot; per chiudere
tutte le finestre appena aperte.</p>
<figure>
<picture>
<img src="clangd_path.png" width="950" height="642" alt="Screenshot del dialogo di sistema per modificare le variabili d'ambiente"/>
</picture>
<figcaption>Variabile Path modificata per clangd</figcaption>
</figure>
<p>Bene, ora che abbiamo installato tutta la roba che ci serve, possiamo procedere
con l'ultimo passaggio: configurare l'editor di codice per fare uso di quello
che abbiamo installato. Essendo clangd un server LSP standard è possibile usare
un qualsiasi editor di codice molto facilmente, ed io ho scelto VSCode. Per
usare clangd su VSCode è sufficiente installare l'estensione &quot;clangd&quot; ed
assicurarsi che l'estensione C/C++ di Microsoft non sia installata, in quanto
andrebbe in conflitto con clangd. Finita l'installazione, il nostro editor
dovrebbe essere in grado di sfruttare tutte le funzionalità intelligenti che
potremmo desiderare, come salti a definizione di funzioni, documentazione
appoggiando il puntatore su un simbolo, eccetera.</p>
<figure>
<picture>
<source srcset="vscode_lsp_light.png" media="(prefers-color-scheme: light)" width="1024" height="728"/>
<img src="vscode_lsp.png" width="1024" height="728" alt="Screenshot di VSCode che mostra la funzionalità di documentazione al passaggio del cursore"/>
</picture>
<figcaption>Alcune delle funzionalità abilitate da LSP</figcaption>
</figure>
<p>Nonostante LSP sia fantastico per quanto riguarda la scrittura di codice, non
fornisce altre funzionalità che potremmo volere, come il debug in un click di un
programma. Quest'area è meno standardizzata, per cui so dirvi solo come
configurare il debugger su VSCode. Il miglior debugger per C e C++ integrato in
VSCode è, a parer mio, contenuto nell'estensione CodeLLDB. Usa, appunto, il
debugger LLDB, parte di LLVM proprio come clangd, e supporta il debug di
programmi scritti per Windows e non. Una volta installata l'estensione, rimane
un ultima parte di configurazione da fare: bisogna dire a VSCode quale programma
vogliamo debuggare, come, e dove. Questa configurazione viene fatta creando un
file chiamato <code>launch.json</code> e memorizzato nella cartella <code>.vscode</code> del progetto,
contenente più o meno questo:</p>
<pre class="shiki shiki-themes dark-plus light-plus" style="background-color:light-dark(#FFFFFF, #1E1E1E);--shiki-dark-bg:#1E1E1E;--shiki-light-bg:#FFFFFF;color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000" tabindex="0"><code><span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">{</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "version"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"0.2.0"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "configurations"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: [</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> {</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "type"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"lldb"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "expressions"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"native"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "request"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"launch"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "name"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"Debug"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "program"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"${workspaceFolder}/mioprogetto.exe"</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> }</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> ]</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">}</span></span></code></pre>
<p>Quel file dice a VSCode che abbiamo creato una configurazione chiamata &quot;Debug&quot;,
da eseguire con il debugger &quot;lldb&quot;, che deve lanciare il programma
&quot;mioprogetto.exe&quot;. L'opzione &quot;expressions: native&quot; dice a LLDB che vogliamo
usare la classica sintassi C per le espressioni inserite nel pannello &quot;Watch&quot;
del debugger, e non una alternativa custom di LLDB.</p>
<p>Bene! Ora ci basta soltanto compilare il nostro file <code>.c</code> dal terminale
integrato di VSCode e premere il triangolino verde per far partire il debugger.
Per compilare, ad esempio, un file chiamato &quot;main.c&quot;, ci è sufficiente usare
questo comando:</p>
<pre class="shiki shiki-themes dark-plus light-plus" style="background-color:light-dark(#FFFFFF, #1E1E1E);--shiki-dark-bg:#1E1E1E;--shiki-light-bg:#FFFFFF;color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000" tabindex="0"><code><span class="line"><span>cl -Zi main.c</span></span></code></pre>
<p>E verrà generato l'eseguibile <code>main.exe</code>, insieme ad altri file intermedi che
non ci interessano. L'uso della opzione <code>-Zi</code> è indispensabile per il debug, in
quanto senza di questa il nostro codice C verrebbe compilato senza informazioni
di debug richieste, appunto, da LLDB per debuggare il programma.</p>
<p>Potremmo fermarci qui, ma c'è un ultima chicca che voglio lasciarvi che renderà
l'esperienza di debug un po' più gradevole. Dover ricompilare a mano tutte le
volte il programma prima di poterlo eseguire è un po' una rottura, vero? Beh,
per me lo è, ma fortunatamente VSCode può automatizzare il tutto con solo un
altro paio di righe di configurazione.</p>
<p>Per prima cosa andiamo a creare un nuovo file <code>tasks.json</code> all'interno della
cartella <code>.vscode</code> creata in precedenza che dice all'editor come compilare il
nostro progetto:</p>
<pre class="shiki shiki-themes dark-plus light-plus" style="background-color:light-dark(#FFFFFF, #1E1E1E);--shiki-dark-bg:#1E1E1E;--shiki-light-bg:#FFFFFF;color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000" tabindex="0"><code><span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">{</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "version"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"2.0.0"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "tasks"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: [</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> {</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "label"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"compile"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "type"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"process"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "command"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"cl"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "args"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: [</span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"-Zi"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">, </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"mioprogetto.c"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">],</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "presentation"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: {</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "reveal"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"silent"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "focus"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#0000FF, #569CD6);--shiki-dark:#569CD6;--shiki-light:#0000FF">false</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> }</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> }</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> ]</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">}</span></span></code></pre>
<p>Il file definisce un task chiamato &quot;compile&quot; che lancia un &quot;process&quot;, &quot;cl&quot;,
passandogli gli argomenti &quot;-Zi&quot; e &quot;mioprogetto.c&quot;. Visto che è un task di bassa
importanza, diciamo anche che la sua &quot;presentation&quot; dev'essere &quot;silent&quot;, ovvero
che l'output della compilazione dev'essere mostrato solo in caso di errore.</p>
<p>Il secondo e ultimo passaggio è quello di dire a VSCode che il task di
compilazione dev'essere lanciato appena prima di far partire il debugger, e per
fare ciò ci basta solamente aggiungere l'opzione <code>&quot;preLaunchTask&quot;: &quot;compile&quot;</code> al
file <code>launch.json</code> creato prima, che dovrebbe ora essere così:</p>
<pre class="shiki shiki-themes dark-plus light-plus" style="background-color:light-dark(#FFFFFF, #1E1E1E);--shiki-dark-bg:#1E1E1E;--shiki-light-bg:#FFFFFF;color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000" tabindex="0"><code><span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">{</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "version"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"0.2.0"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "configurations"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: [</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> {</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "type"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"lldb"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "expressions"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"native"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "request"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"launch"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "name"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"Debug"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "program"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"${workspaceFolder}/mioprogetto.exe"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">,</span></span>
<span class="line"><span style="color:light-dark(#0451A5, #9CDCFE);--shiki-dark:#9CDCFE;--shiki-light:#0451A5"> "preLaunchTask"</span><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">: </span><span style="color:light-dark(#A31515, #CE9178);--shiki-dark:#CE9178;--shiki-light:#A31515">"compile"</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> }</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000"> ]</span></span>
<span class="line"><span style="color:light-dark(#000000, #D4D4D4);--shiki-dark:#D4D4D4;--shiki-light:#000000">}</span></span></code></pre>
<p>E questo è tutto, potete ora giocare col vostro nuovo ambiente di sviluppo per C
e C++ sul sistema operativo di casa Microsoft! A parer mio, questo setup è il
miglior compromesso tra convenienza, semplicità e funzionalità, per non parlare
di quanto sia più leggero rispetto a un IDE completo come Visual Studio. Usare
questi strumenti in questo modo vi permette di mettere mano direttamente al
livello più basso del processo costruzione dei programmi C, così da avere la
possibilità di capire veramente cosa accade dietro alle quinte quando premete
quel bel bottone verde per far partire il programma :)</p>
<p><small>Dedicato al Maestro</small></p>
</div></content>
</entry>
</feed>
@@ -60,7 +60,7 @@ struct HTTP4xxResponse {
/// These URLs are skipped for a period of time.
private var http4xxResponses = [URL: HTTP4xxResponse]()
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "DownloadSession")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DownloadSession")
public init(delegate: DownloadSessionDelegate) {
+19 -7
View File
@@ -21,7 +21,7 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi
private var callbacks = [URL: [(callback: DownloadCallback, fromCache: Bool)]]()
private let cache = DownloadCache.shared
nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Downloader")
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Downloader")
private init() {
let sessionConfiguration = URLSessionConfiguration.ephemeral
@@ -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
@@ -15,6 +15,7 @@ nonisolated public struct SpecialCase {
public static let openRSSOrgHostName = "openrss.org"
public static let youtubeHostName = "youtube.com"
public static let redditHostName = "reddit.com"
public static let relayFMHostName = "relay.fm"
public static func urlStringContainSpecialCase(_ urlString: String, _ specialCases: [String]) -> Bool {
let lowerURLString = urlString.lowercased(with: localeForLowercasing)
@@ -84,6 +85,16 @@ nonisolated extension URL {
public var isRedditURL: Bool {
SpecialCase.urlStringMatchesDomain(absoluteString, [SpecialCase.redditHostName])
}
/// The Relay FM blog, specifically — not the whole relay.fm domain (its root advertises the master
/// podcast feed). Matches the /blog index and /blog/<post> pages.
public var isRelayFMBlogURL: Bool {
guard SpecialCase.urlStringMatchesDomain(absoluteString, [SpecialCase.relayFMHostName]) else {
return false
}
let path = path()
return path == "/blog" || path.hasPrefix("/blog/")
}
}
nonisolated extension Set where Element == URL {
@@ -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
@@ -14,6 +14,7 @@ public enum WebserviceError: LocalizedError, Sendable {
case noURL
case suspended
case httpError(status: Int)
case tooManyRequests(retryAfter: TimeInterval?)
public var errorDescription: String? {
switch self {
@@ -25,6 +26,8 @@ public enum WebserviceError: LocalizedError, Sendable {
return NSLocalizedString("The URL for the request is missing.", comment: "No URL")
case .suspended:
return NSLocalizedString("The request was not sent because syncing is suspended.", comment: "Suspended")
case .tooManyRequests:
return NSLocalizedString("The server reported too many requests. Syncing is paused temporarily.", comment: "Too many requests")
}
}
@@ -100,6 +103,12 @@ nonisolated extension URLSession {
switch httpResponse.forcedStatusCode {
case 200...399:
return httpResponse
case HTTPResponseCode.tooManyRequests:
var retryAfter: TimeInterval?
if let headerValue = httpResponse.value(forHTTPHeaderField: HTTPResponseHeader.retryAfter) {
retryAfter = TimeInterval(headerValue)
}
throw WebserviceError.tooManyRequests(retryAfter: retryAfter)
default:
throw WebserviceError.httpError(status: httpResponse.forcedStatusCode)
}
@@ -23,4 +23,18 @@ struct SpecialCasesTests {
#expect(!URL(string: "https://reddit.com.evil.example/feed")!.isRedditURL)
#expect(!URL(string: "https://example.com/r/reddit.com")!.isRedditURL)
}
@Test func isRelayFMBlogURLMatchesBlog() {
#expect(URL(string: "https://www.relay.fm/blog")!.isRelayFMBlogURL)
#expect(URL(string: "http://relay.fm/blog")!.isRelayFMBlogURL)
#expect(URL(string: "https://www.relay.fm/blog/")!.isRelayFMBlogURL)
#expect(URL(string: "https://www.relay.fm/blog/some-post")!.isRelayFMBlogURL)
}
@Test func isRelayFMBlogURLRejectsNonBlog() {
#expect(!URL(string: "https://relay.fm")!.isRelayFMBlogURL) // root → master feed
#expect(!URL(string: "http://relay.fm/master/feed")!.isRelayFMBlogURL)
#expect(!URL(string: "https://www.relay.fm/blogsomething")!.isRelayFMBlogURL)
#expect(!URL(string: "https://relay.fm.evil.example/blog")!.isRelayFMBlogURL) // host check
}
}
@@ -16,7 +16,7 @@ public struct CredentialsManager {
static let CredentialsManagerErrorSourceID = 100
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "CredentialsManager")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "CredentialsManager")
private static let keychainGroup: String? = {
guard let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String else {
@@ -55,12 +55,14 @@ public actor SyncDatabase {
}
}
public func resetSelectedForProcessing(_ articleIDs: Set<String>) {
SyncStatusTable.resetSelectedForProcessing(articleIDs, database: database)
/// Pass `key` when sending one status kind at a time. A nil key matches all kinds —
/// correct only when every queued kind for these articleIDs was sent together.
public func resetSelectedForProcessing(_ articleIDs: Set<String>, key: SyncStatus.Key? = nil) {
SyncStatusTable.resetSelectedForProcessing(articleIDs, key: key, database: database)
}
public func deleteSelectedForProcessing(_ articleIDs: Set<String>) {
SyncStatusTable.deleteSelectedForProcessing(articleIDs, database: database)
public func deleteSelectedForProcessing(_ articleIDs: Set<String>, key: SyncStatus.Key? = nil) {
SyncStatusTable.deleteSelectedForProcessing(articleIDs, key: key, database: database)
}
}
@@ -66,25 +66,36 @@ struct SyncStatusTable {
database.executeUpdateInTransaction(updateSQL)
}
static func resetSelectedForProcessing(_ articleIDs: Set<String>, database: FMDatabase) {
// An articleID can have both a read row and a starred row queued. Callers that send
// one status kind at a time must pass `key` so they don’t touch the other kind’s rows.
static func resetSelectedForProcessing(_ articleIDs: Set<String>, key: SyncStatus.Key?, database: FMDatabase) {
guard !articleIDs.isEmpty else {
return
}
let parameters = articleIDs.map { $0 as AnyObject }
var parameters = articleIDs.map { $0 as AnyObject }
let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(articleIDs.count))!
let updateSQL = "update \(name) set selected = false where articleID in \(placeholders)"
var updateSQL = "update \(name) set selected = false where articleID in \(placeholders)"
if let key {
updateSQL += " and key = ?"
parameters.append(key.rawValue as AnyObject)
}
database.executeUpdateInTransaction(updateSQL, withArgumentsIn: parameters)
}
static func deleteSelectedForProcessing(_ articleIDs: Set<String>, database: FMDatabase) {
static func deleteSelectedForProcessing(_ articleIDs: Set<String>, key: SyncStatus.Key?, database: FMDatabase) {
guard !articleIDs.isEmpty else {
return
}
let parameters = articleIDs.map { $0 as AnyObject }
var parameters = articleIDs.map { $0 as AnyObject }
let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(articleIDs.count))!
let deleteSQL = "delete from \(name) where selected = true and articleID in \(placeholders)"
var deleteSQL = "delete from \(name) where selected = true and articleID in \(placeholders)"
if let key {
deleteSQL += " and key = ?"
parameters.append(key.rawValue as AnyObject)
}
database.executeUpdateInTransaction(deleteSQL, withArgumentsIn: parameters)
}
+2 -193
View File
@@ -12,14 +12,10 @@
179C39EA26F76B0500D4E741 /* Zip in Frameworks */ = {isa = PBXBuildFile; productRef = 179C39E926F76B0500D4E741 /* Zip */; };
179D280B26F6F93D003B2E0A /* Zip in Frameworks */ = {isa = PBXBuildFile; productRef = 179D280A26F6F93D003B2E0A /* Zip */; };
27692BB9F5D9450894A7EDA4 /* ErrorLog in Frameworks */ = {isa = PBXBuildFile; productRef = C1939AC39272487C923003B8 /* ErrorLog */; };
27B86EEB25A53AAB00264340 /* Account in Frameworks */ = {isa = PBXBuildFile; productRef = 51BC2F4A24D343A500E90810 /* Account */; };
4679674625E599C100844E8D /* Articles in Frameworks */ = {isa = PBXBuildFile; productRef = 4679674525E599C100844E8D /* Articles */; };
4679674725E599C100844E8D /* Articles in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 4679674525E599C100844E8D /* Articles */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
510C416924E5CDE3008226FD /* NetNewsWire Share Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 510C415C24E5CDE3008226FD /* NetNewsWire Share Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
511B148924E5DBDD00C919BD /* Account in Frameworks */ = {isa = PBXBuildFile; productRef = 511B148824E5DBDD00C919BD /* Account */; };
5131463E235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 51314637235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
513146B3235A81A400387FDC /* AddWebFeedIntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 513146B1235A81A400387FDC /* AddWebFeedIntentHandler.swift */; };
51314705235C41FC00387FDC /* Intents.intentdefinition in Sources */ = {isa = PBXBuildFile; fileRef = 51314707235C41FC00387FDC /* Intents.intentdefinition */; };
513277442590FBB60064F1E7 /* Account in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 514C16CD24D2E63F009A3AFA /* Account */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
5132775E2590FC640064F1E7 /* Articles in Frameworks */ = {isa = PBXBuildFile; productRef = 5132775D2590FC640064F1E7 /* Articles */; };
5132775F2590FC640064F1E7 /* Articles in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 5132775D2590FC640064F1E7 /* Articles */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
@@ -63,7 +59,6 @@
848E84D52DB749670023F3BA /* RSCore in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84D42DB749670023F3BA /* RSCore */; };
848E84D62DB749670023F3BA /* RSCore in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 848E84D42DB749670023F3BA /* RSCore */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
848E84D82DB749720023F3BA /* RSCore in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84D72DB749720023F3BA /* RSCore */; };
848E84DB2DB749860023F3BA /* RSCore in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84DA2DB749860023F3BA /* RSCore */; };
848E84DF2DB749A40023F3BA /* RSCore in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84DE2DB749A40023F3BA /* RSCore */; };
849182CC2FD32B1B005C3020 /* Appanoose.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 849182BB2FD32B1B005C3010 /* Appanoose.nnwtheme */; };
849182CC2FD32B1B005C3021 /* Biblioteca.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 849182BB2FD32B1B005C3011 /* Biblioteca.nnwtheme */; };
@@ -86,7 +81,6 @@
84EE3F152DB8A0A0009D3A8D /* RSTree in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F142DB8A0A0009D3A8D /* RSTree */; };
84EE3F162DB8A0A0009D3A8D /* RSTree in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F142DB8A0A0009D3A8D /* RSTree */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
84EE3F182DB8A0AC009D3A8D /* RSTree in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F172DB8A0AC009D3A8D /* RSTree */; };
84EE3F1B2DB8A0B6009D3A8D /* RSTree in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F1A2DB8A0B6009D3A8D /* RSTree */; };
84EE43482DB8A441009D3A8D /* RSDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE43472DB8A441009D3A8D /* RSDatabase */; };
84EE43492DB8A441009D3A8D /* RSDatabase in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 84EE43472DB8A441009D3A8D /* RSDatabase */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
84EE434B2DB8A44C009D3A8D /* RSDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE434A2DB8A44C009D3A8D /* RSDatabase */; };
@@ -124,13 +118,6 @@
remoteGlobalIDString = 510C415B24E5CDE3008226FD;
remoteInfo = ShareExtension;
};
5131463C235A7BBE00387FDC /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 849C64581ED37A5D003D8FC0 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 51314636235A7BBE00387FDC;
remoteInfo = "NetNewsWire iOS Intents Extension";
};
5138E94224D3404300AFF0FE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 849C64581ED37A5D003D8FC0 /* Project object */;
@@ -194,16 +181,6 @@
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
5102AE7724D17FB50050839C /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
513277512590FC000064F1E7 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
@@ -222,7 +199,6 @@
files = (
513C5CF0232571C2003D4054 /* NetNewsWire iOS Share Extension.appex in Embed Foundation Extensions */,
176814002564BB2D00D98635 /* NetNewsWire iOS Widget Extension.appex in Embed Foundation Extensions */,
5131463E235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
@@ -311,10 +287,6 @@
/* Begin PBXFileReference section */
176813F32564BB2C00D98635 /* NetNewsWire iOS Widget Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "NetNewsWire iOS Widget Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
510C415C24E5CDE3008226FD /* NetNewsWire Share Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "NetNewsWire Share Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
51314637235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "NetNewsWire iOS Intents Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
513146B1235A81A400387FDC /* AddWebFeedIntentHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddWebFeedIntentHandler.swift; sourceTree = "<group>"; };
51314706235C41FC00387FDC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.intentdefinition; name = Base; path = Base.lproj/Intents.intentdefinition; sourceTree = "<group>"; };
51314714235C420900387FDC /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Intents.strings; sourceTree = "<group>"; };
513C5CE6232571C2003D4054 /* NetNewsWire iOS Share Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "NetNewsWire iOS Share Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
518B2ED22351B3DD00400001 /* NetNewsWire-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "NetNewsWire-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
6581C73320CED60000F4AD34 /* Subscribe to Feed.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "Subscribe to Feed.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -407,9 +379,6 @@
84A6D03F2D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
/Localized/ShareExtension/MainInterface.storyboard,
IntentsExtension/Info.plist,
IntentsExtension/IntentHandler.swift,
Resources/Info.plist,
ShareExtension/Info.plist,
ShareExtension/ShareFolderPickerAccountCell.xib,
@@ -423,7 +392,6 @@
84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
/Localized/ShareExtension/MainInterface.storyboard,
AppDefaults.swift,
Resources/Assets.xcassets,
ShareExtension/ShareFolderPickerAccountCell.xib,
@@ -434,13 +402,6 @@
);
target = 513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */;
};
84A6D0412D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
IntentsExtension/IntentHandler.swift,
);
target = 51314636235A7BBE00387FDC /* NetNewsWire iOS Intents Extension */;
};
84D35E0A2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
@@ -482,16 +443,6 @@
);
target = 513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */;
};
84D35E0D2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
ShareExtension/ExtensionContainers.swift,
ShareExtension/ExtensionContainersFile.swift,
ShareExtension/ExtensionFeedAddRequest.swift,
ShareExtension/ExtensionFeedAddRequestFile.swift,
);
target = 51314636235A7BBE00387FDC /* NetNewsWire iOS Intents Extension */;
};
84D35E0E2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
@@ -550,9 +501,9 @@
8448F1F62D1E36BF0048BA50 /* Widget */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (8448F2052D1E36BF0048BA50 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Widget; sourceTree = "<group>"; };
84719F0E2DB9C52B00EEF332 /* Tests */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84719F272DB9C52B00EEF332 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Tests; sourceTree = "<group>"; };
84719F372DB9C60400EEF332 /* xcconfig */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84719F392DB9C60500EEF332 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (common, ); path = xcconfig; sourceTree = "<group>"; };
84A6CFB52D1B4EC500F23315 /* iOS */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84A6D03F2D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0412D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = iOS; sourceTree = "<group>"; };
84A6CFB52D1B4EC500F23315 /* iOS */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84A6D03F2D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = iOS; sourceTree = "<group>"; };
84CB35042DB9B5E2002AC251 /* Modules */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Modules; sourceTree = "<group>"; };
84D35D422DB9F32D004AA60E /* Shared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84D35E0A2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0B2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0D2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0E2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0F2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Shared; sourceTree = "<group>"; };
84D35D422DB9F32D004AA60E /* Shared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84D35E0A2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0B2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0E2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0F2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Shared; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -573,16 +524,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
51314634235A7BBE00387FDC /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
27B86EEB25A53AAB00264340 /* Account in Frameworks */,
848E84DB2DB749860023F3BA /* RSCore in Frameworks */,
84EE3F1B2DB8A0B6009D3A8D /* RSTree in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
513C5CE3232571C2003D4054 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -668,15 +609,6 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
513145F9235A55A700387FDC /* Intents */ = {
isa = PBXGroup;
children = (
51314707235C41FC00387FDC /* Intents.intentdefinition */,
513146B1235A81A400387FDC /* AddWebFeedIntentHandler.swift */,
);
path = Intents;
sourceTree = "<group>";
};
84023C9D2FC7E3B800284625 /* Recovered References */ = {
isa = PBXGroup;
children = (
@@ -713,7 +645,6 @@
840A1F092E41337800CFCCFC /* Technotes */,
842E249F2DB9F9B800FF7DD8 /* Mac */,
84A6CFB52D1B4EC500F23315 /* iOS */,
513145F9235A55A700387FDC /* Intents */,
8448F1F62D1E36BF0048BA50 /* Widget */,
84D35D422DB9F32D004AA60E /* Shared */,
849182072FD32B1B005C3150 /* Themes */,
@@ -735,7 +666,6 @@
6581C73320CED60000F4AD34 /* Subscribe to Feed.appex */,
513C5CE6232571C2003D4054 /* NetNewsWire iOS Share Extension.appex */,
518B2ED22351B3DD00400001 /* NetNewsWire-iOSTests.xctest */,
51314637235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex */,
510C415C24E5CDE3008226FD /* NetNewsWire Share Extension.appex */,
176813F32564BB2C00D98635 /* NetNewsWire iOS Widget Extension.appex */,
);
@@ -792,30 +722,6 @@
productReference = 510C415C24E5CDE3008226FD /* NetNewsWire Share Extension.appex */;
productType = "com.apple.product-type.app-extension";
};
51314636235A7BBE00387FDC /* NetNewsWire iOS Intents Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5131463F235A7BBE00387FDC /* Build configuration list for PBXNativeTarget "NetNewsWire iOS Intents Extension" */;
buildPhases = (
51314633235A7BBE00387FDC /* Sources */,
51314634235A7BBE00387FDC /* Frameworks */,
51314635235A7BBE00387FDC /* Resources */,
5102AE7724D17FB50050839C /* Embed Frameworks */,
513F328A2593EFCE0003048F /* Delete Unnecessary Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "NetNewsWire iOS Intents Extension";
packageProductDependencies = (
51BC2F4A24D343A500E90810 /* Account */,
848E84DA2DB749860023F3BA /* RSCore */,
84EE3F1A2DB8A0B6009D3A8D /* RSTree */,
);
productName = "NetNewsWire iOS Intents Extension";
productReference = 51314637235A7BBE00387FDC /* NetNewsWire iOS Intents Extension.appex */;
productType = "com.apple.product-type.app-extension";
};
513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = 513C5CFC232571C2003D4054 /* Build configuration list for PBXNativeTarget "NetNewsWire iOS Share Extension" */;
@@ -891,7 +797,6 @@
);
dependencies = (
5138E94324D3404300AFF0FE /* PBXTargetDependency */,
5131463D235A7BBE00387FDC /* PBXTargetDependency */,
176813FF2564BB2D00D98635 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
@@ -1014,12 +919,6 @@
510C415B24E5CDE3008226FD = {
CreatedOnToolsVersion = 12.0;
};
51314636235A7BBE00387FDC = {
CreatedOnToolsVersion = 11.2;
DevelopmentTeam = SHJK2V3AJG;
LastSwiftMigration = 1120;
ProvisioningStyle = Automatic;
};
513C5CE5232571C2003D4054 = {
CreatedOnToolsVersion = 11.0;
DevelopmentTeam = SHJK2V3AJG;
@@ -1089,7 +988,6 @@
840D617B2029031C009BC708 /* NetNewsWire-iOS */,
6581C73220CED60000F4AD34 /* Subscribe to Feed */,
513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */,
51314636235A7BBE00387FDC /* NetNewsWire iOS Intents Extension */,
176813F22564BB2C00D98635 /* NetNewsWire iOS Widget Extension */,
518B2ED12351B3DD00400001 /* NetNewsWire-iOSTests */,
510C415B24E5CDE3008226FD /* NetNewsWire Share Extension */,
@@ -1112,13 +1010,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
51314635235A7BBE00387FDC /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
513C5CE4232571C2003D4054 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -1180,25 +1071,6 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
513F328A2593EFCE0003048F /* Delete Unnecessary Frameworks */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Delete Unnecessary Frameworks";
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if [ \"${CONFIGURATION}\" = \"Release\" ]; then\n# Delete the framework that Xcode should have never included\n# https://forums.swift.org/t/is-this-an-xcode-bug-or-somehow-related-to-spm/33987\nrm -rf \"${TARGET_BUILD_DIR}/NetNewsWire iOS Intents Extension.appex/Frameworks\"\nfi\n";
};
513F328B2593F03F0003048F /* Delete Unnecessary Frameworks */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
@@ -1345,15 +1217,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
51314633235A7BBE00387FDC /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
513146B3235A81A400387FDC /* AddWebFeedIntentHandler.swift in Sources */,
51314705235C41FC00387FDC /* Intents.intentdefinition in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
513C5CE2232571C2003D4054 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -1410,11 +1273,6 @@
target = 510C415B24E5CDE3008226FD /* NetNewsWire Share Extension */;
targetProxy = 510C416724E5CDE3008226FD /* PBXContainerItemProxy */;
};
5131463D235A7BBE00387FDC /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 51314636235A7BBE00387FDC /* NetNewsWire iOS Intents Extension */;
targetProxy = 5131463C235A7BBE00387FDC /* PBXContainerItemProxy */;
};
5138E94324D3404300AFF0FE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */;
@@ -1437,18 +1295,6 @@
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
51314707235C41FC00387FDC /* Intents.intentdefinition */ = {
isa = PBXVariantGroup;
children = (
51314706235C41FC00387FDC /* Base */,
51314714235C420900387FDC /* en */,
);
name = Intents.intentdefinition;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
176814022564BB2D00D98635 /* Debug */ = {
isa = XCBuildConfiguration;
@@ -1482,22 +1328,6 @@
};
name = Release;
};
51314640235A7BBE00387FDC /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReferenceAnchor = 84719F372DB9C60400EEF332 /* xcconfig */;
baseConfigurationReferenceRelativePath = NetNewsWire_iOSintentextension_target.xcconfig;
buildSettings = {
};
name = Debug;
};
51314642235A7BBE00387FDC /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReferenceAnchor = 84719F372DB9C60400EEF332 /* xcconfig */;
baseConfigurationReferenceRelativePath = NetNewsWire_iOSintentextension_target.xcconfig;
buildSettings = {
};
name = Release;
};
513C5CF2232571C2003D4054 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReferenceAnchor = 84719F372DB9C60400EEF332 /* xcconfig */;
@@ -1631,15 +1461,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
5131463F235A7BBE00387FDC /* Build configuration list for PBXNativeTarget "NetNewsWire iOS Intents Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
51314640235A7BBE00387FDC /* Debug */,
51314642235A7BBE00387FDC /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
513C5CFC232571C2003D4054 /* Build configuration list for PBXNativeTarget "NetNewsWire iOS Share Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -1801,10 +1622,6 @@
isa = XCSwiftPackageProductDependency;
productName = Account;
};
51BC2F4A24D343A500E90810 /* Account */ = {
isa = XCSwiftPackageProductDependency;
productName = Account;
};
51C4CFF524D37DD500AF9874 /* Secrets */ = {
isa = XCSwiftPackageProductDependency;
productName = Secrets;
@@ -1853,10 +1670,6 @@
isa = XCSwiftPackageProductDependency;
productName = RSCore;
};
848E84DA2DB749860023F3BA /* RSCore */ = {
isa = XCSwiftPackageProductDependency;
productName = RSCore;
};
848E84DE2DB749A40023F3BA /* RSCore */ = {
isa = XCSwiftPackageProductDependency;
productName = RSCore;
@@ -1873,10 +1686,6 @@
isa = XCSwiftPackageProductDependency;
productName = RSTree;
};
84EE3F1A2DB8A0B6009D3A8D /* RSTree */ = {
isa = XCSwiftPackageProductDependency;
productName = RSTree;
};
84EE43472DB8A441009D3A8D /* RSDatabase */ = {
isa = XCSwiftPackageProductDependency;
productName = RSDatabase;
+24 -4
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 {
@@ -40,12 +41,11 @@ import Images
}
#else // iOS
var stateRestorationActivity: NSUserActivity {
// State restoration is now handled via UserDefaults (AppDefaults.selectedSidebarItem and AppDefaults.selectedArticle).
// The reading/selecting activities are still maintained for Handoff, Spotlight, and Siri Shortcuts,
// but we don't use them for same-device state restoration anymore.
// State restoration uses UserDefaults; this activity is left non-current so it doesn't displace
// the reading/selecting activity that Handoff advertises.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5368>
let activity = NSUserActivity(activityType: ActivityType.restoration.rawValue)
activity.persistentIdentifier = UUID().uuidString
activity.becomeCurrent()
return activity
}
#endif
@@ -55,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()
@@ -99,6 +118,7 @@ import Images
}
func reading(feed: SidebarItem?, article: Article?) {
invalidateBrowsing()
invalidateReading()
invalidateNextUnread()
@@ -110,11 +110,14 @@ import Account
self.extractedArticle = extractedArticle
self.articleTheme = theme
self.title = ArticleStringFormatter.sanitizedTitle(article?.title, forHTML: true) ?? ""
// Some feeds embed a full HTML document as the article content —
// render just the body fragment.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3008>
if let content = extractedArticle?.content {
self.body = content
self.body = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(content)
self.baseURL = extractedArticle?.url
} else {
self.body = article?.body ?? ""
self.body = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(article?.body ?? "")
self.baseURL = article?.baseURL?.absoluteString
}
}
@@ -38,6 +38,23 @@ struct ArticleRenderingSpecialCases {
return redirectScriptRegex.stringByReplacingMatches(in: html, range: range, withTemplate: "")
}
// Some feeds embed an entire HTML document as item content. Rendered inside
// the article template, the stray <html>/<body> attributes get merged onto
// the page's real elements, clobbering the theme. Render only the body fragment.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3008>
static func extractBodyFragmentIfNeeded(_ html: String) -> String {
guard html.range(of: "<body", options: .caseInsensitive) != nil ||
html.range(of: "<html", options: .caseInsensitive) != nil ||
html.range(of: "<!doctype", options: .caseInsensitive) != nil else {
return html
}
if let fragment = bodyFragment(html) {
return fragment
}
return removingDocumentWrapper(html)
}
static func isVergeSpecialCase(_ baseURL: URL) -> Bool {
guard let host = baseURL.host() else {
return false
@@ -46,6 +63,64 @@ struct ArticleRenderingSpecialCases {
return host.lowercased().contains("theverge.com")
}
// The content between a real <body …> tag and </body> (or the end of the string).
// Returns nil when there's no body tag.
private static func bodyFragment(_ html: String) -> String? {
guard let bodyOpen = rangeOfTag("<body", in: html, startingAt: html.startIndex) else {
return nil
}
guard let tagClose = html.range(of: ">", options: [], range: bodyOpen.upperBound..<html.endIndex) else {
return nil
}
let contentStart = tagClose.upperBound
let contentEnd = rangeOfTag("</body", in: html, startingAt: contentStart)?.lowerBound ?? html.endIndex
return String(html[contentStart..<contentEnd])
}
// A document with <html>/<head> but no <body> tag: remove the wrapper markup, keep the rest.
private static func removingDocumentWrapper(_ html: String) -> String {
var s = html
if let doctype = s.range(of: "<!doctype", options: .caseInsensitive),
let closeBracket = s.range(of: ">", options: [], range: doctype.lowerBound..<s.endIndex) {
s.removeSubrange(doctype.lowerBound..<closeBracket.upperBound)
}
if let headOpen = rangeOfTag("<head", in: s, startingAt: s.startIndex),
let headClose = rangeOfTag("</head", in: s, startingAt: headOpen.upperBound),
let closeBracket = s.range(of: ">", options: [], range: headClose.lowerBound..<s.endIndex) {
s.removeSubrange(headOpen.lowerBound..<closeBracket.upperBound)
}
if let htmlOpen = rangeOfTag("<html", in: s, startingAt: s.startIndex),
let closeBracket = s.range(of: ">", options: [], range: htmlOpen.lowerBound..<s.endIndex) {
s.removeSubrange(htmlOpen.lowerBound..<closeBracket.upperBound)
}
if let htmlClose = rangeOfTag("</html", in: s, startingAt: s.startIndex),
let closeBracket = s.range(of: ">", options: [], range: htmlClose.lowerBound..<s.endIndex) {
s.removeSubrange(htmlClose.lowerBound..<closeBracket.upperBound)
}
return s
}
// Case-insensitive range of a real tag — "<head" must not match "<header".
private static func rangeOfTag(_ tag: String, in html: String, startingAt start: String.Index) -> Range<String.Index>? {
var searchStart = start
while let range = html.range(of: tag, options: .caseInsensitive, range: searchStart..<html.endIndex) {
if range.upperBound == html.endIndex {
return range
}
let next = html[range.upperBound]
if next == ">" || next == "/" || next.isWhitespace {
return range
}
searchStart = range.upperBound
}
return nil
}
static func filterVergeHTML(_ html: String) -> String {
var filteredHTML = html
@@ -7,15 +7,21 @@
//
import Foundation
import RSCore
import os
import WebKit
import RSWeb
@MainActor final class WebViewConfiguration {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "WebViewConfiguration")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "WebViewConfiguration")
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 +36,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 +57,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 {
@@ -120,11 +143,26 @@ private extension WebViewConfiguration {
let filenames = ["main", "main_mac", "newsfoot"]
#endif
let scripts = filenames.map { filename in
var scripts = filenames.map { filename in
let scriptURL = Bundle.main.url(forResource: filename, withExtension: ".js")!
let scriptSource = try! String(contentsOf: scriptURL, encoding: .utf8)
return WKUserScript(source: scriptSource, injectionTime: .atDocumentStart, forMainFrameOnly: true)
}
#if os(iOS)
scripts.insert(feedInfoLabelScript, at: 0)
#endif
return scripts
}()
#if os(iOS)
// main_ios.js uses nnwGetFeedInfoLabel as the feed icon's accessibility label.
// The label is passed in from here because localized strings can't live in a static .js file.
// JSON encoding escapes the translation so it's a valid JavaScript string literal.
static let feedInfoLabelScript: WKUserScript = {
let label = NSLocalizedString("Get Feed Info", comment: "Get Feed Info")
let json = String(data: try! JSONSerialization.data(withJSONObject: label, options: .fragmentsAllowed), encoding: .utf8)!
return WKUserScript(source: "const nnwGetFeedInfoLabel = \(json);", injectionTime: .atDocumentStart, forMainFrameOnly: true)
}()
#endif
}
+42 -1
View File
@@ -6,6 +6,14 @@ html {
scrollbar-gutter: stable;
}
/* Keep absolutely positioned feed content from escaping the body and overlapping the title.
(.article-body is the Biblioteca theme's name for .articleBody.) */
.articleBody,
.article-body {
position: relative;
}
/* This is the activity indicator (currently iOS only) that is used while image zooming */
.activityIndicatorWrap {
@@ -29,6 +37,28 @@ html {
max-height: 1em !important;
}
/* Material for MkDocs and Twemoji render emoji and icons in a .twemoji span or img.
The inline SVGs have no width or height — without the site's stylesheet
they'd render at full column width. */
.twemoji {
display: inline-flex;
height: 1.125em;
vertical-align: text-top;
}
.twemoji svg {
width: 1.125em;
max-height: 100%;
fill: currentColor;
}
img.twemoji, img.emoji {
height: 1em !important;
max-height: 1em !important;
width: auto;
}
/* Hide the external link at the bottom of Daring Fireball posts */
.x-netnewswire-hide {
@@ -66,7 +96,18 @@ img[src*="doubleclick"],
img[src*="feedads"],
img[src*="feedburner"],
img[src*="feedblitz"],
img[src*="share-buttons"] {
img[src*="share-buttons"],
img[src*="/img/social/"] {
display: none !important;
}
.social_items {
display: none !important;
}
/* Mailchimp newsletters end with a follow-our-socials icon wall */
.mcnFollowBlock {
display: none !important;
}
+49 -2
View File
@@ -1,8 +1,10 @@
// Here we are making iframes responsive. Particularly useful for inline Youtube videos.
function wrapFrames() {
document.querySelectorAll("iframe").forEach(element => {
if (parseInt(element.height) > 0)
if (parseInt(element.height) > 0) {
preserveAspectRatioOfFixedSizeFrame(element);
return;
}
var wrapper = document.createElement("div");
wrapper.classList.add("iframeWrap");
element.parentNode.insertBefore(wrapper, element);
@@ -10,6 +12,21 @@ function wrapFrames() {
});
}
// The stylesheet clamps iframes to the article width with max-width: 100%,
// which leaves an attribute-sized iframe with its full height — distorted,
// and a huge blank box when the embed fails to load. Let the height follow
// the width instead.
function preserveAspectRatioOfFixedSizeFrame(element) {
const numeric = /^[1-9]\d*$/;
const width = element.getAttribute("width");
const height = element.getAttribute("height");
if (!numeric.test(width) || !numeric.test(height) || element.style.height) {
return;
}
element.style.aspectRatio = width + " / " + height;
element.style.height = "auto";
}
// Strip out color and font styling
function stripStylesFromElement(element, propertiesToStrip) {
@@ -31,7 +48,10 @@ function constrainBodyRelativeIframes() {
let iframes = document.getElementsByTagName("iframe");
for (iframe of iframes) {
if (iframe.offsetParent === document.body) {
// The article body container is positioned, so it — not document.body —
// is the offsetParent for iframes with no positioned ancestor in the content.
const offsetParent = iframe.offsetParent;
if (offsetParent === document.body || (offsetParent && (offsetParent.classList.contains("articleBody") || offsetParent.classList.contains("article-body")))) {
let heightAttribute = iframe.style.height;
if (/%|vw|vh$/i.test(heightAttribute)) {
@@ -61,6 +81,15 @@ function wrapTables() {
wrapper.className = "nnw-overflow";
table.parentNode.insertBefore(wrapper, table);
wrapper.appendChild(table);
// A negative side margin — usually from the site's own page layout —
// would put part of the table where the wrapper can't scroll to it.
if (parseFloat(getComputedStyle(table).marginLeft) < 0) {
table.style.marginLeft = "0";
}
if (parseFloat(getComputedStyle(table).marginRight) < 0) {
table.style.marginRight = "0";
}
}
}
@@ -150,6 +179,23 @@ function styleLocalFootnotes() {
}
// convert <img alt="📰" src="[...]" class="wp-smiley"> to a text node containing 📰
// Tailwind size classes like w-[22px] and h-[22px] encode an SVG icon's intended size.
// The site stylesheet that implements them is stripped, so apply the sizes directly —
// otherwise an SVG with no width and height renders at full column width.
function sizeTailwindSVGs() {
document.querySelectorAll("div.articleBody svg").forEach(svg => {
const classAttribute = svg.getAttribute("class") || "";
const width = classAttribute.match(/(?:^|\s)w-\[([\d.]+(?:px|em|rem))\]/);
if (width) {
svg.style.width = width[1];
}
const height = classAttribute.match(/(?:^|\s)h-\[([\d.]+(?:px|em|rem))\]/);
if (height) {
svg.style.height = height[1];
}
});
}
function removeWpSmiley() {
for (const img of document.querySelectorAll("img.wp-smiley[alt]")) {
img.parentNode.replaceChild(document.createTextNode(img.alt), img);
@@ -161,6 +207,7 @@ function processPage() {
wrapTables();
inlineVideos();
stripStyles();
sizeTailwindSVGs();
constrainBodyRelativeIframes();
convertImgSrc();
flattenPreElements();
+3 -1
View File
@@ -65,7 +65,9 @@
/** @type {(ev:MouseEvent) => void} */
this.clickoutHandler = (ev) => {
if (!(ev.target instanceof Element)) return;
if (ev.target.closest(`.${POPOVER_CLS}`) === this.popover) return;
// Keep this popover open for clicks anywhere inside it, including a nested footnote popover.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/2372>
if (this.popover.contains(ev.target)) return;
if (ev.target === this.fnref) {
ev.stopPropagation();
ev.preventDefault();
@@ -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)
@@ -19,6 +19,34 @@ final class ArticleThemesManager: NSObject, NSFilePresenter, Sendable {
static let shared = ArticleThemesManager()
public let folderPath: String
/// User-facing message for a failed theme import.
static func importErrorMessage(for error: Error) -> String {
guard let decodingError = error as? DecodingError else {
return error.localizedDescription
}
switch decodingError {
case .typeMismatch(let type, _):
let localizedError = NSLocalizedString("This theme cannot be used because the type “%@” is mismatched in the Info.plist.", comment: "Theme import error — type mismatch in Info.plist")
return NSString.localizedStringWithFormat(localizedError as NSString, String(describing: type)) as String
case .valueNotFound(let value, _):
let localizedError = NSLocalizedString("This theme cannot be used because the value “%@” is not found in the Info.plist.", comment: "Theme import error — value missing from Info.plist")
return NSString.localizedStringWithFormat(localizedError as NSString, String(describing: value)) as String
case .keyNotFound(let codingKey, _):
let localizedError = NSLocalizedString("This theme cannot be used because the key “%@” is not found in the Info.plist.", comment: "Theme import error — key missing from Info.plist")
return NSString.localizedStringWithFormat(localizedError as NSString, codingKey.stringValue) as String
case .dataCorrupted(let context):
guard let underlyingError = context.underlyingError as NSError?,
let debugDescription = underlyingError.userInfo["NSDebugDescription"] as? String else {
return error.localizedDescription
}
let localizedError = NSLocalizedString("This theme cannot be used because of data corruption in the Info.plist: %@.", comment: "Theme import error — Info.plist data corruption")
return NSString.localizedStringWithFormat(localizedError as NSString, debugDescription) as String
default:
return error.localizedDescription
}
}
let presentedItemOperationQueue = OperationQueue.main // NSFilePresenter
let presentedItemURL: URL? // NSFilePresenter
+1 -1
View File
@@ -46,7 +46,7 @@ struct DinosaurRow: Identifiable {
var monthThreshold = 6
private var sortDescriptor: NSSortDescriptor?
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "DinosaursViewModel")
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DinosaursViewModel")
func refresh() async {
let start = Date()
@@ -38,14 +38,14 @@ import Articles
return
}
send(article, to: app)
send(article, to: app, selectedText: selectedText)
}
}
}
private extension SendToMarsEditCommand {
func send(_ article: Article, to app: UserApp) {
func send(_ article: Article, to app: UserApp, selectedText: String?) {
// App has already been launched.
@@ -53,7 +53,8 @@ private extension SendToMarsEditCommand {
return
}
let body = article.contentHTML ?? article.contentText ?? article.summary
// The selection, when there is one, is the body.
let body = selectedText ?? article.contentHTML ?? article.contentText ?? article.summary
let authorName = article.authors?.first?.name
let sender = SendToBlogEditorApp(targetDescriptor: targetDescriptor, title: article.title, body: body, summary: article.summary, link: article.externalLink, permalink: article.link, subject: nil, creator: authorName, commentsURL: nil, guid: article.uniqueID, sourceName: article.feed?.nameForDisplay, sourceHomeURL: article.feed?.homePageURL, sourceFeedURL: article.feed?.url)
@@ -41,9 +41,12 @@ import RSCore
}
// TODO: get text from contentHTML or contentText if no title and no selectedText.
// TODO: consider selectedText.
let s = article.attributionString + article.linkString
// The selection, when there is one, is quoted below the link.
var s = article.attributionString + article.linkString
if let selectedText {
s += "\n\n> " + selectedText
}
let urlQueryDictionary = ["text": s]
guard let urlQueryString = urlQueryDictionary.urlQueryString else {
+2 -1
View File
@@ -7,12 +7,13 @@
//
import Foundation
import RSCore
import os
import RSWeb
struct CacheCleaner {
static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "CacheCleaner")
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "CacheCleaner")
private static let didPurgeImageCachesForResizingKey = "didPurgeImageCachesForResizing-2026-03-30"
+7 -10
View File
@@ -1021,19 +1021,16 @@
"comment" : "Clean up confirmation suffix"
},
"This theme cannot be used because of data corruption in the Info.plist: %@." : {
"comment" : "Decoding key missing"
"comment" : "Theme import error — Info.plist data corruption"
},
"This theme cannot be used because of data corruption in the Info.plist. %@." : {
"comment" : "Decoding key missing"
"This theme cannot be used because the key “%@” is not found in the Info.plist." : {
"comment" : "Theme import error — key missing from Info.plist"
},
"This theme cannot be used because the the key—“%@”—is not found in the Info.plist." : {
"comment" : "Decoding key missing"
"This theme cannot be used because the type “%@” is mismatched in the Info.plist." : {
"comment" : "Theme import error — type mismatch in Info.plist"
},
"This theme cannot be used because the the type—“%@”—is mismatched in the Info.plist" : {
"comment" : "Type mismatch"
},
"This theme cannot be used because the the value—“%@”—is not found in the Info.plist." : {
"comment" : "Decoding value missing"
"This theme cannot be used because the value “%@” is not found in the Info.plist." : {
"comment" : "Theme import error — value missing from Info.plist"
},
"This will delete any not-starred content records.\n\nThis may take several minutes." : {
"comment" : "Clean up confirmation when plan is stale"
@@ -166,5 +166,15 @@
<key>action</key>
<string>openInBrowserUsingOppositeOfSettings:</string>
</dict>
<dict>
<key>title</key>
<string>Clean Up</string>
<key>key</key>
<string>'</string>
<key>commandModifier</key>
<true/>
<key>action</key>
<string>cleanUp:</string>
</dict>
</array>
</plist>
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more