diff --git a/Intents/AddWebFeedIntentHandler.swift b/Intents/AddWebFeedIntentHandler.swift deleted file mode 100644 index f87259ea5..000000000 --- a/Intents/AddWebFeedIntentHandler.swift +++ /dev/null @@ -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) - } -} diff --git a/Intents/Base.lproj/Intents.intentdefinition b/Intents/Base.lproj/Intents.intentdefinition deleted file mode 100644 index e1969b641..000000000 --- a/Intents/Base.lproj/Intents.intentdefinition +++ /dev/null @@ -1,314 +0,0 @@ - - - - - INEnums - - INIntentDefinitionModelVersion - 1.1 - INIntentDefinitionNamespace - U6u7RF - INIntentDefinitionSystemVersion - 19D76 - INIntentDefinitionToolsBuildVersion - 11B53 - INIntentDefinitionToolsVersion - 11.2.1 - INIntents - - - INIntentCategory - create - INIntentConfigurable - - INIntentDescription - Add a web feed - INIntentDescriptionID - IuAbef - INIntentIneligibleForSuggestions - - INIntentInput - url - INIntentKeyParameter - url - INIntentLastParameterTag - 4 - INIntentManagedParameterCombinations - - url,accountName - - INIntentParameterCombinationSupportsBackgroundExecution - - INIntentParameterCombinationTitle - Add ${url} to ${accountName} - INIntentParameterCombinationTitleID - kaKsEY - INIntentParameterCombinationUpdatesLinked - - - url,accountName,folderName - - INIntentParameterCombinationSupportsBackgroundExecution - - INIntentParameterCombinationTitle - Add ${url} to ${folderName} in ${accountName} - INIntentParameterCombinationTitleID - dkSFD2 - INIntentParameterCombinationUpdatesLinked - - - - INIntentName - AddWebFeed - INIntentParameters - - - INIntentParameterDisplayName - URL - INIntentParameterDisplayNameID - BCHr23 - INIntentParameterDisplayPriority - 1 - INIntentParameterName - url - INIntentParameterPromptDialogs - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogFormatString - What is the ${url} you would like add? - INIntentParameterPromptDialogFormatStringID - jLLidQ - INIntentParameterPromptDialogType - Primary - - - INIntentParameterSupportsResolution - - INIntentParameterTag - 2 - INIntentParameterType - URL - INIntentParameterUnsupportedReasons - - - INIntentParameterUnsupportedReasonCode - required - INIntentParameterUnsupportedReasonCustom - - INIntentParameterUnsupportedReasonFormatString - You must supply a URL. - INIntentParameterUnsupportedReasonFormatStringID - 4xjRes - - - - - INIntentParameterCustomDisambiguation - - INIntentParameterDisplayName - Account Name - INIntentParameterDisplayNameID - CSrgUY - INIntentParameterDisplayPriority - 2 - INIntentParameterMetadata - - INIntentParameterMetadataCapitalization - Sentences - - INIntentParameterName - accountName - INIntentParameterPromptDialogs - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogType - Primary - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogFormatString - There are ${count} options matching ‘${accountName}’. - INIntentParameterPromptDialogFormatStringID - IbqUVS - INIntentParameterPromptDialogType - DisambiguationIntroduction - - - INIntentParameterPromptDialogFormatString - Which one? - INIntentParameterPromptDialogFormatStringID - fWs3li - INIntentParameterPromptDialogType - DisambiguationSelection - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogFormatString - Just to confirm, you wanted ‘${accountName}’? - INIntentParameterPromptDialogFormatStringID - HHiZUh - INIntentParameterPromptDialogType - Confirmation - - - INIntentParameterSupportsDynamicEnumeration - - INIntentParameterSupportsResolution - - INIntentParameterTag - 3 - INIntentParameterType - String - INIntentParameterUnsupportedReasons - - - INIntentParameterUnsupportedReasonCode - invalid - INIntentParameterUnsupportedReasonCustom - - INIntentParameterUnsupportedReasonFormatString - A valid Account Name is required. - INIntentParameterUnsupportedReasonFormatStringID - JGkCuS - - - INIntentParameterUnsupportedReasonCode - communication - INIntentParameterUnsupportedReasonCustom - - INIntentParameterUnsupportedReasonFormatString - Unable to communicate with NetNewsWire. - INIntentParameterUnsupportedReasonFormatStringID - uSfloN - - - - - INIntentParameterCustomDisambiguation - - INIntentParameterDisplayName - Folder Name - INIntentParameterDisplayNameID - zXhMPF - INIntentParameterDisplayPriority - 3 - INIntentParameterMetadata - - INIntentParameterMetadataCapitalization - Sentences - - INIntentParameterName - folderName - INIntentParameterPromptDialogs - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogType - Primary - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogFormatString - There are ${count} options matching ‘${folderName}’. - INIntentParameterPromptDialogFormatStringID - 5CYbGL - INIntentParameterPromptDialogType - DisambiguationIntroduction - - - INIntentParameterPromptDialogFormatString - Which one? - INIntentParameterPromptDialogFormatStringID - gEzXaM - INIntentParameterPromptDialogType - DisambiguationSelection - - - INIntentParameterPromptDialogCustom - - INIntentParameterPromptDialogFormatString - Just to confirm, you wanted ‘${folderName}’? - INIntentParameterPromptDialogFormatStringID - k5GTo0 - INIntentParameterPromptDialogType - Confirmation - - - INIntentParameterRelationship - - INIntentParameterRelationshipParentName - accountName - INIntentParameterRelationshipPredicateName - HasAnyValue - - INIntentParameterSupportsDynamicEnumeration - - INIntentParameterSupportsResolution - - INIntentParameterTag - 4 - INIntentParameterType - String - INIntentParameterUnsupportedReasons - - - INIntentParameterUnsupportedReasonCode - invalid - INIntentParameterUnsupportedReasonCustom - - INIntentParameterUnsupportedReasonFormatString - A valid Folder Name is required. - INIntentParameterUnsupportedReasonFormatStringID - ef5kBt - - - INIntentParameterUnsupportedReasonCode - communication - INIntentParameterUnsupportedReasonCustom - - INIntentParameterUnsupportedReasonFormatString - Unable to communicate with NetNewsWire. - INIntentParameterUnsupportedReasonFormatStringID - ExjqcE - - - - - INIntentResponse - - INIntentResponseCodes - - - INIntentResponseCodeName - success - INIntentResponseCodeSuccess - - - - INIntentResponseCodeName - failure - - - - INIntentTitle - Add Web Feed - INIntentTitleID - oV681v - INIntentType - Custom - INIntentVerb - Add - - - INTypes - - - diff --git a/Intents/en.lproj/Intents.strings b/Intents/en.lproj/Intents.strings deleted file mode 100644 index 187512780..000000000 --- a/Intents/en.lproj/Intents.strings +++ /dev/null @@ -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."; - diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index a54c50a06..8e03d1fb3 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -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() diff --git a/Mac/ErrorHandler.swift b/Mac/ErrorHandler.swift index 1a7d84502..2c101182c 100644 --- a/Mac/ErrorHandler.swift +++ b/Mac/ErrorHandler.swift @@ -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) + } } diff --git a/Mac/MainWindow/Detail/DetailViewController.swift b/Mac/MainWindow/Detail/DetailViewController.swift index 1cc6ee4d1..99847c9ad 100644 --- a/Mac/MainWindow/Detail/DetailViewController.swift +++ b/Mac/MainWindow/Detail/DetailViewController.swift @@ -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() } diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index 9ca8a5a7c..8a6c24292 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -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. + // + 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)) } diff --git a/Mac/MainWindow/Detail/main_mac.js b/Mac/MainWindow/Detail/main_mac.js index 45995d080..1a2e0fbf6 100644 --- a/Mac/MainWindow/Detail/main_mac.js +++ b/Mac/MainWindow/Detail/main_mac.js @@ -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

wrapper. + if (container.childNodes.length === 1 && container.firstChild.nodeName === "P") { + return container.firstChild.innerHTML; + } + return container.innerHTML; +} + function postRenderProcessing() { scrollDetection(); linkHover(); diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift index 08288658d..0de2caccb 100644 --- a/Mac/MainWindow/MainWindowController.swift +++ b/Mac/MainWindow/MainWindowController.swift @@ -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. + // + 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 } diff --git a/Mac/MainWindow/SharingServicePickerDelegate.swift b/Mac/MainWindow/SharingServicePickerDelegate.swift index f34349e5d..fe18ca747 100644 --- a/Mac/MainWindow/SharingServicePickerDelegate.swift +++ b/Mac/MainWindow/SharingServicePickerDelegate.swift @@ -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) } } } diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift index 1a14017c9..42aea739b 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift @@ -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) diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift index 15d0adca4..9dbf1e9c1 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift @@ -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 } diff --git a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift index 23401be3e..9e8a68785 100644 --- a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift +++ b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift @@ -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) { diff --git a/Mac/MainWindow/Sidebar/SidebarViewController.swift b/Mac/MainWindow/Sidebar/SidebarViewController.swift index 70337a415..3dc26b077 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController.swift @@ -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 diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index c8ca42936..40e92fcda 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -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. + // + 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. + // + 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?() } } diff --git a/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift b/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift index 9f435d91f..24098a7c5 100644 --- a/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift @@ -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 diff --git a/Mac/Resources/Assets.xcassets/StarColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/StarColor.colorset/Contents.json index c464941a7..25c10e9d4 100644 --- a/Mac/Resources/Assets.xcassets/StarColor.colorset/Contents.json +++ b/Mac/Resources/Assets.xcassets/StarColor.colorset/Contents.json @@ -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" : { diff --git a/Mac/SafariExtension/SafariExtensionHandler.swift b/Mac/SafariExtension/SafariExtensionHandler.swift index 95d079e7f..65f97a7ec 100644 --- a/Mac/SafariExtension/SafariExtensionHandler.swift +++ b/Mac/SafariExtension/SafariExtensionHandler.swift @@ -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) { diff --git a/Mac/SafariExtension/netnewswire-subscribe-to-feed.js b/Mac/SafariExtension/netnewswire-subscribe-to-feed.js index 267674c97..e615c3207 100644 --- a/Mac/SafariExtension/netnewswire-subscribe-to-feed.js +++ b/Mac/SafariExtension/netnewswire-subscribe-to-feed.js @@ -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(); } }); diff --git a/Mac/Scripting/AppDelegate+Scriptability.swift b/Mac/Scripting/AppDelegate+Scriptability.swift index 439a86878..e3433a1dc 100644 --- a/Mac/Scripting/AppDelegate+Scriptability.swift +++ b/Mac/Scripting/AppDelegate+Scriptability.swift @@ -61,21 +61,7 @@ extension AppDelegate: AppDelegateAppleEvents { } if let themeURL = URL(string: themeURLString) { - let request = URLRequest(url: themeURL) - let task = URLSession.shared.downloadTask(with: request) { location, _, error in - guard let location = location else { - return - } - - Task { @MainActor in - do { - try ArticleThemeDownloader.shared.handleFile(at: location) - } catch { - NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) - } - } - } - task.resume() + ArticleThemeDownloader.shared.downloadTheme(from: themeURL) } return } diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index ba5b877d2..546336335 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -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. + // + 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], defaultRead: Bool) async { + @discardableResult + func updateAsync(feedIDsAndItems: [String: Set], 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. diff --git a/Modules/Account/Sources/Account/AccountError.swift b/Modules/Account/Sources/Account/AccountError.swift index 8bc5f05cc..3fb6d5efa 100644 --- a/Modules/Account/Sources/Account/AccountError.swift +++ b/Modules/Account/Sources/Account/AccountError.swift @@ -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 { diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index e8f6a0ab6..c9be76cfd 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -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] { diff --git a/Modules/Account/Sources/Account/AccountSettingsImporter.swift b/Modules/Account/Sources/Account/AccountSettingsImporter.swift index d8830da0f..0e9afd414 100644 --- a/Modules/Account/Sources/Account/AccountSettingsImporter.swift +++ b/Modules/Account/Sources/Account/AccountSettingsImporter.swift @@ -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. diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 2278fe306..654fa479e 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -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. + // + defer { + syncProgress.completeTask() + } do { let articles = await account.fetchArticlesAsync(.feed(feed)) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift index 0f2318341..09e3c288b 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift @@ -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. + // + if account.existingContainers(withFeed: feed).isEmpty { + account.addFeedToTreeAtTopLevel(feed) + } } @MainActor func createFeedIfNecessary(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, container: Container) { diff --git a/Modules/Account/Sources/Account/FeedSettings.swift b/Modules/Account/Sources/Account/FeedSettings.swift index 7ff5d53f0..34bb13199 100644 --- a/Modules/Account/Sources/Account/FeedSettings.swift +++ b/Modules/Account/Sources/Account/FeedSettings.swift @@ -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 { diff --git a/Modules/Account/Sources/Account/FeedSettingsDatabase.swift b/Modules/Account/Sources/Account/FeedSettingsDatabase.swift index df15aed85..6ef96d776 100644 --- a/Modules/Account/Sources/Account/FeedSettingsDatabase.swift +++ b/Modules/Account/Sources/Account/FeedSettingsDatabase.swift @@ -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 diff --git a/Modules/Account/Sources/Account/FeedSettingsImporter.swift b/Modules/Account/Sources/Account/FeedSettingsImporter.swift index c7a1ae048..456a1629d 100644 --- a/Modules/Account/Sources/Account/FeedSettingsImporter.swift +++ b/Modules/Account/Sources/Account/FeedSettingsImporter.swift @@ -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") diff --git a/Modules/Account/Sources/Account/Feedbin/Feedbin.swift b/Modules/Account/Sources/Account/Feedbin/Feedbin.swift index 17d2d1d8c..d771cc660 100644 --- a/Modules/Account/Sources/Account/Feedbin/Feedbin.swift +++ b/Modules/Account/Sources/Account/Feedbin/Feedbin.swift @@ -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") } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index ab7e02bf4..f886f615a 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -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 diff --git a/Modules/Account/Sources/Account/Feedly/Feedly.swift b/Modules/Account/Sources/Account/Feedly/Feedly.swift index d7064d28d..b544bf78e 100644 --- a/Modules/Account/Sources/Account/Feedly/Feedly.swift +++ b/Modules/Account/Sources/Account/Feedly/Feedly.swift @@ -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") } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index b6ab63538..b6a6aa5e8 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -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. + // + 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() + // 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() + // 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. + /// + /// 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() + } + + /// 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") diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift index 074bd89a2..e7e58422a 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift @@ -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() } } - diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift index 3748dbfd6..fa5a6ea81 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift @@ -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) async { await withCheckedContinuation { continuation in diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index dd2516189..c639d2b1f 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -112,25 +112,27 @@ import os // Add any feeds we don't have and update any we do var feedsToAdd = Set() - 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) 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 diff --git a/Modules/Account/Sources/Account/OPMLFile.swift b/Modules/Account/Sources/Account/OPMLFile.swift index aef9a8673..c62bea808 100644 --- a/Modules/Account/Sources/Account/OPMLFile.swift +++ b/Modules/Account/Sources/Account/OPMLFile.swift @@ -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) diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index c5f2c2fe0..6d381d4af 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -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. + // + 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. + // + 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, 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() - - 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() - 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. + // + // 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) diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift index ab993fdc3..be3cb86ab 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift @@ -16,6 +16,14 @@ enum CreateReaderAPISubscriptionResult { case notFound } +/// Inoreader’s per-zone API usage, reported on every response. Zone 1 is reads. +/// +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)" + } } diff --git a/Modules/Account/Tests/AccountTests/FeedSettingsDatabaseTests.swift b/Modules/Account/Tests/AccountTests/FeedSettingsDatabaseTests.swift new file mode 100644 index 000000000..0b0b4d960 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/FeedSettingsDatabaseTests.swift @@ -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:") + } +} diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyFolderReconciliationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyFolderReconciliationTests.swift index 8080e6131..430f61356 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyFolderReconciliationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyFolderReconciliationTests.swift @@ -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() { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 597dd7ebb..e178dcc4f 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -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)") diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 425801834..496c73904 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -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) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsSchemaMigration.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsSchemaMigration.swift index aacc472c5..350747092 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsSchemaMigration.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsSchemaMigration.swift @@ -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() diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift index 0701ddb01..aa2a76f92 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift @@ -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. + /// + 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 + } +} diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitLogger.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitLogger.swift index 9f1295b46..299dabb6f 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitLogger.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitLogger.swift @@ -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") diff --git a/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift b/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift index 6c91d292a..989450000 100644 --- a/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift +++ b/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift @@ -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. diff --git a/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift b/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift index af8b20be0..f8f5c8b86 100644 --- a/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift +++ b/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift @@ -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 , so the finder would + // otherwise miss the blog feed. + 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 } diff --git a/Modules/FeedFinder/Tests/FeedFinderTests/FeedFinderTests.swift b/Modules/FeedFinder/Tests/FeedFinderTests/FeedFinderTests.swift index 8d43fc7e8..3e503a19c 100644 --- a/Modules/FeedFinder/Tests/FeedFinderTests/FeedFinderTests.swift +++ b/Modules/FeedFinder/Tests/FeedFinderTests/FeedFinderTests.swift @@ -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")!)) + } } diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift index 6fe321e00..5e14cfc35 100644 --- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift +++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift @@ -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 diff --git a/Modules/Images/Sources/Images/FaviconDownloader.swift b/Modules/Images/Sources/Images/FaviconDownloader.swift index f99f7e5ee..3d6075e28 100644 --- a/Modules/Images/Sources/Images/FaviconDownloader.swift +++ b/Modules/Images/Sources/Images/FaviconDownloader.swift @@ -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. + // + func downloadNextFavicon(forHomePageURL homePageURL: String) { + while let faviconURL = remainingFaviconURLs[homePageURL]?.first { + remainingFaviconURLs[homePageURL] = remainingFaviconURLs[homePageURL]?.dropFirst() + if canAttemptDownload(faviconURL) { + _ = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL) + return + } + } + + remainingFaviconURLs[homePageURL] = nil + if currentHomePageHasOnlyFaviconICO { + ImageMetadataDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: nil) + } + } + func faviconDownloader(withURL faviconURL: String, homePageURL: String?) -> SingleFaviconDownloader { var firstTimeSeeingHomepageURL = false @@ -295,6 +308,12 @@ private extension HTMLMetadataRecord { private func shouldAllowFavicon(_ favicon: HTMLMetadataRecord.Favicon) -> Bool { + // Only http(s) — a data: or other non-web URL can't be downloaded as a favicon. + guard let urlString = favicon.urlString, + urlString.hasPrefix("http://") || urlString.hasPrefix("https://") else { + return false + } + // Check mime type. if let mimeType = favicon.type, let utType = UTType(mimeType: mimeType) { if Self.ignoredTypes.contains(utType) { @@ -303,7 +322,7 @@ private extension HTMLMetadataRecord { } // Check file extension. - if let urlString = favicon.urlString, let url = URL(string: urlString), let utType = UTType(filenameExtension: url.pathExtension) { + if let url = URL(string: urlString), let utType = UTType(filenameExtension: url.pathExtension) { if Self.ignoredTypes.contains(utType) { return false } diff --git a/Modules/Images/Sources/Images/HomePageFaviconTable.swift b/Modules/Images/Sources/Images/HomePageFaviconTable.swift index 98b113de2..f69980905 100644 --- a/Modules/Images/Sources/Images/HomePageFaviconTable.swift +++ b/Modules/Images/Sources/Images/HomePageFaviconTable.swift @@ -13,6 +13,7 @@ import RSDatabaseObjC public struct HomePageFaviconRecord: Sendable { public let homePageURL: String public let faviconURL: String? + public let lastChecked: Date } struct HomePageFaviconTable { @@ -27,7 +28,7 @@ struct HomePageFaviconTable { static func fetchAll(database: FMDatabase) -> [HomePageFaviconRecord] { var results = [HomePageFaviconRecord]() - guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.faviconURL) FROM \(name);", withArgumentsIn: []) else { + guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.faviconURL), \(Column.lastChecked) FROM \(name);", withArgumentsIn: []) else { return results } defer { @@ -38,7 +39,8 @@ struct HomePageFaviconTable { continue } let faviconURL = resultSet.string(forColumn: Column.faviconURL) - results.append(HomePageFaviconRecord(homePageURL: homePageURL, faviconURL: faviconURL)) + let lastChecked = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastChecked)) + results.append(HomePageFaviconRecord(homePageURL: homePageURL, faviconURL: faviconURL, lastChecked: lastChecked)) } return results } diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift index 2b6e0d4b8..1b1d17a44 100644 --- a/Modules/Images/Sources/Images/ImageDownloader.swift +++ b/Modules/Images/Sources/Images/ImageDownloader.swift @@ -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) diff --git a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift index 25cbb7393..e9751a82f 100644 --- a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift +++ b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift @@ -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) } } diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index 643315b33..49b2ebe46 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -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) diff --git a/Modules/NewsBlur/Sources/NewsBlur/NewsBlur.swift b/Modules/NewsBlur/Sources/NewsBlur/NewsBlur.swift index 5ba5b1713..a66438471 100644 --- a/Modules/NewsBlur/Sources/NewsBlur/NewsBlur.swift +++ b/Modules/NewsBlur/Sources/NewsBlur/NewsBlur.swift @@ -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") } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift b/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift index 556d76845..0ca9a6be8 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift @@ -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 } diff --git a/Modules/RSCore/Sources/RSCore/AppNotifications.swift b/Modules/RSCore/Sources/RSCore/AppNotifications.swift index 412ca449f..e9bdee847 100644 --- a/Modules/RSCore/Sources/RSCore/AppNotifications.swift +++ b/Modules/RSCore/Sources/RSCore/AppNotifications.swift @@ -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) + } } diff --git a/Modules/RSCore/Sources/RSCore/Logging.swift b/Modules/RSCore/Sources/RSCore/Logging.swift new file mode 100644 index 000000000..baf87b639 --- /dev/null +++ b/Modules/RSCore/Sources/RSCore/Logging.swift @@ -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" +} diff --git a/Modules/RSCore/Sources/RSCore/Platform.swift b/Modules/RSCore/Sources/RSCore/Platform.swift index 320e6e02e..572aed3b1 100644 --- a/Modules/RSCore/Sources/RSCore/Platform.swift +++ b/Modules/RSCore/Sources/RSCore/Platform.swift @@ -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 diff --git a/Modules/RSCore/Sources/RSCore/RSImage.swift b/Modules/RSCore/Sources/RSCore/RSImage.swift index 12a8839c5..adc9795cd 100644 --- a/Modules/RSCore/Sources/RSCore/RSImage.swift +++ b/Modules/RSCore/Sources/RSCore/RSImage.swift @@ -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 { diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index 8ccddeefe..2498b3b99 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -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. + // + 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? { diff --git a/Modules/RSCore/Sources/RSCore/URL+RSCore.swift b/Modules/RSCore/Sources/RSCore/URL+RSCore.swift index b54537e7b..14cd447b7 100644 --- a/Modules/RSCore/Sources/RSCore/URL+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/URL+RSCore.swift @@ -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: "%")) +} diff --git a/Modules/RSCore/Tests/RSCoreTests/URL+RSCoreTests.swift b/Modules/RSCore/Tests/RSCoreTests/URL+RSCoreTests.swift new file mode 100644 index 000000000..f8d2f9e90 --- /dev/null +++ b/Modules/RSCore/Tests/RSCoreTests/URL+RSCoreTests.swift @@ -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. + // + // + @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") + } +} diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift index cb3cbcb4b..d05469118 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift @@ -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)") diff --git a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift index bb2d4ef10..b7401a295 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift @@ -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" diff --git a/Modules/RSDatabase/Sources/RSDatabase/Logging.swift b/Modules/RSDatabase/Sources/RSDatabase/Logging.swift new file mode 100644 index 000000000..900199801 --- /dev/null +++ b/Modules/RSDatabase/Sources/RSDatabase/Logging.swift @@ -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" diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift index 623bb38d1..a032123cf 100644 --- a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift +++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift @@ -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 diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift new file mode 100644 index 000000000..38489077f --- /dev/null +++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift @@ -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 `&` 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, 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, 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.. + let bytes: [UInt8] + } + + /// Scans HTML bytes and collects the URL attribute-value replacements to make. + struct URLReplacementScanner { + + private let bytes: ArraySlice + private let baseURL: URL + private var pos: Int + private var replacements: [Replacement] = [] + + private var end: Int { + bytes.endIndex + } + + init(bytes: ArraySlice, 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("") + } else if matches("") + } 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.. + 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..` (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.., valueRange: Range) { + 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) { + 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..) { + // 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) -> Range { + 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..) -> [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) -> 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) -> 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.. from being mistaken for . + private func isCloseTagNameBoundary(at index: Int) -> Bool { + guard index < end else { + return true + } + let b = bytes[index] + return b == .asciiGreaterThan || b == .asciiSlash || b.isASCIIWhitespace + } + } +} diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift index 7288b1478..e2b5885c5 100644 --- a/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift +++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift @@ -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 { diff --git a/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift b/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift index ebaa34080..eb1cfbdd2 100644 --- a/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift +++ b/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift @@ -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: "/") diff --git a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift index 74faa1360..5427b6104 100644 --- a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift @@ -67,6 +67,189 @@ import RSParser #expect(foundTestArticle) } + // MARK: - xml:base + // + + @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 and 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" })) + + // 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 = """ + + + turn:t + + + urn:t:1 + nested base + 2020-05-01T00:00:00Z + + + <a href="pic.png">pic</a> + + + """ + 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 = """ + + + turn:t + + urn:t:1 + mime type html + 2020-05-01T00:00:00Z + <img src="pic.png"> + + + """ + 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 = """ + + + turn:t + + /2024/04/23/qemu-9-0-0 + release + 2024-04-23T23:02:00Z + <a href="changelog.html">changelog</a> + + + """ + 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 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 = """ + + + turn:t + + urn:t:1 + summary only + 2020-05-01T00:00:00Z +

<img src="pic.png"> + + + """ + 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 = """ + + + turn:t + + urn:t:1 + relative author uri + 2020-05-01T00:00:00Z + Aliceabout/ + + + """ + 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 = """ + + + turn:t + + urn:t:1 + text content + 2020-05-01T00:00:00Z + See src="pic.png" for details. + + + """ + 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)) diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLMetadataTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLMetadataTests.swift index 4d63846d2..0b26fc2bc 100644 --- a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLMetadataTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLMetadataTests.swift @@ -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 = """ + + + + + """ + 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") + } } diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift new file mode 100644 index 000000000..80c39149a --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift @@ -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)] = [ + ("x", "x"), + ("", ""), + ("", ""), + ("x", "x"), + ("x", "x"), + ("x", "x"), + ("x", "x") + ] + for c in cases { + #expect(resolved(c.input) == c.expected, "mismatch for \(c.input)") + } + } + + @Test func ampersandEntityInRelativeURLSurvives() { + let html = "x" + #expect(resolved(html) == "x") + } + + @Test func attributeNamesAreCaseInsensitive() { + #expect(resolved("y") == "y") + #expect(resolved("") == "") + } + + @Test func unquotedAndSingleQuotedValuesResolve() { + #expect(resolved("x") == "x") + #expect(resolved("y") == "y") + } + + // MARK: - Values left alone + + @Test func untouchedValues() { + let cases = [ + "x", + "x", + "x", + "x", + "", + "x", + "x", + "not URL attributes" + ] + for html in cases { + #expect(resolved(html) == html, "expected no change for \(html)") + } + } + + @Test func scriptStyleCommentsAndCDATAUntouched() { + let cases = [ + "", + "", + "", + "]]>" + ] + 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 = "" + #expect(resolved(html) == "") + } + + // MARK: - srcset + + @Test func srcsetCandidatesResolve() { + let cases: [(input: String, expected: String)] = [ + ("", + ""), + ("", + ""), + ("", + ""), + ("", + ""), + ("", + "") + ] + 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("x") == "x") + + // A padded relative value resolves — the padding stays in place. + #expect(resolved("x") == "x") + } + + @Test func similarlyNamedCloseTagDoesNotEndRawText() { + // is not — everything inside stays untouched. + let html = "" + #expect(resolved(html) == html) + } + + // MARK: - Malformed input + + @Test func malformedInputIsSafe() { + // Unterminated quote: scanning stops, input preserved. + let unterminated = "y" + #expect(resolved(strayLessThan) == "1 < 2 and y") + } + + // MARK: - No-op guarantee + + @Test func allAbsoluteDocumentIsUnchanged() { + let html = """ +

Intro text with an absolute link.

+ +

More text, an footnote, and an empty href.

+ """ + #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 = """ +
+ + + A screenshot + +
Caption & more
+
+ """ + let expected = """ +
+ + + A screenshot + +
Caption & more
+
+ """ + #expect(resolved(html) == expected) + } + + // MARK: - Bytes entry point + + @Test func bytesEntryPointMatchesStringEntryPoint() { + let html = "" + let bytes = Array(html.utf8)[...] + let fromBytes = HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: bytes, baseURL: base) + #expect(fromBytes == resolved(html)) + + let absolute = "" + let absoluteBytes = Array(absolute.utf8)[...] + #expect(HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: absoluteBytes, baseURL: base) == absolute) + } +} diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom b/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom new file mode 100644 index 000000000..e73bb45c1 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom @@ -0,0 +1,586 @@ + + + https://andrea.pappacoda.it/blog/feed.atom + + + + Andrea Pappacoda - Blog + 2026-05-24T13:02:30+02:00 + + Andrea Pappacoda + https://andrea.pappacoda.it + + Vim + /andrea_pappacoda.jpg + /assets/debian-button.gif + © 2026 Andrea Pappacoda + Faccio cose + + tag:andrea.pappacoda.it,2026-05-24:favicon_2026 + Le favicon non sono difficili + 2026-05-24T13:02:30+02:00 + 2026-05-24T13:02:30+02:00 + Una guida ragionata alle favicon (e non solo) + +
+ +

Le favicon non sono difficili

+

+ Sembra che nel mondo della creazione dei siti web ci sia una enorme confusione + su come specificare le + Favicon, ovvero l'icona di + un particolare sito web. +

+

+ Il mio sito al momento in cui sto scrivendo non ha nessuna favicon, ma in + questi giorni ho impostato quella del + sito di HackInPovo, 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. +

+

+ 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? +

+

Il problema

+

+ In breve, il problema è che il web è vecchio. Mi spiego meglio. +

+

+ 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ì. +

+

+ 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 + home page del mio telefono che icona uso? E come + facciamo per i temi chiaro/scuro? E così via. +

+

+ È 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. +

+

La soluzione

+

+ La soluzione è non ascoltare quello che dicono i guru. Sì, questo articolo + compreso. +

+

+ 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. +

+

+ 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. +

+

+ Lo standard HTML viene sviluppato principalmente da un gruppo di persone + chiamato "WHATWG", e pubblicato come una + grossa specifica nota come + "HTML Living Standard". + 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 link, in particolare la sezione + 4.6.6.9 Link type "icon". +

+

+ Lo standard mostra come per specificare una icona sia necessario creare + un elemento link con l'attributo rel impostato a + icon, l'attributo type che specifichi il + media type + dell'immagine, l'attributo sizes che specifichi le dimensioni + in pixel dell'immagine e infine l'attributo href che contenga il + percorso all'immagine da usare come icona. +

+

+ 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. +

+

+ O forse no. +

+

+ Non ci importa sapere che cosa un determinato browser faccia oggi, + 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. +

+

Il buon senso

+

+ Arriviamo quindi alle mie raccomandazioni personali, basate su quello che credo + sia un po' di ragionamento e buon senso. +

+

+ Storicamente i browser web hanno usato una immagine in + formato ICO + chiamata "favicon.ico" e disponibile nella cartella primaria del sito web. + Quindi, se il nostro sito è blog.example.org, dovrebbe essere + accessibile dall'URL https://blog.example.org/favicon.ico. +

+

+ È 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 + ImageMagick: +

+
$ magick immagine.png -resize 256x -define icon:auto-resize favicon.ico
+

+ L'opzione + + -define + icon:auto-resize + 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 identify: +

+
$ magick identify favicon.ico
+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
+

+ 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 -define icon:auto-resize, ad esempio con + -define icon:auto-resize=128,96,64,48,40,32,24,16. +

+

+ Infine, questa immagine dovrà essere aggiunta all'intestazione del documento + HTML del nostro sito con un elemento link: +

+
<link
+	rel="icon"
+	type="image/vnd.microsoft.icon"
+	sizes="128x128 96x96 64x64 48x48 40x40 32x32 24x24 16x16"
+	href="/favicon.ico"
+/>
+

+ 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. +

+

+ 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. +

+

+ Il secondo elemento link che quindi consiglio è questo qui: +

+
<link
+	rel="icon"
+	type="image/png"
+	sizes="256x256"
+	href="/favicon.png"
+/>
+

+ 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 solo un SVG è che non tutti i browser li + supportano. +

+

+ Il terzo e ultimo elemento link da aggiungere è quindi questo: +

+
<link
+	rel="icon"
+	type="image/svg+xml"
+	sizes="any"
+	href="/favicon.svg"
+/>
+

La mela

+

+ E anche oggi mi tocca parlar di Apple... +

+

+ 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". +

+

+ Nonostante Safari di Apple utilizzi le icone specificate con + rel="icon" 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. +

+

+ Al suo posto viene invece usata l'immagine specificata attraverso il valore + apple-touch-icon dell'attributo rel. Questa immagine + ha dei requisiti particolari imposti da Apple, sparsi in diverse pagine di + documentazione ufficiale. + L'originale + (e ormai obsoleto) documento mostra diverse dimensioni come esempi, + raccomandando di leggere le iOS Human Interface Guidelines per i valori effettivi. + Queste, nella + sezione dedicata alle icone + raccomandano che le icone siano quadrati di 1024 pixel. E, ancora, in una + pagina + di documentazione per sviluppatori riguardante le API di gestione del dispositivo, + viene raccomandato che l'immagine non superi i 400x400 pixel. +

+

+ Insomma, un casino. +

+

+ Per capire effettivamente cosa fare bisogna fare un passo indietro nel tempo, + quando la documentazione di Apple conteneva ancora informazioni precise. + Nel 2023, infatti, le + HIG 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. +

+

+ 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™. +

+ +

+ 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 apple-touch-icon.png. + Inoltre, l'immagine dev'essere quadrata, non circolare (così come le icone di iOS). +

+

+ Ed ecco quindi il vero ultimo elemento link da aggiungere alla + nostra pagina HTML: +

+
<link
+	rel="apple-touch-icon"
+	type="image/png"
+	sizes="180x180"
+	href="/apple-touch-icon.png"
+/>
+

Trick extra

+

+ 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: + pngquant, + oxipng e + usvg. +

+

+ 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à. +

+

+ Ad esempio, per creare la favicon di tipo PNG che ho descritto prima potete + usare una combo di ImageMagick + pngquant + oxipng in questo modo: +

+
$ magick immagine.png -resize 256x png:- \
+| pngquant --speed 1 - \
+| oxipng --opt max --strip all --out favicon.png -
+

+ 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: +

+
$ usvg immagine.svg favicon.svg
+

Conclusioni

+

+ Spero che questo articolo abbia fatto un po' di chiarezza! +

+

+ Non solo: il messaggio più importante che voglio far passare è che + importantissimo sviluppare la capacità di individuare da chi + 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 vera risposta è l'unico modo per trovare quale, + tra il mare di dati, è l'informazione corretta. +

+

+ E se siete dei nerd come me, è anche divertente :D +

+

Dedicato a viirginiax

+ +
+
+ + tag:andrea.pappacoda.it,2024-12-12:tesi + Una nuova primitiva di creazione dei processi per sistemi Unix + 2024-12-12T15:30:00+01:00 + 2026-06-02T15:14:31+02:00 + + 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() + + + + + tag:andrea.pappacoda.it,2023-06-09:c_su_windows + C su Windows + 2023-06-09T16:00:00+01:00 + 2025-12-26T20:30:00+01:00 + Come installare un ambiente di sviluppo flessibile e moderno per C su Windows + +
+ +

C su Windows

+

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.

+

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.

+

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 "standard", 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, "di libreria", come +printf(), scanf(), e insomma tutte le funzioni che possiamo includere nel +nostro codice con direttive come #include <stdlib.h> eccetera.

+

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 "MSVC", che sta per +"Microsoft Visual C", che come dice il nome sono parte della suite di Visual +Studio. Per installarli è necessario scaricare i "Visual Studio Build Tools", +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 +https://visualstudio.microsoft.com/it/downloads/#build-tools-for-visual-studio-2022). +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 "Singoli +componenti" selezionare "Funzionalità di base per C++ Build Tools", la versione +più recente di MSVC (nel mio caso "MSVC v143 - VS 2022 C++ Build Tools x64/x86 +(più recente)"), l'ultimo Windows SDK (nel mio caso "Windows 11 SDK +(10.0.22621.0)"), e "Windows Universal C Runtime". Una volta selezionati, +possiamo procedere con l'installazione. Il tutto andrà a occupare un paio di GB +di spazio di archiviazione.

+
+ + + Screenshot del Visual Studio Installer + +
Componenti da selezionare dal Visual Studio Installer
+
+

A questo punto abbiamo già un ambiente di sviluppo C, benché molto minimale. +Possiamo accedere al compilatore aprendo il "Prompt dei comandi di sviluppo +nativo x64", e dando il comando cl. Per compilare un file si può dare cl nomefile.c, ed eseguire il .exe generato.

+

Per come Microsoft ha sviluppato i suoi compilatori, l'uso di questo prompt di +comandi di sviluppo, a volte installato in inglese come "x64 Native Tools +Command Prompt", è 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 cmd, e da lì tutti i programmi (ad esempio, se vogliamo +usare VSCode, dovremo aprire un developer command prompt e digitare code per +lanciarlo direttamente dal cmd di sviluppo).

+

Con questo set up, però, aprendo un editor di codice come VSCode non ci saranno +funzionalità "smart" 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.

+

La seconda opzione consiste nell'usare clangd, un Language Server basato sul +compilatore Clang, che parla il Language Server Protocol (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.

+

Per ottenere clangd è sufficiente scaricare l'ultima release pubblicata sulla +sua pagina GitHub, disponibile al link +https://github.com/clangd/clangd/releases/latest nella sezione "Assets". 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 clangd alla variabile +d'ambiente PATH. Per fare ciò ci basta cercare "Variabili d'ambiente" nella +casella di ricerca di sistema, aprire la pagina delle impostazioni, e andare a +modificare la variabile Path per l'utente corrente. Una volta schiacciato +"Modifica", andiamo a schiacciare "Nuovo" nella finestra di dialogo appena +aperta e incolliamo il percorso completo alla cartella bin contenuta nello zip +di clangd appena estratto. Fatto ciò, possiamo schiacciare "Ok" per chiudere +tutte le finestre appena aperte.

+
+ + Screenshot del dialogo di sistema per modificare le variabili d'ambiente + +
Variabile Path modificata per clangd
+
+

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 "clangd" 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.

+
+ + + Screenshot di VSCode che mostra la funzionalità di documentazione al passaggio del cursore + +
Alcune delle funzionalità abilitate da LSP
+
+

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 launch.json e memorizzato nella cartella .vscode del progetto, +contenente più o meno questo:

+
{
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "lldb",
+            "expressions": "native",
+            "request": "launch",
+            "name": "Debug",
+            "program": "${workspaceFolder}/mioprogetto.exe"
+        }
+    ]
+}
+

Quel file dice a VSCode che abbiamo creato una configurazione chiamata "Debug", +da eseguire con il debugger "lldb", che deve lanciare il programma +"mioprogetto.exe". L'opzione "expressions: native" dice a LLDB che vogliamo +usare la classica sintassi C per le espressioni inserite nel pannello "Watch" +del debugger, e non una alternativa custom di LLDB.

+

Bene! Ora ci basta soltanto compilare il nostro file .c dal terminale +integrato di VSCode e premere il triangolino verde per far partire il debugger. +Per compilare, ad esempio, un file chiamato "main.c", ci è sufficiente usare +questo comando:

+
cl -Zi main.c
+

E verrà generato l'eseguibile main.exe, insieme ad altri file intermedi che +non ci interessano. L'uso della opzione -Zi è 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.

+

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.

+

Per prima cosa andiamo a creare un nuovo file tasks.json all'interno della +cartella .vscode creata in precedenza che dice all'editor come compilare il +nostro progetto:

+
{
+    "version": "2.0.0",
+    "tasks": [
+        {
+            "label": "compile",
+            "type": "process",
+            "command": "cl",
+            "args": ["-Zi", "mioprogetto.c"],
+            "presentation": {
+                "reveal": "silent",
+                "focus": false
+            }
+        }
+    ]
+}
+

Il file definisce un task chiamato "compile" che lancia un "process", "cl", +passandogli gli argomenti "-Zi" e "mioprogetto.c". Visto che è un task di bassa +importanza, diciamo anche che la sua "presentation" dev'essere "silent", ovvero +che l'output della compilazione dev'essere mostrato solo in caso di errore.

+

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 "preLaunchTask": "compile" al +file launch.json creato prima, che dovrebbe ora essere così:

+
{
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "lldb",
+            "expressions": "native",
+            "request": "launch",
+            "name": "Debug",
+            "program": "${workspaceFolder}/mioprogetto.exe",
+            "preLaunchTask": "compile"
+        }
+    ]
+}
+

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 :)

+

Dedicato al Maestro

+ +
+
+
diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift index 9fdbbe145..20c7c5cf6 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift @@ -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) { diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index dac4fad84..c045be624 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -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 diff --git a/Modules/RSWeb/Sources/RSWeb/SpecialCases.swift b/Modules/RSWeb/Sources/RSWeb/SpecialCases.swift index 304b532fe..0aae2aaa2 100644 --- a/Modules/RSWeb/Sources/RSWeb/SpecialCases.swift +++ b/Modules/RSWeb/Sources/RSWeb/SpecialCases.swift @@ -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/ 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 { diff --git a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift index 8b1942cfa..14d597e12 100755 --- a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift +++ b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift @@ -8,8 +8,28 @@ import Foundation +/// Which User-Agent a download sends. +public enum UserAgentStyle: Sendable { + + /// The app's normal feed-reader user agent — the session default. + case feed + + /// The extended feed-reader user agent that some hosts require. + case specialCaseFeed + + /// The browser-style user agent that matches the article web view. + case browser +} + nonisolated public struct UserAgent { + /// Browser-style user agent for favicon and homepage-HTML downloads — + /// some servers reject requests without a browser-like user agent. + /// The app replaces this at startup with the article web view's actual + /// user agent, so the two match. This value is the fallback. + /// + @MainActor public static var browserUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) NetNewsWire" + public static func fromInfoPlist() -> String? { return Bundle.main.object(forInfoDictionaryKey: "UserAgent") as? String diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift index 612867c53..9c49b9b72 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift @@ -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) } diff --git a/Modules/RSWeb/Tests/RSWebTests/SpecialCasesTests.swift b/Modules/RSWeb/Tests/RSWebTests/SpecialCasesTests.swift index c0e5bd3ae..c1086d512 100644 --- a/Modules/RSWeb/Tests/RSWebTests/SpecialCasesTests.swift +++ b/Modules/RSWeb/Tests/RSWebTests/SpecialCasesTests.swift @@ -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 + } } diff --git a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift index 52d8076f4..49257ffb5 100644 --- a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift +++ b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift @@ -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 { diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift index 77c30e468..913dcc89e 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift @@ -55,12 +55,14 @@ public actor SyncDatabase { } } - public func resetSelectedForProcessing(_ articleIDs: Set) { - 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, key: SyncStatus.Key? = nil) { + SyncStatusTable.resetSelectedForProcessing(articleIDs, key: key, database: database) } - public func deleteSelectedForProcessing(_ articleIDs: Set) { - SyncStatusTable.deleteSelectedForProcessing(articleIDs, database: database) + public func deleteSelectedForProcessing(_ articleIDs: Set, key: SyncStatus.Key? = nil) { + SyncStatusTable.deleteSelectedForProcessing(articleIDs, key: key, database: database) } } diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift index 3a446f0f8..86655a1d3 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift @@ -66,25 +66,36 @@ struct SyncStatusTable { database.executeUpdateInTransaction(updateSQL) } - static func resetSelectedForProcessing(_ articleIDs: Set, 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, 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, database: FMDatabase) { + static func deleteSelectedForProcessing(_ articleIDs: Set, 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) } diff --git a/NetNewsWire.xcodeproj/project.pbxproj b/NetNewsWire.xcodeproj/project.pbxproj index e7e8072ad..dbc57a42e 100644 --- a/NetNewsWire.xcodeproj/project.pbxproj +++ b/NetNewsWire.xcodeproj/project.pbxproj @@ -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 = ""; }; - 51314706235C41FC00387FDC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.intentdefinition; name = Base; path = Base.lproj/Intents.intentdefinition; sourceTree = ""; }; - 51314714235C420900387FDC /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Intents.strings; sourceTree = ""; }; 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 = ""; }; 84719F0E2DB9C52B00EEF332 /* Tests */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84719F272DB9C52B00EEF332 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Tests; sourceTree = ""; }; 84719F372DB9C60400EEF332 /* xcconfig */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84719F392DB9C60500EEF332 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (common, ); path = xcconfig; sourceTree = ""; }; - 84A6CFB52D1B4EC500F23315 /* iOS */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84A6D03F2D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0412D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = iOS; sourceTree = ""; }; + 84A6CFB52D1B4EC500F23315 /* iOS */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84A6D03F2D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = iOS; sourceTree = ""; }; 84CB35042DB9B5E2002AC251 /* Modules */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Modules; sourceTree = ""; }; - 84D35D422DB9F32D004AA60E /* Shared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84D35E0A2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0B2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0D2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0E2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0F2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Shared; sourceTree = ""; }; + 84D35D422DB9F32D004AA60E /* Shared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (84D35E0A2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0B2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0E2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 84D35E0F2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Shared; sourceTree = ""; }; /* 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 = ""; - }; 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 = ""; - }; -/* 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; diff --git a/Shared/Activity/ActivityManager.swift b/Shared/Activity/ActivityManager.swift index 6eab3d76d..3f1758554 100644 --- a/Shared/Activity/ActivityManager.swift +++ b/Shared/Activity/ActivityManager.swift @@ -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. + // 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. + // + 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() diff --git a/Shared/Article Rendering/ArticleRenderer.swift b/Shared/Article Rendering/ArticleRenderer.swift index d9f57708d..7567670cc 100644 --- a/Shared/Article Rendering/ArticleRenderer.swift +++ b/Shared/Article Rendering/ArticleRenderer.swift @@ -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. + // 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 } } diff --git a/Shared/Article Rendering/ArticleRenderingSpecialCases.swift b/Shared/Article Rendering/ArticleRenderingSpecialCases.swift index 71ef3603e..d0b2d9ba9 100644 --- a/Shared/Article Rendering/ArticleRenderingSpecialCases.swift +++ b/Shared/Article Rendering/ArticleRenderingSpecialCases.swift @@ -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 / attributes get merged onto + // the page's real elements, clobbering the theme. Render only the body fragment. + // + static func extractBodyFragmentIfNeeded(_ html: String) -> String { + guard html.range(of: " 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 tag and (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("", options: [], range: bodyOpen.upperBound../ but no tag: remove the wrapper markup, keep the rest. + private static func removingDocumentWrapper(_ html: String) -> String { + var s = html + + if let doctype = s.range(of: "", options: [], range: doctype.lowerBound..", options: [], range: headClose.lowerBound..", options: [], range: htmlOpen.lowerBound..", options: [], range: htmlClose.lowerBound.. Range? { + var searchStart = start + while let range = html.range(of: tag, options: .caseInsensitive, range: searchStart.." || next == "/" || next.isWhitespace { + return range + } + searchStart = range.upperBound + } + return nil + } + static func filterVergeHTML(_ html: String) -> String { var filteredHTML = html diff --git a/Shared/Article Rendering/WebViewConfiguration.swift b/Shared/Article Rendering/WebViewConfiguration.swift index b2288652e..ce45458e8 100644 --- a/Shared/Article Rendering/WebViewConfiguration.swift +++ b/Shared/Article Rendering/WebViewConfiguration.swift @@ -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.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. // - 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 } diff --git a/Shared/Article Rendering/core.css b/Shared/Article Rendering/core.css index 80ef06314..6802fd715 100644 --- a/Shared/Article Rendering/core.css +++ b/Shared/Article Rendering/core.css @@ -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; } diff --git a/Shared/Article Rendering/main.js b/Shared/Article Rendering/main.js index 48eafcd34..1856d2e14 100644 --- a/Shared/Article Rendering/main.js +++ b/Shared/Article Rendering/main.js @@ -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 📰 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(); diff --git a/Shared/Article Rendering/newsfoot.js b/Shared/Article Rendering/newsfoot.js index 56885f374..9f1dae3f6 100644 --- a/Shared/Article Rendering/newsfoot.js +++ b/Shared/Article Rendering/newsfoot.js @@ -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. + // + if (this.popover.contains(ev.target)) return; if (ev.target === this.fnref) { ev.stopPropagation(); ev.preventDefault(); diff --git a/Shared/ArticleStyles/ArticleThemeDownloader.swift b/Shared/ArticleStyles/ArticleThemeDownloader.swift index 4f4503553..47097c8a7 100644 --- a/Shared/ArticleStyles/ArticleThemeDownloader.swift +++ b/Shared/ArticleStyles/ArticleThemeDownloader.swift @@ -8,15 +8,19 @@ import Foundation import Zip +import RSWeb public final class ArticleThemeDownloader: Sendable { public static let shared = ArticleThemeDownloader() public enum ArticleThemeDownloaderError: LocalizedError { + case downloadFailed case noThemeFile public var errorDescription: String? { switch self { + case .downloadFailed: + return "The NetNewsWire theme could not be downloaded." case .noThemeFile: return "There is no NetNewsWire theme available." } @@ -25,6 +29,29 @@ public final class ArticleThemeDownloader: Sendable { private init() {} + @MainActor public func downloadTheme(from url: URL) { + NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil) + + Task { @MainActor in + do { + let downloadResponse = try await Downloader.shared.download(url, userAgentStyle: .browser) + guard let data = downloadResponse.data, !data.isEmpty, + let response = downloadResponse.response, response.statusIsOK else { + throw ArticleThemeDownloaderError.downloadFailed + } + + // handleFile expects a file whose .tmp name becomes the .zip name. + let temporaryFileURL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString) + .appendingPathExtension("tmp") + try data.write(to: temporaryFileURL) + try handleFile(at: temporaryFileURL) + } catch { + NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) + } + } + } + public func handleFile(at location: URL) throws { createDownloadDirectoryIfRequired() let movedFileLocation = try moveTheme(from: location) diff --git a/Shared/ArticleStyles/ArticleThemesManager.swift b/Shared/ArticleStyles/ArticleThemesManager.swift index be3af5f97..110a4ccff 100644 --- a/Shared/ArticleStyles/ArticleThemesManager.swift +++ b/Shared/ArticleStyles/ArticleThemesManager.swift @@ -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 diff --git a/Shared/Dinosaurs/DinosaursViewModel.swift b/Shared/Dinosaurs/DinosaursViewModel.swift index 0a2994b90..c9c0479f7 100644 --- a/Shared/Dinosaurs/DinosaursViewModel.swift +++ b/Shared/Dinosaurs/DinosaursViewModel.swift @@ -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() diff --git a/Shared/ExtensionPoints/SendToMarsEditCommand.swift b/Shared/ExtensionPoints/SendToMarsEditCommand.swift index b69decb4a..cfbb8f013 100644 --- a/Shared/ExtensionPoints/SendToMarsEditCommand.swift +++ b/Shared/ExtensionPoints/SendToMarsEditCommand.swift @@ -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) diff --git a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift index 7abd8338c..5384b5291 100644 --- a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift +++ b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift @@ -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 { diff --git a/Shared/Extensions/CacheCleaner.swift b/Shared/Extensions/CacheCleaner.swift index e62ae1ad3..aed75196a 100644 --- a/Shared/Extensions/CacheCleaner.swift +++ b/Shared/Extensions/CacheCleaner.swift @@ -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" diff --git a/Shared/Localizable.xcstrings b/Shared/Localizable.xcstrings index fa805319e..7ec517e42 100644 --- a/Shared/Localizable.xcstrings +++ b/Shared/Localizable.xcstrings @@ -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" diff --git a/Shared/Resources/GlobalKeyboardShortcuts.plist b/Shared/Resources/GlobalKeyboardShortcuts.plist index 8eb6694a9..a1bc06a28 100644 --- a/Shared/Resources/GlobalKeyboardShortcuts.plist +++ b/Shared/Resources/GlobalKeyboardShortcuts.plist @@ -166,5 +166,15 @@ action openInBrowserUsingOppositeOfSettings: + + title + Clean Up + key + ' + commandModifier + + action + cleanUp: + diff --git a/Shared/ShareExtension/ExtensionContainersFile.swift b/Shared/ShareExtension/ExtensionContainersFile.swift index 5c782238d..ef05cf15c 100644 --- a/Shared/ShareExtension/ExtensionContainersFile.swift +++ b/Shared/ShareExtension/ExtensionContainersFile.swift @@ -15,7 +15,7 @@ import Account @MainActor final class ExtensionContainersFile { static let shared = ExtensionContainersFile() - static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ExtensionContainersFile") + static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ExtensionContainersFile") private static var filePath: String = { let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String diff --git a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift index 4990ecc04..9ea8fbbc5 100644 --- a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift +++ b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift @@ -7,13 +7,14 @@ // import Foundation +import RSCore import os import Account final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter, Sendable { static let shared = ExtensionFeedAddRequestFile() - static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ExtensionFeedAddRequestFile") + static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ExtensionFeedAddRequestFile") private static let filePath: String = { let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String diff --git a/Shared/SmartFeeds/SmartFeed.swift b/Shared/SmartFeeds/SmartFeed.swift index 1305d402e..9bc89ff71 100644 --- a/Shared/SmartFeeds/SmartFeed.swift +++ b/Shared/SmartFeeds/SmartFeed.swift @@ -52,6 +52,10 @@ import Images init(delegate: SmartFeedDelegate) { self.delegate = delegate NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) + // Refetch on activation and on day change to prevent staleness. + // + NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidBecomeActive(_:)), name: .appDidBecomeActive, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleCalendarDayChanged(_:)), name: .NSCalendarDayChanged, object: nil) queueFetchUnreadCounts() // Fetch unread count at startup } @@ -61,6 +65,17 @@ import Images } } + @objc func handleAppDidBecomeActive(_ note: Notification) { + queueFetchUnreadCounts() + } + + // NSCalendarDayChanged isn't guaranteed to arrive on the main thread. + @objc nonisolated func handleCalendarDayChanged(_ note: Notification) { + Task { @MainActor in + self.queueFetchUnreadCounts() + } + } + @objc func fetchUnreadCounts() { let activeAccounts = AccountManager.shared.activeAccounts diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index c88067fe7..0de7a9d07 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -208,7 +208,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio private extension FetchRequestOperation { - static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FetchRequestOperation") + static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FetchRequestOperation") static let errorLogSourceID = 101 static func postFetchError(_ error: Error, fileName: String = #fileID, functionName: String = #function, lineNumber: Int = #line) { diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index 3e20837b8..4ce6e1324 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -23,7 +23,7 @@ import Account private let imageContainer: URL private let dataURL: URL - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "WidgetDataEncoder") + private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "WidgetDataEncoder") init?() { guard let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String else { diff --git a/Technotes/Status.md b/Technotes/Status.md index cbcbb6a35..20c073149 100644 --- a/Technotes/Status.md +++ b/Technotes/Status.md @@ -3,6 +3,9 @@ Current milestone: NetNewsWire 7.1.3 on 7.1.3-pre https://github.com/Ranchero-Software/NetNewsWire/milestone/74 +Doing advance work on 7.1.3 on 7.1.3-pre +https://github.com/Ranchero-Software/NetNewsWire/milestone/74 + ## iOS iOS shipping: 7.1.2 (7112) diff --git a/Tests/NetNewsWireTests/ExtractBodyFragmentTests.swift b/Tests/NetNewsWireTests/ExtractBodyFragmentTests.swift new file mode 100644 index 000000000..7f1a5cd63 --- /dev/null +++ b/Tests/NetNewsWireTests/ExtractBodyFragmentTests.swift @@ -0,0 +1,71 @@ +// +// ExtractBodyFragmentTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 7/30/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import Testing + +@testable import NetNewsWire + +/// Tests for `ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(_:)`. +/// +@Suite struct ExtractBodyFragmentTests { + + private func extracted(_ html: String) -> String { + ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(html) + } + + @Test func fullDocumentYieldsBodyFragmentOnly() { + let html = """ + + + +

Newsletter content

+ + """ + #expect(extracted(html) == "

Newsletter content

") + } + + @Test func uppercaseBodyTag() { + let html = "

x

" + #expect(extracted(html) == "

x

") + } + + @Test func unclosedBodyRunsToEnd() { + let html = "

one

two

" + #expect(extracted(html) == "

one

two

") + } + + @Test func documentWithoutBodyTagLosesWrapper() { + let html = "t

content

" + #expect(extracted(html) == "

content

") + } + + @Test func doctypeOnlyPrefixIsRemoved() { + let html = "

content

" + #expect(extracted(html) == "

content

") + } + + @Test func plainFragmentIsUnchanged() { + let html = "

Just a normal article fragment.

" + #expect(extracted(html) == html) + } + + @Test func bodyPrefixedTagIsNotMistakenForBodyTag() { + // isn't a body tag — and with no real document markers + // beyond it, nothing should change. + let html = "

The stood watch.

" + #expect(extracted(html) == html) + } + + @Test func headerElementSurvivesDocumentUnwrapping() { + //
/ confusion: the header element must not be + // treated as the head block. + let html = "

Title

content

" + #expect(extracted(html) == "

Title

content

") + } +} diff --git a/Tests/NetNewsWireTests/SanitizedTitleTests.swift b/Tests/NetNewsWireTests/SanitizedTitleTests.swift index 687c24bd9..1e3c4e278 100644 --- a/Tests/NetNewsWireTests/SanitizedTitleTests.swift +++ b/Tests/NetNewsWireTests/SanitizedTitleTests.swift @@ -34,6 +34,27 @@ import Testing #expect(ArticleStringFormatter.sanitizedTitle(nil, forHTML: forHTML) == nil) } + // MARK: - Angle-bracketed text that isn't HTML + + // A title that is literal text in angle brackets — from an Atom + // — must display as-is, not vanish or mangle. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/722> + + @Test func angleBracketedTextForHTMLIsEscaped() { + #expect(ArticleStringFormatter.sanitizedTitle("<hello-world>", forHTML: true) == "<hello-world>") + } + + @Test func angleBracketedTextNotForHTMLIsPreserved() { + #expect(ArticleStringFormatter.sanitizedTitle("<hello-world>", forHTML: false) == "<hello-world>") + } + + @Test func htmlLookingTitleWordForHTMLIsEscaped() { + #expect( + ArticleStringFormatter.sanitizedTitle("It All Starts with a Humble <textarea>", forHTML: true) + == "It All Starts with a Humble <textarea>" + ) + } + // MARK: - Allowed tags (b, i, em, etc.) @Test func allowedTagForHTMLIsPreserved() { diff --git a/iOS/Account/ReaderAPIAccountViewController.swift b/iOS/Account/ReaderAPIAccountViewController.swift index eb43b3cf1..5512657bc 100644 --- a/iOS/Account/ReaderAPIAccountViewController.swift +++ b/iOS/Account/ReaderAPIAccountViewController.swift @@ -142,7 +142,7 @@ final class ReaderAPIAccountViewController: UITableViewController { // When you fill in the email address via auto-complete it adds extra whitespace let trimmedUsername = username.trimmingWhitespace - guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: type, username: trimmedUsername) else { + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: type, username: trimmedUsername, endpoint: url) else { showError(NSLocalizedString("There is already an account of that type with that username created.", comment: "Duplicate Error")) return } diff --git a/iOS/AppDefaults.swift b/iOS/AppDefaults.swift index 8249905b3..6692ac539 100644 --- a/iOS/AppDefaults.swift +++ b/iOS/AppDefaults.swift @@ -6,6 +6,7 @@ // Copyright © 2017 Ranchero Software. All rights reserved. // +import RSCore import UIKit import os import Account @@ -38,7 +39,7 @@ extension Notification.Name { final class AppDefaults: Sendable { static let shared = AppDefaults() static let defaultThemeName = "Default" - fileprivate static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppDefaults") + fileprivate static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "AppDefaults") private init() {} @@ -78,6 +79,7 @@ final class AppDefaults: Sendable { static let selectedArticle = "selectedArticle" static let didMigrateLegacyStateRestorationInfo = "didMigrateLegacyStateRestorationInfo" static let splitViewPreferredDisplayMode = "splitViewPreferredDisplayMode" + static let timelineWidth = "timelineWidth" } let isDeveloperBuild: Bool = { @@ -229,6 +231,20 @@ final class AppDefaults: Sendable { } } + // The iPad timeline (supplementary) column width. nil until the user has resized it. + var timelineWidth: Int? { + get { + return AppDefaults.store.object(forKey: Key.timelineWidth) as? Int + } + set { + if let newValue { + AppDefaults.store.set(newValue, forKey: Key.timelineWidth) + } else { + AppDefaults.store.removeObject(forKey: Key.timelineWidth) + } + } + } + var lastRefresh: Date? { get { return AppDefaults.date(for: Key.lastRefresh) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index ef1d36398..7bb4df215 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -36,7 +36,7 @@ import Images } } - nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application") + nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Application") var unreadCount = 0 { didSet { @@ -63,6 +63,7 @@ import Images func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FaviconGenerator.templateImage = Assets.Images.faviconTemplate + WebViewConfiguration.resolveBrowserUserAgent() Task { await WebViewConfiguration.compileContentBlockingRules() } @@ -166,6 +167,7 @@ import Images /// Un-suspend network activity if it was suspended on background entry. func resumeIfNecessary() { + AppNotification.postAppDidBecomeActive() if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() Self.logger.info("Application processing resumed.") diff --git a/iOS/AppIntents/AddFeedAppIntent.swift b/iOS/AppIntents/AddFeedAppIntent.swift new file mode 100644 index 000000000..cebac627f --- /dev/null +++ b/iOS/AppIntents/AddFeedAppIntent.swift @@ -0,0 +1,122 @@ +// +// AddFeedAppIntent.swift +// NetNewsWire-iOS +// +// Modern App Intents replacement for the legacy SiriKit "Add Feed" intent. +// <https://github.com/Ranchero-Software/NetNewsWire/issues/5248> +// + +import Foundation +import AppIntents + +struct AddFeedAppIntent: AppIntent { + + static let title: LocalizedStringResource = "Add Feed" + static let description = IntentDescription("Adds a feed to NetNewsWire.") + + // Runs in the background: like the Share Extension, this only enqueues a request into the + // app group; the main app turns it into an actual feed the next time it processes the queue. + static let openAppWhenRun = false + + @Parameter(title: "URL") + var url: URL + + @Parameter(title: "Account", optionsProvider: AccountNameOptionsProvider()) + var accountName: String? + + @Parameter(title: "Folder", optionsProvider: FolderNameOptionsProvider()) + var folderName: String? + + static var parameterSummary: some ParameterSummary { + Summary("Add \(\.$url) to \(\.$accountName)") { + \.$folderName + } + } + + func perform() async throws -> some IntentResult & ProvidesDialog { + guard let extensionContainers = await ExtensionContainersFile.read() else { + throw AddFeedAppIntentError.noAccounts + } + + let account: ExtensionAccount? + if let accountName { + account = extensionContainers.findAccount(forName: accountName) + } else { + account = extensionContainers.accounts.first + } + guard let account else { + throw AddFeedAppIntentError.noAccounts + } + + // Resolve the destination container: the named folder if it exists in this account; + // otherwise the account itself — but substitute its first folder when the account + // disallows feeds at the root (mirrors AddFeedDefaultContainer.substituteContainerIfNeeded). + // Not hard-failing on an unknown folder name also covers cross-account name mismatches. + let container: ExtensionContainer + if let folderName, let folder = account.findFolder(forName: folderName) { + container = folder + } else if account.disallowFeedInRootFolder, let firstFolder = account.folders.first { + container = firstFolder + } else { + container = account + } + + guard let containerID = container.containerID else { + throw AddFeedAppIntentError.noContainer + } + + let request = ExtensionFeedAddRequest(name: nil, feedURL: url, destinationContainerID: containerID) + ExtensionFeedAddRequestFile.save(request) + + // Neutral wording: the feed is queued here and actually created when the app next runs. + return .result(dialog: "Adding \(url.absoluteString) to NetNewsWire.") + } +} + +enum AddFeedAppIntentError: Error, CustomLocalizedStringResourceConvertible { + case noAccounts + case noContainer + + var localizedStringResource: LocalizedStringResource { + switch self { + case .noAccounts: + return "There are no accounts to add the feed to." + case .noContainer: + return "Couldn’t find a place to add the feed." + } + } +} + +struct AccountNameOptionsProvider: DynamicOptionsProvider { + func results() async throws -> [String] { + guard let extensionContainers = await ExtensionContainersFile.read() else { + return [] + } + return extensionContainers.accounts.map { $0.name } + } +} + +struct FolderNameOptionsProvider: DynamicOptionsProvider { + + // Scope folder options to the account the user picked (falls back to all accounts' folders + // when no account is chosen yet). + @IntentParameterDependency<AddFeedAppIntent>(\.$accountName) + var addFeedIntent + + func results() async throws -> [String] { + guard let extensionContainers = await ExtensionContainersFile.read() else { + return [] + } + + let accounts: [ExtensionAccount] + if let accountName = addFeedIntent?.accountName, let account = extensionContainers.findAccount(forName: accountName) { + accounts = [account] + } else { + accounts = extensionContainers.accounts + } + + // Dedupe: folder names can repeat across accounts when unscoped. + var seen = Set<String>() + return accounts.flatMap { $0.folders.map { $0.name } }.filter { seen.insert($0).inserted } + } +} diff --git a/iOS/AppIntents/NetNewsWireAppShortcuts.swift b/iOS/AppIntents/NetNewsWireAppShortcuts.swift new file mode 100644 index 000000000..eec6d2dd4 --- /dev/null +++ b/iOS/AppIntents/NetNewsWireAppShortcuts.swift @@ -0,0 +1,24 @@ +// +// NetNewsWireAppShortcuts.swift +// NetNewsWire-iOS +// +// Makes App Intents available in the Shortcuts app / Spotlight / Siri with no user setup. +// <https://github.com/Ranchero-Software/NetNewsWire/issues/5248> +// + +import AppIntents + +struct NetNewsWireAppShortcuts: AppShortcutsProvider { + + static var appShortcuts: [AppShortcut] { + AppShortcut( + intent: AddFeedAppIntent(), + phrases: [ + "Add a feed to \(.applicationName)", + "Add feed in \(.applicationName)" + ], + shortTitle: "Add Feed", + systemImageName: "plus" + ) + } +} diff --git a/iOS/Article/ArticleViewController.swift b/iOS/Article/ArticleViewController.swift index a6c17a307..fe306b3d3 100644 --- a/iOS/Article/ArticleViewController.swift +++ b/iOS/Article/ArticleViewController.swift @@ -55,7 +55,7 @@ final class ArticleViewController: UIViewController { weak var coordinator: SceneCoordinator! private let poppableDelegate = PoppableGestureRecognizerDelegate() - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ArticleViewController") + private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ArticleViewController") var article: Article? { didSet { diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index 1cd63b890..04b077a5f 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -37,6 +37,8 @@ final class WebViewController: UIViewController { return view.subviews[0] as? PreloadedWebView } + private var webViewProcessDidTerminate = false + private lazy var contextMenuInteraction = UIContextMenuInteraction(delegate: self) private var isFullScreenAvailable: Bool { return AppDefaults.shared.articleFullscreenAvailable && traitCollection.userInterfaceIdiom == .phone @@ -454,6 +456,7 @@ extension WebViewController: WKNavigationDelegate { } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + webViewProcessDidTerminate = true fullReload() } @@ -554,11 +557,15 @@ private extension WebViewController { func loadWebView(replaceExistingWebView: Bool = false) { guard isViewLoaded else { return } - if !replaceExistingWebView, let webView = webView { + // Never render into a web view whose content process died — the load + // can fail silently, leaving the article view blank. + if !replaceExistingWebView, !webViewProcessDidTerminate, let webView = webView { self.renderPage(webView) return } + webViewProcessDidTerminate = false + coordinator.webViewProvider.dequeueWebView { webView in webView.ready { @@ -696,7 +703,7 @@ private extension WebViewController { guard let imageURL = URL(string: clickMessage.imageURL) else { return } - Downloader.shared.download(imageURL) { [weak self] downloadResponse, error in + Downloader.shared.download(imageURL, userAgentStyle: .browser) { [weak self] downloadResponse, error in guard let self, let data = downloadResponse.data, error == nil, !data.isEmpty, let image = UIImage(data: data) else { return @@ -881,10 +888,21 @@ private extension WebViewController { guard let viewController = SFSafariViewController.safeSafariViewController(url) else { return } + viewController.delegate = self + coordinator?.beganBrowsing(url: url) present(viewController, animated: true) } } +// MARK: SFSafariViewControllerDelegate + +extension WebViewController: @preconcurrency SFSafariViewControllerDelegate { + + func safariViewControllerDidFinish(_ controller: SFSafariViewController) { + coordinator?.endedBrowsing() + } +} + // MARK: Find in Article private struct FindInArticleOptions: Codable { diff --git a/iOS/Article/WebViewProvider.swift b/iOS/Article/WebViewProvider.swift index 25b5eab92..3f739fb1a 100644 --- a/iOS/Article/WebViewProvider.swift +++ b/iOS/Article/WebViewProvider.swift @@ -7,6 +7,7 @@ // import Foundation +import UIKit import RSCore import WebKit @@ -21,12 +22,21 @@ import WebKit articleIconSchemeHandler = ArticleIconSchemeHandler(coordinator: coordinator) super.init() replenishQueueIfNeeded() + NotificationCenter.default.addObserver(self, selector: #selector(handleWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) } func replenishQueueIfNeeded() { operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) } + // Pooled web views can lose their content process while the app is in the + // background. A load into a dead web view can fail silently, showing blank — + // so start over with fresh web views. + @objc func handleWillEnterForeground(_ note: Notification) { + queue.removeAllObjects() + replenishQueueIfNeeded() + } + func dequeueWebView(completion: @escaping (PreloadedWebView) -> Void) { operationQueue.add(WebViewProviderDequeueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler, completion: completion)) operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) diff --git a/iOS/ErrorHandler.swift b/iOS/ErrorHandler.swift index 10f8517d4..546f00f4b 100644 --- a/iOS/ErrorHandler.swift +++ b/iOS/ErrorHandler.swift @@ -12,7 +12,7 @@ import RSCore 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(_ viewController: UIViewController) -> @Sendable (Error) -> Void { return { [weak viewController] error in diff --git a/iOS/IntentsExtension/Info.plist b/iOS/IntentsExtension/Info.plist deleted file mode 100644 index 3b75a62cc..000000000 --- a/iOS/IntentsExtension/Info.plist +++ /dev/null @@ -1,48 +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>OrganizationIdentifier</key> - <string>$(ORGANIZATION_IDENTIFIER)</string> - <key>AppGroup</key> - <string>$(APP_GROUP_ID)</string> - <key>AppIdentifierPrefix</key> - <string>$(AppIdentifierPrefix)</string> - <key>CFBundleDevelopmentRegion</key> - <string>$(DEVELOPMENT_LANGUAGE)</string> - <key>CFBundleDisplayName</key> - <string>NetNewsWire iOS Intents Extension</string> - <key>CFBundleExecutable</key> - <string>$(EXECUTABLE_NAME)</string> - <key>CFBundleIdentifier</key> - <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundleName</key> - <string>$(PRODUCT_NAME)</string> - <key>CFBundlePackageType</key> - <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string> - <key>CFBundleShortVersionString</key> - <string>$(MARKETING_VERSION)</string> - <key>CFBundleVersion</key> - <string>$(CURRENT_PROJECT_VERSION)</string> - <key>NSExtension</key> - <dict> - <key>NSExtensionAttributes</key> - <dict> - <key>IntentsRestrictedWhileLocked</key> - <array/> - <key>IntentsRestrictedWhileProtectedDataUnavailable</key> - <array/> - <key>IntentsSupported</key> - <array> - <string>AddWebFeedIntent</string> - </array> - </dict> - <key>NSExtensionPointIdentifier</key> - <string>com.apple.intents-service</string> - <key>NSExtensionPrincipalClass</key> - <string>$(PRODUCT_MODULE_NAME).IntentHandler</string> - </dict> -</dict> -</plist> diff --git a/iOS/IntentsExtension/IntentHandler.swift b/iOS/IntentsExtension/IntentHandler.swift deleted file mode 100644 index 5e5e20ebc..000000000 --- a/iOS/IntentsExtension/IntentHandler.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// IntentHandler.swift -// NetNewsWire iOS Intents Extension -// -// Created by Maurice Parker on 10/18/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import Intents - -final class IntentHandler: INExtension { - - override func handler(for intent: INIntent) -> Any { - switch intent { - case is AddWebFeedIntent: - return AddWebFeedIntentHandler() - default: - fatalError("Unhandled intent type: \(intent)") - } - } - -} diff --git a/iOS/IntentsExtension/NetNewsWire_iOS_IntentsExtension.entitlements b/iOS/IntentsExtension/NetNewsWire_iOS_IntentsExtension.entitlements deleted file mode 100644 index 54049ed3b..000000000 --- a/iOS/IntentsExtension/NetNewsWire_iOS_IntentsExtension.entitlements +++ /dev/null @@ -1,14 +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>com.apple.security.application-groups</key> - <array> - <string>$(APP_GROUP_ID)</string> - </array> - <key>keychain-access-groups</key> - <array> - <string>$(AppIdentifierPrefix)$(ORGANIZATION_IDENTIFIER).NetNewsWire.iOS$(BUNDLE_ID_SUFFIX)</string> - </array> -</dict> -</plist> diff --git a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift index e68b5a1b6..627008445 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift @@ -66,7 +66,7 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { if source.account == destination.account { moveFeedInAccount(feed: feed, sourceContainer: source, destinationContainer: destination) } else { - moveFeedBetweenAccounts(feed: feed, sourceContainer: source, destinationContainer: destination) + copyFeedBetweenAccounts(feed: feed, destinationContainer: destination) } } @@ -90,15 +90,19 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { return UICollectionViewDropProposal(operation: .forbidden) } + // Cross-account drops copy the feed; same-account drops move it. + let sourceFeed = (session.localDragSession?.items.first?.localObject as? Node)?.representedObject as? Feed + let operation: UIDropOperation = (sourceFeed?.account?.accountID != destAccount.accountID) ? .copy : .move + // Determine the correct drop proposal if destFeed is Folder { if session.location(in: destCell).y >= 0 { - return UICollectionViewDropProposal(operation: .move, intent: .insertIntoDestinationIndexPath) + return UICollectionViewDropProposal(operation: operation, intent: .insertIntoDestinationIndexPath) } else { - return UICollectionViewDropProposal(operation: .move, intent: .unspecified) + return UICollectionViewDropProposal(operation: operation, intent: .unspecified) } } else { - return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) + return UICollectionViewDropProposal(operation: operation, intent: .insertAtDestinationIndexPath) } } @@ -124,25 +128,17 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { } } - func moveFeedBetweenAccounts(feed: Feed, sourceContainer: Container, destinationContainer: Container) { + func copyFeedBetweenAccounts(feed: Feed, destinationContainer: Container) { if let existingFeed = destinationContainer.account?.existingFeed(withURL: feed.url) { BatchUpdate.shared.start() destinationContainer.account?.addFeed(existingFeed, to: destinationContainer) { result in + BatchUpdate.shared.end() switch result { case .success: - sourceContainer.account?.removeFeed(feed, from: sourceContainer) { result in - BatchUpdate.shared.end() - switch result { - case .success: - break - case .failure(let error): - self.presentError(error) - } - } + break case .failure(let error): - BatchUpdate.shared.end() self.presentError(error) } } @@ -151,19 +147,11 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { BatchUpdate.shared.start() destinationContainer.account?.createFeed(url: feed.url, name: feed.editedName, container: destinationContainer, validateFeed: false) { result in + BatchUpdate.shared.end() switch result { case .success: - sourceContainer.account?.removeFeed(feed, from: sourceContainer) { result in - BatchUpdate.shared.end() - switch result { - case .success: - break - case .failure(let error): - self.presentError(error) - } - } + break case .failure(let error): - BatchUpdate.shared.end() self.presentError(error) } } diff --git a/iOS/MainFeed/MainFeedCollectionViewController.swift b/iOS/MainFeed/MainFeedCollectionViewController.swift index c04c1d83e..0bcde6317 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController.swift @@ -33,7 +33,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab } } - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainFeedCollectionViewController") + private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "MainFeedCollectionViewController") private let keyboardManager = KeyboardManager(type: .sidebar) override var keyCommands: [UIKeyCommand]? { @@ -118,7 +118,12 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab self.navigationController?.navigationBar.prefersLargeTitles = true self.navigationItem.largeTitleDisplayMode = .always DispatchQueue.main.async { - /// This sizes the navigation bar to large. + // Sizes the bar to large. Skip if a pushed VC (e.g. the timeline, which shares this bar + // on iPhone) is now on top, or it would be forced large too. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/5141> + guard self.navigationController?.topViewController === self else { + return + } self.navigationController?.navigationBar.sizeToFit() } @@ -148,26 +153,15 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab self.isAnimating = false } - // Pro Max may have split view in landscape — give the device some - // time to change its size class and then decide to deselect + // Rotating a Pro Max to landscape expands the split view — wait for the transition to settle. // <https://github.com/Ranchero-Software/NetNewsWire/issues/5043> - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { - // If the iPhone is in portrait, deselect. - if UIDevice.current.orientation.isPortrait { - if self.collectionView.indexPathsForSelectedItems != nil { - self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select]) - } - return + DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { + // Deselect only when the feeds list is full screen. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/4691> + if self.coordinator.isRootSplitCollapsed, self.collectionView.indexPathsForSelectedItems?.first != nil { + self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select]) } - - // If the iPhone is in landscape, and the horizontal - // size class is compact, deselect. - if self.view.window?.traitCollection.horizontalSizeClass == .compact { - if self.collectionView.indexPathsForSelectedItems != nil { self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select]) - } - return - } - }) + } } func registerForNotifications() { @@ -405,9 +399,21 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { becomeFirstResponder() + } + + // Fires on every tap — even on the already-selected feed, which doesn't get didSelectItemAt. + override func collectionView(_ collectionView: UICollectionView, performPrimaryActionForItemAt indexPath: IndexPath) { + becomeFirstResponder() coordinator.selectSidebarItem(indexPath: indexPath, animations: [.navigation, .select, .scroll]) } + override func collectionView(_ collectionView: UICollectionView, canPerformPrimaryActionForItemAt indexPath: IndexPath) -> Bool { + if traitCollection.userInterfaceIdiom == .pad { + return true + } + return !isAnimating + } + // MARK: UICollectionViewDelegate /* diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index 40803b2ee..9a5c15536 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -150,7 +150,7 @@ final class MainTimelineModernViewController: UIViewController, UndoableCommandR // MARK: Private Constants private let searchController = UISearchController(searchResultsController: nil) private let keyboardManager = KeyboardManager(type: .timeline) - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineModernViewController") + private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "MainTimelineModernViewController") // MARK: Constants private let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) @@ -222,6 +222,10 @@ final class MainTimelineModernViewController: UIViewController, UndoableCommandR navigationController?.navigationBar.alpha = 0 } + // Re-assert small title in case the shared iPhone nav bar was left in large mode. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/5141> + navigationItem.largeTitleDisplayMode = .never + updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") coordinator?.updateNavigationBarSubtitles(nil) updateToolbarProgressView() diff --git a/iOS/Resources/Info.plist b/iOS/Resources/Info.plist index 7eed09d23..d3a7aaddb 100644 --- a/iOS/Resources/Info.plist +++ b/iOS/Resources/Info.plist @@ -70,7 +70,6 @@ <string>Grant permission to save images from the article.</string> <key>NSUserActivityTypes</key> <array> - <string>AddWebFeedIntent</string> <string>NextUnread</string> <string>ReadArticle</string> <string>Restoration</string> diff --git a/iOS/Resources/main_ios.js b/iOS/Resources/main_ios.js index 4e34d9aa8..37f7f31a8 100644 --- a/iOS/Resources/main_ios.js +++ b/iOS/Resources/main_ios.js @@ -8,7 +8,8 @@ class ImageViewer { } isLoaded() { - return this.img.classList.contains("nnwLoaded"); + // img.complete covers images that loaded before the onload handler was added. + return this.img.classList.contains("nnwLoaded") || this.img.complete; } clicked() { @@ -95,6 +96,9 @@ class ImageViewer { // Add the click listener for images window.onclick = function(event) { if (event.target.matches("img") && !event.target.classList.contains("nnw-nozoom")) { + // Without this, tapping an image wrapped in a link also navigates. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/5275> + event.preventDefault(); if (activeImageViewer && activeImageViewer.img === event.target) { cancelImageLoad(); } else { @@ -129,7 +133,18 @@ function showClickedImage() { } function showFeedInspectorSetup() { - document.getElementById("nnwImageIcon").onclick = function(event) { + const imageIcon = document.getElementById("nnwImageIcon"); + if (!imageIcon) { + return; + } + + // Tell VoiceOver the icon is a button that opens the Feed Info sheet. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/4591> + imageIcon.setAttribute("role", "button"); + imageIcon.setAttribute("tabindex", "0"); + imageIcon.setAttribute("aria-label", nnwGetFeedInfoLabel); + + imageIcon.onclick = function(event) { window.webkit.messageHandlers.showFeedInspector.postMessage(""); } } diff --git a/iOS/Resources/page.html b/iOS/Resources/page.html index b03c530ef..97e7b7740 100644 --- a/iOS/Resources/page.html +++ b/iOS/Resources/page.html @@ -8,7 +8,6 @@ <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(event) { window.scrollTo(0, [[windowScrollY]]); - processPage(); }) </script> <base href="[[baseURL]]"> diff --git a/iOS/RootSplitViewController.swift b/iOS/RootSplitViewController.swift index 01f113ad7..6b05f7a44 100644 --- a/iOS/RootSplitViewController.swift +++ b/iOS/RootSplitViewController.swift @@ -26,6 +26,13 @@ final class RootSplitViewController: UISplitViewController { } override func show(_ column: UISplitViewController.Column) { + show(column, bypassDisplayModeRestriction: false) + } + + /// Pass `bypassDisplayModeRestriction: true` for user-initiated keyboard navigation, so it can + /// reveal a column the display-mode suppression below would otherwise keep hidden. + /// <https://github.com/Ranchero-Software/NetNewsWire/issues/3138> + func show(_ column: UISplitViewController.Column, bypassDisplayModeRestriction: Bool) { guard !coordinator.isNavigationDisabled else { return } /// Always show the column on iPhone @@ -37,15 +44,17 @@ final class RootSplitViewController: UISplitViewController { /// In certain scenarios, we don't want to select a feed or article /// and have the display mode change as this interferes with state /// restoration of the feeds and timeline display modes. + if !bypassDisplayModeRestriction { - /// Don't show primary when the preferred display mode is timeline + article or article only. - if column == .primary && (preferredDisplayMode == .oneBesideSecondary || preferredDisplayMode == .secondaryOnly) { - return - } + /// Don't show primary when the preferred display mode is timeline + article or article only. + if column == .primary && (preferredDisplayMode == .oneBesideSecondary || preferredDisplayMode == .secondaryOnly) { + return + } - /// Don't show the timeline when the preferred display mode is article only. - if column == .supplementary && preferredDisplayMode == .secondaryOnly { - return + /// Don't show the timeline when the preferred display mode is article only. + if column == .supplementary && preferredDisplayMode == .secondaryOnly { + return + } } super.show(column) @@ -79,8 +88,28 @@ final class RootSplitViewController: UISplitViewController { } @objc func markAllAsReadAndGoToNextUnread(_ sender: Any?) { - coordinator.markAsReadAndShowSidebar(coordinator.articles) { - self.coordinator.selectNextUnread() + if !coordinator.isTimelineUnreadAvailable { + coordinator.selectNextUnread() + return + } + let articlesToMark = coordinator.articles + let title = NSLocalizedString("Mark All as Read", comment: "Command") + + let completion: () -> Void = { [weak self] in + guard let self else { + return + } + self.coordinator.markAsReadAndShowSidebar(articlesToMark) { + self.coordinator.selectNextUnread() + } + } + + // Anchor to the Mark All as Read button (keyboard shortcut has no source view). + // <https://github.com/Ranchero-Software/NetNewsWire/issues/5370> + if let markAllAsReadButton = (viewController(for: .supplementary) as? MainTimelineModernViewController)?.markAllAsReadButton { + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: markAllAsReadButton, completion: completion) + } else { + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: view as UIView, completion: completion) } } diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index f0c8405d8..48b6e9ced 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -67,7 +67,7 @@ struct SidebarItemNode: Hashable, Sendable { private var fetchSerialNumber = 0 private let fetchRequestQueue = FetchRequestQueue() - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SceneCoordinator") + private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "SceneCoordinator") // Which Containers are expanded private var expandedContainers = Set<ContainerIdentifier>() @@ -304,13 +304,32 @@ struct SidebarItemNode: Hashable, Sendable { } } + private static let minimumTimelineWidth: CGFloat = 280 + private static let maximumTimelineWidth: CGFloat = 440 + + private static func clampTimelineWidth(_ width: CGFloat) -> CGFloat { + if width < minimumTimelineWidth { + return minimumTimelineWidth + } + if width > maximumTimelineWidth { + return maximumTimelineWidth + } + return width + } + init(rootSplitViewController: RootSplitViewController) { self.rootSplitViewController = rootSplitViewController self.rootSplitViewController.minimumPrimaryColumnWidth = 300 self.rootSplitViewController.maximumPrimaryColumnWidth = 500 - self.rootSplitViewController.minimumSupplementaryColumnWidth = 300 - self.rootSplitViewController.preferredSupplementaryColumnWidth = 320 - self.rootSplitViewController.maximumSupplementaryColumnWidth = 360 + self.rootSplitViewController.minimumSupplementaryColumnWidth = SceneCoordinator.minimumTimelineWidth + self.rootSplitViewController.maximumSupplementaryColumnWidth = SceneCoordinator.maximumTimelineWidth + let restoredTimelineWidth: CGFloat + if let savedTimelineWidth = AppDefaults.shared.timelineWidth { + restoredTimelineWidth = CGFloat(savedTimelineWidth) + } else { + restoredTimelineWidth = 320 + } + self.rootSplitViewController.preferredSupplementaryColumnWidth = Self.clampTimelineWidth(restoredTimelineWidth) self.rootSplitViewController.preferredSplitBehavior = .tile self.treeController = TreeController(delegate: treeControllerDelegate) @@ -356,12 +375,12 @@ struct SidebarItemNode: Hashable, Sendable { } } - func restoreWindowState(activity: NSUserActivity?) { + func restoreWindowState(activity: NSUserActivity?, restoreSelection: Bool) { let stateInfo = StateRestorationInfo(legacyState: activity) - restoreWindowState(stateInfo) + restoreWindowState(stateInfo, restoreSelection: restoreSelection) } - private func restoreWindowState(_ stateInfo: StateRestorationInfo) { + private func restoreWindowState(_ stateInfo: StateRestorationInfo, restoreSelection: Bool) { Self.logger.debug("SceneCoordinator: restoreWindowState") isRestoringState = true @@ -387,6 +406,11 @@ struct SidebarItemNode: Hashable, Sendable { // for state restoration to work with while we are waiting for the unread counts to initialize. treeControllerDelegate.isReadFiltered = stateInfo.hideReadFeeds + guard restoreSelection else { + isRestoringState = false + return + } + restoreSelectedSidebarItemAndArticle(stateInfo) } @@ -629,7 +653,8 @@ struct SidebarItemNode: Hashable, Sendable { return } DispatchQueue.main.async { - self.rootSplitViewController.presentError(error, dismiss: nil) + let title = NSLocalizedString("Theme Error", comment: "Theme download error") + self.rootSplitViewController.presentError(title: title, message: ArticleThemesManager.importErrorMessage(for: error)) } } @@ -744,6 +769,19 @@ struct SidebarItemNode: Hashable, Sendable { func didEnterBackground() { hidingReadArticlesState.save() saveExpandedContainers() + saveTimelineWidth() + } + + private func saveTimelineWidth() { + // Only meaningful when the timeline is its own column (iPad, expanded); when collapsed its view fills the screen. + guard !rootSplitViewController.isCollapsed else { + return + } + let width = mainTimelineViewController?.view.bounds.width ?? 0 + guard width > 0 else { + return + } + AppDefaults.shared.timelineWidth = Int(SceneCoordinator.clampTimelineWidth(width)) } func suspend() { @@ -953,6 +991,10 @@ struct SidebarItemNode: Hashable, Sendable { tappedFeed = nodeFor(indexPath)?.representedObject as AnyObject? } guard tappedFeed !== timelineFeed as AnyObject? else { + // Same feed — just make sure the timeline is showing. + if indexPath != nil { + rootSplitViewController.show(.supplementary) + } completion?() return } @@ -1334,14 +1376,22 @@ struct SidebarItemNode: Hashable, Sendable { } rebuildBackingStores(initialLoad: initialLoad, completion: { - self.treeControllerDelegate.resetFilterExceptions() self.selectFeed(nil) { - if self.rootSplitViewController.traitCollection.horizontalSizeClass == .compact { - DispatchQueue.main.asyncAfter(deadline: .now() + 1) { + // Deselecting rebuilds the sidebar, which can hide the feed when + // read feeds are filtered — put it back right before selecting it. + let ensureAndSelect: @MainActor () -> Void = { + if self.isReadFeedsFiltered { + self.ensureFeedIsAvailableToSelect(feed) { + self.selectFeed(feed, animations: animations, completion: completion) + } + } else { self.selectFeed(feed, animations: animations, completion: completion) } + } + if self.rootSplitViewController.traitCollection.horizontalSizeClass == .compact { + DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: ensureAndSelect) } else { - self.selectFeed(feed, animations: animations, completion: completion) + ensureAndSelect() } } }) @@ -1484,20 +1534,50 @@ struct SidebarItemNode: Hashable, Sendable { } } + func beganBrowsing(url: URL) { + activityManager.browsing(url: url) + } + + func endedBrowsing() { + activityManager.invalidateBrowsing() + } + func navigateToFeeds() { - mainFeedCollectionViewController?.focus() - selectArticle(nil) + if !isRootSplitCollapsed { + // In three-pane mode, focusing the sidebar deselects the article. + // In collapsed mode the pop below drives cleanup via navigationController(_:didShow:). + selectArticle(nil) + } + revealColumn(.primary) { [weak self] in + self?.mainFeedCollectionViewController?.focus() + } } func navigateToTimeline() { - if currentArticle == nil && articles.count > 0 { + // Only auto-select the first article in three-pane mode, where it populates the + // detail pane without hiding the timeline. + let displayMode = rootSplitViewController.preferredDisplayMode + let isThreePane = !isRootSplitCollapsed && displayMode != .oneBesideSecondary && displayMode != .secondaryOnly + if isThreePane && currentArticle == nil && articles.count > 0 { selectArticle(articles[0]) } - mainTimelineViewController?.focus() + revealColumn(.supplementary) { [weak self] in + self?.mainTimelineViewController?.focus() + } } func navigateToDetail() { - articleViewController?.focus() + // If nothing is selected, open the first article so right-arrow reveals the detail even in + // collapsed and two-pane layouts. selectArticle reveals/pushes the detail column itself. + if currentArticle == nil { + guard articles.count > 0 else { + return + } + selectArticle(articles[0]) + } + revealColumn(.secondary) { [weak self] in + self?.articleViewController?.focus() + } } func selectArticleInCurrentFeed(_ articleID: String, isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) { @@ -1624,6 +1704,66 @@ extension SceneCoordinator: UINavigationControllerDelegate { private extension SceneCoordinator { + // Reveal the destination column, then focus it. Works across collapsed (iPhone), + // two-pane, and three-pane layouts, so arrow-key navigation isn't limited to the + // case where all columns are already visible. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/3138> + func revealColumn(_ column: UISplitViewController.Column, thenFocus focus: @escaping () -> Void) { + if isRootSplitCollapsed { + revealColumnInCollapsedMode(column, thenFocus: focus) + } else { + rootSplitViewController.show(column, bypassDisplayModeRestriction: true) + // Defer focus so becomeFirstResponder targets the revealed column, not the outgoing one. + DispatchQueue.main.async(execute: focus) + } + } + + func revealColumnInCollapsedMode(_ column: UISplitViewController.Column, thenFocus focus: @escaping () -> Void) { + guard !isNavigationDisabled, let navController = mainFeedCollectionViewController.navigationController else { + return + } + let targetViewController: UIViewController? + switch column { + case .primary: + targetViewController = mainFeedCollectionViewController + case .supplementary: + targetViewController = mainTimelineViewController + case .secondary: + targetViewController = articleViewController + default: + targetViewController = nil + } + guard let targetViewController else { + return + } + + if navController.topViewController === targetViewController { + // Already on the destination column — just move focus. + DispatchQueue.main.async(execute: focus) + } else if navController.viewControllers.contains(targetViewController) { + // Backward navigation. The pop fires navigationController(_:didShow:), which performs + // the existing collapsed-mode cleanup. Don't duplicate that here. + navController.popToViewController(targetViewController, animated: true) + focusWhenTransitionCompletes(in: navController, thenFocus: focus) + } else { + // Forward navigation — push the destination column onto the stack. + rootSplitViewController.show(column) + focusWhenTransitionCompletes(in: navController, thenFocus: focus) + } + } + + // Focus once the navigation transition finishes, so becomeFirstResponder lands on the + // revealed column rather than firing mid-animation. Falls back to the next runloop. + func focusWhenTransitionCompletes(in navController: UINavigationController, thenFocus focus: @escaping () -> Void) { + if let transitionCoordinator = navController.transitionCoordinator { + transitionCoordinator.animate(alongsideTransition: nil) { _ in + focus() + } + } else { + DispatchQueue.main.async(execute: focus) + } + } + func markArticlesWithUndo(_ articles: [Article], statusKey: ArticleStatus.Key, flag: Bool, completion: (() -> Void)? = nil) { guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articles, statusKey: statusKey, flag: flag, undoManager: undoManager, completion: completion) else { @@ -2349,6 +2489,9 @@ private extension SceneCoordinator { return } + // A deep link supersedes any in-flight state restoration. + isRestoringState = false + guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable: Any], let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String, let accountName = articlePathUserInfo[ArticlePathKey.accountName] as? String, diff --git a/iOS/SceneDelegate.swift b/iOS/SceneDelegate.swift index c66d7cdc2..02ce220c0 100644 --- a/iOS/SceneDelegate.swift +++ b/iOS/SceneDelegate.swift @@ -35,7 +35,17 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { rootViewController.coordinator = coordinator rootViewController.delegate = coordinator - coordinator.restoreWindowState(activity: session.stateRestorationActivity) + // An external action (notification tap, URL, shortcut, or user activity) + // dictates navigation. Also doing selection restoration — previously selected feed + // and article — at the same time would start two competing navigations. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/4638> + // Restore the window state, but skip restoring the selection. + let hasPendingExternalAction = connectionOptions.notificationResponse != nil || + connectionOptions.urlContexts.first?.url != nil || + connectionOptions.shortcutItem != nil || + !connectionOptions.userActivities.isEmpty + + coordinator.restoreWindowState(activity: session.stateRestorationActivity, restoreSelection: !hasPendingExternalAction) updateUserInterfaceStyle() @@ -192,32 +202,9 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - if let providedThemeURL = queryItems.first(where: { $0.name == "url" })?.value { - if let themeURL = URL(string: providedThemeURL) { - let request = URLRequest(url: themeURL) - - DispatchQueue.main.async { - NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil) - } - let task = URLSession.shared.downloadTask(with: request) { location, _, error in - guard - let location = location else { return } - - Task { @MainActor in - do { - try ArticleThemeDownloader.shared.handleFile(at: location) - } catch { - NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) - } - } - } - task.resume() - } else { - print("No theme URL") - return - } - } else { - return + if let providedThemeURL = queryItems.first(where: { $0.name == "url" })?.value, + let themeURL = URL(string: providedThemeURL) { + ArticleThemeDownloader.shared.downloadTheme(from: themeURL) } } } diff --git a/iOS/ShareExtension/Base.lproj/MainInterface.storyboard b/iOS/ShareExtension/Base.lproj/MainInterface.storyboard deleted file mode 100644 index cac1c7bb8..000000000 --- a/iOS/ShareExtension/Base.lproj/MainInterface.storyboard +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14868" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="j1y-V4-xli"> - <device id="retina6_1" orientation="portrait" appearance="light"/> - <dependencies> - <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14824"/> - <capability name="Safe area layout guides" minToolsVersion="9.0"/> - <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> - </dependencies> - <scenes> - <!--Share View Controller--> - <scene sceneID="ceB-am-kn3"> - <objects> - <viewController id="j1y-V4-xli" customClass="ShareViewController" customModule="NetNewsWire_iOS_Share_Extension" customModuleProvider="target" sceneMemberID="viewController"> - <view key="view" opaque="NO" contentMode="scaleToFill" id="wbc-yd-nQP"> - <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> - <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> - <color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/> - <viewLayoutGuide key="safeArea" id="1Xd-am-t49"/> - </view> - </viewController> - <placeholder placeholderIdentifier="IBFirstResponder" id="CEy-Cv-SGf" userLabel="First Responder" sceneMemberID="firstResponder"/> - </objects> - <point key="canvasLocation" x="139" y="139"/> - </scene> - </scenes> -</document> diff --git a/iOS/ShareExtension/Info.plist b/iOS/ShareExtension/Info.plist index 8f97cc69a..45063a305 100644 --- a/iOS/ShareExtension/Info.plist +++ b/iOS/ShareExtension/Info.plist @@ -40,8 +40,8 @@ <key>NSExtensionJavaScriptPreprocessingFile</key> <string>SafariExt</string> </dict> - <key>NSExtensionMainStoryboard</key> - <string>MainInterface</string> + <key>NSExtensionPrincipalClass</key> + <string>ShareViewController</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.share-services</string> </dict> diff --git a/iOS/ShareExtension/ShareViewController.swift b/iOS/ShareExtension/ShareViewController.swift index 89fd81acb..d76638aad 100644 --- a/iOS/ShareExtension/ShareViewController.swift +++ b/iOS/ShareExtension/ShareViewController.swift @@ -7,172 +7,227 @@ // import UIKit -import MobileCoreServices -import os import UniformTypeIdentifiers -import Social import Account -import RSCore -import RSTree -final class ShareViewController: SLComposeServiceViewController, ShareFolderPickerControllerDelegate { - private var extensionContainers: ExtensionContainers? - private var flattenedContainers: [ExtensionContainer]! - private var selectedContainer: ExtensionContainer? - private var folderItem: SLComposeSheetConfigurationItem! +// The share extension's principal class (see NSExtensionPrincipalClass in Info.plist). +// A custom form replaces the old SLComposeServiceViewController, which no longer renders correctly. +@objc(ShareViewController) +final class ShareViewController: UINavigationController { - private struct State { - var url: URL? + override func viewDidLoad() { + super.viewDidLoad() + viewControllers = [ShareAddFeedViewController()] } - private let state = OSAllocatedUnfairLock(initialState: State()) +} - nonisolated private var url: URL? { - get { - state.withLock { $0.url } - } - set { - state.withLock { $0.url = newValue } +final class ShareAddFeedViewController: UITableViewController, ShareFolderPickerControllerDelegate { + + private var extensionContainers: ExtensionContainers? + private var flattenedContainers = [ExtensionContainer]() + private var selectedContainer: ExtensionContainer? + private var addFeedButton: UIBarButtonItem? + private let nameTextField = UITextField() + private lazy var nameCell = makeNameCell() + + private var url: URL? { + didSet { + updateUI() } } + private enum Section: Int, CaseIterable { + case name + case folder + case urlDisplay + } + + init() { + super.init(style: .insetGrouped) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + override func viewDidLoad() { super.viewDidLoad() + + title = "NetNewsWire" + navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(_:))) + let addFeedButton = UIBarButtonItem(title: "Add Feed", style: .done, target: self, action: #selector(addFeed(_:))) + navigationItem.rightBarButtonItem = addFeedButton + self.addFeedButton = addFeedButton + + tableView.keyboardDismissMode = .onDrag + extensionContainers = ExtensionContainersFile.read() flattenedContainers = extensionContainers?.flattened ?? [ExtensionContainer]() if let extensionContainers { selectedContainer = ShareDefaultContainer.defaultContainer(containers: extensionContainers) } - title = "NetNewsWire" - placeholder = "Feed Name (Optional)" - if let button = navigationController?.navigationBar.topItem?.rightBarButtonItem { - button.title = "Add Feed" - button.isEnabled = true - } - - // Hack the bottom table rows to be smaller since the controller itself doesn't have enough sense to size itself correctly - if let nav = self.children.first as? UINavigationController, let tableView = nav.children.first?.view.subviews.first as? UITableView { - tableView.rowHeight = 38 - } - - var provider: NSItemProvider? - - // Try to get any HTML that is maybe passed in - for item in self.extensionContext!.inputItems as! [NSExtensionItem] { - for itemProvider in item.attachments! { - if itemProvider.hasItemConformingToTypeIdentifier(UTType.propertyList.identifier) { - provider = itemProvider - } - } - } - - if provider != nil { - provider!.loadItem(forTypeIdentifier: UTType.propertyList.identifier, options: nil, completionHandler: { [weak self] (pList, error) in - if error != nil { - return - } - guard let dataGraph = pList as? NSDictionary else { - return - } - guard let results = dataGraph["NSExtensionJavaScriptPreprocessingResultsKey"] as? NSDictionary else { - return - } - if let url = URL(string: results["url"] as! String) { - self?.url = url - } - }) - return - } - - // Try to get the URL if it is passed in - for item in self.extensionContext!.inputItems as! [NSExtensionItem] { - for itemProvider in item.attachments! { - if itemProvider.hasItemConformingToTypeIdentifier(UTType.url.identifier) { - provider = itemProvider - } - } - } - - if provider != nil { - provider!.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil, completionHandler: { [weak self] (urlCoded, error) in - if error != nil { - return - } - guard let url = urlCoded as? URL else { - return - } - self?.url = url - return - }) - } - - // Reddit in particular doesn't pass the URL correctly and instead puts it in the contentText - url = URL(string: contentText) + updateUI() + resolveURL() } - override func isContentValid() -> Bool { - return url != nil && selectedContainer != nil + // MARK: - Actions + + @objc func cancel(_ sender: Any?) { + extensionContext?.cancelRequest(withError: CocoaError(.userCancelled)) } - override func didSelectPost() { + @objc func addFeed(_ sender: Any?) { guard let url, let selectedContainer, let containerID = selectedContainer.containerID else { - self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) + extensionContext?.completeRequest(returningItems: [], completionHandler: nil) return } - var name: String? - if !contentText.mayBeURL { - name = contentText.isEmpty ? nil : contentText - } + let trimmedName = nameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) + let name = (trimmedName?.isEmpty ?? true) ? nil : trimmedName let request = ExtensionFeedAddRequest(name: name, feedURL: url, destinationContainerID: containerID) ExtensionFeedAddRequestFile.save(request) - self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) + extensionContext?.completeRequest(returningItems: [], completionHandler: nil) } + // MARK: - ShareFolderPickerControllerDelegate + func shareFolderPickerDidSelect(_ container: ExtensionContainer) { ShareDefaultContainer.saveDefaultContainer(container) - self.selectedContainer = container - updateFolderItemValue() - self.popConfigurationViewController() + selectedContainer = container + updateUI() + navigationController?.popViewController(animated: true) } - override func configurationItems() -> [Any]! { - // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. - guard let urlItem = SLComposeSheetConfigurationItem() else { return nil } - urlItem.title = "URL" - urlItem.value = url?.absoluteString ?? "" + // MARK: - Table view - folderItem = SLComposeSheetConfigurationItem() - folderItem.title = "Folder" - updateFolderItemValue() + override func numberOfSections(in tableView: UITableView) -> Int { + Section.allCases.count + } - folderItem.tapHandler = { + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 1 + } - let folderPickerController = ShareFolderPickerController() + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + if section == Section.urlDisplay.rawValue { + return "URL" + } + return nil + } - folderPickerController.navigationController?.title = NSLocalizedString("Folder", comment: "Folder") - folderPickerController.delegate = self - folderPickerController.containers = self.flattenedContainers - folderPickerController.selectedContainerID = self.selectedContainer?.containerID - - self.pushConfigurationViewController(folderPickerController) + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + switch Section(rawValue: indexPath.section) { + case .name: + return nameCell + case .folder: + let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) + var content = UIListContentConfiguration.valueCell() + content.text = "Folder" + content.secondaryText = folderValueText + cell.contentConfiguration = content + cell.accessoryType = .disclosureIndicator + return cell + case .urlDisplay, nil: + let cell = UITableViewCell(style: .default, reuseIdentifier: nil) + var content = cell.defaultContentConfiguration() + content.text = url?.absoluteString ?? "" + content.textProperties.color = .secondaryLabel + content.textProperties.numberOfLines = 0 + cell.contentConfiguration = content + cell.selectionStyle = .none + return cell + } + } + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + guard indexPath.section == Section.folder.rawValue else { + return } - return [folderItem!, urlItem] - + let folderPickerController = ShareFolderPickerController() + folderPickerController.title = "Folder" + folderPickerController.delegate = self + folderPickerController.containers = flattenedContainers + folderPickerController.selectedContainerID = selectedContainer?.containerID + navigationController?.pushViewController(folderPickerController, animated: true) } } -private extension ShareViewController { +private extension ShareAddFeedViewController { - func updateFolderItemValue() { + var folderValueText: String { if let account = selectedContainer as? ExtensionAccount { - self.folderItem.value = account.name - } else if let folder = selectedContainer as? ExtensionFolder { - self.folderItem.value = "\(folder.accountName) / \(folder.name)" + return account.name + } + if let folder = selectedContainer as? ExtensionFolder { + return "\(folder.accountName) / \(folder.name)" + } + return "" + } + + func makeNameCell() -> UITableViewCell { + let cell = UITableViewCell(style: .default, reuseIdentifier: nil) + cell.selectionStyle = .none + + nameTextField.placeholder = "Feed Name (Optional)" + nameTextField.font = .preferredFont(forTextStyle: .body) + nameTextField.adjustsFontForContentSizeCategory = true + nameTextField.clearButtonMode = .whileEditing + nameTextField.autocapitalizationType = .words + + nameTextField.translatesAutoresizingMaskIntoConstraints = false + cell.contentView.addSubview(nameTextField) + NSLayoutConstraint.activate([ + nameTextField.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor), + nameTextField.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor), + nameTextField.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 11), + nameTextField.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -11) + ]) + + return cell + } + + func updateUI() { + addFeedButton?.isEnabled = url != nil && selectedContainer != nil + if isViewLoaded { + tableView.reloadData() + } + } + + // Find the shared URL. It arrives as JavaScript preprocessing results (Safari), + // a URL item, or plain text that may be a URL. + func resolveURL() { + let inputItems = extensionContext?.inputItems as? [NSExtensionItem] ?? [] + let providers = inputItems.compactMap(\.attachments).flatMap { $0 } + + Task { [weak self] in + if let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.propertyList.identifier) }) { + let item = try? await provider.loadItem(forTypeIdentifier: UTType.propertyList.identifier) + let results = (item as? NSDictionary)?["NSExtensionJavaScriptPreprocessingResultsKey"] as? NSDictionary + if let urlString = results?["url"] as? String { + self?.url = URL(string: urlString) + return + } + } + + if let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.url.identifier) }) { + let item = try? await provider.loadItem(forTypeIdentifier: UTType.url.identifier) + if let url = item as? URL { + self?.url = url + return + } + } + + if let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) }) { + let item = try? await provider.loadItem(forTypeIdentifier: UTType.plainText.identifier) + if let text = item as? String { + self?.url = URL(string: text) + } + } } } } diff --git a/iOS/UIKit Extensions/UIActivityViewController+Extras.swift b/iOS/UIKit Extensions/UIActivityViewController+Extras.swift index 5a1931516..09f92dbfc 100644 --- a/iOS/UIKit Extensions/UIActivityViewController+Extras.swift +++ b/iOS/UIKit Extensions/UIActivityViewController+Extras.swift @@ -16,7 +16,10 @@ public extension UIActivityViewController { let itemSource = ArticleActivityItemSource(url: url, subject: title) let titleSource = TitleActivityItemSource(title: title) - self.init(activityItems: [titleSource, itemSource], applicationActivities: applicationActivities) + // URL source first so the shared item Shortcuts (and other consumers) sees is the article URL. + // The title source returns NSNull for everything except a few apps, so it must not be first. + // <https://github.com/Ranchero-Software/NetNewsWire/issues/5167> + self.init(activityItems: [itemSource, titleSource], applicationActivities: applicationActivities) } } diff --git a/iOS/UIKit Extensions/UIViewController+Extras.swift b/iOS/UIKit Extensions/UIViewController+Extras.swift index 72aec3e0c..6b8fa1c7e 100644 --- a/iOS/UIKit Extensions/UIViewController+Extras.swift +++ b/iOS/UIKit Extensions/UIViewController+Extras.swift @@ -15,46 +15,11 @@ extension UIViewController { func presentError(_ error: Error, dismiss: (() -> Void)? = nil) { if let accountError = error as? AccountError, accountError.isCredentialsError { presentAccountError(accountError, dismiss: dismiss) - } else if let decodingError = error as? DecodingError { - let errorTitle = NSLocalizedString("Error", comment: "Error") - var informativeText: String = "" - 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 - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - 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 - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - 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 - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - case .dataCorrupted(let context): - guard let error = context.underlyingError as NSError?, - let debugDescription = error.userInfo["NSDebugDescription"] as? String else { - informativeText = error.localizedDescription - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - return - } - 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 - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - - default: - informativeText = error.localizedDescription - presentError(title: errorTitle, message: informativeText, dismiss: dismiss) - } + } else if let recoverableError = error as? (RecoverableError & LocalizedError), !recoverableError.recoveryOptions.isEmpty { + presentErrorWithRecovery(error: recoverableError, dismiss: dismiss) } else { - // Check if error supports recovery options - if let recoverableError = error as? (RecoverableError & LocalizedError), - !recoverableError.recoveryOptions.isEmpty { - presentErrorWithRecovery(error: recoverableError, dismiss: dismiss) - } else { - let errorTitle = NSLocalizedString("Error", comment: "Error") - presentError(title: errorTitle, message: error.localizedDescription, dismiss: dismiss) - } + let errorTitle = NSLocalizedString("Error", comment: "Error") + presentError(title: errorTitle, message: error.localizedDescription, dismiss: dismiss) } } diff --git a/xcconfig/NetNewsWire_iOSintentextension_target.xcconfig b/xcconfig/NetNewsWire_iOSintentextension_target.xcconfig deleted file mode 100644 index 509c30776..000000000 --- a/xcconfig/NetNewsWire_iOSintentextension_target.xcconfig +++ /dev/null @@ -1,4 +0,0 @@ -#include "./common/NetNewsWire_iOSextension_common.xcconfig" -CODE_SIGN_ENTITLEMENTS = iOS/IntentsExtension/NetNewsWire_iOS_IntentsExtension.entitlements -INFOPLIST_FILE = iOS/IntentsExtension/Info.plist -PRODUCT_BUNDLE_IDENTIFIER = $(ORGANIZATION_IDENTIFIER).NetNewsWire.iOS$(BUNDLE_ID_SUFFIX).IntentsExtension diff --git a/xcconfig/common/NetNewsWire_mac_target_common.xcconfig b/xcconfig/common/NetNewsWire_mac_target_common.xcconfig index 67abe7034..f3d6ee4cb 100644 --- a/xcconfig/common/NetNewsWire_mac_target_common.xcconfig +++ b/xcconfig/common/NetNewsWire_mac_target_common.xcconfig @@ -1,7 +1,7 @@ #include "./NetNewsWire_version.xcconfig" // High Level Settings common to both the Mac application and any extensions we bundle with it -MARKETING_VERSION = 7.1.2 +MARKETING_VERSION = 7.1.3b1 APP_GROUP_ID = group.$(ORGANIZATION_IDENTIFIER).NetNewsWire-Evergreen$(APP_GROUP_SUFFIX) diff --git a/xcconfig/common/NetNewsWire_version.xcconfig b/xcconfig/common/NetNewsWire_version.xcconfig index 490b78d16..bda8af627 100644 --- a/xcconfig/common/NetNewsWire_version.xcconfig +++ b/xcconfig/common/NetNewsWire_version.xcconfig @@ -1 +1 @@ -CURRENT_PROJECT_VERSION = 7113 +CURRENT_PROJECT_VERSION = 7200