diff --git a/Intents/AddWebFeedIntentHandler.swift b/Intents/AddWebFeedIntentHandler.swift index fb0711fdb..595d275c5 100644 --- a/Intents/AddWebFeedIntentHandler.swift +++ b/Intents/AddWebFeedIntentHandler.swift @@ -9,16 +9,16 @@ import Intents public enum AddWebFeedIntentHandlerError: LocalizedError { - + 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 { @@ -26,7 +26,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { override init() { super.init() } - + public func resolveUrl(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedUrlResolutionResult) -> Void) { guard let url = intent.url else { completion(.unsupported(forReason: .required)) @@ -34,7 +34,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { } completion(.success(with: url)) } - + public func provideAccountNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { guard let extensionContainers = ExtensionContainersFile.read() else { completion(nil, AddWebFeedIntentHandlerError.communicationFailure) @@ -44,7 +44,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { let accountNames = extensionContainers.accounts.map { $0.name } completion(accountNames, nil) } - + public func resolveAccountName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedAccountNameResolutionResult) -> Void) { guard let accountName = intent.accountName else { completion(AddWebFeedAccountNameResolutionResult.notRequired()) @@ -62,7 +62,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { completion(.success(with: accountName)) } } - + public func provideFolderNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { guard let extensionContainers = ExtensionContainersFile.read() else { completion(nil, AddWebFeedIntentHandlerError.communicationFailure) @@ -77,13 +77,13 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { let folderNames = account.folders.map { $0.name } completion(folderNames, nil) } - + public func resolveFolderName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedFolderNameResolutionResult) -> Void) { guard let accountName = intent.accountName, let folderName = intent.folderName else { completion(AddWebFeedFolderNameResolutionResult.notRequired()) return } - + guard let extensionContainers = ExtensionContainersFile.read() else { completion(.unsupported(forReason: .communication)) return @@ -93,7 +93,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { completion(.unsupported(forReason: .invalid)) return } - + if account.findFolder(forName: folderName) == nil { completion(.unsupported(forReason: .invalid)) } else { @@ -102,13 +102,13 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { return } - + public func handle(intent: AddWebFeedIntent, completion: @escaping (AddWebFeedIntentResponse) -> Void) { guard let url = intent.url, let extensionContainers = ExtensionContainersFile.read() else { completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) return } - + let account: ExtensionAccount? = { if let accountName = intent.accountName { return extensionContainers.findAccount(forName: accountName) @@ -139,5 +139,5 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { ExtensionFeedAddRequestFile.save(request) completion(AddWebFeedIntentResponse(code: .success, userActivity: nil)) } - + } diff --git a/Mac/About/AboutWindowController.swift b/Mac/About/AboutWindowController.swift index 64a4a61cc..3262fd379 100644 --- a/Mac/About/AboutWindowController.swift +++ b/Mac/About/AboutWindowController.swift @@ -9,7 +9,7 @@ import Cocoa class AboutWindowController: NSWindowController { - + @IBOutlet weak var appIconImageView: NSImageView! @IBOutlet weak var appTitleLabel: NSTextField! @IBOutlet weak var versionLabel: NSTextField! @@ -22,7 +22,7 @@ class AboutWindowController: NSWindowController { configureWindow() updateUI() } - + func configureWindow() { window?.isOpaque = false window?.backgroundColor = .clear @@ -36,22 +36,22 @@ class AboutWindowController: NSWindowController { contentView.addSubview(visualEffectView, positioned: .below, relativeTo: nil) } } - + private func updateUI() { - + // App Icon appIconImageView.image = NSApp.applicationIconImage - + // Version let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown" let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown" let versionString = "Version \(version) (Build \(build))" versionLabel.stringValue = versionString - + // Copyright let copyright = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? "Copyright © 2002-2025 Brent Simmons. All rights reserved." copyrightLabel.stringValue = copyright - + // Credits if let creditsURL = Bundle.main.url(forResource: "Credits", withExtension: "rtf"), let creditsData = try? Data(contentsOf: creditsURL), @@ -60,12 +60,12 @@ class AboutWindowController: NSWindowController { } else { creditsTextView.string = "Credits not available." } - + let fullRange = NSRange(location: 0, length: creditsTextView.string.utf16.count) let leadingParagraphStyle = NSMutableParagraphStyle() leadingParagraphStyle.alignment = .left creditsTextView.textStorage?.addAttribute(.paragraphStyle, value: leadingParagraphStyle, range: fullRange) - + // URL let url = URL(string: "https://inessential.com")! let attributedString = NSMutableAttributedString(string: "inessential.com") @@ -74,5 +74,5 @@ class AboutWindowController: NSWindowController { attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length)) websiteLabel.attributedStringValue = attributedString } - + } diff --git a/Mac/About/LinkLabel.swift b/Mac/About/LinkLabel.swift index 4f298175b..5f3459398 100644 --- a/Mac/About/LinkLabel.swift +++ b/Mac/About/LinkLabel.swift @@ -8,7 +8,7 @@ class LinkLabel: NSTextField { - + /// pièces de résistance -- keeping it a mac-assed mac app. override func resetCursorRects() { addCursorRect(bounds, cursor: .pointingHand) diff --git a/Mac/AppAssets.swift b/Mac/AppAssets.swift index eb7f24dbb..3e0ec7023 100644 --- a/Mac/AppAssets.swift +++ b/Mac/AppAssets.swift @@ -23,11 +23,11 @@ struct AppAssets { static var accountFeedbin: RSImage! = { return RSImage(named: "accountFeedbin") }() - + static var accountFeedly: RSImage! = { return RSImage(named: "accountFeedly") }() - + static var accountFreshRSS: RSImage! = { return RSImage(named: "accountFreshRSS") }() @@ -43,14 +43,14 @@ struct AppAssets { static var accountNewsBlur: RSImage! = { return RSImage(named: "accountNewsBlur") }() - + static var accountTheOldReader: RSImage! = { return RSImage(named: "accountTheOldReader") }() static let nnwFeedIcon = RSImage(named: "nnwFeedIcon")! - + static var addNewSidebarItemImage: RSImage = { return NSImage(systemSymbolName: "plus", accessibilityDescription: nil)! }() @@ -67,20 +67,20 @@ struct AppAssets { return RSImage(named: "articleExtractorOn")! }() - + static var articleTheme: RSImage = { return NSImage(systemSymbolName: "doc.richtext", accessibilityDescription: nil)! }() - + static var cleanUpImage: RSImage = { return NSImage(systemSymbolName: "bubbles.and.sparkles", accessibilityDescription: nil)! }() - + static var copyImage: RSImage = { return NSImage(systemSymbolName: "document.on.document", accessibilityDescription: nil)! }() - + static var deleteImage: RSImage = { return NSImage(systemSymbolName: "xmark.bin", accessibilityDescription: nil)! }() @@ -88,11 +88,11 @@ struct AppAssets { static var marsEditIcon: RSImage = { return RSImage(named: "MarsEditIcon")! }() - + static var microblogIcon: RSImage = { return RSImage(named: "MicroblogIcon")! }() - + static var faviconTemplateImage: RSImage = { return RSImage(named: "faviconTemplateImage")! }() @@ -112,67 +112,67 @@ struct AppAssets { static var iconDarkBackgroundColor: NSColor = { return NSColor(named: NSColor.Name("iconDarkBackgroundColor"))! }() - + static var legacyArticleExtractor: RSImage! = { return RSImage(named: "legacyArticleExtractor") }() - + static var legacyArticleExtractorError: RSImage! = { return RSImage(named: "legacyArticleExtractorError") }() - + static var legacyArticleExtractorInactiveDark: RSImage! = { return RSImage(named: "legacyArticleExtractorInactiveDark") }() - + static var legacyArticleExtractorInactiveLight: RSImage! = { return RSImage(named: "legacyArticleExtractorInactiveLight") }() - + static var legacyArticleExtractorProgress1: RSImage! = { return RSImage(named: "legacyArticleExtractorProgress1") }() - + static var legacyArticleExtractorProgress2: RSImage! = { return RSImage(named: "legacyArticleExtractorProgress2") }() - + static var legacyArticleExtractorProgress3: RSImage! = { return RSImage(named: "legacyArticleExtractorProgress3") }() - + static var legacyArticleExtractorProgress4: RSImage! = { return RSImage(named: "legacyArticleExtractorProgress4") }() - + static var mainFolderImage: IconImage { let image = NSImage(systemSymbolName: "folder", accessibilityDescription: nil)! let preferredColor = NSColor(named: "AccentColor")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: preferredColor.cgColor) } - + static var markAllAsReadMenuImage: RSImage = { let image = RSImage(named: "markAllAsRead") return image! }() - + static var markAllAsReadImage: RSImage = { let image = RSImage(named: "markAllAsRead") return image! }() - + static var markBelowAsReadImage: RSImage = { let image = RSImage(named: "markBelowAsRead") return image! }() - + static var markAboveAsReadImage: RSImage = { let image = RSImage(named: "markAboveAsRead") return image! }() - + static var nextUnreadImage: RSImage = { return NSImage(systemSymbolName: "chevron.down.circle", accessibilityDescription: nil)! }() @@ -180,7 +180,7 @@ struct AppAssets { static var notificationImage: RSImage = { return NSImage(systemSymbolName: "bell.badge", accessibilityDescription: nil)! }() - + static var openInBrowserImage: RSImage = { return NSImage(systemSymbolName: "safari", accessibilityDescription: nil)! }() @@ -188,58 +188,58 @@ struct AppAssets { static var preferencesToolbarAccountsImage: RSImage = { return NSImage(systemSymbolName: "at", accessibilityDescription: nil)! }() - + static var preferencesToolbarGeneralImage: RSImage = { return NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)! }() - + static var preferencesToolbarAdvancedImage: RSImage = { return NSImage(systemSymbolName: "gearshape.2", accessibilityDescription: nil)! }() - + static var readClosedImage: RSImage = { return NSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: nil)! }() - + static var readOpenImage: RSImage = { return NSImage(systemSymbolName: "circle", accessibilityDescription: nil)! }() - - + + static var refreshImage: RSImage = { return NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: nil)! }() - + static var renameImage: RSImage = { return NSImage(systemSymbolName: "pencil", accessibilityDescription: nil)! }() - + static var searchFeedImage: IconImage = { return IconImage(RSImage(named: NSImage.smartBadgeTemplateName)!, isSymbol: true, isBackgroundSuppressed: true) }() - - + + static var shareImage: RSImage = { return NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: nil)! }() - + static var sidebarToggleImage: RSImage = { return NSImage(systemSymbolName: "sidebar.left", accessibilityDescription: nil)! }() - - + + static var starClosedImage: RSImage = { return NSImage(systemSymbolName: "star.fill", accessibilityDescription: nil)! }() - + static var starOpenImage: RSImage = { return NSImage(systemSymbolName: "star", accessibilityDescription: nil)! }() - + static var starredFeedImage: IconImage = { let image = NSImage(systemSymbolName: "star.fill", accessibilityDescription: nil)! let preferredColor = NSColor(named: "StarColor")! @@ -249,7 +249,7 @@ struct AppAssets { static var timelineSeparatorColor: NSColor = { return NSColor(named: "timelineSeparatorColor")! }() - + static var timelineStarSelected: RSImage! = { return RSImage(named: "timelineStar")?.tinted(with: .white) }() @@ -285,11 +285,11 @@ struct AppAssets { static var swipeMarkUnstarredImage: RSImage = { return RSImage(systemSymbolName: "star", accessibilityDescription: "Unstar")! }() - + static var starColor: NSColor = { return NSColor(named: NSColor.Name("StarColor"))! }() - + static func image(for accountType: AccountType) -> NSImage? { switch accountType { case .onMyMac: @@ -312,5 +312,5 @@ struct AppAssets { return AppAssets.accountTheOldReader } } - + } diff --git a/Mac/AppDefaults.swift b/Mac/AppDefaults.swift index 973b45269..3bff00800 100644 --- a/Mac/AppDefaults.swift +++ b/Mac/AppDefaults.swift @@ -16,7 +16,7 @@ enum FontSize: Int { } final class AppDefaults { - + static let defaultThemeName = "Default" static let shared = AppDefaults() @@ -63,7 +63,7 @@ final class AppDefaults { } return false }() - + var isFirstRun: Bool = { if let _ = UserDefaults.standard.object(forKey: Key.firstRunDate) as? Date { return false @@ -101,7 +101,7 @@ final class AppDefaults { AppDefaults.setDate(for: Key.lastImageCacheFlushDate, newValue) } } - + var openInBrowserInBackground: Bool { get { return AppDefaults.bool(for: Key.openInBrowserInBackground) @@ -167,7 +167,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.addFeedAccountID, newValue) } } - + var addFeedFolderName: String? { get { return AppDefaults.string(for: Key.addFeedFolderName) @@ -185,7 +185,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.addFolderAccountID, newValue) } } - + var importOPMLAccountID: String? { get { return AppDefaults.string(for: Key.importOPMLAccountID) @@ -194,7 +194,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.importOPMLAccountID, newValue) } } - + var exportOPMLAccountID: String? { get { return AppDefaults.string(for: Key.exportOPMLAccountID) @@ -212,7 +212,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.defaultBrowserID, newValue) } } - + var currentThemeName: String? { get { return AppDefaults.string(for: Key.currentThemeName) @@ -221,7 +221,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.currentThemeName, newValue) } } - + var showTitleOnMainWindow: Bool { return AppDefaults.bool(for: Key.showTitleOnMainWindow) } @@ -256,7 +256,7 @@ final class AppDefaults { AppDefaults.setBool(for: Key.webInspectorEnabled, newValue) } } - + var webInspectorStartsAttached: Bool { get { return AppDefaults.bool(for: Key.webInspectorStartsAttached) @@ -274,7 +274,7 @@ final class AppDefaults { AppDefaults.setSortDirection(for: Key.timelineSortDirection, newValue) } } - + var timelineGroupByFeed: Bool { get { return AppDefaults.bool(for: Key.timelineGroupByFeed) @@ -283,7 +283,7 @@ final class AppDefaults { AppDefaults.setBool(for: Key.timelineGroupByFeed, newValue) } } - + var timelineShowsSeparators: Bool { return AppDefaults.bool(for: Key.timelineShowsSeparators) } @@ -391,19 +391,19 @@ private extension AppDefaults { // } // return FontSize(rawValue: rawFontSize)! } - + static func setFontSize(for key: String, _ fontSize: FontSize) { setInt(for: key, fontSize.rawValue) } - + static func string(for key: String) -> String? { return UserDefaults.standard.string(forKey: key) } - + static func setString(for key: String, _ value: String?) { UserDefaults.standard.set(value, forKey: key) } - + static func bool(for key: String) -> Bool { return UserDefaults.standard.bool(forKey: key) } @@ -415,11 +415,11 @@ private extension AppDefaults { static func int(for key: String) -> Int { return UserDefaults.standard.integer(forKey: key) } - + static func setInt(for key: String, _ x: Int) { UserDefaults.standard.set(x, forKey: key) } - + static func date(for key: String) -> Date? { return UserDefaults.standard.object(forKey: key) as? Date } diff --git a/Mac/Browser.swift b/Mac/Browser.swift index e2558667a..023092fc3 100644 --- a/Mac/Browser.swift +++ b/Mac/Browser.swift @@ -44,7 +44,7 @@ struct Browser { /// to open in the background. static func open(_ urlString: String, inBackground: Bool) { guard let url = URL(string: urlString), let preparedURL = url.preparedForOpeningInBrowser() else { return } - + let configuration = NSWorkspace.OpenConfiguration() configuration.requiresUniversalLinks = true configuration.promptsUserIfNeeded = false diff --git a/Mac/CrashReporter/CrashReporter.swift b/Mac/CrashReporter/CrashReporter.swift index 3228e8ff3..ba78f3e7f 100644 --- a/Mac/CrashReporter/CrashReporter.swift +++ b/Mac/CrashReporter/CrashReporter.swift @@ -41,7 +41,7 @@ struct CrashReporter { } else { runCrashReporterWindow(crashLogText) } - + crashReporter.purgePendingCrashReport() } diff --git a/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift b/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift index 3c6c7b908..309fc646b 100644 --- a/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift +++ b/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift @@ -12,7 +12,7 @@ final class BuiltinSmartFeedInspectorViewController: NSViewController, Inspector @IBOutlet var nameTextField: NSTextField? @IBOutlet weak var smartFeedImageView: NSImageView! - + private var smartFeed: PseudoFeed? { didSet { updateUI() diff --git a/Mac/Inspector/FeedInspectorViewController.swift b/Mac/Inspector/FeedInspectorViewController.swift index 1d5dafc2a..be9eab51e 100644 --- a/Mac/Inspector/FeedInspectorViewController.swift +++ b/Mac/Inspector/FeedInspectorViewController.swift @@ -19,7 +19,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { @IBOutlet weak var urlTextField: NSTextField? @IBOutlet weak var isNotifyAboutNewArticlesCheckBox: NSButton! @IBOutlet weak var isReaderViewAlwaysOnCheckBox: NSButton? - + private var feed: Feed? { didSet { if feed != oldValue { @@ -52,15 +52,15 @@ final class FeedInspectorViewController: NSViewController, Inspector { NotificationCenter.default.addObserver(self, selector: #selector(imageDidBecomeAvailable(_:)), name: .ImageDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: .DidUpdateFeedPreferencesFromContextMenu, object: nil) } - + override func viewDidAppear() { updateNotificationSettings() } - + override func viewDidDisappear() { renameFeedIfNecessary() } - + // MARK: Actions @IBAction func isNotifyAboutNewArticlesChanged(_ sender: Any) { guard userNotificationSettings != nil else { @@ -69,10 +69,10 @@ final class FeedInspectorViewController: NSViewController, Inspector { } return } - + UNUserNotificationCenter.current().getNotificationSettings { (settings) in self.updateNotificationSettings() - + if settings.authorizationStatus == .denied { DispatchQueue.main.async { self.isNotifyAboutNewArticlesCheckBox.setNextState() @@ -99,17 +99,17 @@ final class FeedInspectorViewController: NSViewController, Inspector { } } } - + @IBAction func isReaderViewAlwaysOnChanged(_ sender: Any) { feed?.isArticleExtractorAlwaysOn = (isReaderViewAlwaysOnCheckBox?.state ?? .off) == .on ? true : false } - + // MARK: Notifications @objc func imageDidBecomeAvailable(_ note: Notification) { updateImage() } - + } extension FeedInspectorViewController: NSTextFieldDelegate { @@ -117,7 +117,7 @@ extension FeedInspectorViewController: NSTextFieldDelegate { func controlTextDidEndEditing(_ note: Notification) { renameFeedIfNecessary() } - + } private extension FeedInspectorViewController { @@ -130,7 +130,7 @@ private extension FeedInspectorViewController { feed = singleFeed } - + @objc func updateUI() { updateImage() updateName() @@ -209,7 +209,7 @@ private extension FeedInspectorViewController { feed.nameForDisplay != nameTextField.stringValue else { return } - + account.renameFeed(feed, to: nameTextField.stringValue) { [weak self] result in if case .failure(let error) = result { self?.presentError(error) @@ -218,5 +218,5 @@ private extension FeedInspectorViewController { } } } - + } diff --git a/Mac/Inspector/FolderInspectorViewController.swift b/Mac/Inspector/FolderInspectorViewController.swift index 63f76b0d7..b88bf7732 100644 --- a/Mac/Inspector/FolderInspectorViewController.swift +++ b/Mac/Inspector/FolderInspectorViewController.swift @@ -14,7 +14,7 @@ final class FolderInspectorViewController: NSViewController, Inspector { @IBOutlet var nameTextField: NSTextField? @IBOutlet weak var folderImageView: NSImageView! - + private var folder: Folder? { didSet { if folder != oldValue { @@ -46,18 +46,18 @@ final class FolderInspectorViewController: NSViewController, Inspector { override func viewDidLoad() { updateUI() - + let image = NSImage(systemSymbolName: "folder", accessibilityDescription: nil)! folderImageView.image = image folderImageView.contentTintColor = NSColor.controlAccentColor - + NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) } override func viewDidDisappear() { renameFolderIfNecessary() } - + // MARK: Notifications @objc func displayNameDidChange(_ note: Notification) { @@ -73,7 +73,7 @@ extension FolderInspectorViewController: NSTextFieldDelegate { func controlTextDidEndEditing(_ obj: Notification) { renameFolderIfNecessary() } - + } private extension FolderInspectorViewController { @@ -104,7 +104,7 @@ private extension FolderInspectorViewController { } windowTitle = folder?.nameForDisplay ?? NSLocalizedString("Folder Inspector", comment: "Folder Inspector window title") } - + func renameFolderIfNecessary() { guard let folder = folder, let account = folder.account, @@ -112,7 +112,7 @@ private extension FolderInspectorViewController { folder.nameForDisplay != nameTextField.stringValue else { return } - + account.renameFolder(folder, to: nameTextField.stringValue) { [weak self] result in if case .failure(let error) = result { self?.presentError(error) @@ -121,5 +121,5 @@ private extension FolderInspectorViewController { } } } - + } diff --git a/Mac/Inspector/InspectorWindowController.swift b/Mac/Inspector/InspectorWindowController.swift index 2686f86c4..c8c5c4434 100644 --- a/Mac/Inspector/InspectorWindowController.swift +++ b/Mac/Inspector/InspectorWindowController.swift @@ -121,7 +121,7 @@ private extension InspectorWindowController { window.contentViewController = inspector window.makeFirstResponder(nil) } - + window.layoutIfNeeded() if let flippedOrigin = flippedOrigin { window.setFlippedOriginAdjustingForScreen(flippedOrigin) diff --git a/Mac/MainWindow/AddFeed/AddFeedController.swift b/Mac/MainWindow/AddFeed/AddFeedController.swift index b3b1f0200..5ed845738 100644 --- a/Mac/MainWindow/AddFeed/AddFeedController.swift +++ b/Mac/MainWindow/AddFeed/AddFeedController.swift @@ -28,7 +28,7 @@ final class AddFeedController: AddFeedWindowControllerDelegate { private var addFeedWindowController: AddFeedWindowController? private var foundFeedURLString: String? private var titleFromFeed: String? - + init(hostWindow: NSWindow) { self.hostWindow = hostWindow } @@ -63,11 +63,11 @@ final class AddFeedController: AddFeedWindowControllerDelegate { } account.createFeed(url: url.absoluteString, name: title, container: container, validateFeed: true) { result in - + DispatchQueue.main.async { self.endShowingProgress() } - + switch result { case .success(let feed): NotificationCenter.default.post(name: .UserDidAddFeed, object: self, userInfo: [UserInfoKey.feed: feed]) @@ -83,9 +83,9 @@ final class AddFeedController: AddFeedWindowControllerDelegate { } } } - + } - + beginShowingProgress() } @@ -103,7 +103,7 @@ private extension AddFeedController { } return nil } - + struct AccountAndFolderSpecifier { let account: Account let folder: Folder? @@ -159,11 +159,11 @@ private extension AddFeedController { func beginShowingProgress() { runIndeterminateProgressWithMessage(NSLocalizedString("Finding feed…", comment:"Feed finder")) } - + func endShowingProgress() { stopIndeterminateProgress() hostWindow.makeKeyAndOrderFront(self) } - + } diff --git a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift index 75446789c..9ea239ce0 100644 --- a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift +++ b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift @@ -40,7 +40,7 @@ final class AddFeedWindowController : NSWindowController { } return s } - + var hostWindow: NSWindow! convenience init(urlString: String?, name: String?, account: Account?, folder: Folder?, folderTreeController: TreeController, delegate: AddFeedWindowControllerDelegate?) { @@ -52,7 +52,7 @@ final class AddFeedWindowController : NSWindowController { self.delegate = delegate self.folderTreeController = folderTreeController } - + func runSheetOnWindow(_ hostWindow: NSWindow) { guard let window else { return @@ -70,7 +70,7 @@ final class AddFeedWindowController : NSWindowController { } folderPopupButton.menu = FolderTreeMenu.createFolderPopupMenu(with: folderTreeController.rootNode) - + if let account = initialAccount { FolderTreeMenu.select(account: account, folder: initialFolder, in: folderPopupButton) } else if let container = AddFeedDefaultContainer.defaultContainer { @@ -82,16 +82,16 @@ final class AddFeedWindowController : NSWindowController { } } } - + updateUI() } // MARK: Actions - + @IBAction func cancel(_ sender: Any?) { cancelSheet() } - + @IBAction func addFeed(_ sender: Any?) { let urlString = urlTextField.stringValue let normalizedURLString = urlString.normalizedURL @@ -104,19 +104,19 @@ final class AddFeedWindowController : NSWindowController { cancelSheet() return } - + guard let container = selectedContainer() else { return } AddFeedDefaultContainer.saveDefaultContainer(container) delegate?.addFeedWindowController(self, userEnteredURL: url, userEnteredTitle: userEnteredTitle, container: container) - + } @IBAction func localShowFeedList(_ sender: Any?) { NSApplication.shared.sendAction(NSSelectorFromString("showFeedList:"), to: nil, from: sender) hostWindow.endSheet(window!, returnCode: NSApplication.ModalResponse.continue) } - + // MARK: NSTextFieldDelegate @objc func controlTextDidEndEditing(_ obj: Notification) { @@ -129,7 +129,7 @@ final class AddFeedWindowController : NSWindowController { } private extension AddFeedWindowController { - + private func updateUI() { addButton.isEnabled = urlTextField.stringValue.mayBeURL && selectedContainer() != nil } diff --git a/Mac/MainWindow/AddFeed/FolderTreeMenu.swift b/Mac/MainWindow/AddFeed/FolderTreeMenu.swift index 7d21dc790..c18ff05bc 100644 --- a/Mac/MainWindow/AddFeed/FolderTreeMenu.swift +++ b/Mac/MainWindow/AddFeed/FolderTreeMenu.swift @@ -14,34 +14,34 @@ import Account final class FolderTreeMenu { static func createFolderPopupMenu(with rootNode: Node, restrictToSpecialAccounts: Bool = false) -> NSMenu { - + let menu = NSMenu(title: "Folders") menu.autoenablesItems = false - + for childNode in rootNode.childNodes { - + guard let account = childNode.representedObject as? Account else { continue } - + if restrictToSpecialAccounts && !(account.type == .onMyMac || account.type == .cloudKit) { continue } - + let menuItem = NSMenuItem(title: account.nameForDisplay, action: nil, keyEquivalent: "") menuItem.representedObject = childNode.representedObject - + if account.behaviors.contains(.disallowFeedInRootFolder) { menuItem.isEnabled = false } - + menu.addItem(menuItem) let childNodes = childNode.childNodes addFolderItemsToMenuWithNodes(menu: menu, nodes: childNodes, indentationLevel: 1) - + } - + return menu } @@ -61,21 +61,21 @@ final class FolderTreeMenu { } private static func addFolderItemsToMenuWithNodes(menu: NSMenu, nodes: [Node], indentationLevel: Int) { - + nodes.forEach { (oneNode) in - + if let nameProvider = oneNode.representedObject as? DisplayNameProvider { - + let menuItem = NSMenuItem(title: nameProvider.nameForDisplay, action: nil, keyEquivalent: "") menuItem.indentationLevel = indentationLevel menuItem.representedObject = oneNode.representedObject menu.addItem(menuItem) - + if oneNode.numberOfChildNodes > 0 { addFolderItemsToMenuWithNodes(menu: menu, nodes: oneNode.childNodes, indentationLevel: indentationLevel + 1) } } } } - + } diff --git a/Mac/MainWindow/AddFolder/AddFolderWindowController.swift b/Mac/MainWindow/AddFolder/AddFolderWindowController.swift index 36f2e0d5e..b77581ea5 100644 --- a/Mac/MainWindow/AddFolder/AddFolderWindowController.swift +++ b/Mac/MainWindow/AddFolder/AddFolderWindowController.swift @@ -11,7 +11,7 @@ import Articles import Account final class AddFolderWindowController : NSWindowController { - + @IBOutlet var folderNameTextField: NSTextField! @IBOutlet var accountPopupButton: NSPopUpButton! @IBOutlet var addFolderButton: NSButton! @@ -22,7 +22,7 @@ final class AddFolderWindowController : NSWindowController { } // MARK: - API - + func runSheetOnWindow(_ hostWindow: NSWindow) { guard let window else { return @@ -37,33 +37,33 @@ final class AddFolderWindowController : NSWindowController { } // MARK: - NSViewController - + override func windowDidLoad() { let preferredAccountID = AppDefaults.shared.addFolderAccountID accountPopupButton.removeAllItems() - + let menu = NSMenu() accountPopupButton.menu = menu - + let accounts = AccountManager.shared .sortedActiveAccounts .filter { !$0.behaviors.contains(.disallowFolderManagement) } - + for oneAccount in accounts { - + let oneMenuItem = NSMenuItem() oneMenuItem.title = oneAccount.nameForDisplay oneMenuItem.representedObject = oneAccount menu.addItem(oneMenuItem) - + if oneAccount.accountID == preferredAccountID { accountPopupButton.select(oneMenuItem) } } } - + // MARK: - Actions - + @IBAction func cancel(_ sender: Any?) { guard let hostWindow, let window else { return @@ -71,7 +71,7 @@ final class AddFolderWindowController : NSWindowController { hostWindow.endSheet(window, returnCode: .cancel) self.hostWindow = nil } - + @IBAction func addFolder(_ sender: Any?) { guard let hostWindow, let window else { return diff --git a/Mac/MainWindow/ArticleExtractorButton.swift b/Mac/MainWindow/ArticleExtractorButton.swift index d0887d0e0..28396f48f 100644 --- a/Mac/MainWindow/ArticleExtractorButton.swift +++ b/Mac/MainWindow/ArticleExtractorButton.swift @@ -16,9 +16,9 @@ enum ArticleExtractorButtonState { } final class ArticleExtractorButton: NSButton { - + private var animatedLayer: CALayer? - + var buttonState: ArticleExtractorButtonState = .off { didSet { if buttonState != oldValue { @@ -39,7 +39,7 @@ final class ArticleExtractorButton: NSButton { } } } - + override func accessibilityLabel() -> String? { switch buttonState { case .error: @@ -57,12 +57,12 @@ final class ArticleExtractorButton: NSButton { super.init(frame: frameRect) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } - + private func commonInit() { wantsLayer = true bezelStyle = .texturedRounded @@ -70,7 +70,7 @@ final class ArticleExtractorButton: NSButton { imageScaling = .scaleProportionallyDown widthAnchor.constraint(equalTo: heightAnchor).isActive = true } - + override func layout() { super.layout() guard case .animated = buttonState else { @@ -79,31 +79,31 @@ final class ArticleExtractorButton: NSButton { stripAnimatedSublayer() addAnimatedSublayer(to: layer!) } - + private func stripAnimatedSublayer() { animatedLayer?.removeFromSuperlayer() } - + private func addAnimatedSublayer(to hostedLayer: CALayer) { let image1 = AppAssets.articleExtractorOff.tinted(with: NSColor.controlTextColor) let image2 = AppAssets.articleExtractorOn.tinted(with: NSColor.controlTextColor) let images = [image1, image2, image1] - + animatedLayer = CALayer() let imageSize = AppAssets.articleExtractorOff.size animatedLayer!.bounds = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height) animatedLayer!.position = CGPoint(x: bounds.midX, y: bounds.midY) - + hostedLayer.addSublayer(animatedLayer!) - + let animation = CAKeyframeAnimation(keyPath: "contents") animation.calculationMode = CAAnimationCalculationMode.linear animation.keyTimes = [0, 0.5, 1] animation.duration = 2 animation.values = images animation.repeatCount = HUGE - + animatedLayer!.add(animation, forKey: "contents") } - + } diff --git a/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift b/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift index 334605cbe..2bb7ed356 100644 --- a/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift +++ b/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift @@ -11,9 +11,9 @@ import WebKit import Articles final class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler { - + var currentArticle: Article? - + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { guard let responseURL = urlSchemeTask.request.url, let iconImage = self.currentArticle?.iconImage() else { @@ -24,12 +24,12 @@ final class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler { let iconView = IconView(frame: CGRect(x: 0, y: 0, width: 48, height: 48)) iconView.iconImage = iconImage let renderedImage = iconView.asImage() - + guard let data = renderedImage.dataRepresentation() else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)) return } - + let headerFields = ["Cache-Control": "no-cache"] if let response = HTTPURLResponse(url: responseURL, statusCode: 200, httpVersion: nil, headerFields: headerFields) { urlSchemeTask.didReceive(response) @@ -38,9 +38,9 @@ final class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler { } } - + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { urlSchemeTask.didFailWithError(URLError(.unknown)) } - + } diff --git a/Mac/MainWindow/Detail/DetailStatusBarView.swift b/Mac/MainWindow/Detail/DetailStatusBarView.swift index eea5f72d2..db550f430 100644 --- a/Mac/MainWindow/Detail/DetailStatusBarView.swift +++ b/Mac/MainWindow/Detail/DetailStatusBarView.swift @@ -38,7 +38,7 @@ final class DetailStatusBarView: NSView { override var isOpaque: Bool { return false } - + override var isFlipped: Bool { return true } diff --git a/Mac/MainWindow/Detail/DetailViewController.swift b/Mac/MainWindow/Detail/DetailViewController.swift index 236047f03..36ce8c8a2 100644 --- a/Mac/MainWindow/Detail/DetailViewController.swift +++ b/Mac/MainWindow/Detail/DetailViewController.swift @@ -31,7 +31,7 @@ final class DetailViewController: NSViewController, WKUIDelegate { var windowState: DetailWindowState { currentWebViewController.windowState } - + private var currentWebViewController: DetailWebViewController! { didSet { let webview = currentWebViewController.view @@ -86,7 +86,7 @@ final class DetailViewController: NSViewController, WKUIDelegate { func stopMediaPlayback() { currentWebViewController.stopMediaPlayback() } - + func canScrollDown(_ callback: @escaping (Bool) -> Void) { currentWebViewController.canScrollDown(callback) } @@ -102,9 +102,9 @@ final class DetailViewController: NSViewController, WKUIDelegate { override func scrollPageUp(_ sender: Any?) { currentWebViewController.scrollPageUp(sender) } - + // MARK: - Navigation - + func focus() { guard let window = currentWebViewController.webView.window else { return diff --git a/Mac/MainWindow/Detail/DetailWebView.swift b/Mac/MainWindow/Detail/DetailWebView.swift index 6c8ae9219..58922083f 100644 --- a/Mac/MainWindow/Detail/DetailWebView.swift +++ b/Mac/MainWindow/Detail/DetailWebView.swift @@ -13,13 +13,13 @@ import RSCore final class DetailWebView: WKWebView { weak var keyboardDelegate: KeyboardDelegate? - + override func accessibilityLabel() -> String? { return NSLocalizedString("Article", comment: "Article") } // MARK: - NSResponder - + override func keyDown(with event: NSEvent) { if keyboardDelegate?.keydown(event, in: self) ?? false { return diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index f314f5172..bc1ddce00 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -34,11 +34,11 @@ final class DetailWebViewController: NSViewController { } } } - + var windowState: DetailWindowState { DetailWindowState(isShowingExtractedArticle: isShowingExtractedArticle, windowScrollY: windowScrollY ?? 0) } - + var article: Article? { switch state { case .article(let article, _): @@ -49,7 +49,7 @@ final class DetailWebViewController: NSViewController { return nil } } - + private var articleTextSize = AppDefaults.shared.articleTextSize private var webInspectorEnabled: Bool { @@ -118,7 +118,7 @@ final class DetailWebViewController: NSViewController { } // MARK: Notifications - + @objc func feedIconDidBecomeAvailable(_ note: Notification) { reloadArticleImage() } @@ -130,24 +130,24 @@ final class DetailWebViewController: NSViewController { @objc func faviconDidBecomeAvailable(_ note: Notification) { reloadArticleImage() } - + @objc func userDefaultsDidChange(_ note: Notification) { if articleTextSize != AppDefaults.shared.articleTextSize { articleTextSize = AppDefaults.shared.articleTextSize reloadHTMLMaintainingScrollPosition() } } - + @objc func currentArticleThemeDidChangeNotification(_ note: Notification) { reloadHTMLMaintainingScrollPosition() } - + // MARK: Media Functions - + func stopMediaPlayback() { webView.evaluateJavaScript("stopMediaPlayback();") } - + // MARK: Scrolling func canScrollDown(_ completion: @escaping (Bool) -> Void) { @@ -236,7 +236,7 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate { } // WKUIDelegate - + func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // This method is reached when WebKit handles a JavaScript based window.open() invocation, for example. One // example where this is used is in YouTube's embedded video player when a user clicks on the video's title @@ -256,16 +256,16 @@ private extension DetailWebViewController { func reloadArticleImage() { guard let article = article else { return } - + var components = URLComponents() components.scheme = ArticleRenderer.imageIconScheme components.path = article.articleID - + if let imageSrc = components.string { webView?.evaluateJavaScript("reloadArticleImage(\"\(imageSrc)\")") } } - + func reloadHTMLMaintainingScrollPosition() { fetchScrollInfo() { scrollInfo in self.windowScrollY = scrollInfo?.offsetY @@ -275,7 +275,7 @@ private extension DetailWebViewController { func reloadHTML() { delegate?.mouseDidExit(self) - + let theme = ArticleThemesManager.shared.currentTheme let rendering: ArticleRenderer.Rendering @@ -293,14 +293,14 @@ private extension DetailWebViewController { detailIconSchemeHandler.currentArticle = article rendering = ArticleRenderer.articleHTML(article: article, extractedArticle: extractedArticle, theme: theme) } - + let substitutions = [ "title": rendering.title, "baseURL": rendering.baseURL, "style": rendering.style, "body": rendering.html ] - + var html = try! MacroProcessor.renderedText(withTemplate: ArticleRenderer.page.html, substitutions: substitutions) html = ArticleRenderingSpecialCases.filterHTMLIfNeeded(baseURL: rendering.baseURL, html: html) webView.loadHTMLString(html, baseURL: URL(string: rendering.baseURL)) diff --git a/Mac/MainWindow/Detail/DetailWindowState.swift b/Mac/MainWindow/Detail/DetailWindowState.swift index f277c2c33..775524d7f 100644 --- a/Mac/MainWindow/Detail/DetailWindowState.swift +++ b/Mac/MainWindow/Detail/DetailWindowState.swift @@ -9,12 +9,12 @@ import Foundation final class DetailWindowState: NSObject, NSSecureCoding { - + static let supportsSecureCoding = true let isShowingExtractedArticle: Bool let windowScrollY: CGFloat - + init(isShowingExtractedArticle: Bool, windowScrollY: CGFloat) { self.isShowingExtractedArticle = isShowingExtractedArticle self.windowScrollY = windowScrollY @@ -29,7 +29,7 @@ final class DetailWindowState: NSObject, NSSecureCoding { isShowingExtractedArticle = coder.decodeBool(forKey: Key.isShowingExtractedArticle) windowScrollY = CGFloat(coder.decodeDouble(forKey: Key.windowScrollY)) } - + func encode(with coder: NSCoder) { coder.encode(isShowingExtractedArticle, forKey: Key.isShowingExtractedArticle) coder.encode(Double(windowScrollY), forKey: Key.windowScrollY) diff --git a/Mac/MainWindow/IconView.swift b/Mac/MainWindow/IconView.swift index e4dad50ce..578b8128c 100644 --- a/Mac/MainWindow/IconView.swift +++ b/Mac/MainWindow/IconView.swift @@ -39,7 +39,7 @@ final class IconView: NSView { } private var isDiscernable = true - + override var isFlipped: Bool { return true } @@ -108,7 +108,7 @@ private extension IconView { guard !(iconImage?.isSymbol ?? false) else { return NSMakeRect(0.0, 0.0, bounds.size.width, bounds.size.height) } - + guard let image = iconImage?.image else { return NSRect.zero } diff --git a/Mac/MainWindow/LegacyArticleExtractorButton.swift b/Mac/MainWindow/LegacyArticleExtractorButton.swift index d6c2bbad6..aa2bbdeba 100644 --- a/Mac/MainWindow/LegacyArticleExtractorButton.swift +++ b/Mac/MainWindow/LegacyArticleExtractorButton.swift @@ -9,7 +9,7 @@ import Foundation final class LegacyArticleExtractorButton: NSButton { - + var isError = false { didSet { if isError != oldValue { @@ -17,7 +17,7 @@ final class LegacyArticleExtractorButton: NSButton { } } } - + var isInProgress = false { didSet { if isInProgress != oldValue { @@ -25,12 +25,12 @@ final class LegacyArticleExtractorButton: NSButton { } } } - + override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true } - + required init?(coder: NSCoder) { super.init(coder: coder) wantsLayer = true @@ -38,7 +38,7 @@ final class LegacyArticleExtractorButton: NSButton { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) - + guard let hostedLayer = self.layer else { return } @@ -52,7 +52,7 @@ final class LegacyArticleExtractorButton: NSButton { } let opacity: Float = isEnabled ? 1.0 : 0.5 - + switch true { case isError: addImageSublayer(to: hostedLayer, image: AppAssets.legacyArticleExtractorError, opacity: opacity) @@ -70,42 +70,42 @@ final class LegacyArticleExtractorButton: NSButton { } } } - + private func makeLayerForImage(_ image: NSImage) -> CALayer { let imageLayer = CALayer() imageLayer.bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) imageLayer.position = CGPoint(x: bounds.midX, y: floor(bounds.midY)) return imageLayer } - + private func addImageSublayer(to hostedLayer: CALayer, image: NSImage, opacity: Float = 1.0) { let imageLayer = makeLayerForImage(image) imageLayer.contents = image imageLayer.opacity = opacity hostedLayer.addSublayer(imageLayer) } - + private func addAnimatedSublayer(to hostedLayer: CALayer) { let imageProgress1 = AppAssets.legacyArticleExtractorProgress1 let imageProgress2 = AppAssets.legacyArticleExtractorProgress2 let imageProgress3 = AppAssets.legacyArticleExtractorProgress3 let imageProgress4 = AppAssets.legacyArticleExtractorProgress4 let images = [imageProgress1, imageProgress2, imageProgress3, imageProgress4, imageProgress3, imageProgress2, imageProgress1] - + let imageLayer = CALayer() imageLayer.bounds = CGRect(x: 0, y: 0, width: imageProgress1?.size.width ?? 0, height: imageProgress1?.size.height ?? 0) imageLayer.position = CGPoint(x: bounds.midX, y: floor(bounds.midY)) - + hostedLayer.addSublayer(imageLayer) - + let animation = CAKeyframeAnimation(keyPath: "contents") animation.calculationMode = CAAnimationCalculationMode.linear animation.keyTimes = [0, 0.16, 0.32, 0.50, 0.66, 0.82, 1] animation.duration = 2 animation.values = images as [Any] animation.repeatCount = HUGE - + imageLayer.add(animation, forKey: "contents") } - + } diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift index 1a5c99bd9..f84b78b8a 100644 --- a/Mac/MainWindow/MainWindowController.swift +++ b/Mac/MainWindow/MainWindowController.swift @@ -19,7 +19,7 @@ enum TimelineSourceMode { final class MainWindowController : NSWindowController, NSUserInterfaceValidations { @IBOutlet weak var articleThemePopUpButton: NSPopUpButton? - + private var activityManager = ActivityManager() private var isShowingExtractedArticle = false @@ -36,7 +36,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation } return selectedObjects.first } - + private var shareToolbarItem: NSToolbarItem? { return window?.toolbar?.existingItem(withIdentifier: .share) } @@ -100,10 +100,10 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) - + NotificationCenter.default.addObserver(self, selector: #selector(articleThemeNamesDidChangeNotification(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(currentArticleThemeDidChangeNotification(_:)), name: .CurrentArticleThemeDidChangeNotification, object: nil) - + DispatchQueue.main.async { self.updateWindowTitle() } @@ -135,7 +135,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation AppDefaults.shared.secureWindowState = data window?.saveFrame(usingName: windowAutosaveName) } - + func restoreStateFromUserDefaults() { if let data = AppDefaults.shared.secureWindowState, let state = try? NSKeyedUnarchiver.unarchivedObject(ofClass: MainWindowState.self, from: data) { @@ -158,7 +158,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation @objc func unreadCountDidChange(_ note: Notification) { updateWindowTitleIfNecessary(note.object) } - + @objc func displayNameDidChange(_ note: Notification) { updateWindowTitleIfNecessary(note.object) } @@ -172,21 +172,21 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation } private func updateWindowTitleIfNecessary(_ noteObject: Any?) { - + if let folder = currentFeedOrFolder as? Folder, let noteObject = noteObject as? Folder { if folder == noteObject { updateWindowTitle() return } } - + if let feed = currentFeedOrFolder as? Feed, let noteObject = noteObject as? Feed { if feed == noteObject { updateWindowTitle() return } } - + // If we don't recognize the changed object, we will test it for identity instead // of equality. This works well for us if the window title is displaying a // PsuedoFeed object. @@ -195,28 +195,28 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation updateWindowTitle() } } - + } // MARK: - Toolbar - + @objc func makeToolbarValidate() { - + window?.toolbar?.validateVisibleItems() } // MARK: - NSUserInterfaceValidations - + public func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { - + if item.action == #selector(copyArticleURL(_:)) { return canCopyArticleURL() } - + if item.action == #selector(copyExternalURL(_:)) { return canCopyExternalURL() } - + if item.action == #selector(openArticleInBrowser(_:)) { if let item = item as? NSMenuItem, item.keyEquivalentModifierMask.contains(.shift) { item.title = Browser.titleForOpenInBrowserInverted @@ -224,11 +224,11 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation return currentLink != nil } - + if item.action == #selector(nextUnread(_:)) { return canGoToNextUnread(wrappingToTop: true) } - + if item.action == #selector(markAllAsRead(_:)) { return canMarkAllAsRead() } @@ -252,7 +252,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation if item.action == #selector(toggleArticleExtractor(_:)) { return validateToggleArticleExtractor(item) } - + if item.action == #selector(toolbarShowShareMenu(_:)) { return canShowShareMenu() } @@ -398,7 +398,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation } @IBAction func toggleArticleExtractor(_ sender: Any?) { - + guard let currentLink = currentLink, let article = oneSelectedArticle else { return } @@ -406,12 +406,12 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation defer { makeToolbarValidate() } - + if articleExtractor?.state == .failedToParse { startArticleExtractorForCurrentLink() return } - + guard articleExtractor?.state != .processing else { articleExtractor?.cancel() articleExtractor = nil @@ -419,13 +419,13 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation detailViewController?.setState(DetailState.article(article, nil), mode: timelineSourceMode) return } - + guard !isShowingExtractedArticle else { isShowingExtractedArticle = false detailViewController?.setState(DetailState.article(article, nil), mode: timelineSourceMode) return } - + if let articleExtractor = articleExtractor, let extractedArticle = articleExtractor.article { if currentLink == articleExtractor.articleLink { isShowingExtractedArticle = true @@ -435,7 +435,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation } else { startArticleExtractorForCurrentLink() } - + } @IBAction func markAllAsReadAndGoToNextUnread(_ sender: Any?) { @@ -457,7 +457,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation @IBAction func markOlderArticlesAsRead(_ sender: Any?) { currentTimelineViewController?.markOlderArticlesRead() } - + @IBAction func markAboveArticlesAsRead(_ sender: Any?) { currentTimelineViewController?.markAboveArticlesRead() } @@ -477,7 +477,7 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation @IBAction func navigateToDetail(_ sender: Any?) { detailViewController?.focus() } - + @IBAction func goToPreviousSubscription(_ sender: Any?) { sidebarViewController?.outlineView.selectPreviousRow(sender) } @@ -529,25 +529,25 @@ final class MainWindowController : NSWindowController, NSUserInterfaceValidation @IBAction func cleanUp(_ sender: Any?) { timelineContainerViewController?.cleanUp() } - + @IBAction func toggleReadFeedsFilter(_ sender: Any?) { sidebarViewController?.toggleReadFilter() } - + @IBAction func toggleReadArticlesFilter(_ sender: Any?) { timelineContainerViewController?.toggleReadFilter() } - + @objc func selectArticleTheme(_ menuItem: NSMenuItem) { ArticleThemesManager.shared.currentThemeName = menuItem.title } - + } // MARK: NSWindowDelegate extension MainWindowController: NSWindowDelegate { - + func window(_ window: NSWindow, willEncodeRestorableState coder: NSCoder) { coder.encode(savableState(), forKey: UserInfoKey.windowState) } @@ -561,7 +561,7 @@ extension MainWindowController: NSWindowDelegate { detailViewController?.stopMediaPlayback() appDelegate.removeMainWindow(self) } - + } // MARK: - SidebarDelegate @@ -588,11 +588,11 @@ extension MainWindowController: SidebarDelegate { } return timelineViewController.unreadCount } - + func sidebarInvalidatedRestorationState(_: SidebarViewController) { invalidateRestorableState() } - + } // MARK: - TimelineContainerViewControllerDelegate @@ -601,12 +601,12 @@ extension MainWindowController: TimelineContainerViewControllerDelegate { func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode) { activityManager.invalidateReading() - + articleExtractor?.cancel() articleExtractor = nil isShowingExtractedArticle = false makeToolbarValidate() - + let detailState: DetailState if let articles = articles { if articles.count == 1 { @@ -631,11 +631,11 @@ extension MainWindowController: TimelineContainerViewControllerDelegate { func timelineRequestedFeedSelection(_: TimelineContainerViewController, feed: Feed) { sidebarViewController?.selectFeed(feed) } - + func timelineInvalidatedRestorationState(_: TimelineContainerViewController) { invalidateRestorableState() } - + } // MARK: - NSSearchFieldDelegate @@ -708,11 +708,11 @@ extension MainWindowController: NSSearchFieldDelegate { // MARK: - ArticleExtractorDelegate extension MainWindowController: ArticleExtractorDelegate { - + func articleExtractionDidFail(with: Error) { makeToolbarValidate() } - + func articleExtractionDidComplete(extractedArticle: ExtractedArticle) { if let article = oneSelectedArticle, articleExtractor?.state != .cancelled { isShowingExtractedArticle = true @@ -722,7 +722,7 @@ extension MainWindowController: ArticleExtractorDelegate { makeToolbarValidate() } } - + } // MARK: - Scripting Access @@ -730,7 +730,7 @@ extension MainWindowController: ArticleExtractorDelegate { /* the ScriptingMainWindowController protocol exposes a narrow set of accessors with internal visibility which are very similar to some private vars. - + These would be unnecessary if the similar accessors were marked internal rather than private, but for now, we'll keep the stratification of visibility */ @@ -852,7 +852,7 @@ extension MainWindowController: NSToolbarDelegate { return nil } - + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { [ NSToolbarItem.Identifier.toggleSidebar, @@ -954,7 +954,7 @@ private extension MainWindowController { var detailSplitViewItem: NSSplitViewItem? { return splitViewController?.splitViewItems[2] } - + var selectedArticles: [Article]? { return currentTimelineViewController?.selectedArticles } @@ -971,10 +971,10 @@ private extension MainWindowController { } // MARK: - State Restoration - + func savableState() -> MainWindowState { let isFullScreen = window?.styleMask.contains(.fullScreen) ?? false - + let splitViewWidths: [Int] if let splitView = splitViewController?.splitView { splitViewWidths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) } @@ -997,9 +997,9 @@ private extension MainWindowController { window?.toggleFullScreen(self) } restoreSplitViewState(from: state) - + sidebarViewController?.restoreState(from: state.sidebarWindowState) - + timelineContainerViewController?.restoreState(from: state.timelineWindowState) restoreArticleWindowScrollY = state.detailWindowState?.windowScrollY @@ -1036,7 +1036,7 @@ private extension MainWindowController { } // MARK: - Command Validation - + func canCopyArticleURL() -> Bool { guard let selectedArticles else { return false @@ -1049,7 +1049,7 @@ private extension MainWindowController { } return false } - + func canCopyExternalURL() -> Bool { guard let selectedArticles else { return false @@ -1064,25 +1064,25 @@ private extension MainWindowController { } func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool { - + guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else { return false } // TODO: handle search mode return timelineViewController.canGoToNextUnread(wrappingToTop: wrapping) || sidebarViewController.canGoToNextUnread(wrappingToTop: wrapping) } - + func canMarkAllAsRead() -> Bool { - + return currentTimelineViewController?.canMarkAllAsRead() ?? false } - + func validateToggleRead(_ item: NSValidatedUserInterfaceItem) -> Bool { let validationStatus = currentTimelineViewController?.markReadCommandStatus() ?? .canDoNothing let markingRead: Bool let result: Bool - + switch validationStatus { case .canMark: markingRead = true @@ -1094,21 +1094,21 @@ private extension MainWindowController { markingRead = true result = false } - + let commandName = markingRead ? NSLocalizedString("Mark as Read", comment: "Command") : NSLocalizedString("Mark as Unread", comment: "Command") - + if let toolbarItem = item as? NSToolbarItem { toolbarItem.toolTip = commandName } - + if let menuItem = item as? NSMenuItem { menuItem.title = commandName } - + if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton { button.image = markingRead ? AppAssets.readClosedImage : AppAssets.readOpenImage } - + return result } @@ -1152,7 +1152,7 @@ private extension MainWindowController { func canMarkBelowArticlesAsRead() -> Bool { return currentTimelineViewController?.canMarkBelowArticlesAsRead() ?? false } - + func canShowShareMenu() -> Bool { guard let selectedArticles = selectedArticles else { @@ -1195,7 +1195,7 @@ private extension MainWindowController { return result } - + func validateCleanUp(_ item: NSValidatedUserInterfaceItem) -> Bool { return timelineContainerViewController?.isCleanUpAvailable ?? false } @@ -1235,7 +1235,7 @@ private extension MainWindowController { button.image = AppAssets.filterInactive } } - + return true } @@ -1268,7 +1268,7 @@ private extension MainWindowController { window?.subtitle = "" return } - + func setSubtitle(_ count: Int) { let localizedLabel = NSLocalizedString("%d unread", comment: "Unread") let formattedLabel = NSString.localizedStringWithFormat(localizedLabel as NSString, count) @@ -1368,13 +1368,13 @@ private extension MainWindowController { func buildToolbarButton(_ itemIdentifier: NSToolbarItem.Identifier, _ title: String, _ image: NSImage, _ selector: String) -> NSToolbarItem { let toolbarItem = RSToolbarItem(itemIdentifier: itemIdentifier) toolbarItem.autovalidates = true - + let button = NSButton() button.bezelStyle = .texturedRounded button.image = image button.imageScaling = .scaleProportionallyDown button.action = Selector((selector)) - + toolbarItem.view = button toolbarItem.toolTip = title toolbarItem.label = title @@ -1383,23 +1383,23 @@ private extension MainWindowController { func buildNewSidebarItemMenu() -> NSMenu { let menu = NSMenu() - + let newFeedItem = NSMenuItem() newFeedItem.title = NSLocalizedString("New Feed…", comment: "New Feed") newFeedItem.action = Selector(("showAddFeedWindow:")) menu.addItem(newFeedItem) - + let newFolderFeedItem = NSMenuItem() newFolderFeedItem.title = NSLocalizedString("New Folder…", comment: "New Folder") newFolderFeedItem.action = Selector(("showAddFolderWindow:")) menu.addItem(newFolderFeedItem) - + return menu } func updateArticleThemeMenu() { let articleThemeMenu = NSMenu() - + let defaultThemeItem = NSMenuItem() defaultThemeItem.title = ArticleTheme.defaultTheme.name defaultThemeItem.action = #selector(selectArticleTheme(_:)) diff --git a/Mac/MainWindow/NNW3/NNW3ImportController.swift b/Mac/MainWindow/NNW3/NNW3ImportController.swift index c54a77c76..bdeb7e466 100644 --- a/Mac/MainWindow/NNW3/NNW3ImportController.swift +++ b/Mac/MainWindow/NNW3/NNW3ImportController.swift @@ -74,7 +74,7 @@ private extension NNW3ImportController { panel.accessoryView = accessoryViewController.view panel.isAccessoryViewDisclosed = true panel.title = NSLocalizedString("Choose a Subscriptions.plist file:", comment: "NNW3 Import") - + panel.beginSheetModal(for: window) { modalResult in guard modalResult == .OK, let subscriptionsPlistURL = panel.url else { return diff --git a/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift b/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift index 110377b11..c6a53edb1 100644 --- a/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift +++ b/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift @@ -22,7 +22,7 @@ final class NNW3OpenPanelAccessoryViewController: NSViewController { } // MARK: - NSViewController - + required init?(coder: NSCoder) { preconditionFailure("NNW3OpenPanelAccessoryViewController.init(coder) not implemented by design.") } diff --git a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift index 3cc6faa8f..afb10b12b 100644 --- a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift +++ b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift @@ -14,24 +14,24 @@ final class ExportOPMLWindowController: NSWindowController { @IBOutlet weak var accountPopUpButton: NSPopUpButton! private weak var hostWindow: NSWindow? - + convenience init() { self.init(windowNibName: NSNib.Name("ExportOPMLSheet")) } - + override func windowDidLoad() { accountPopUpButton.removeAllItems() let menu = NSMenu() accountPopUpButton.menu = menu - + for oneAccount in AccountManager.shared.sortedAccounts { - + let oneMenuItem = NSMenuItem() oneMenuItem.title = oneAccount.nameForDisplay oneMenuItem.representedObject = oneAccount menu.addItem(oneMenuItem) - + if oneAccount.accountID == AppDefaults.shared.exportOPMLAccountID { accountPopUpButton.select(oneMenuItem) } @@ -40,14 +40,14 @@ final class ExportOPMLWindowController: NSWindowController { } // MARK: API - + func runSheetOnWindow(_ hostWindow: NSWindow) { guard let window else { return } self.hostWindow = hostWindow - + if AccountManager.shared.accounts.count == 1 { let account = AccountManager.shared.accounts.first! exportOPML(account: account) @@ -55,13 +55,13 @@ final class ExportOPMLWindowController: NSWindowController { hostWindow.beginSheet(window) } } - + // MARK: Actions - + @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func exportOPML(_ sender: Any) { guard let menuItem = accountPopUpButton.selectedItem else { @@ -72,11 +72,11 @@ final class ExportOPMLWindowController: NSWindowController { AppDefaults.shared.exportOPMLAccountID = account.accountID hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK) exportOPML(account: account) - + } - + func exportOPML(account: Account) { - + let panel = NSSavePanel() panel.allowedContentTypes = [UTType.opml] panel.allowsOtherFileTypes = false @@ -85,10 +85,10 @@ final class ExportOPMLWindowController: NSWindowController { panel.nameFieldLabel = NSLocalizedString("Export to:", comment: "Export OPML") panel.message = NSLocalizedString("Choose a location for the exported OPML file.", comment: "Export OPML") panel.isExtensionHidden = false - + let accountName = account.nameForDisplay.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespaces) panel.nameFieldStringValue = "Subscriptions-\(accountName).opml" - + panel.beginSheetModal(for: hostWindow!) { result in if result == NSApplication.ModalResponse.OK, let url = panel.url { DispatchQueue.main.async { @@ -103,7 +103,7 @@ final class ExportOPMLWindowController: NSWindowController { } } } - + } - + } diff --git a/Mac/MainWindow/OPML/ImportOPMLWindowController.swift b/Mac/MainWindow/OPML/ImportOPMLWindowController.swift index b2f8cf610..e640a78bf 100644 --- a/Mac/MainWindow/OPML/ImportOPMLWindowController.swift +++ b/Mac/MainWindow/OPML/ImportOPMLWindowController.swift @@ -14,44 +14,44 @@ final class ImportOPMLWindowController: NSWindowController { @IBOutlet weak var accountPopUpButton: NSPopUpButton! private weak var hostWindow: NSWindow? - + convenience init() { self.init(windowNibName: NSNib.Name("ImportOPMLSheet")) } - + override func windowDidLoad() { accountPopUpButton.removeAllItems() - + let menu = NSMenu() accountPopUpButton.menu = menu for oneAccount in AccountManager.shared.sortedActiveAccounts { - + if oneAccount.behaviors.contains(.disallowOPMLImports) { continue } - + let oneMenuItem = NSMenuItem() oneMenuItem.title = oneAccount.nameForDisplay oneMenuItem.representedObject = oneAccount menu.addItem(oneMenuItem) - + if oneAccount.accountID == AppDefaults.shared.importOPMLAccountID { accountPopUpButton.select(oneMenuItem) } - + } } - + // MARK: API - + func runSheetOnWindow(_ hostWindow: NSWindow) { guard let window else { return } self.hostWindow = hostWindow - + if AccountManager.shared.activeAccounts.count == 1 { let account = AccountManager.shared.activeAccounts.first! importOPML(account: account) @@ -59,28 +59,28 @@ final class ImportOPMLWindowController: NSWindowController { hostWindow.beginSheet(window) } } - + // MARK: Actions - + @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func importOPML(_ sender: Any) { guard let menuItem = accountPopUpButton.selectedItem else { return } - + let account = menuItem.representedObject as! Account AppDefaults.shared.importOPMLAccountID = account.accountID hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK) importOPML(account: account) - + } - + func importOPML(account: Account) { - + let panel = NSOpenPanel() panel.canDownloadUbiquitousContents = true panel.canResolveUbiquitousConflicts = true @@ -90,7 +90,7 @@ final class ImportOPMLWindowController: NSWindowController { panel.resolvesAliases = true panel.allowedContentTypes = [UTType.opml, UTType.xml] panel.allowsOtherFileTypes = false - + panel.beginSheetModal(for: hostWindow!) { modalResult in if modalResult == NSApplication.ModalResponse.OK, let url = panel.url { account.importOPML(url) { result in @@ -103,7 +103,7 @@ final class ImportOPMLWindowController: NSWindowController { } } } - + } } diff --git a/Mac/MainWindow/SharingServiceDelegate.swift b/Mac/MainWindow/SharingServiceDelegate.swift index 01e78fc3f..298616d33 100644 --- a/Mac/MainWindow/SharingServiceDelegate.swift +++ b/Mac/MainWindow/SharingServiceDelegate.swift @@ -11,7 +11,7 @@ import AppKit @objc final class SharingServiceDelegate: NSObject, NSSharingServiceDelegate { weak var window: NSWindow? - + init(_ window: NSWindow?) { self.window = window } @@ -24,9 +24,9 @@ import AppKit } .joined(separator: ", ") } - + func sharingService(_ sharingService: NSSharingService, sourceWindowForShareItems items: [Any], sharingContentScope: UnsafeMutablePointer) -> NSWindow? { return window } - + } diff --git a/Mac/MainWindow/SharingServicePickerDelegate.swift b/Mac/MainWindow/SharingServicePickerDelegate.swift index b95793e2e..9a1d42e98 100644 --- a/Mac/MainWindow/SharingServicePickerDelegate.swift +++ b/Mac/MainWindow/SharingServicePickerDelegate.swift @@ -10,13 +10,13 @@ import AppKit import RSCore @objc final class SharingServicePickerDelegate: NSObject, NSSharingServicePickerDelegate { - + private let sharingServiceDelegate: SharingServiceDelegate - + init(_ window: NSWindow?) { sharingServiceDelegate = SharingServiceDelegate(window) } - + func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, sharingServicesForItems items: [Any], proposedSharingServices proposedServices: [NSSharingService]) -> [NSSharingService] { let filteredServices = proposedServices.filter { $0.menuItemTitle != "NetNewsWire" } return filteredServices + SharingServicePickerDelegate.customSharingServices(for: items) @@ -34,7 +34,7 @@ import RSCore guard let object = items.first else { return nil } - + guard sendToCommand.canSendObject(object, selectedText: nil) else { return nil } diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift index 3ade9ba66..dcaf1d927 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift @@ -81,7 +81,7 @@ final class SidebarCell : NSTableCellView { unreadCountView.isSelected = (backgroundStyle != .normal) } } - + override var isFlipped: Bool { return true } @@ -90,7 +90,7 @@ final class SidebarCell : NSTableCellView { super.init(frame: frameRect) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() @@ -139,10 +139,10 @@ private extension SidebarCell { titleView.setFrame(ifNotEqualTo: layout.titleRect) unreadCountView.setFrame(ifNotEqualTo: layout.unreadCountRect) } - + func updateFaviconImage() { var updatedIconImage = iconImage - + if let iconImage = iconImage, iconImage.isSymbol { var tintColor: CGColor if backgroundStyle != .normal { @@ -163,5 +163,5 @@ private extension SidebarCell { faviconImageView.iconImage = nil } } - + } diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift index c13996732..9dce61a40 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift @@ -28,7 +28,7 @@ struct SidebarCellAppearance: Equatable { imageSize = CGSize(width: 19, height: 19) textFieldFontSize = 13 } - + self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize) } } diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift index e054b924a..0cf32d22a 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift @@ -16,7 +16,7 @@ struct SidebarCellLayout { let faviconRect: CGRect let titleRect: CGRect let unreadCountRect: CGRect - + init(appearance: SidebarCellAppearance, cellSize: NSSize, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) { let bounds = NSRect(x: 0.0, y: 0.0, width: floor(cellSize.width), height: floor(cellSize.height)) diff --git a/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift b/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift index 26d5a299d..69ad338e6 100644 --- a/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift +++ b/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift @@ -23,7 +23,7 @@ import RSCore super.init() } - + func keydown(_ event: NSEvent, in view: NSView) -> Bool { if MainWindowKeyboardHandler.shared.keydown(event, in: view) { diff --git a/Mac/MainWindow/Sidebar/PasteboardFeed.swift b/Mac/MainWindow/Sidebar/PasteboardFeed.swift index d8a1735d2..ad83e3734 100644 --- a/Mac/MainWindow/Sidebar/PasteboardFeed.swift +++ b/Mac/MainWindow/Sidebar/PasteboardFeed.swift @@ -67,7 +67,7 @@ struct PasteboardFeed: Hashable { if let accountTypeString = dictionary[Key.accountType], let accountTypeInt = Int(accountTypeString) { accountType = AccountType(rawValue: accountTypeInt) } - + let containerName = dictionary[Key.containerName] self.init(url: url, feedID: feedID, homePageURL: homePageURL, name: name, editedName: editedName, accountID: accountID, accountType: accountType, containerName: containerName) } diff --git a/Mac/MainWindow/Sidebar/PasteboardFolder.swift b/Mac/MainWindow/Sidebar/PasteboardFolder.swift index 0d8f1cc33..6fc3ec614 100644 --- a/Mac/MainWindow/Sidebar/PasteboardFolder.swift +++ b/Mac/MainWindow/Sidebar/PasteboardFolder.swift @@ -13,7 +13,7 @@ import RSCore typealias PasteboardFolderDictionary = [String: String] struct PasteboardFolder: Hashable { - + private struct Key { static let name = "name" // Internal @@ -21,30 +21,30 @@ struct PasteboardFolder: Hashable { static let accountID = "accountID" } - + let name: String let folderID: String? let accountID: String? - + init(name: String, folderID: String?, accountID: String?) { self.name = name self.folderID = folderID self.accountID = accountID } - + // MARK: - Reading - + init?(dictionary: PasteboardFolderDictionary) { guard let name = dictionary[Key.name] else { return nil } - + let folderID = dictionary[Key.folderID] let accountID = dictionary[Key.accountID] - + self.init(name: name, folderID: folderID, accountID: accountID) } - + init?(pasteboardItem: NSPasteboardItem) { var pasteboardType: NSPasteboard.PasteboardType? if pasteboardItem.types.contains(FolderPasteboardWriter.folderUTIInternalType) { @@ -57,10 +57,10 @@ struct PasteboardFolder: Hashable { return } } - + return nil } - + static func pasteboardFolders(with pasteboard: NSPasteboard) -> Set? { guard let items = pasteboard.pasteboardItems else { return nil @@ -68,9 +68,9 @@ struct PasteboardFolder: Hashable { let folders = items.compactMap { PasteboardFolder(pasteboardItem: $0) } return folders.isEmpty ? nil : Set(folders) } - + // MARK: - Writing - + func internalDictionary() -> PasteboardFolderDictionary { var d = PasteboardFeedDictionary() d[PasteboardFolder.Key.name] = name @@ -130,7 +130,7 @@ private extension FolderPasteboardWriter { var pasteboardFolder: PasteboardFolder { return PasteboardFolder(name: folder.name ?? "", folderID: String(folder.folderID), accountID: folder.account?.accountID) } - + var internalDictionary: PasteboardFeedDictionary { return pasteboardFolder.internalDictionary() } diff --git a/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift b/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift index 5cb8b6309..229a791ad 100644 --- a/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift +++ b/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift @@ -18,7 +18,7 @@ final class RenameWindowController: NSWindowController { @IBOutlet var renamePrompt: NSTextField! @IBOutlet var newTitleTextField: NSTextField! @IBOutlet var renameButton: NSButton! - + private var originalTitle: String? private var representedObject: Any? private var delegate: RenameWindowControllerDelegate? diff --git a/Mac/MainWindow/Sidebar/SidebarDeleteItemsAlert.swift b/Mac/MainWindow/Sidebar/SidebarDeleteItemsAlert.swift index 20814e69b..b4e7d48bd 100644 --- a/Mac/MainWindow/Sidebar/SidebarDeleteItemsAlert.swift +++ b/Mac/MainWindow/Sidebar/SidebarDeleteItemsAlert.swift @@ -11,12 +11,12 @@ import RSTree import Account enum SidebarDeleteItemsAlert { - + /// Builds a delete confirmation dialog for the supplied nodes static func build(_ nodes: [Node]) -> NSAlert { let alert = NSAlert() alert.alertStyle = .warning - + if nodes.count == 1 { if let folder = nodes.first?.representedObject as? Folder { alert.messageText = NSLocalizedString("Delete Folder", comment: "Delete Folder") @@ -32,11 +32,11 @@ enum SidebarDeleteItemsAlert { let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the %d selected items?", comment: "Items delete text") alert.informativeText = NSString.localizedStringWithFormat(localizedInformativeText as NSString, nodes.count) as String } - + alert.addButton(withTitle: NSLocalizedString("Delete", comment: "Delete Account")) alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel Delete Account")) - + return alert } - + } diff --git a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift index 4b1c762c3..7966c923b 100644 --- a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift +++ b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift @@ -46,7 +46,7 @@ import Account guard var pasteboardWriter = (node.representedObject as? PasteboardWriterOwner)?.pasteboardWriter else { return nil } - + // Feed objects don't have knowledge of their parent so we inject parent container information // into FeedPasteboardWriter instance and it adds this field to the PasteboardFeed objects it writes. // Add similar to FolderPasteboardWriter if/when we allow sub-folders @@ -76,7 +76,7 @@ import Account return validateLocalFoldersDrop(outlineView, draggedFolders, parentNode, index) } } - + if let draggedFeeds = draggedFeeds { let contentsType = draggedFeedContentsType(draggedFeeds) @@ -96,7 +96,7 @@ import Account return SidebarOutlineDataSource.dragOperationNone } - + func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool { let draggedFolders = PasteboardFolder.pasteboardFolders(with: info.draggingPasteboard) let draggedFeeds = PasteboardFeed.pasteboardFeeds(with: info.draggingPasteboard) @@ -108,7 +108,7 @@ import Account if let draggedFolders = draggedFolders { return acceptLocalFoldersDrop(outlineView, draggedFolders, parentNode, index) } - + if let draggedFeeds = draggedFeeds { let contentsType = draggedFeedContentsType(draggedFeeds) @@ -124,7 +124,7 @@ import Account return false } } - + return false } } @@ -236,7 +236,7 @@ private extension SidebarOutlineDataSource { } return localDragOperation(parentNode: parentNode, draggedFeeds) } - + func localDragOperation(parentNode: Node, _ draggedFeeds: Set)-> NSDragOperation { guard let firstDraggedFeed = draggedFeeds.first else { return .move } if sameAccount(firstDraggedFeed, parentNode) { @@ -282,7 +282,7 @@ private extension SidebarOutlineDataSource { } return false } - + func validateLocalFolderDrop(_ outlineView: NSOutlineView, _ draggedFolder: PasteboardFolder, _ parentNode: Node, _ index: Int) -> NSDragOperation { guard let dropAccount = parentNode.representedObject as? Account, dropAccount.accountID != draggedFolder.accountID else { return SidebarOutlineDataSource.dragOperationNone @@ -296,7 +296,7 @@ private extension SidebarOutlineDataSource { } return .copy // different AccountIDs means can only copy } - + func validateLocalFoldersDrop(_ outlineView: NSOutlineView, _ draggedFolders: Set, _ parentNode: Node, _ index: Int) -> NSDragOperation { guard let dropAccount = parentNode.representedObject as? Account else { return SidebarOutlineDataSource.dragOperationNone @@ -314,7 +314,7 @@ private extension SidebarOutlineDataSource { } return .copy // different AccountIDs means can only copy } - + func copyFeedInAccount(_ feed: Feed, _ destination: Container ) { destination.account?.addFeed(feed, to: destination) { result in switch result { @@ -325,7 +325,7 @@ private extension SidebarOutlineDataSource { } } } - + func moveFeedInAccount(_ feed: Feed, _ source: Container, _ destination: Container) { BatchUpdate.shared.start() source.account?.moveFeed(feed, from: source, to: destination) { result in @@ -338,12 +338,12 @@ private extension SidebarOutlineDataSource { } } } - + func copyFeedBetweenAccounts(_ feed: Feed, _ destinationContainer: Container) { guard let destinationAccount = destinationContainer.account else { return } - + if let existingFeed = destinationAccount.existingFeed(withURL: feed.url) { destinationAccount.addFeed(existingFeed, to: destinationContainer) { result in switch result { @@ -369,7 +369,7 @@ private extension SidebarOutlineDataSource { guard draggedFeeds.isEmpty == false else { return false } - + draggedFeeds.forEach { pasteboardFeed in guard let sourceAccountID = pasteboardFeed.accountID, let sourceAccount = AccountManager.shared.existingAccount(with: sourceAccountID), @@ -379,7 +379,7 @@ private extension SidebarOutlineDataSource { else { return } - + var sourceContainer: Container = sourceAccount // default to top level, if let containerName = pasteboardFeed.containerName { // then check if have folder info to use instead. if let folderContainer = sourceAccount.existingFolder(with: containerName ) { @@ -388,7 +388,7 @@ private extension SidebarOutlineDataSource { sourceContainer = folderContainer } } - + if sameAccount(pasteboardFeed, parentNode) { if NSApplication.shared.currentEvent?.modifierFlags.contains(.option) ?? false { copyFeedInAccount(feed, destinationContainer) @@ -399,7 +399,7 @@ private extension SidebarOutlineDataSource { copyFeedBetweenAccounts(feed, destinationContainer) } } - + return true } @@ -434,12 +434,12 @@ private extension SidebarOutlineDataSource { } return ancestorThatCanAcceptNonLocalFeed(parentNode) } - + func copyFolderBetweenAccounts(folder: Folder, to parentNode: Node) { guard let destinationAccount = nodeAccount(parentNode) else { return } - + destinationAccount.addFolder(folder.name ?? "") { result in switch result { case .success(let destinationFolder): @@ -488,7 +488,7 @@ private extension SidebarOutlineDataSource { copyFolderBetweenAccounts(folder: folder, to: parentNode) } } - + return true } @@ -505,7 +505,7 @@ private extension SidebarOutlineDataSource { let folder = parentNode.representedObject as? Folder appDelegate.addFeed(draggedFeed.url, name: draggedFeed.editedName ?? draggedFeed.name, account: account, folder: folder) } - + return true } @@ -524,14 +524,14 @@ private extension SidebarOutlineDataSource { } return false } - + func sameAccount(_ pasteboardFeed: PasteboardFeed, _ parentNode: Node) -> Bool { if let accountID = pasteboardFeed.accountID { return sameAccount(accountID, parentNode) } return false } - + func sameAccount(_ pasteboardFolder: PasteboardFolder, _ parentNode: Node) -> Bool { if let accountID = pasteboardFolder.accountID { return sameAccount(accountID, parentNode) @@ -547,7 +547,7 @@ private extension SidebarOutlineDataSource { } return false } - + func nodeAccount(_ node: Node) -> Account? { if let account = node.representedObject as? Account { return account @@ -560,11 +560,11 @@ private extension SidebarOutlineDataSource { } } - + func nodeAccountID(_ node: Node) -> String? { return nodeAccount(node)?.accountID } - + func nodeHasChildRepresentingAnyDraggedFeed(_ parentNode: Node, _ draggedFeeds: Set) -> Bool { for node in parentNode.childNodes { if nodeRepresentsAnyDraggedFeed(node, draggedFeeds) { @@ -577,7 +577,7 @@ private extension SidebarOutlineDataSource { func violatesAccountSpecificBehavior(_ dropTargetNode: Node, _ draggedFeed: PasteboardFeed) -> Bool { return violatesAccountSpecificBehavior(dropTargetNode, Set([draggedFeed])) } - + func violatesAccountSpecificBehavior(_ dropTargetNode: Node, _ draggedFeeds: Set) -> Bool { if violatesDisallowFeedInRootFolder(dropTargetNode) { return true @@ -586,23 +586,23 @@ private extension SidebarOutlineDataSource { if violatesDisallowFeedCopyInRootFolder(dropTargetNode, draggedFeeds) { return true } - + if violatesDisallowFeedInMultipleFolders(dropTargetNode, draggedFeeds) { return true } - + return false } - + func violatesDisallowFeedInRootFolder(_ dropTargetNode: Node) -> Bool { guard let parentAccount = nodeAccount(dropTargetNode), parentAccount.behaviors.contains(.disallowFeedInRootFolder) else { return false } - + if dropTargetNode.representedObject is Account { return true } - + return false } @@ -610,17 +610,17 @@ private extension SidebarOutlineDataSource { guard let dropTargetAccount = nodeAccount(dropTargetNode), dropTargetAccount.behaviors.contains(.disallowFeedCopyInRootFolder) else { return false } - + for draggedFeed in draggedFeeds { if dropTargetAccount.accountID != draggedFeed.accountID { return false } } - + if dropTargetNode.representedObject is Account && (NSApplication.shared.currentEvent?.modifierFlags.contains(.option) ?? false) { return true } - + return false } @@ -628,7 +628,7 @@ private extension SidebarOutlineDataSource { guard let dropTargetAccount = nodeAccount(dropTargetNode), dropTargetAccount.behaviors.contains(.disallowFeedInMultipleFolders) else { return false } - + for draggedFeed in draggedFeeds { if dropTargetAccount.accountID == draggedFeed.accountID { if NSApplication.shared.currentEvent?.modifierFlags.contains(.option) ?? false { @@ -640,7 +640,7 @@ private extension SidebarOutlineDataSource { } } } - + return false } @@ -660,7 +660,7 @@ private extension SidebarOutlineDataSource { let draggedFolderNode = Node(representedObject: draggedFolderWrapper, parent: nil) draggedFolderNode.canHaveChildNodes = true let nodes = parentNode.childNodes + [draggedFolderNode] - + // Revisit if the tree controller can ever be sorted in some other way. let sortedNodes = nodes.sortedAlphabeticallyWithFoldersAtEnd() let index = sortedNodes.firstIndex(of: draggedFolderNode)! @@ -681,12 +681,12 @@ final class PasteboardFeedObjectWrapper: DisplayNameProvider { } final class PasteboardFolderObjectWrapper: DisplayNameProvider { - + var nameForDisplay: String { return pasteboardFolder.name } let pasteboardFolder: PasteboardFolder - + init(pasteboardFolder: PasteboardFolder) { self.pasteboardFolder = pasteboardFolder } diff --git a/Mac/MainWindow/Sidebar/SidebarOutlineView.swift b/Mac/MainWindow/Sidebar/SidebarOutlineView.swift index 5e0d11a65..00d1b1dd2 100644 --- a/Mac/MainWindow/Sidebar/SidebarOutlineView.swift +++ b/Mac/MainWindow/Sidebar/SidebarOutlineView.swift @@ -40,15 +40,15 @@ final class SidebarOutlineView : NSOutlineView { // MARK: NSView override func viewWillStartLiveResize() { - + if let scrollView = self.enclosingScrollView { scrollView.hasVerticalScroller = false } super.viewWillStartLiveResize() } - + override func viewDidEndLiveResize() { - + if let scrollView = self.enclosingScrollView { scrollView.hasVerticalScroller = true } diff --git a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift b/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift index d1e9de7dc..236bc8003 100644 --- a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift +++ b/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift @@ -33,7 +33,7 @@ final class SidebarStatusBarView: NSView { let progressLabelFontSize = progressLabel.font?.pointSize ?? 13.0 progressLabel.font = NSFont.monospacedDigitSystemFont(ofSize: progressLabelFontSize, weight: NSFont.Weight.regular) progressLabel.stringValue = "" - + NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) } diff --git a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift index 7655c7759..c792a171e 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift @@ -68,7 +68,7 @@ extension SidebarViewController { guard let menuItem = sender as? NSMenuItem, let objects = menuItem.representedObject as? [Any] else { return } - + let articles = unreadArticles(for: objects) guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: Array(articles), markingRead: true, undoManager: undoManager) else { return @@ -80,7 +80,7 @@ extension SidebarViewController { guard let menuItem = sender as? NSMenuItem, let objects = menuItem.representedObject as? [AnyObject] else { return } - + let nodes = objects.compactMap { treeController.nodeInTreeRepresentingObject($0) } let alert = SidebarDeleteItemsAlert.build(nodes) @@ -103,7 +103,7 @@ extension SidebarViewController { } window.beginSheet(renameSheet) } - + @objc func toggleNotificationsFromContextMenu(_ sender: Any?) { guard let item = sender as? NSMenuItem, let feed = item.representedObject as? Feed else { @@ -134,7 +134,7 @@ extension SidebarViewController { } } } - + @objc func toggleArticleExtractorFromContextMenu(_ sender: Any?) { guard let item = sender as? NSMenuItem, let feed = item.representedObject as? Feed else { @@ -144,7 +144,7 @@ extension SidebarViewController { feed.isArticleExtractorAlwaysOn?.toggle() NotificationCenter.default.post(Notification(name: .DidUpdateFeedPreferencesFromContextMenu)) } - + func showNotificationsNotEnabledAlert() { DispatchQueue.main.async { let alert = NSAlert() @@ -163,7 +163,7 @@ extension SidebarViewController { } } } - + } extension SidebarViewController: RenameWindowControllerDelegate { @@ -229,9 +229,9 @@ private extension SidebarViewController { menu.addItem(item) } menu.addItem(NSMenuItem.separator()) - + let notificationText = feed.notificationDisplayName.capitalized - + let notificationMenuItem = menuItem(notificationText, #selector(toggleNotificationsFromContextMenu(_:)), feed, image: AppAssets.notificationImage) if feed.isNotifyAboutNewArticles == nil || feed.isNotifyAboutNewArticles! == false { notificationMenuItem.state = .off @@ -251,7 +251,7 @@ private extension SidebarViewController { menu.addItem(articleExtractorMenuItem) menu.addItem(NSMenuItem.separator()) - + menu.addItem(renameMenuItem(feed)) menu.addItem(deleteMenuItem([feed])) diff --git a/Mac/MainWindow/Sidebar/SidebarViewController.swift b/Mac/MainWindow/Sidebar/SidebarViewController.swift index cf4f6779e..c9b1446d7 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController.swift @@ -23,9 +23,9 @@ protocol SidebarDelegate: AnyObject { } @objc final class SidebarViewController: NSViewController, NSOutlineViewDelegate, NSMenuDelegate, UndoableCommandRunner { - + @IBOutlet weak var outlineView: NSOutlineView! - + weak var delegate: SidebarDelegate? weak var splitViewItem: NSSplitViewItem? @@ -35,7 +35,7 @@ protocol SidebarDelegate: AnyObject { let selectedFeeds = selectedFeeds.compactMap { $0.sidebarItemID?.userInfo as? [String: String] } return SidebarWindowState(isReadFiltered: isReadFiltered, expandedContainers: expandedContainers, selectedFeeds: selectedFeeds) } - + private let rebuildTreeAndRestoreSelectionQueue = CoalescingQueue(name: "Rebuild Tree Queue", interval: 1.0) let treeControllerDelegate = SidebarTreeControllerDelegate() lazy var treeController: TreeController = { @@ -44,7 +44,7 @@ protocol SidebarDelegate: AnyObject { lazy var dataSource: SidebarOutlineDataSource = { return SidebarOutlineDataSource(treeController: treeController) }() - + var isReadFiltered: Bool { get { return treeControllerDelegate.isReadFiltered @@ -97,22 +97,22 @@ protocol SidebarDelegate: AnyObject { } } expandNodes() - + } // MARK: State Restoration - + func restoreState(from state: SidebarWindowState?) { guard let state else { return } - + let containerIdentifers = state.expandedContainers.compactMap( { ContainerIdentifier(userInfo: $0) }) expandedTable = Set(containerIdentifers) let selectedFeedIdentifers = Set(state.selectedFeeds.compactMap( { SidebarItemIdentifier(userInfo: $0) })) selectedFeedIdentifers.forEach { treeControllerDelegate.addFilterException($0) } - + rebuildTreeAndReloadDataIfNeeded() - + var selectIndexes = IndexSet() func selectFeedsVisitor(node: Node) { @@ -126,7 +126,7 @@ protocol SidebarDelegate: AnyObject { treeController.visitNodes(selectFeedsVisitor(node:)) outlineView.selectRowIndexes(selectIndexes, byExtendingSelection: false) focus() - + isReadFiltered = state.isReadFiltered } @@ -183,7 +183,7 @@ protocol SidebarDelegate: AnyObject { guard let representedObject = note.object else { return } - + if let timelineViewController = representedObject as? TimelineViewController { configureUnreadCountForCellsForRepresentedObjects(timelineViewController.representedObjects) } else { @@ -206,7 +206,7 @@ protocol SidebarDelegate: AnyObject { @objc func accountsDidChange(_ notification: Notification) { rebuildTreeAndRestoreSelection() } - + @objc func accountStateDidChange(_ notification: Notification) { rebuildTreeAndRestoreSelection() } @@ -214,7 +214,7 @@ protocol SidebarDelegate: AnyObject { @objc func batchUpdateDidPerform(_ notification: Notification) { rebuildTreeAndRestoreSelection() } - + @objc func userDidAddFeed(_ notification: Notification) { guard let feed = notification.userInfo?[UserInfoKey.feed] else { return @@ -230,7 +230,7 @@ protocol SidebarDelegate: AnyObject { guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { return } configureCellsForRepresentedObject(feed) } - + @objc func feedSettingDidChange(_ note: Notification) { guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? String else { return @@ -259,18 +259,18 @@ protocol SidebarDelegate: AnyObject { self.restoreSelection(to: savedSelection, sendNotificationIfChanged: true) } } - + // MARK: - Actions @IBAction func delete(_ sender: AnyObject?) { let availableSelectedNodes = selectedNodes.filter { !($0.representedObject is PseudoFeed) } - + if availableSelectedNodes.isEmpty { return } - + let alert = SidebarDeleteItemsAlert.build(availableSelectedNodes) - + alert.beginSheetModal(for: view.window!) { [weak self] result in if result == NSApplication.ModalResponse.alertFirstButtonReturn { guard let self = self else { return } @@ -283,7 +283,7 @@ protocol SidebarDelegate: AnyObject { } } } - + @IBAction func doubleClickedSidebar(_ sender: Any?) { guard outlineView.clickedRow == outlineView.selectedRow else { return @@ -331,20 +331,20 @@ protocol SidebarDelegate: AnyObject { } // MARK: - Navigation - + func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool { if let _ = nextSelectableRowWithUnreadArticle(wrappingToTop: wrapping) { return true } return false } - + func goToNextUnread(wrappingToTop wrapping: Bool = false) { guard let row = nextSelectableRowWithUnreadArticle(wrappingToTop: wrapping) else { assertionFailure("goToNextUnread called before checking if there is a next unread.") return } - + NSCursor.setHiddenUntilMouseMoves(true) outlineView.selectRowIndexes(IndexSet([row]), byExtendingSelection: false) outlineView.scrollTo(row: row) @@ -371,13 +371,13 @@ protocol SidebarDelegate: AnyObject { // If the clickedRow is part of the selected rows, then do a contextual menu for all the selected rows. return contextualMenuForSelectedObjects() } - + let object = node.representedObject return menu(for: [object]) } // MARK: - NSMenuDelegate - + public func menuNeedsUpdate(_ menu: NSMenu) { menu.removeAllItems() guard let contextualMenu = contextualMenuForClickedRows() else { @@ -388,7 +388,7 @@ protocol SidebarDelegate: AnyObject { // MARK: - NSOutlineViewDelegate - + func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { let node = item as! Node @@ -433,7 +433,7 @@ protocol SidebarDelegate: AnyObject { func outlineViewSelectionDidChange(_ notification: Notification) { selectionDidChange(selectedObjects.isEmpty ? nil : selectedObjects) } - + func outlineViewItemDidExpand(_ notification: Notification) { guard let node = notification.userInfo?["NSObject"] as? Node, let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { @@ -444,7 +444,7 @@ protocol SidebarDelegate: AnyObject { delegate?.sidebarInvalidatedRestorationState(self) } } - + func outlineViewItemDidCollapse(_ notification: Notification) { guard let node = notification.userInfo?["NSObject"] as? Node, let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { @@ -455,32 +455,32 @@ protocol SidebarDelegate: AnyObject { delegate?.sidebarInvalidatedRestorationState(self) } } - + //MARK: - Node Manipulation - + func deleteNodes(_ nodes: [Node]) { let nodesToDelete = treeController.normalizedSelectedNodes(nodes) - + guard let undoManager = undoManager, let deleteCommand = DeleteCommand(nodesToDelete: nodesToDelete, treeController: treeController, undoManager: undoManager, errorHandler: ErrorHandler.present) else { return } - + animatingChanges = true outlineView.beginUpdates() - + let indexSetsGroupedByParent = Node.indexSetsGroupedByParent(nodesToDelete) for (parent, indexSet) in indexSetsGroupedByParent { outlineView.removeItems(at: indexSet, inParent: parent.isRoot ? nil : parent, withAnimation: [.slideDown]) } - + outlineView.endUpdates() - + runCommand(deleteCommand) animatingChanges = false } // MARK: - API - + func selectFeed(_ sidebarItem: SidebarItem) { if isReadFiltered, let sidebarItemID = sidebarItem.sidebarItemID { self.treeControllerDelegate.addFilterException(sidebarItemID) @@ -491,7 +491,7 @@ protocol SidebarDelegate: AnyObject { self.treeControllerDelegate.addFilterException(parentFolderSidebarItemID) } } - + addTreeControllerToFilterExceptions() rebuildTreeAndRestoreSelection() } @@ -517,7 +517,7 @@ protocol SidebarDelegate: AnyObject { delegate?.sidebarInvalidatedRestorationState(self) rebuildTreeAndRestoreSelection() } - + } // MARK: - NSUserInterfaceValidations @@ -535,18 +535,18 @@ extension SidebarViewController: NSUserInterfaceValidations { //MARK: - Private private extension SidebarViewController { - + var accountNodes: [Account] { return treeController.rootNode.childNodes.compactMap { $0.representedObject as? Account } } - + var selectedNodes: [Node] { if let nodes = outlineView.selectedItems as? [Node] { return nodes } return [Node]() } - + var selectedFeeds: [SidebarItem] { selectedNodes.compactMap { $0.representedObject as? SidebarItem } } @@ -564,11 +564,11 @@ private extension SidebarViewController { } return node.representedObject as? Feed } - + func addAllSelectedToFilterExceptions() { selectedFeeds.forEach { addToFilterExceptionsIfNecessary($0) } } - + func addToFilterExceptionsIfNecessary(_ sidebarItem: SidebarItem?) { if isReadFiltered, let sidebarItemID = sidebarItem?.sidebarItemID { if sidebarItem is PseudoFeed { @@ -585,29 +585,29 @@ private extension SidebarViewController { } } } - + func addParentFolderToFilterExceptions(_ sidebarItem: SidebarItem) { guard let node = treeController.rootNode.descendantNodeRepresentingObject(sidebarItem as AnyObject), let folder = node.parent?.representedObject as? Folder, let folderSidebarItemID = folder.sidebarItemID else { return } - + treeControllerDelegate.addFilterException(folderSidebarItemID) } - + func queueRebuildTreeAndRestoreSelection() { rebuildTreeAndRestoreSelectionQueue.add(self, #selector(rebuildTreeAndRestoreSelection)) } - + @objc func rebuildTreeAndRestoreSelection() { let savedAccounts = accountNodes let savedSelection = selectedNodes - + rebuildTreeAndReloadDataIfNeeded() restoreSelection(to: savedSelection, sendNotificationIfChanged: true) - + // Automatically expand any new or newly active accounts AccountManager.shared.activeAccounts.forEach { account in if !savedAccounts.contains(account) { @@ -615,9 +615,9 @@ private extension SidebarViewController { outlineView.expandItem(accountNode) } } - + } - + func rebuildTreeAndReloadDataIfNeeded() { if !animatingChanges && !BatchUpdate.shared.isPerforming { addAllSelectedToFilterExceptions() @@ -627,11 +627,11 @@ private extension SidebarViewController { expandNodes() } } - + func expandNodes() { treeController.visitNodes(expandNodesVisitor(node:)) } - + func expandNodesVisitor(node: Node) { if let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID { if expandedTable.contains(containerID) { @@ -641,7 +641,7 @@ private extension SidebarViewController { } } } - + func addTreeControllerToFilterExceptions() { treeController.visitNodes(addTreeControllerToFilterExceptionsVisitor(node:)) } @@ -688,13 +688,13 @@ private extension SidebarViewController { if row < 0 || row >= outlineView.numberOfRows { return nil } - + if let node = outlineView.item(atRow: row) as? Node { return node } return nil } - + func rowHasAtLeastOneUnreadArticle(_ row: Int) -> Bool { if let oneNode = nodeForRow(row) { if let unreadCountProvider = oneNode.representedObject as? UnreadCountProvider { @@ -750,7 +750,7 @@ private extension SidebarViewController { return row } } - + return nil } @@ -758,7 +758,7 @@ private extension SidebarViewController { guard let accountID = userInfo?[ArticlePathKey.accountID] as? String else { return nil } - + if let node = treeController.rootNode.descendantNode(where: { ($0.representedObject as? Account)?.accountID == accountID }) { return node } @@ -773,7 +773,7 @@ private extension SidebarViewController { return nil } - + func findFeedNode(_ userInfo: [AnyHashable : Any]?, beginningAt startingNode: Node) -> Node? { guard let feedID = userInfo?[ArticlePathKey.feedID] as? String else { return nil @@ -783,7 +783,7 @@ private extension SidebarViewController { } return nil } - + func configure(_ cell: SidebarCell, _ node: Node) { cell.cellAppearance = SidebarCellAppearance(rowSizeStyle: outlineView.effectiveRowSizeStyle) cell.name = nameFor(node) @@ -886,7 +886,7 @@ private extension SidebarViewController { func revealAndSelectRepresentedObject(_ representedObject: AnyObject) -> Bool { return outlineView.revealAndSelectRepresentedObject(representedObject, treeController) } - + } private extension Node { diff --git a/Mac/MainWindow/Sidebar/SidebarWindowState.swift b/Mac/MainWindow/Sidebar/SidebarWindowState.swift index 1674a1437..074b350fc 100644 --- a/Mac/MainWindow/Sidebar/SidebarWindowState.swift +++ b/Mac/MainWindow/Sidebar/SidebarWindowState.swift @@ -15,7 +15,7 @@ final class SidebarWindowState: NSObject, NSSecureCoding { let isReadFiltered: Bool let expandedContainers: [[String: String]] let selectedFeeds: [[String: String]] - + init(isReadFiltered: Bool, expandedContainers: [[String : String]], selectedFeeds: [[String : String]]) { self.isReadFiltered = isReadFiltered self.expandedContainers = expandedContainers @@ -33,7 +33,7 @@ final class SidebarWindowState: NSObject, NSSecureCoding { expandedContainers = coder.decodeObject(of: [NSArray.self, NSDictionary.self, NSString.self], forKey: Key.expandedContainers) as? [[String: String]] ?? [] selectedFeeds = coder.decodeObject(of: [NSArray.self, NSDictionary.self, NSString.self], forKey: Key.selectedFeeds) as? [[String: String]] ?? [] } - + func encode(with coder: NSCoder) { coder.encode(isReadFiltered, forKey: Key.isReadFiltered) coder.encode(expandedContainers, forKey: Key.expandedContainers) diff --git a/Mac/MainWindow/Sidebar/UnreadCountView.swift b/Mac/MainWindow/Sidebar/UnreadCountView.swift index 26e6c6492..67f9a7ea8 100644 --- a/Mac/MainWindow/Sidebar/UnreadCountView.swift +++ b/Mac/MainWindow/Sidebar/UnreadCountView.swift @@ -33,11 +33,11 @@ final class UnreadCountView : NSView { needsDisplay = true } } - + private var currentTextColor: NSColor { return isSelected ? NSColor.white : NSColor.secondaryLabelColor } - + private var textAttributes: [NSAttributedString.Key: AnyObject] { return [ .foregroundColor: currentTextColor, @@ -48,7 +48,7 @@ final class UnreadCountView : NSView { private var intrinsicContentSizeIsValid = false private var _intrinsicContentSize = NSZeroSize - + override var intrinsicContentSize: NSSize { if !intrinsicContentSizeIsValid { var size = NSZeroSize @@ -62,11 +62,11 @@ final class UnreadCountView : NSView { } return _intrinsicContentSize } - + override var isFlipped: Bool { return true } - + override func invalidateIntrinsicContentSize() { intrinsicContentSizeIsValid = false } diff --git a/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift b/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift index 82f49370a..c9af1fbee 100644 --- a/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift +++ b/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift @@ -56,7 +56,7 @@ final class MultilineTextFieldSizer { guard attributedString.length > 0 else { return TextFieldSizeInfo(size: NSSize.zero, numberOfLinesUsed: 0) } - + // Assumes the same font family/size for the whole string let font = attributedString.attribute(.font, at: 0, effectiveRange: nil) as! NSFont diff --git a/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift b/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift index e40db7235..db598d3fa 100644 --- a/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift +++ b/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift @@ -38,7 +38,7 @@ final class SingleLineTextFieldSizer { var calculatedSize = textField.fittingSize calculatedSize.height = ceil(calculatedSize.height) calculatedSize.width = ceil(calculatedSize.width) - + cache[text] = calculatedSize return calculatedSize } diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift index 83e5a81c5..457919e6c 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift @@ -13,7 +13,7 @@ struct TimelineCellAppearance: Equatable { let showIcon: Bool let cellPadding: NSEdgeInsets - + let feedNameFont: NSFont let dateFont: NSFont @@ -22,7 +22,7 @@ struct TimelineCellAppearance: Equatable { let titleFont: NSFont let titleBottomMargin: CGFloat = 1.0 let titleNumberOfLines = 3 - + let textFont: NSFont let textOnlyFont: NSFont @@ -55,7 +55,7 @@ struct TimelineCellAppearance: Equatable { self.textOnlyFont = NSFont.systemFont(ofSize: largeItemFontSize) self.showIcon = showIcon - + cellPadding = NSEdgeInsets(top: 8.0, left: 4.0, bottom: 10.0, right: 4.0) let margin = self.cellPadding.left + self.unreadCircleDimension + self.unreadCircleMarginRight diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift index 1b2dd91d9..de446b329 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift @@ -10,9 +10,9 @@ import AppKit import Articles struct TimelineCellData { - + private static let noText = NSLocalizedString("(No Text)", comment: "No Text") - + let title: String let attributedTitle: NSAttributedString let text: String @@ -36,7 +36,7 @@ struct TimelineCellData { } else { self.text = truncatedSummary } - + self.dateString = ArticleStringFormatter.dateString(article.logicalDatePublished) if let feedName = feedName { @@ -44,7 +44,7 @@ struct TimelineCellData { } else { self.feedName = "" } - + if let byline = byline { self.byline = byline } else { diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift index df4fb42b2..d46f565f7 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift @@ -10,7 +10,7 @@ import AppKit import RSCore struct TimelineCellLayout { - + let width: CGFloat let height: CGFloat let feedNameRect: NSRect @@ -24,9 +24,9 @@ struct TimelineCellLayout { let iconImageRect: NSRect let separatorRect: NSRect let paddingBottom: CGFloat - + init(width: CGFloat, height: CGFloat, feedNameRect: NSRect, dateRect: NSRect, titleRect: NSRect, numberOfLinesForTitle: Int, summaryRect: NSRect, textRect: NSRect, unreadIndicatorRect: NSRect, starRect: NSRect, iconImageRect: NSRect, separatorRect: NSRect, paddingBottom: CGFloat) { - + self.width = width self.feedNameRect = feedNameRect self.dateRect = dateRect @@ -114,7 +114,7 @@ private extension TimelineCellLayout { r.size.height = 0 return (r, 0) } - + let attributedTitle = cellData.attributedTitle.adding(font: appearance.titleFont) let sizeInfo = MultilineTextFieldSizer.size(for: attributedTitle, numberOfLines: appearance.titleNumberOfLines, width: Int(textBoxRect.width)) r.size.height = sizeInfo.size.height @@ -132,7 +132,7 @@ private extension TimelineCellLayout { var r = textBoxRect r.origin.y = NSMaxY(titleRect) let summaryNumberOfLines = appearance.titleNumberOfLines - titleNumberOfLines - + let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: summaryNumberOfLines, width: Int(textBoxRect.width)) r.size.height = sizeInfo.size.height if sizeInfo.numberOfLinesUsed < 1 { @@ -160,7 +160,7 @@ private extension TimelineCellLayout { static func rectForDate(_ textBoxRect: NSRect, _ rectAbove: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { let textFieldSize = SingleLineTextFieldSizer.size(for: cellData.dateString, font: appearance.dateFont) - + var r = NSZeroRect r.size = textFieldSize r.origin.y = NSMaxY(rectAbove) + appearance.titleBottomMargin @@ -182,7 +182,7 @@ private extension TimelineCellLayout { r.origin.y = dateRect.minY r.origin.x = textBoxRect.origin.x r.size.width = (textBoxRect.maxX - (dateRect.size.width + appearance.dateMarginLeft)) - textBoxRect.origin.x - + return r } @@ -220,7 +220,7 @@ private extension TimelineCellLayout { return r } - + static func rectForSeparator(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ alignmentRect: NSRect, _ width: CGFloat, _ height: CGFloat) -> NSRect { return NSRect(x: alignmentRect.minX, y: height - 1, width: width - alignmentRect.minX, height: 1) } diff --git a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift index dc51a997c..c6436cf77 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift @@ -35,13 +35,13 @@ final class TimelineTableCellView: NSTableCellView { } } } - + var cellData: TimelineCellData! { didSet { updateSubviews() } } - + var isEmphasized: Bool = false { didSet { unreadIndicatorView.isEmphasized = isEmphasized @@ -55,7 +55,7 @@ final class TimelineTableCellView: NSTableCellView { updateStarView() } } - + override var isFlipped: Bool { return true } @@ -64,7 +64,7 @@ final class TimelineTableCellView: NSTableCellView { super.init(frame: frameRect) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() @@ -73,29 +73,29 @@ final class TimelineTableCellView: NSTableCellView { convenience init() { self.init(frame: NSRect.zero) } - + override func setFrameSize(_ newSize: NSSize) { - + if newSize == self.frame.size { return } - + super.setFrameSize(newSize) needsLayout = true } override func viewDidMoveToSuperview() { - + updateSubviews() } - + override func layout() { resizeSubviews(withOldSize: NSZeroSize) } - + override func resizeSubviews(withOldSize oldSize: NSSize) { - + let layoutRects = updatedLayoutRects() setFrame(for: titleView, rect: layoutRects.titleRect) @@ -144,7 +144,7 @@ private extension TimelineTableCellView { imageView.imageScaling = scaling return imageView } - + func setFrame(for textField: NSTextField, rect: NSRect) { if Int(floor(rect.height)) == 0 || Int(floor(rect.width)) == 0 { diff --git a/Mac/MainWindow/Timeline/Cell/UnreadIndicatorView.swift b/Mac/MainWindow/Timeline/Cell/UnreadIndicatorView.swift index e19428070..c3a99ba56 100644 --- a/Mac/MainWindow/Timeline/Cell/UnreadIndicatorView.swift +++ b/Mac/MainWindow/Timeline/Cell/UnreadIndicatorView.swift @@ -11,7 +11,7 @@ import AppKit final class UnreadIndicatorView: NSView { static let unreadCircleDimension: CGFloat = 8.0 - + var isEmphasized = false { didSet { if isEmphasized != oldValue { @@ -19,7 +19,7 @@ final class UnreadIndicatorView: NSView { } } } - + var isSelected = false { didSet { if isSelected != oldValue { @@ -41,5 +41,5 @@ final class UnreadIndicatorView: NSView { } UnreadIndicatorView.bezierPath.fill() } - + } diff --git a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift index 78abb4aff..a6668408b 100644 --- a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift @@ -23,7 +23,7 @@ final class TimelineContainerViewController: NSViewController { @IBOutlet weak var newestToOldestMenuItem: NSMenuItem! @IBOutlet weak var oldestToNewestMenuItem: NSMenuItem! @IBOutlet weak var groupByFeedMenuItem: NSMenuItem! - + @IBOutlet weak var readFilteredButton: NSButton! @IBOutlet var containerView: TimelineContainerView! @@ -37,7 +37,7 @@ final class TimelineContainerViewController: NSViewController { view?.window?.recalculateKeyViewLoop() } } - + var windowState: TimelineWindowState? { return currentTimelineViewController?.windowState } @@ -53,7 +53,7 @@ final class TimelineContainerViewController: NSViewController { guard let currentTimelineViewController = currentTimelineViewController, mode(for: currentTimelineViewController) == .regular else { return false } return regularTimelineViewController.isCleanUpAvailable } - + lazy var regularTimelineViewController = { return TimelineViewController(delegate: self) }() @@ -67,23 +67,23 @@ final class TimelineContainerViewController: NSViewController { super.viewDidLoad() setRepresentedObjects(nil, mode: .regular) showTimeline(for: .regular) - + makeMenuItemTitleLarger(newestToOldestMenuItem) makeMenuItemTitleLarger(oldestToNewestMenuItem) makeMenuItemTitleLarger(groupByFeedMenuItem) updateViewOptionsPopUpButton() - + NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) } - + // MARK: - Notifications - + @objc func userDefaultsDidChange(_ note: Notification) { Task { updateViewOptionsPopUpButton() } } - + // MARK: - API func setRepresentedObjects(_ objects: [AnyObject]?, mode: TimelineSourceMode) { @@ -119,21 +119,21 @@ final class TimelineContainerViewController: NSViewController { } return true } - + func cleanUp() { regularTimelineViewController.cleanUp() } - + func toggleReadFilter() { regularTimelineViewController.toggleReadFilter() updateReadFilterButton() } - + // MARK: State Restoration - + func restoreState(from state: TimelineWindowState?) { guard let state else { return } - + regularTimelineViewController.restoreState(from: state) updateReadFilterButton() } @@ -156,11 +156,11 @@ extension TimelineContainerViewController: TimelineDelegate { func timelineRequestedFeedSelection(_: TimelineViewController, feed: Feed) { delegate?.timelineRequestedFeedSelection(self, feed: feed) } - + func timelineInvalidatedRestorationState(_: TimelineViewController) { delegate?.timelineInvalidatedRestorationState(self) } - + } private extension TimelineContainerViewController { @@ -169,7 +169,7 @@ private extension TimelineContainerViewController { menuItem.attributedTitle = NSAttributedString(string: menuItem.title, attributes: [NSAttributedString.Key.font: NSFont.controlContentFont(ofSize: NSFont.systemFontSize)]) } - + func timelineViewController(for mode: TimelineSourceMode) -> TimelineViewController { switch mode { case .regular: @@ -189,7 +189,7 @@ private extension TimelineContainerViewController { assertionFailure("Expected timelineViewController to match either regular or search timelineViewController, but it doesn’t.") return .regular // Should never get here. } - + @MainActor func updateViewOptionsPopUpButton() { if AppDefaults.shared.timelineSortDirection == .orderedAscending { newestToOldestMenuItem.state = .off @@ -200,32 +200,32 @@ private extension TimelineContainerViewController { oldestToNewestMenuItem.state = .off viewOptionsPopUpButton.setTitle(newestToOldestMenuItem.title) } - + if AppDefaults.shared.timelineGroupByFeed == true { groupByFeedMenuItem.state = .on } else { groupByFeedMenuItem.state = .off } } - + func updateReadFilterButton() { guard currentTimelineViewController == regularTimelineViewController else { readFilteredButton.isHidden = true return } - + guard let isReadFiltered = regularTimelineViewController.isReadFiltered else { readFilteredButton.isHidden = true return } - + readFilteredButton.isHidden = false - + if isReadFiltered { readFilteredButton.image = AppAssets.filterActive } else { readFilteredButton.image = AppAssets.filterInactive } } - + } diff --git a/Mac/MainWindow/Timeline/TimelineTableRowView.swift b/Mac/MainWindow/Timeline/TimelineTableRowView.swift index 8d757de3f..03be0a3d8 100644 --- a/Mac/MainWindow/Timeline/TimelineTableRowView.swift +++ b/Mac/MainWindow/Timeline/TimelineTableRowView.swift @@ -11,7 +11,7 @@ import AppKit final class TimelineTableRowView : NSTableRowView { private var separator: NSView? - + override var isOpaque: Bool { return true } @@ -21,14 +21,14 @@ final class TimelineTableRowView : NSTableRowView { cellView?.isEmphasized = isEmphasized } } - + override var isSelected: Bool { didSet { cellView?.isSelected = isSelected separator?.isHidden = isSelected } } - + init() { super.init(frame: NSRect.zero) } @@ -36,7 +36,7 @@ final class TimelineTableRowView : NSTableRowView { required init?(coder: NSCoder) { super.init(coder: coder) } - + private var cellView: TimelineTableCellView? { for oneSubview in subviews { if let foundView = oneSubview as? TimelineTableCellView { @@ -51,7 +51,7 @@ final class TimelineTableRowView : NSTableRowView { addSeparatorView() } } - + private func addSeparatorView() { guard let cellView = cellView, separator == nil else { return } separator = NSView() @@ -66,5 +66,5 @@ final class TimelineTableRowView : NSTableRowView { separator!.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0) ]) } - + } diff --git a/Mac/MainWindow/Timeline/TimelineTableView.swift b/Mac/MainWindow/Timeline/TimelineTableView.swift index 85610cf10..1d4c0d7e4 100644 --- a/Mac/MainWindow/Timeline/TimelineTableView.swift +++ b/Mac/MainWindow/Timeline/TimelineTableView.swift @@ -10,15 +10,15 @@ import AppKit import RSCore final class TimelineTableView: NSTableView { - + weak var keyboardDelegate: KeyboardDelegate? - + override func accessibilityLabel() -> String? { return NSLocalizedString("Timeline", comment: "Timeline") } - + // MARK: - NSResponder - + override func keyDown(with event: NSEvent) { if keyboardDelegate?.keydown(event, in: self) ?? false { return @@ -31,14 +31,14 @@ final class TimelineTableView: NSTableView { override var isOpaque: Bool { return true } - + override func viewWillStartLiveResize() { if let scrollView = self.enclosingScrollView { scrollView.hasVerticalScroller = false } super.viewWillStartLiveResize() } - + override func viewDidEndLiveResize() { if let scrollView = self.enclosingScrollView { scrollView.hasVerticalScroller = true diff --git a/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift b/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift index 2d1af736d..c2fbdfeb1 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift @@ -70,7 +70,7 @@ extension TimelineViewController { } delegate?.timelineRequestedFeedSelection(self, feed: feed) } - + @objc func markAllInFeedAsRead(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let feed = menuItem.representedObject as? Feed else { @@ -90,7 +90,7 @@ extension TimelineViewController { runCommand(markReadCommand) } - + @objc func openInBrowserFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let urlString = menuItem.representedObject as? String else { @@ -98,7 +98,7 @@ extension TimelineViewController { } Browser.open(urlString, inBackground: false) } - + @objc func copyURLFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let urlString = menuItem.representedObject as? String else { return @@ -170,7 +170,7 @@ private extension TimelineViewController { } menu.addSeparatorIfNeeded() - + if articles.count == 1, let feed = articles.first!.feed { if !(representedObjects?.contains(where: { $0 as? Feed == feed }) ?? false) { menu.addItem(selectFeedInSidebarMenuItem(feed)) @@ -179,13 +179,13 @@ private extension TimelineViewController { menu.addItem(markAllMenuItem) } } - + if articles.count == 1, let link = articles.first!.preferredLink { menu.addSeparatorIfNeeded() menu.addItem(openInBrowserMenuItem(link)) menu.addSeparatorIfNeeded() menu.addItem(copyArticleURLMenuItem(link)) - + if let externalLink = articles.first?.externalLink, externalLink != link { menu.addItem(copyExternalURLMenuItem(externalLink)) } @@ -251,7 +251,7 @@ private extension TimelineViewController { func markAboveReadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark Above as Read", comment: "Command"), #selector(markAboveArticlesReadFromContextualMenu(_:)), articles, image: AppAssets.markAboveAsReadImage) } - + func markBelowReadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark Below as Read", comment: "Command"), #selector(markBelowArticlesReadFromContextualMenu(_:)), articles, image: AppAssets.markBelowAsReadImage) } @@ -269,19 +269,19 @@ private extension TimelineViewController { let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let menuText = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String - + return menuItem(menuText, #selector(markAllInFeedAsRead(_:)), feed, image: AppAssets.markAllAsReadImage) } - + func openInBrowserMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Open in Browser", comment: "Command"), #selector(openInBrowserFromContextualMenu(_:)), urlString, image: AppAssets.openInBrowserImage) } - + func copyArticleURLMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Copy Article URL", comment: "Command"), #selector(copyURLFromContextualMenu(_:)), urlString, image: AppAssets.copyImage) } - + func copyExternalURLMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Copy External URL", comment: "Command"), #selector(copyURLFromContextualMenu(_:)), urlString, image: AppAssets.copyImage) } diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index 213d6c74b..0e19fb4c4 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -42,10 +42,10 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr return timelineFeed.defaultReadFilterType == .read } } - + var isCleanUpAvailable: Bool { let isEligibleForCleanUp: Bool? - + if representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? SidebarItem, timelineFeed.defaultReadFilterType == .alwaysRead { isEligibleForCleanUp = true } else { @@ -53,14 +53,14 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } guard isEligibleForCleanUp ?? false else { return false } - + let readSelectedCount = selectedArticles.filter({ $0.status.read }).count let readArticleCount = articles.count - unreadCount let availableToCleanCount = readArticleCount - readSelectedCount - + return availableToCleanCount > 0 } - + var representedObjects: [AnyObject]? { didSet { if !representedObjectArraysAreEqual(oldValue, representedObjects) { @@ -83,7 +83,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr var windowState: TimelineWindowState { let readArticlesFilterStateKeys = readFilterEnabledTable.keys.compactMap { $0.userInfo as? [String: String] } let readArticlesFilterStateValues = readFilterEnabledTable.values.compactMap( { $0 }) - + if selectedArticles.count == 1 { let path = selectedArticles.first!.pathUserInfo return TimelineWindowState(readArticlesFilterStateKeys: readArticlesFilterStateKeys, @@ -216,7 +216,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr self.init(nibName: "TimelineTableView", bundle: nil) self.delegate = delegate } - + override func viewDidLoad() { cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize) cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize) @@ -227,9 +227,9 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr tableView.doubleAction = #selector(openArticleInBrowser(_:)) tableView.setDraggingSourceOperationMask(.copy, forLocal: false) tableView.keyboardDelegate = keyboardDelegate - + tableView.style = .inset - + if !didRegisterForNotifications { NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) @@ -244,13 +244,13 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr didRegisterForNotifications = true } } - + override func viewDidAppear() { sharingServiceDelegate = SharingServiceDelegate(self.view.window) } // MARK: - API - + func markAllAsRead(completion: (() -> Void)? = nil) { guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articles, markingRead: true, undoManager: undoManager, completion: completion) else { return @@ -275,7 +275,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } return representedObjects.first! === object } - + func cleanUp() { fetchAndReplacePreservingSelection() } @@ -286,23 +286,23 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr delegate?.timelineInvalidatedRestorationState(self) fetchAndReplacePreservingSelection() } - + // MARK: State Restoration - + func restoreState(from state: TimelineWindowState) { for i in 0..= tableMaxIndex { tableView.scrollTo(row: tableMaxIndex, extraHeight: 0) } - + tableView.selectRow(nextRowIndex) - + let followingRowIndex = nextRowIndex + 1 if followingRowIndex > tableMaxIndex { return @@ -435,11 +435,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr tableView.scrollToRowIfNotVisible(followingRowIndex) } - + func toggleReadStatusForSelectedArticles() { // If any one of the selected articles is unread, then mark them as read. // If all articles are read, then mark them as unread them. - + let commandStatus = markReadCommandStatus() let markingRead: Bool switch commandStatus { @@ -450,14 +450,14 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr case .canDoNothing: return } - + guard let undoManager = undoManager, let markStarredCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: markingRead, undoManager: undoManager) else { return } - + runCommand(markStarredCommand) } - + func toggleStarredStatusForSelectedArticles() { // If any one of the selected articles is not starred, then star them. @@ -486,11 +486,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr func markReadCommandStatus() -> MarkCommandValidationStatus { let articles = selectedArticles - + if articles.anyArticleIsUnread() { return .canMark } - + if articles.anyArticleIsReadAndCanMarkUnread() { return .canUnmark } @@ -568,7 +568,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } // MARK: - Navigation - + func goToDeepLink(for userInfo: [AnyHashable : Any]) { guard let articleID = userInfo[ArticlePathKey.articleID] as? String else { return } @@ -581,12 +581,12 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } guard let ix = articles.firstIndex(where: { $0.articleID == articleID }) else { return } - + NSCursor.setHiddenUntilMouseMoves(true) tableView.selectRow(ix) tableView.scrollTo(row: ix) } - + func goToNextUnread(wrappingToTop wrapping: Bool = false) { guard let ix = indexOfNextUnreadArticle() else { return @@ -595,14 +595,14 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr tableView.selectRow(ix) tableView.scrollTo(row: ix) } - + func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool { guard let _ = indexOfNextUnreadArticle(wrappingToTop: wrapping) else { return false } return true } - + func indexOfNextUnreadArticle(wrappingToTop wrapping: Bool = false) -> Int? { return articles.rowOfNextUnreadArticle(tableView.selectedRow, wrappingToTop: wrapping) } @@ -611,7 +611,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr guard let window = tableView.window else { return } - + window.makeFirstResponderUnlessDescendantIsFirstResponder(tableView) if !hasAtLeastOneSelectedArticle && articles.count > 0 { tableView.selectRowAndScrollToVisible(0) @@ -686,7 +686,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr fetchAndReplaceArticlesAsync() } } - + @objc func accountsDidChange(_ note: Notification) { if representedObjectsContainsAnyPseudoFeed() { fetchAndReplaceArticlesAsync() @@ -706,7 +706,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr self.groupByFeed = AppDefaults.shared.timelineGroupByFeed } } - + // MARK: - Reloading Data private func cellForRowView(_ rowView: NSView) -> NSView? { @@ -722,7 +722,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } reloadVisibleCells(for: indexes) } - + private func reloadVisibleCells(for articles: [Article]) { reloadVisibleCells(for: Set(articles.articleIDs())) } @@ -730,7 +730,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr private func reloadVisibleCells(for articles: Set
) { reloadVisibleCells(for: articles.articleIDs()) } - + private func reloadVisibleCells(for articleIDs: Set) { if articleIDs.isEmpty { return @@ -754,7 +754,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } tableView.reloadData(forRowIndexes: indexes, columnIndexes: NSIndexSet(index: 0) as IndexSet) } - + // MARK: - Cell Configuring private func calculateRowHeight() -> CGFloat { @@ -990,7 +990,7 @@ extension TimelineViewController: NSTableViewDelegate { // MARK: - Private private extension TimelineViewController { - + func fetchAndReplacePreservingSelection() { if let article = oneSelectedArticle, let account = article.account { exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID) @@ -999,7 +999,7 @@ private extension TimelineViewController { fetchAndReplaceArticlesSync() } } - + @objc func reloadAvailableCells() { if let indexesToReload = tableView.indexesOfAvailableRows() { reloadCells(for: indexesToReload) @@ -1034,7 +1034,7 @@ private extension TimelineViewController { self.showIcons = false return } - + for article in articles { if let authors = article.authors { for author in authors { @@ -1061,7 +1061,7 @@ private extension TimelineViewController { replaceArticles(with: unsortedArticles) } } - + func selectedArticleIDs() -> [String] { return selectedArticles.articleIDs() } @@ -1136,7 +1136,7 @@ private extension TimelineViewController { } // MARK: - Fetching Articles - + func fetchAndReplaceArticlesSync() { // To be called when the user has made a change of selection in the sidebar. // It blocks the main thread, so that there’s no async delay, @@ -1147,12 +1147,12 @@ private extension TimelineViewController { emptyTheTimeline() return } - + if exceptionArticleFetcher != nil { representedObjects.append(exceptionArticleFetcher as AnyObject) exceptionArticleFetcher = nil } - + let fetchedArticles = fetchUnsortedArticlesSync(for: representedObjects) replaceArticles(with: fetchedArticles) } @@ -1165,12 +1165,12 @@ private extension TimelineViewController { emptyTheTimeline() return } - + if exceptionArticleFetcher != nil { representedObjects.append(exceptionArticleFetcher as AnyObject) exceptionArticleFetcher = nil } - + fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (articles) in self?.replaceArticles(with: articles) } diff --git a/Mac/MainWindow/Timeline/TimelineWindowState.swift b/Mac/MainWindow/Timeline/TimelineWindowState.swift index 3cafa9975..3882d3dd1 100644 --- a/Mac/MainWindow/Timeline/TimelineWindowState.swift +++ b/Mac/MainWindow/Timeline/TimelineWindowState.swift @@ -37,7 +37,7 @@ final class TimelineWindowState: NSObject, NSSecureCoding { selectedAccountID = coder.decodeObject(of: NSString.self, forKey: Key.selectedAccountID) as? String selectedArticleID = coder.decodeObject(of: NSString.self, forKey: Key.selectedArticleID) as? String } - + func encode(with coder: NSCoder) { coder.encode(readArticlesFilterStateKeys, forKey: Key.readArticlesFilterStateKeys) coder.encode(readArticlesFilterStateValues, forKey: Key.readArticlesFilterStateValues) diff --git a/Mac/Preferences/Accounts/AccountCell.swift b/Mac/Preferences/Accounts/AccountCell.swift index 0d9549413..6da8d4ca9 100644 --- a/Mac/Preferences/Accounts/AccountCell.swift +++ b/Mac/Preferences/Accounts/AccountCell.swift @@ -9,33 +9,33 @@ import AppKit final class AccountCell: NSTableCellView { - + private var originalImage: NSImage? - + var isImageTemplateCapable = true - + override func prepareForReuse() { originalImage = nil } - + override var backgroundStyle: NSView.BackgroundStyle { didSet { updateImage() } } - + } private extension AccountCell { - + func updateImage() { guard isImageTemplateCapable else { return } - + if backgroundStyle != .normal { guard !(imageView?.image?.isTemplate ?? false) else { return } - + originalImage = imageView?.image - + let templateImage = imageView?.image?.copy() as? NSImage templateImage?.isTemplate = true imageView?.image = templateImage @@ -44,5 +44,5 @@ private extension AccountCell { imageView?.image = originalImage } } - + } diff --git a/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift b/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift index b542896de..23f8372f5 100644 --- a/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift @@ -36,13 +36,13 @@ final class AccountsAddCloudKitWindowController: NSWindowController { guard let hostWindow, let window else { return } - + hostWindow.endSheet(window, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func create(_ sender: Any) { assert(!AccountManager.shared.hasiCloudAccount) - + guard AddCloudKitAccountUtilities.isiCloudDriveEnabled else { presentError(AddCloudKitAccountError.iCloudDriveMissing) return diff --git a/Mac/Preferences/Accounts/AccountsAddLocalWindowController.swift b/Mac/Preferences/Accounts/AccountsAddLocalWindowController.swift index e6c385ca3..1a6f71268 100644 --- a/Mac/Preferences/Accounts/AccountsAddLocalWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsAddLocalWindowController.swift @@ -13,21 +13,21 @@ final class AccountsAddLocalWindowController: NSWindowController { @IBOutlet private weak var nameTextField: NSTextField! @IBOutlet private weak var localAccountNameTextField: NSTextField! - + private weak var hostWindow: NSWindow? convenience init() { self.init(windowNibName: NSNib.Name("AccountsAddLocal")) } - + override func windowDidLoad() { super.windowDidLoad() - + localAccountNameTextField.stringValue = NSLocalizedString("Create a local account on your Mac.", comment: "Account Local") } - + // MARK: API - + func runSheetOnWindow(_ hostWindow: NSWindow) { guard let window else { return @@ -38,11 +38,11 @@ final class AccountsAddLocalWindowController: NSWindowController { } // MARK: Actions - + @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func create(_ sender: Any) { let account = AccountManager.shared.createAccount(type: .onMyMac) if !nameTextField.stringValue.isEmpty { @@ -50,5 +50,5 @@ final class AccountsAddLocalWindowController: NSWindowController { } hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK) } - + } diff --git a/Mac/Preferences/Accounts/AccountsDetailViewController.swift b/Mac/Preferences/Accounts/AccountsDetailViewController.swift index 5386dd67e..ebd839911 100644 --- a/Mac/Preferences/Accounts/AccountsDetailViewController.swift +++ b/Mac/Preferences/Accounts/AccountsDetailViewController.swift @@ -15,7 +15,7 @@ final class AccountsDetailViewController: NSViewController, NSTextFieldDelegate @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var activeButton: NSButtonCell! @IBOutlet weak var credentialsButton: NSButton! - + private var accountsWindowController: NSWindowController? private var account: Account? @@ -27,7 +27,7 @@ final class AccountsDetailViewController: NSViewController, NSTextFieldDelegate public required init?(coder: NSCoder) { super.init(coder: coder) } - + private var hidesCredentialsButton: Bool { guard let account = account else { return true @@ -39,17 +39,17 @@ final class AccountsDetailViewController: NSViewController, NSTextFieldDelegate return false } } - + override func viewDidLoad() { super.viewDidLoad() - + nameTextField.delegate = self typeLabel.stringValue = account?.defaultName ?? "" nameTextField.stringValue = account?.name ?? "" activeButton.state = account?.isActive ?? false ? .on : .off credentialsButton.isHidden = hidesCredentialsButton } - + func controlTextDidEndEditing(_ obj: Notification) { if !nameTextField.stringValue.isEmpty { account?.name = nameTextField.stringValue @@ -57,15 +57,15 @@ final class AccountsDetailViewController: NSViewController, NSTextFieldDelegate account?.name = nil } } - + @IBAction func active(_ sender: NSButtonCell) { account?.isActive = sender.state == .on ? true : false } - + @IBAction func credentials(_ sender: Any) { - + guard let account = account else { return } - + switch account.type { case .feedbin: let accountsFeedbinWindowController = AccountsFeedbinWindowController() @@ -87,7 +87,7 @@ final class AccountsDetailViewController: NSViewController, NSTextFieldDelegate default: break } - + } - + } diff --git a/Mac/Preferences/Accounts/AccountsFeedbinWindowController.swift b/Mac/Preferences/Accounts/AccountsFeedbinWindowController.swift index 5164a6f84..323570277 100644 --- a/Mac/Preferences/Accounts/AccountsFeedbinWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsFeedbinWindowController.swift @@ -21,15 +21,15 @@ final class AccountsFeedbinWindowController: NSWindowController { @IBOutlet weak var passwordTextField: NSSecureTextField! @IBOutlet weak var errorMessageLabel: NSTextField! @IBOutlet weak var actionButton: NSButton! - + var account: Account? - + private weak var hostWindow: NSWindow? - + convenience init() { self.init(windowNibName: NSNib.Name("AccountsFeedbin")) } - + override func windowDidLoad() { if let account = account, let credentials = try? account.retrieveCredentials(type: .basic) { usernameTextField.stringValue = credentials.username @@ -41,14 +41,14 @@ final class AccountsFeedbinWindowController: NSWindowController { actionButton.title = NSLocalizedString("Create", comment: "Add Account") signInTextField.stringValue = NSLocalizedString("Sign in to your Feedbin account.", comment: "SignIn") } - + enableAutofill() - + usernameTextField.becomeFirstResponder() } - + // MARK: API - + func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) { guard let window else { return @@ -63,15 +63,15 @@ final class AccountsFeedbinWindowController: NSWindowController { @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func action(_ sender: Any) { errorMessageLabel.stringValue = "" - + guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else { errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error") return } - + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .feedbin, username: usernameTextField.stringValue) else { errorMessageLabel.stringValue = NSLocalizedString("There is already a Feedbin account with that username created.", comment: "Duplicate Error") return @@ -123,11 +123,11 @@ final class AccountsFeedbinWindowController: NSWindowController { } } } - + @IBAction func createAccountWithProvider(_ sender: Any) { NSWorkspace.shared.open(URL(string: "https://feedbin.com/signup")!) } - + // MARK: Autofill func enableAutofill() { usernameTextField.contentType = .username diff --git a/Mac/Preferences/Accounts/AccountsNewsBlurWindowController.swift b/Mac/Preferences/Accounts/AccountsNewsBlurWindowController.swift index 0d97f3b63..a398ddba7 100644 --- a/Mac/Preferences/Accounts/AccountsNewsBlurWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsNewsBlurWindowController.swift @@ -12,7 +12,7 @@ import RSWeb import Secrets final class AccountsNewsBlurWindowController: NSWindowController { - + @IBOutlet weak var signInTextField: NSTextField! @IBOutlet weak var noAccountTextField: NSTextField! @IBOutlet weak var createNewAccountButton: NSButton! @@ -69,7 +69,7 @@ final class AccountsNewsBlurWindowController: NSWindowController { errorMessageLabel.stringValue = NSLocalizedString("Username required.", comment: "Credentials Error") return } - + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .newsBlur, username: usernameTextField.stringValue) else { errorMessageLabel.stringValue = NSLocalizedString("There is already a NewsBlur account with that username created.", comment: "Duplicate Error") return @@ -79,27 +79,27 @@ final class AccountsNewsBlurWindowController: NSWindowController { actionButton.isEnabled = false progressIndicator.isHidden = false progressIndicator.startAnimation(self) - + @MainActor func stopAnimation() { actionButton.isEnabled = true progressIndicator.isHidden = true progressIndicator.stopAnimation(self) } - + let credentials = Credentials(type: .newsBlurBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue) do { let validatedCredentials = try await Account.validateCredentials(type: .newsBlur, credentials: credentials) stopAnimation() - + guard let validatedCredentials else { errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error") return } - + if account == nil { account = AccountManager.shared.createAccount(type: .newsBlur) } - + do { try account?.removeCredentials(type: .newsBlurBasic) try account?.removeCredentials(type: .newsBlurSessionId) @@ -111,7 +111,7 @@ final class AccountsNewsBlurWindowController: NSWindowController { } catch { NSApplication.shared.presentError(error) } - + hostWindow?.endSheet(window!, returnCode: NSApplication.ModalResponse.OK) } catch { self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error") @@ -122,15 +122,15 @@ final class AccountsNewsBlurWindowController: NSWindowController { } } } - + @IBAction func createAccountWithProvider(_ sender: Any) { NSWorkspace.shared.open(URL(string: "https://newsblur.com")!) } - + // MARK: Autofill func enableAutofill() { usernameTextField.contentType = .username passwordTextField.contentType = .password } - + } diff --git a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift index 25913e4a4..d0bc1502a 100644 --- a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift +++ b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift @@ -35,7 +35,7 @@ final class AccountsPreferencesViewController: NSViewController { tableView.delegate = self tableView.dataSource = self addAccountDelegate = self - + NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidDeleteAccount, object: nil) @@ -45,34 +45,34 @@ final class AccountsPreferencesViewController: NSViewController { var rTable = tableView.frame rTable.size.width = tableView.superview!.frame.size.width tableView.frame = rTable - + hideController() } - + @IBAction func addAccount(_ sender: Any) { let controller = NSHostingController(rootView: AddAccountsView(delegate: self)) controller.rootView.parent = controller addAccountsViewController = controller presentAsSheet(controller) } - + @IBAction func removeAccount(_ sender: Any) { - + guard tableView.selectedRow != -1 else { return } - + let acctName = sortedAccounts[tableView.selectedRow].nameForDisplay - + let alert = NSAlert() alert.alertStyle = .warning let deletePrompt = NSLocalizedString("Delete", comment: "Delete") alert.messageText = "\(deletePrompt) “\(acctName)”?" alert.informativeText = NSLocalizedString("Are you sure you want to delete the account “\(acctName)”? This cannot be undone.", comment: "Delete text") - + alert.addButton(withTitle: NSLocalizedString("Delete", comment: "Delete Account")) alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel Delete Account")) - + alert.beginSheetModal(for: view.window!) { [weak self] result in if result == NSApplication.ModalResponse.alertFirstButtonReturn { guard let self = self else { return } @@ -80,19 +80,19 @@ final class AccountsPreferencesViewController: NSViewController { self.hideController() } } - + } - + @objc func displayNameDidChange(_ note: Notification) { updateSortedAccounts() tableView.reloadData() } - + @objc func accountsDidChange(_ note: Notification) { updateSortedAccounts() tableView.reloadData() } - + } // MARK: - NSTableViewDataSource @@ -118,18 +118,18 @@ extension AccountsPreferencesViewController: NSTableViewDelegate { let account = sortedAccounts[row] cell.textField?.stringValue = account.nameForDisplay cell.imageView?.image = account.smallIcon?.image - + if account.type == .feedbin { cell.isImageTemplateCapable = false } - + return cell } return nil } func tableViewSelectionDidChange(_ notification: Notification) { - + let selectedRow = tableView.selectedRow if tableView.selectedRow == -1 { deleteButton.isEnabled = false @@ -143,12 +143,12 @@ extension AccountsPreferencesViewController: NSTableViewDelegate { if AccountManager.shared.defaultAccount == account { deleteButton.isEnabled = false } - + let controller = AccountsDetailViewController(account: account) showController(controller) - + } - + } extension AccountsPreferencesViewController: AccountsPreferencesAddAccountDelegate { @@ -187,26 +187,26 @@ extension AccountsPreferencesViewController: AccountsPreferencesAddAccountDelega addAccountWindowController = accountsNewsBlurWindowController } } - + private func runAwaitingFeedlyLoginAlertModal(forLifetimeOf operation: OAuthAccountAuthorizationOperation) { let alert = NSAlert() alert.alertStyle = .informational alert.messageText = NSLocalizedString("Waiting for access to Feedly", comment: "Alert title when adding a Feedly account and waiting for authorization from the user.") - + alert.informativeText = NSLocalizedString("A web browser will open the Feedly login for you to authorize access.", comment: "Alert informative text when adding a Feedly account and waiting for authorization from the user.") - + alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel")) - + let attachedWindow = self.view.window! - + alert.beginSheetModal(for: attachedWindow) { response in if response == .alertFirstButtonReturn { operation.cancel() } } - + operation.completionBlock = { _ in guard alert.window.isVisible else { return @@ -223,22 +223,22 @@ private extension AccountsPreferencesViewController { func updateSortedAccounts() { sortedAccounts = AccountManager.shared.sortedAccounts } - + func showController(_ controller: NSViewController) { hideController() - + addChild(controller) controller.view.translatesAutoresizingMaskIntoConstraints = false detailView.addSubview(controller.view) detailView.addFullSizeConstraints(forSubview: controller.view) } - + func hideController() { if let controller = children.first { children.removeAll() controller.view.removeFromSuperview() } - + if tableView.selectedRow == -1 { var helpText = "" if sortedAccounts.count == 0 { @@ -246,7 +246,7 @@ private extension AccountsPreferencesViewController { } else { helpText = NSLocalizedString("To add an account to NetNewsWire,\nclick its icon above.\n\nOr click the + button in the lower left.", comment: "Add Account Explainer") } - + let textHostingController = NSHostingController(rootView: AddAccountHelpView(delegate: addAccountDelegate, helpText: helpText)) addChild(textHostingController) @@ -257,14 +257,14 @@ private extension AccountsPreferencesViewController { NSLayoutConstraint(item: textHostingController.view, attribute: .bottom, relatedBy: .equal, toItem: detailView, attribute: .bottom, multiplier: 1, constant: -deleteButton.frame.height), NSLayoutConstraint(item: textHostingController.view, attribute: .width, relatedBy: .equal, toItem: detailView, attribute: .width, multiplier: 1, constant: 1) ]) - + } } - + } extension AccountsPreferencesViewController: OAuthAccountAuthorizationOperationDelegate { - + func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) { // `OAuthAccountAuthorizationOperation` is using `ASWebAuthenticationSession` which bounces the user // to their browser on macOS for authorizing NetNewsWire to access the user's Feedly account. @@ -280,12 +280,12 @@ extension AccountsPreferencesViewController: OAuthAccountAuthorizationOperationD } } } - + func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) { // `OAuthAccountAuthorizationOperation` is using `ASWebAuthenticationSession` which bounces the user // to their browser on macOS for authorizing NetNewsWire to access the user's Feedly account. NSApp.activate(ignoringOtherApps: true) - + view.window?.presentError(error) } } diff --git a/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift b/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift index 073e57cc3..b40c78f7f 100644 --- a/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsReaderAPIWindowController.swift @@ -15,7 +15,7 @@ final class AccountsReaderAPIWindowController: NSWindowController { @IBOutlet weak var titleImageView: NSImageView! @IBOutlet weak var titleLabel: NSTextField! - + @IBOutlet weak var gridView: NSGridView! @IBOutlet weak var progressIndicator: NSProgressIndicator! @IBOutlet weak var usernameTextField: NSTextField! @@ -25,16 +25,16 @@ final class AccountsReaderAPIWindowController: NSWindowController { @IBOutlet weak var errorMessageLabel: NSTextField! @IBOutlet weak var actionButton: NSButton! @IBOutlet weak var noAccountTextField: NSTextField! - + var account: Account? var accountType: AccountType? - + private weak var hostWindow: NSWindow? - + convenience init() { self.init(windowNibName: NSNib.Name("AccountsReaderAPI")) } - + override func windowDidLoad() { if let accountType = accountType { switch accountType { @@ -63,7 +63,7 @@ final class AccountsReaderAPIWindowController: NSWindowController { break } } - + if let account = account, let credentials = try? account.retrieveCredentials(type: .readerBasic) { usernameTextField.stringValue = credentials.username apiURLTextField.stringValue = account.endpointURL?.absoluteString ?? "" @@ -71,13 +71,13 @@ final class AccountsReaderAPIWindowController: NSWindowController { } else { actionButton.title = NSLocalizedString("Create", comment: "Create") } - + enableAutofill() usernameTextField.becomeFirstResponder() } - + // MARK: API - + func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) { guard let window else { return @@ -88,29 +88,29 @@ final class AccountsReaderAPIWindowController: NSWindowController { } // MARK: Actions - + @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } - + @IBAction func action(_ sender: Any) { self.errorMessageLabel.stringValue = "" - + guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else { self.errorMessageLabel.stringValue = NSLocalizedString("Username, password & API URL are required.", comment: "Credentials Error") return } - + guard let accountType = accountType, !(accountType == .freshRSS && apiURLTextField.stringValue.isEmpty) else { self.errorMessageLabel.stringValue = NSLocalizedString("Username, password & API URL are required.", comment: "Credentials Error") return } - + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: accountType, username: usernameTextField.stringValue) 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: @@ -181,7 +181,7 @@ final class AccountsReaderAPIWindowController: NSWindowController { } } } - + @IBAction func createAccountWithProvider(_ sender: Any) { switch accountType { case .freshRSS: @@ -196,11 +196,11 @@ final class AccountsReaderAPIWindowController: NSWindowController { return } } - + // MARK: Autofill func enableAutofill() { usernameTextField.contentType = .username passwordTextField.contentType = .password } - + } diff --git a/Mac/Preferences/Accounts/AddAccountHelpView.swift b/Mac/Preferences/Accounts/AddAccountHelpView.swift index 482232507..eee6f2224 100644 --- a/Mac/Preferences/Accounts/AddAccountHelpView.swift +++ b/Mac/Preferences/Accounts/AddAccountHelpView.swift @@ -10,7 +10,7 @@ import SwiftUI import Account struct AddAccountHelpView: View { - + let accountTypes: [AccountType] = AddAccountSections.allOrdered.sectionContent var delegate: AccountsPreferencesAddAccountDelegate? var helpText: String @@ -38,7 +38,7 @@ struct AddAccountHelpView: View { } } } - + Text(helpText) .multilineTextAlignment(.center) .padding(.top, 8) diff --git a/Mac/Preferences/Accounts/AddAccountsView.swift b/Mac/Preferences/Accounts/AddAccountsView.swift index 774a6c868..1cdf69990 100644 --- a/Mac/Preferences/Accounts/AddAccountsView.swift +++ b/Mac/Preferences/Accounts/AddAccountsView.swift @@ -16,7 +16,7 @@ enum AddAccountSections: Int, CaseIterable { case web case selfhosted case allOrdered - + var sectionHeader: String { switch self { case .local: @@ -31,7 +31,7 @@ enum AddAccountSections: Int, CaseIterable { return "" } } - + var sectionFooter: String { switch self { case .local: @@ -46,7 +46,7 @@ enum AddAccountSections: Int, CaseIterable { return "" } } - + var sectionContent: [AccountType] { switch self { case .local: @@ -68,38 +68,38 @@ enum AddAccountSections: Int, CaseIterable { AddAccountSections.selfhosted.sectionContent } } - - - - + + + + } struct AddAccountsView: View { - + weak var parent: NSHostingController? // required because presentationMode.dismiss() doesn't work var addAccountDelegate: AccountsPreferencesAddAccountDelegate? private let chunkLimit = 4 // use this to control number of accounts in each web account column @State private var selectedAccount: AccountType = .onMyMac - + init(delegate: AccountsPreferencesAddAccountDelegate?) { self.addAccountDelegate = delegate } - + var body: some View { VStack(alignment: .leading, spacing: 8) { Text("Choose an account type to add...") .font(.headline) .padding() - + localAccount - + if !AppDefaults.shared.isDeveloperBuild { icloudAccount } - + webAccounts selfhostedAccounts - + HStack(spacing: 12) { Spacer() Button(action: { @@ -128,13 +128,13 @@ struct AddAccountsView: View { .frame(width: 420) .padding() } - + var localAccount: some View { VStack(alignment: .leading) { Text("Local") .font(.headline) .padding(.horizontal) - + Picker(selection: $selectedAccount, label: Text(""), content: { ForEach(AddAccountSections.local.sectionContent, id: \.self, content: { account in HStack(alignment: .center) { @@ -150,23 +150,23 @@ struct AddAccountsView: View { }) .pickerStyle(RadioGroupPickerStyle()) .offset(x: 7.5, y: 0) - + Text(AddAccountSections.local.sectionFooter).foregroundColor(.gray) .padding(.horizontal) .lineLimit(3) .fixedSize(horizontal: false, vertical: true) - + } - + } - + var icloudAccount: some View { VStack(alignment: .leading) { Text("iCloud") .font(.headline) .padding(.horizontal) .padding(.top, 8) - + Picker(selection: $selectedAccount, label: Text(""), content: { ForEach(AddAccountSections.icloud.sectionContent, id: \.self, content: { account in HStack(alignment: .center) { @@ -175,7 +175,7 @@ struct AddAccountsView: View { .aspectRatio(contentMode: .fit) .frame(width: 20, height: 20, alignment: .center) .padding(.leading, 4) - + Text(account.localizedAccountName()) } .tag(account) @@ -190,7 +190,7 @@ struct AddAccountsView: View { .fixedSize(horizontal: false, vertical: true) } } - + @ViewBuilder var webAccounts: some View { VStack(alignment: .leading) { @@ -198,13 +198,13 @@ struct AddAccountsView: View { .font(.headline) .padding(.horizontal) .padding(.top, 8) - + HStack { ForEach(0.. String { return UserDefaults.standard.string(forKey: appcastDefaultsKey) ?? "" } diff --git a/Mac/Preferences/General/GeneralPrefencesViewController.swift b/Mac/Preferences/General/GeneralPrefencesViewController.swift index 7fb93a71a..8ad06f129 100644 --- a/Mac/Preferences/General/GeneralPrefencesViewController.swift +++ b/Mac/Preferences/General/GeneralPrefencesViewController.swift @@ -51,7 +51,7 @@ final class GeneralPreferencesViewController: NSViewController { let url = URL(fileURLWithPath: ArticleThemesManager.shared.folderPath) NSWorkspace.shared.open(url) } - + @IBAction func articleThemePopUpDidChange(_ sender: Any) { guard let menuItem = articleThemePopup.selectedItem else { return @@ -59,7 +59,7 @@ final class GeneralPreferencesViewController: NSViewController { ArticleThemesManager.shared.currentThemeName = menuItem.title updateArticleThemePopup() } - + @IBAction func browserPopUpDidChangeValue(_ sender: Any?) { guard let menuItem = defaultBrowserPopup.selectedItem else { return @@ -84,18 +84,18 @@ private extension GeneralPreferencesViewController { updateArticleThemePopup() updateBrowserPopup() } - + func updateArticleThemePopup() { let menu = articleThemePopup.menu! menu.removeAllItems() - + menu.addItem(NSMenuItem(title: ArticleTheme.defaultTheme.name, action: nil, keyEquivalent: "")) menu.addItem(NSMenuItem.separator()) for themeName in ArticleThemesManager.shared.themeNames { menu.addItem(NSMenuItem(title: themeName, action: nil, keyEquivalent: "")) } - + articleThemePopup.selectItem(withTitle: ArticleThemesManager.shared.currentThemeName) if articleThemePopup.indexOfSelectedItem == -1 { articleThemePopup.selectItem(withTitle: ArticleTheme.defaultTheme.name) diff --git a/Mac/Preferences/PreferencesWindowController.swift b/Mac/Preferences/PreferencesWindowController.swift index 1af02886f..8be35d94b 100644 --- a/Mac/Preferences/PreferencesWindowController.swift +++ b/Mac/Preferences/PreferencesWindowController.swift @@ -13,7 +13,7 @@ private struct PreferencesToolbarItemSpec { let identifier: NSToolbarItem.Identifier let name: String let image: NSImage? - + init(identifierRawValue: String, name: String, image: NSImage?) { self.identifier = NSToolbarItem.Identifier(identifierRawValue) self.name = name @@ -28,7 +28,7 @@ private struct ToolbarItemIdentifier { } final class PreferencesWindowController : NSWindowController, NSToolbarDelegate { - + private let windowWidth = CGFloat(512.0) // Width is constant for all views; only the height changes private var viewControllers = [String: NSViewController]() private let toolbarItemSpecs: [PreferencesToolbarItemSpec] = { @@ -126,7 +126,7 @@ private extension PreferencesWindowController { assertionFailure("Preferences window: no view controller matching \(identifier).") return } - + if newViewController.view == currentView { return } @@ -167,23 +167,23 @@ private extension PreferencesWindowController { let viewFrame = view.frame let windowFrame = window!.frame let contentViewFrame = window!.contentView!.frame - + let deltaHeight = NSHeight(contentViewFrame) - NSHeight(viewFrame) let heightForWindow = NSHeight(windowFrame) - deltaHeight let windowOriginY = NSMinY(windowFrame) + deltaHeight - + var updatedWindowFrame = windowFrame updatedWindowFrame.size.height = heightForWindow updatedWindowFrame.origin.y = windowOriginY updatedWindowFrame.size.width = windowWidth //NSWidth(viewFrame) - + var updatedViewFrame = viewFrame updatedViewFrame.origin = NSZeroPoint updatedViewFrame.size.width = windowWidth if viewFrame != updatedViewFrame { view.frame = updatedViewFrame } - + if windowFrame != updatedWindowFrame { window!.contentView?.alphaValue = 0.0 window!.setFrame(updatedWindowFrame, display: true, animate: true) diff --git a/Mac/SafariExtension/SafariExtensionHandler.swift b/Mac/SafariExtension/SafariExtensionHandler.swift index 4c51e8680..d4366203d 100644 --- a/Mac/SafariExtension/SafariExtensionHandler.swift +++ b/Mac/SafariExtension/SafariExtensionHandler.swift @@ -70,7 +70,7 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { } } } - + override func toolbarItemClicked(in window: SFSafariWindow) { window.getActiveTab { (activeTab) in activeTab?.getActivePage(completionHandler: { (activePage) in diff --git a/Mac/Scriptability/Account+Scriptability.swift b/Mac/Scriptability/Account+Scriptability.swift index 8aedef6f7..485a53208 100644 --- a/Mac/Scriptability/Account+Scriptability.swift +++ b/Mac/Scriptability/Account+Scriptability.swift @@ -13,12 +13,12 @@ import RSCore @objc(ScriptableAccount) final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { - + let account:Account init (_ account:Account) { self.account = account } - + @objc(objectSpecifier) override var objectSpecifier: NSScriptObjectSpecifier? { let myContainer = NSApplication.shared @@ -47,13 +47,13 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec } // MARK: --- ScriptingObject protocol --- - + var scriptingKey: String { return "accounts" } // MARK: --- UniqueIdScriptingObject protocol --- - + // I am not sure if account should prefer to be specified by name or by ID // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) @@ -62,11 +62,11 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec } // MARK: --- ScriptingObjectContainer protocol --- - + var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } - + func deleteElement(_ element:ScriptingObject) { if let scriptableFolder = element as? ScriptableFolder { BatchUpdate.shared.perform { @@ -93,30 +93,30 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec } // MARK: --- Scriptable elements --- - + @objc(feeds) var feeds:NSArray { return account.topLevelFeeds.map { ScriptableFeed($0, container:self) } as NSArray } - + @objc(countOfFeeds) func countOfFeeds() -> Int { return account.topLevelFeeds.count } - + @objc(objectInFeedsAtIndex:) func objectInFeedsAtIndex(_ index: Int) -> ScriptableFeed? { let feeds = Array(account.topLevelFeeds) guard index >= 0 && index < feeds.count else { return nil } return ScriptableFeed(feeds[index], container: self) } - + @objc(valueInFeedsWithUniqueID:) func valueInFeeds(withUniqueID id:String) -> ScriptableFeed? { guard let feed = account.existingFeed(withFeedID: id) else { return nil } return ScriptableFeed(feed, container:self) } - + @objc(valueInFeedsWithName:) func valueInFeeds(withName name:String) -> ScriptableFeed? { let feeds = Array(account.flattenedFeeds()) @@ -130,12 +130,12 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec let folders = Array(foldersSet) return folders.map { ScriptableFolder($0, container:self) } as NSArray } - + @objc(countOfFolders) func countOfFolders() -> Int { return account.folders?.count ?? 0 } - + @objc(objectInFoldersAtIndex:) func objectInFoldersAtIndex(_ index: Int) -> ScriptableFolder? { let foldersSet = account.folders ?? Set() @@ -143,7 +143,7 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec guard index >= 0 && index < folders.count else { return nil } return ScriptableFolder(folders[index], container: self) } - + @objc(valueInFoldersWithUniqueID:) func valueInFolders(withUniqueID id:NSNumber) -> ScriptableFolder? { let folderId = id.intValue @@ -163,25 +163,25 @@ final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjec } return scriptableFeeds as NSArray } - + @objc(countOfAllFeeds) func countOfAllFeeds() -> Int { return account.flattenedFeeds().count } - + @objc(objectInAllFeedsAtIndex:) func objectInAllFeedsAtIndex(_ index: Int) -> ScriptableFeed? { let allFeeds = Array(account.flattenedFeeds()) guard index >= 0 && index < allFeeds.count else { return nil } return ScriptableFeed(allFeeds[index], container: self) } - + @objc(valueInAllFeedsWithUniqueID:) func valueInAllFeeds(withUniqueID id:String) -> ScriptableFeed? { guard let feed = account.existingFeed(withFeedID: id) else { return nil } return ScriptableFeed(feed, container:self) } - + @objc(valueInAllFeedsWithName:) func valueInAllFeeds(withName name:String) -> ScriptableFeed? { let feeds = Array(account.flattenedFeeds()) diff --git a/Mac/Scriptability/AppDelegate+Scriptability.swift b/Mac/Scriptability/AppDelegate+Scriptability.swift index 39a13c703..29906aba6 100644 --- a/Mac/Scriptability/AppDelegate+Scriptability.swift +++ b/Mac/Scriptability/AppDelegate+Scriptability.swift @@ -31,13 +31,13 @@ protocol ScriptingAppDelegate { } extension AppDelegate : AppDelegateAppleEvents { - + // MARK: GetURL Apple Event func installAppleEventHandlers() { NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(AppDelegate.getURL(_:_:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) } - + @objc func getURL(_ event: NSAppleEventDescriptor, _ withReplyEvent: NSAppleEventDescriptor) { guard var urlString = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else { @@ -51,14 +51,14 @@ extension AppDelegate : AppDelegateAppleEvents { let themeURLString = queryItems.first(where: { $0.name == "url" })?.value else { return } - + if let themeURL = URL(string: themeURLString) { let request = URLRequest(url: themeURL) let task = URLSession.shared.downloadTask(with: request) { location, response, error in guard let location = location else { return } - + do { try ArticleThemeDownloader.shared.handleFile(at: location) } catch { @@ -68,10 +68,10 @@ extension AppDelegate : AppDelegateAppleEvents { task.resume() } return - + } - - + + // Special case URL with specific scheme handler x-netnewswire-feed: intended to ensure we open // it regardless of which news reader may be set as the default let nnwScheme = "x-netnewswire-feed:" @@ -128,7 +128,7 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { container.deleteElement(element) } } - + /* delete(specifier:, from container:) At this point in handling the command, the container could be a list or a single object, @@ -177,7 +177,7 @@ final class NetNewsWireExistsCommand : NSExistsCommand { // must not exist. Otherwise, we return the result of the defaultImplementation // The wrinkle is that it is possible that the direct object is a list, so we need to // handle that case as well - + override func performDefaultImplementation() -> Any? { guard let result = super.performDefaultImplementation() else { return NSNumber(booleanLiteral:false) } return result diff --git a/Mac/Scriptability/Article+Scriptability.swift b/Mac/Scriptability/Article+Scriptability.swift index e3a34e46f..328b0cad7 100644 --- a/Mac/Scriptability/Article+Scriptability.swift +++ b/Mac/Scriptability/Article+Scriptability.swift @@ -15,7 +15,7 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec let article:Article let container:ScriptingObjectContainer - + init (_ article:Article, container:ScriptingObjectContainer) { self.article = article self.container = container @@ -44,17 +44,17 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec } // MARK: --- ScriptingObjectContainer protocol --- - + var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } - + func deleteElement(_ element:ScriptingObject) { print ("delete event not handled") } // MARK: --- Scriptable properties --- - + @objc(url) var url:String? { return article.preferredLink @@ -69,7 +69,7 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec var externalUrl:String? { return article.externalLink } - + @objc(title) var title:String { return article.title ?? "" @@ -134,7 +134,7 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec var imageURL:String { return article.imageLink ?? "" } - + @objc(authors) var authors:NSArray { let articleAuthors = article.authors ?? [] diff --git a/Mac/Scriptability/Author+Scriptability.swift b/Mac/Scriptability/Author+Scriptability.swift index ca6f23335..33bcd6104 100644 --- a/Mac/Scriptability/Author+Scriptability.swift +++ b/Mac/Scriptability/Author+Scriptability.swift @@ -15,7 +15,7 @@ final class ScriptableAuthor: NSObject, UniqueIdScriptingObject { let author:Author let container:ScriptingObjectContainer - + init (_ author:Author, container:ScriptingObjectContainer) { self.author = author self.container = container @@ -44,14 +44,14 @@ final class ScriptableAuthor: NSObject, UniqueIdScriptingObject { var scriptingUniqueId:Any { return author.authorID } - + // MARK: --- Scriptable properties --- - + @objc(url) var url:String { return self.author.url ?? "" } - + @objc(name) var name:String { return self.author.name ?? "" diff --git a/Mac/Scriptability/Feed+Scriptability.swift b/Mac/Scriptability/Feed+Scriptability.swift index 659f04446..9e2982e1c 100644 --- a/Mac/Scriptability/Feed+Scriptability.swift +++ b/Mac/Scriptability/Feed+Scriptability.swift @@ -16,7 +16,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo let feed:Feed let container:ScriptingObjectContainer - + init (_ feed:Feed, container:ScriptingObjectContainer) { self.feed = feed self.container = container @@ -49,11 +49,11 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo } // MARK: --- ScriptingObjectContainer protocol --- - + var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } - + func deleteElement(_ element:ScriptingObject) { } @@ -70,7 +70,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo } return url } - + class func scriptableFeed(_ feed:Feed, account:Account, folder:Folder?) -> ScriptableFeed { let scriptableAccount = ScriptableAccount(account) if let folder = folder { @@ -80,14 +80,14 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo return ScriptableFeed(feed, container:scriptableAccount) } } - + class func scriptableFeed(for feed: Feed) -> ScriptableFeed? { guard let account = feed.account else { return nil } - + // Find the proper container hierarchy let containers = account.existingContainers(withFeed: feed) var folder: Folder? = nil - + // Check if feed is in a folder for container in containers { if let foundFolder = container as? Folder { @@ -95,23 +95,23 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo break } } - + return scriptableFeed(feed, account: account, folder: folder) } - + class func handleCreateElement(command:NSCreateCommand) -> Any? { guard command.isCreateCommand(forClass:"Feed") else { return nil } guard let arguments = command.arguments else {return nil} let titleFromArgs = command.property(forKey:"name") as? String let (account, folder) = command.accountAndFolderForNewChild() guard let url = self.urlForNewFeed(arguments:arguments) else {return nil} - + if let existingFeed = account.existingFeed(withURL:url) { return scriptableFeed(existingFeed, account:account, folder:folder).objectSpecifier } - + let container: Container = folder != nil ? folder! : account - + // We need to download the feed and parse it. // RSParser does the callback for the download on the main thread. // Because we can't wait here (on the main thread) for the callback, we have to return from this function. @@ -119,7 +119,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo // but we don’t yet have the result of the event yet, so we prevent the Apple event from returning by calling // suspendExecution(). When we get the callback, we supply the event result and call resumeExecution(). command.suspendExecution() - + account.createFeed(url: url, name: titleFromArgs, container: container, validateFeed: true) { result in switch result { case .success(let feed): @@ -131,7 +131,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo } } - + return nil } @@ -141,7 +141,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo var url:String { return self.feed.url } - + @objc(name) var name:String { return self.feed.name ?? "" @@ -166,7 +166,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo var opmlRepresentation:String { return self.feed.OPMLString(indentLevel:0) } - + // MARK: --- scriptable elements --- @objc(authors) @@ -174,13 +174,13 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo let feedAuthors = feed.authors ?? [] return feedAuthors.map { ScriptableAuthor($0, container:self) } as NSArray } - + @objc(valueInAuthorsWithUniqueID:) func valueInAuthors(withUniqueID id:String) -> ScriptableAuthor? { guard let author = feed.authors?.first(where:{$0.authorID == id}) else { return nil } return ScriptableAuthor(author, container:self) } - + @objc(articles) var articles:NSArray { let feedArticles = (try? feed.fetchArticles()) ?? Set
() @@ -190,7 +190,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo }) return sortedArticles.map { ScriptableArticle($0, container:self) } as NSArray } - + @objc(valueInArticlesWithUniqueID:) func valueInArticles(withUniqueID id:String) -> ScriptableArticle? { let articles = (try? feed.fetchArticles()) ?? Set
() diff --git a/Mac/Scriptability/Folder+Scriptability.swift b/Mac/Scriptability/Folder+Scriptability.swift index bab26ff62..9c2793a27 100644 --- a/Mac/Scriptability/Folder+Scriptability.swift +++ b/Mac/Scriptability/Folder+Scriptability.swift @@ -43,13 +43,13 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject var scriptingUniqueId:Any { return folder.folderID } - + // MARK: --- ScriptingObjectContainer protocol --- - + var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } - + func deleteElement(_ element:ScriptingObject) { if let scriptableFeed = element as? ScriptableFeed { BatchUpdate.shared.perform { @@ -76,9 +76,9 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject print("support for folders within folders is NYI"); return nil } - + command.suspendExecution() - + account.addFolder(name) { result in switch result { case .success(let folder): @@ -89,12 +89,12 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject command.resumeExecution(withResult:nil) } } - + return nil } - + // MARK: --- Scriptable elements --- - + @objc(feeds) var feeds:NSArray { let feeds = Array(folder.topLevelFeeds) @@ -137,7 +137,7 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject } // MARK: --- Scriptable properties --- - + @objc(name) var name:String { return self.folder.name ?? "" diff --git a/Mac/Scriptability/NSApplication+Scriptability.swift b/Mac/Scriptability/NSApplication+Scriptability.swift index a3c44d565..dba8ea9f9 100644 --- a/Mac/Scriptability/NSApplication+Scriptability.swift +++ b/Mac/Scriptability/NSApplication+Scriptability.swift @@ -25,7 +25,7 @@ extension NSApplication : ScriptingObjectContainer { var scriptingKey: String { return "application" } - + @objc(currentArticle) func currentArticle() -> ScriptableArticle? { var scriptableArticle: ScriptableArticle? @@ -51,18 +51,18 @@ extension NSApplication : ScriptingObjectContainer { } return scriptableArticles as NSArray } - + @objc(countOfSelectedArticles) func countOfSelectedArticles() -> Int { return appDelegate.scriptingSelectedArticles.count } - + @objc(objectInSelectedArticlesAtIndex:) func objectInSelectedArticlesAtIndex(_ index: Int) -> ScriptableArticle? { let articles = appDelegate.scriptingSelectedArticles guard index >= 0 && index < articles.count else { return nil } let article = articles[index] - + if let feed = article.feed, let scriptableFeed = ScriptableFeed.scriptableFeed(for: feed) { return ScriptableArticle(article, container: scriptableFeed) @@ -78,19 +78,19 @@ extension NSApplication : ScriptingObjectContainer { let accounts = AccountManager.shared.accounts return accounts.map { ScriptableAccount($0) } as NSArray } - + @objc(countOfAccounts) func countOfAccounts() -> Int { return AccountManager.shared.accounts.count } - + @objc(objectInAccountsAtIndex:) func objectInAccountsAtIndex(_ index: Int) -> ScriptableAccount? { let accounts = Array(AccountManager.shared.accounts) guard index >= 0 && index < accounts.count else { return nil } return ScriptableAccount(accounts[index]) } - + @objc(valueInAccountsWithUniqueID:) func valueInAccounts(withUniqueID id:String) -> ScriptableAccount? { let accounts = AccountManager.shared.accounts @@ -103,7 +103,7 @@ extension NSApplication : ScriptingObjectContainer { this allows a script like 'articles of feed "The Shape of Everything"' as a shorthand for 'articles of feed "The Shape of Everything" of account "On My Mac"' */ - + func allFeeds() -> [Feed] { let accounts = AccountManager.shared.activeAccounts let emptyFeeds:[Feed] = [] @@ -117,12 +117,12 @@ extension NSApplication : ScriptingObjectContainer { func feeds() -> NSArray { allFeeds().map { ScriptableFeed($0, container:self) } as NSArray } - + @objc(countOfFeeds) func countOfFeeds() -> Int { allFeeds().count } - + @objc(objectInFeedsAtIndex:) func objectInFeedsAtIndex(_ index: Int) -> ScriptableFeed? { let feeds = allFeeds() diff --git a/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift b/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift index 1cc5e36e5..c9b11bf5e 100644 --- a/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift +++ b/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift @@ -18,7 +18,7 @@ extension NSScriptCommand { } return nil } - + func isCreateCommand(forClass whatClass:String) -> Bool { guard let arguments = self.arguments else {return false} guard let newObjectClass = arguments["ObjectClass"] as? Int else {return false} @@ -44,7 +44,7 @@ extension NSScriptCommand { } else if let subjectDescriptor = appleEvent.attributeDescriptor(forKeyword:"subj".fourCharCode) { descriptorToConsider = subjectDescriptor } - + if let descriptorToConsider = descriptorToConsider { guard let newContainerSpecifier = NSScriptObjectSpecifier(descriptor:descriptorToConsider) else {return (account, folder)} let newContainer = newContainerSpecifier.objectsByEvaluatingSpecifier diff --git a/Mac/Scriptability/ScriptingObjectContainer.swift b/Mac/Scriptability/ScriptingObjectContainer.swift index 8bfe695d7..d9bc2bf34 100644 --- a/Mac/Scriptability/ScriptingObjectContainer.swift +++ b/Mac/Scriptability/ScriptingObjectContainer.swift @@ -25,7 +25,7 @@ extension ScriptingObjectContainer { containerSpecifier:containerScriptObjectSpecifier, key:scriptingKey, name:name) return specifier } - + func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIdScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier diff --git a/Mac/ShareExtension/ShareViewController.swift b/Mac/ShareExtension/ShareViewController.swift index a977e41bc..fe2cbc33d 100644 --- a/Mac/ShareExtension/ShareViewController.swift +++ b/Mac/ShareExtension/ShareViewController.swift @@ -13,7 +13,7 @@ final class ShareViewController: NSViewController { @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var folderPopUpButton: NSPopUpButton! - + private var url: URL? private var extensionContainers: ExtensionContainers? @@ -23,10 +23,10 @@ final class ShareViewController: NSViewController { override func loadView() { super.loadView() - + extensionContainers = ExtensionContainersFile.read() buildFolderPopupMenu() - + var provider: NSItemProvider? = nil // Try to get any HTML that is maybe passed in @@ -91,7 +91,7 @@ final class ShareViewController: NSViewController { let name = nameTextField.stringValue.isEmpty ? nil : nameTextField.stringValue let request = ExtensionFeedAddRequest(name: name, feedURL: url, destinationContainerID: containerID) ExtensionFeedAddRequestFile.save(request) - + self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } @@ -103,12 +103,12 @@ final class ShareViewController: NSViewController { } private extension ShareViewController { - + func buildFolderPopupMenu() { - + let menu = NSMenu(title: "Folders") menu.autoenablesItems = false - + guard let extensionContainers = extensionContainers else { folderPopUpButton.menu = nil return @@ -116,18 +116,18 @@ private extension ShareViewController { let defaultContainer = ShareDefaultContainer.defaultContainer(containers: extensionContainers) var defaultMenuItem: NSMenuItem? = nil - + for account in extensionContainers.accounts { - + let menuItem = NSMenuItem(title: account.name, action: nil, keyEquivalent: "") menuItem.representedObject = account - + if account.disallowFeedInRootFolder { menuItem.isEnabled = false } - + menu.addItem(menuItem) - + if defaultContainer?.containerID == account.containerID { defaultMenuItem = menuItem } @@ -141,15 +141,15 @@ private extension ShareViewController { defaultMenuItem = menuItem } } - + } - + folderPopUpButton.menu = menu folderPopUpButton.select(defaultMenuItem) } - + func selectedContainer() -> ExtensionContainer? { return folderPopUpButton.selectedItem?.representedObject as? ExtensionContainer } - + } diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index 91a3a65b8..e92dc9903 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -43,11 +43,11 @@ public enum AccountType: Int, Codable { case inoreader = 21 case bazQux = 22 case theOldReader = 23 - + public var isDeveloperRestricted: Bool { return self == .cloudKit || self == .feedbin || self == .feedly || self == .inoreader } - + } public enum FetchType { @@ -79,11 +79,11 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public static let defaultLocalAccountName = NSLocalizedString("account.name.on-my-device", tableName: "DefaultAccountNames", comment: "Device specific default account name, e.g: On My iPhone") public var isDeleted = false - + public var containerID: ContainerIdentifier? { return ContainerIdentifier.account(accountID) } - + public var account: Account? { return self } @@ -111,7 +111,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } public let defaultName: String - + public var isActive: Bool { get { return metadata.isActive @@ -128,7 +128,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public var topLevelFeeds = Set() public var folders: Set? = Set() - + public var externalID: String? { get { return metadata.externalID @@ -137,14 +137,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, metadata.externalID = newValue } } - + public var sortedFolders: [Folder]? { if let folders = folders { return Array(folders).sorted(by: { $0.nameForDisplay.caseInsensitiveCompare($1.nameForDisplay) == .orderedAscending }) } return nil } - + private var feedDictionariesNeedUpdate = true private var _idToFeedDictionary = [String: Feed]() var idToFeedDictionary: [String: Feed] { @@ -160,7 +160,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } return _externalIDToFeedDictionary } - + var flattenedFeedURLs: Set { return Set(flattenedFeeds().map({ $0.url })) } @@ -175,7 +175,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } } - + public var endpointURL: URL? { get { return metadata.endpointURL @@ -186,7 +186,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } } - + private var fetchingAllUnreadCounts = false var isUnreadCountsInitialized = false @@ -219,11 +219,11 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } } - + public var behaviors: AccountBehaviors { return delegate.behaviors } - + var refreshInProgress = false { didSet { if refreshInProgress != oldValue { @@ -265,7 +265,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } self.delegate.accountMetadata = metadata - + self.accountID = accountID self.type = type self.dataFolder = dataFolder @@ -312,9 +312,9 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, self.delegate.accountDidInitialize(self) } - + // MARK: - API - + public func storeCredentials(_ credentials: Credentials) throws { username = credentials.username guard let server = delegate.server else { @@ -324,14 +324,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, try CredentialsManager.storeCredentials(credentials, server: server) delegate.credentials = credentials } - + public func retrieveCredentials(type: CredentialsType) throws -> Credentials? { guard let username = self.username, let server = delegate.server else { return nil } return try CredentialsManager.retrieveCredentials(type: type, server: server, username: username) } - + public func removeCredentials(type: CredentialsType) throws { guard let username = self.username, let server = delegate.server else { return @@ -351,7 +351,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return nil } } - + internal static func oauthAuthorizationClient(for type: AccountType) -> OAuthAuthorizationClient { switch type { case .feedly: @@ -360,7 +360,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, fatalError("\(type) is not a client for OAuth authorization code granting.") } } - + public static func oauthAuthorizationCodeGrantRequest(for type: AccountType) -> URLRequest { let grantingType: OAuthAuthorizationGranting.Type switch type { @@ -369,24 +369,24 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, default: fatalError("\(type) does not support OAuth authorization code granting.") } - + return grantingType.oauthAuthorizationCodeGrantRequest() } - + public static func requestOAuthAccessToken(with response: OAuthAuthorizationResponse, client: OAuthAuthorizationClient, accountType: AccountType, transport: Transport = URLSession.webserviceTransport(), completion: @escaping (Result) -> ()) { let grantingType: OAuthAuthorizationGranting.Type - + switch accountType { case .feedly: grantingType = FeedlyAccountDelegate.self default: fatalError("\(accountType) does not support OAuth authorization code granting.") } - + grantingType.requestOAuthAccessToken(with: response, transport: transport, completion: completion) } @@ -416,17 +416,17 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } } - + public func syncArticleStatus(completion: ((Result) -> Void)? = nil) { delegate.syncArticleStatus(for: self, completion: completion) } - + public func importOPML(_ opmlFile: URL, completion: @escaping (Result) -> Void) { guard !delegate.isOPMLImportInProgress else { completion(.failure(AccountError.opmlImportInProgress)) return } - + delegate.importOPML(for: self, opmlFile: opmlFile) { [weak self] result in switch result { case .success: @@ -438,13 +438,13 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, completion(.failure(error)) } } - + } - + public func suspendNetwork() { delegate.suspendNetwork() } - + public func suspendDatabase() { #if os(iOS) database.cancelAndSuspend() @@ -471,7 +471,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, feedMetadataFile.save() opmlFile.save() } - + public func prepareForDeletion() { delegate.accountWillBeDeleted(self) } @@ -492,11 +492,11 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } } - + func loadOPMLItems(_ items: [RSOPMLItem]) { addOPMLItems(OPMLNormalizer.normalize(items)) } - + public func markArticles(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result) -> Void) { delegate.markArticles(for: self, articles: articles, statusKey: statusKey, flag: flag, completion: completion) } @@ -507,7 +507,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } return existingFolder(withExternalID: externalID) } - + public func existingContainers(withFeed feed: Feed) -> [Container] { var containers = [Container]() if topLevelFeeds.contains(feed) { @@ -520,7 +520,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } return containers } - + @discardableResult func ensureFolder(with name: String) -> Folder? { // TODO: support subfolders, maybe, some day @@ -554,11 +554,11 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public func existingFolder(withDisplayName displayName: String) -> Folder? { return folders?.first(where: { $0.nameForDisplay == displayName }) } - + public func existingFolder(withExternalID externalID: String) -> Folder? { return folders?.first(where: { $0.externalID == externalID }) } - + func newFeed(with opmlFeedSpecifier: RSOPMLFeedSpecifier) -> Feed { let feedURL = opmlFeedSpecifier.feedURL let metadata = feedMetadata(feedURL: feedURL, feedID: feedURL) @@ -578,7 +578,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public func createFeed(url: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result) -> Void) { delegate.createFeed(for: self, url: url, name: name, container: container, validateFeed: validateFeed, completion: completion) } - + func createFeed(with name: String?, url: String, feedID: String, homePageURL: String?) -> Feed { let metadata = feedMetadata(feedURL: url, feedID: feedID) let feed = Feed(account: self, url: url, metadata: metadata) @@ -586,31 +586,31 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, feed.homePageURL = homePageURL return feed } - + public func removeFeed(_ feed: Feed, from container: Container, completion: @escaping (Result) -> Void) { delegate.removeFeed(for: self, with: feed, from: container, completion: completion) } - + public func moveFeed(_ feed: Feed, from: Container, to: Container, completion: @escaping (Result) -> Void) { delegate.moveFeed(for: self, with: feed, from: from, to: to, completion: completion) } - + public func renameFeed(_ feed: Feed, to name: String, completion: @escaping (Result) -> Void) { delegate.renameFeed(for: self, with: feed, to: name, completion: completion) } - + public func restoreFeed(_ feed: Feed, container: Container, completion: @escaping (Result) -> Void) { delegate.restoreFeed(for: self, feed: feed, container: container, completion: completion) } - + public func addFolder(_ name: String, completion: @escaping (Result) -> Void) { delegate.createFolder(for: self, name: name, completion: completion) } - + public func removeFolder(_ folder: Folder, completion: @escaping (Result) -> Void) { delegate.removeFolder(for: self, with: folder, completion: completion) } - + public func renameFolder(_ folder: Folder, to name: String, completion: @escaping (Result) -> Void) { delegate.renameFolder(for: self, with: folder, to: name, completion: completion) } @@ -618,17 +618,17 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public func restoreFolder(_ folder: Folder, completion: @escaping (Result) -> Void) { delegate.restoreFolder(for: self, folder: folder, completion: completion) } - + func clearFeedMetadata(_ feed: Feed) { feedMetadata[feed.url] = nil } - + func addFolder(_ folder: Folder) { folders!.insert(folder) postChildrenDidChangeNotification() structureDidChange() } - + public func updateUnreadCounts(for feeds: Set, completion: VoidCompletionBlock? = nil) { fetchUnreadCounts(for: feeds, completion: completion) } @@ -707,7 +707,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { database.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(completion) } - + public func unreadCount(for feed: Feed) -> Int { return unreadCounts[feed.feedID] ?? 0 } @@ -748,15 +748,15 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, completion(.success(ArticleChanges())) return } - + update(feed.feedID, with: parsedItems, completion: completion) } - + func update(_ feedID: String, with parsedItems: Set, deleteOlder: Bool = true, completion: @escaping UpdateArticlesCompletionBlock) { // Used only by an On My Mac or iCloud account. precondition(Thread.isMainThread) precondition(type == .onMyMac || type == .cloudKit) - + database.update(with: parsedItems, feedID: feedID, deleteOlder: deleteOlder) { updateArticlesResult in switch updateArticlesResult { case .success(let articleChanges): @@ -794,7 +794,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, completion(.success(Set
())) return } - + database.mark(articles, statusKey: statusKey, flag: flag) { result in switch result { case .success(let updatedStatuses): @@ -877,7 +877,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } database.delete(articleIDs: articleIDs, completion: completion) } - + /// Empty caches that can reasonably be emptied. Call when the app goes in the background, for instance. func emptyCaches() { database.emptyCaches() @@ -898,7 +898,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, structureDidChange() postChildrenDidChangeNotification() } - + public func removeFeeds(_ feeds: Set) { guard !feeds.isEmpty else { return @@ -907,7 +907,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, structureDidChange() postChildrenDidChangeNotification() } - + public func addFeed(_ feed: Feed) { topLevelFeeds.insert(feed) structureDidChange() @@ -919,13 +919,13 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, addFeed(feed) } } - + func removeFolder(_ folder: Folder) { folders?.remove(folder) structureDidChange() postChildrenDidChangeNotification() } - + // MARK: - Debug public func debugDropConditionalGetInfo() { @@ -956,13 +956,13 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, refreshInProgress = refreshProgress.numberRemaining > 0 NotificationCenter.default.post(name: .AccountRefreshProgressDidChange, object: self) } - + @objc func unreadCountDidChange(_ note: Notification) { if let feed = note.object as? Feed, feed.account === self { updateUnreadCount() } } - + @objc func batchUpdateDidPerform(_ note: Notification) { flattenedFeedsNeedUpdate = true rebuildFeedDictionaries() @@ -1091,7 +1091,7 @@ private extension Account { func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set) throws -> Set
{ return try database.fetchArticlesMatchingWithArticleIDs(searchString, articleIDs) } - + func fetchArticlesMatchingAsync(_ searchString: String, _ completion: @escaping ArticleSetResultBlock) { database.fetchArticlesMatchingAsync(searchString, flattenedFeeds().feedIDs(), completion) } @@ -1137,13 +1137,13 @@ private extension Account { func fetchUnreadArticles(forContainer container: Container, limit: Int?) throws -> Set
{ let feeds = container.flattenedFeeds() let articles = try database.fetchUnreadArticles(feeds.feedIDs(), limit) - + // We don't validate limit queries because they, by definition, won't correctly match the // complete unread state for the given container. if limit == nil { validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) } - + return articles } @@ -1152,13 +1152,13 @@ private extension Account { database.fetchUnreadArticlesAsync(feeds.feedIDs(), limit) { [weak self] (articleSetResult) in switch articleSetResult { case .success(let articles): - + // We don't validate limit queries because they, by definition, won't correctly match the // complete unread state for the given container. if limit == nil { self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) } - + completion(.success(articles)) case .failure(let databaseError): completion(.failure(databaseError)) @@ -1226,7 +1226,7 @@ private extension Account { func rebuildFeedDictionaries() { var idDictionary = [String: Feed]() var externalIDDictionary = [String: Feed]() - + flattenedFeeds().forEach { (feed) in idDictionary[feed.feedID] = feed if let externalID = feed.externalID { @@ -1238,7 +1238,7 @@ private extension Account { _externalIDToFeedDictionary = externalIDDictionary feedDictionariesNeedUpdate = false } - + func updateUnreadCount() { if fetchingAllUnreadCounts { return @@ -1249,7 +1249,7 @@ private extension Account { } unreadCount = updatedUnreadCount } - + func noteStatusesForArticlesDidChange(_ articles: Set
) { let feeds = Set(articles.compactMap { $0.feed }) let statuses = Set(articles.map { $0.status }) @@ -1258,7 +1258,7 @@ private extension Account { // .UnreadCountDidChange notification will get sent to Folder and Account objects, // which will update their own unread counts. updateUnreadCounts(for: feeds) - + NotificationCenter.default.post(name: .StatusesDidChange, object: self, userInfo: [UserInfoKey.statuses: statuses, UserInfoKey.articles: articles, UserInfoKey.articleIDs: articleIDs, UserInfoKey.feeds: feeds]) } @@ -1389,7 +1389,7 @@ extension Account { public func existingFeed(withExternalID externalID: String) -> Feed? { return externalIDToFeedDictionary[externalID] } - + } // MARK: - OPMLRepresentable diff --git a/Modules/Account/Sources/Account/AccountBehaviors.swift b/Modules/Account/Sources/Account/AccountBehaviors.swift index fed082b4c..4d7afdd30 100644 --- a/Modules/Account/Sources/Account/AccountBehaviors.swift +++ b/Modules/Account/Sources/Account/AccountBehaviors.swift @@ -17,32 +17,32 @@ import Foundation public typealias AccountBehaviors = [AccountBehavior] public enum AccountBehavior: Equatable { - + /** Account doesn't support copies of a feed that are in a folder to be made to the root folder. */ case disallowFeedCopyInRootFolder - + /** Account doesn't support feeds in the root folder. */ case disallowFeedInRootFolder - + /** Account doesn't support a feed being in more than one folder. */ case disallowFeedInMultipleFolders - + /** Account doesn't support folders */ case disallowFolderManagement - + /** Account doesn't support OPML imports */ case disallowOPMLImports - + /** Account doesn't allow mark as read after a period of days */ diff --git a/Modules/Account/Sources/Account/AccountDelegate.swift b/Modules/Account/Sources/Account/AccountDelegate.swift index 952ba6aa8..7f59a3843 100644 --- a/Modules/Account/Sources/Account/AccountDelegate.swift +++ b/Modules/Account/Sources/Account/AccountDelegate.swift @@ -16,11 +16,11 @@ protocol AccountDelegate { var behaviors: AccountBehaviors { get } var isOPMLImportInProgress: Bool { get } - + var server: String? { get } var credentials: Credentials? { get set } var accountMetadata: AccountMetadata? { get set } - + var refreshProgress: DownloadProgress { get } func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) @@ -29,9 +29,9 @@ protocol AccountDelegate { func syncArticleStatus(for account: Account, completion: ((Result) -> Void)?) func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) func refreshArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) - + func importOPML(for account:Account, opmlFile: URL, completion: @escaping (Result) -> Void) - + func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result) -> Void) @@ -49,17 +49,17 @@ protocol AccountDelegate { // Called at the end of account’s init method. func accountDidInitialize(_ account: Account) - + func accountWillBeDeleted(_ account: Account) static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? /// Suspend all network activity func suspendNetwork() - + /// Suspend the SQLite databases func suspendDatabase() - + /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() } diff --git a/Modules/Account/Sources/Account/AccountError.swift b/Modules/Account/Sources/Account/AccountError.swift index 75852b178..38f2b164c 100644 --- a/Modules/Account/Sources/Account/AccountError.swift +++ b/Modules/Account/Sources/Account/AccountError.swift @@ -10,12 +10,12 @@ import Foundation import RSWeb public enum AccountError: LocalizedError { - + case createErrorNotFound case createErrorAlreadySubscribed case opmlImportInProgress case wrappedError(error: Error, account: Account) - + public var account: Account? { if case .wrappedError(_, let account) = self { return account @@ -23,7 +23,7 @@ public enum AccountError: LocalizedError { return nil } } - + public var isCredentialsError: Bool { if case .wrappedError(let error, _) = self { if case TransportError.httpError(let status) = error { @@ -32,7 +32,7 @@ public enum AccountError: LocalizedError { } return false } - + public var errorDescription: String? { switch self { case .createErrorNotFound: @@ -55,7 +55,7 @@ public enum AccountError: LocalizedError { } } } - + public var recoverySuggestion: String? { switch self { case .createErrorNotFound: @@ -77,20 +77,20 @@ public enum AccountError: LocalizedError { return NSLocalizedString("Please try again later.", comment: "Try later") } } - + } // MARK: Private private extension AccountError { - + func unknownError(_ error: Error, _ account: Account) -> String { let localizedText = NSLocalizedString("An error occurred while processing the “%@” account: %@", comment: "Unknown error") return NSString.localizedStringWithFormat(localizedText as NSString, account.nameForDisplay, error.localizedDescription) as String } - + func isCredentialsError(status: Int) -> Bool { return status == 401 || status == 403 } - + } diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index c08ecb33c..2da067422 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -38,7 +38,7 @@ public final class AccountManager: UnreadCountProvider { } return true } - + public var unreadCount = 0 { didSet { if unreadCount != oldValue { @@ -73,7 +73,7 @@ public final class AccountManager: UnreadCountProvider { public var sortedActiveAccounts: [Account] { return sortByName(activeAccounts) } - + public var lastArticleFetchEndTime: Date? { var lastArticleFetchEndTime: Date? = nil for account in activeAccounts { @@ -89,7 +89,7 @@ public final class AccountManager: UnreadCountProvider { public func existingActiveAccount(forDisplayName displayName: String) -> Account? { return AccountManager.shared.activeAccounts.first(where: { $0.nameForDisplay == displayName }) } - + public var refreshInProgress: Bool { for account in activeAccounts { if account.refreshInProgress { @@ -103,7 +103,7 @@ public final class AccountManager: UnreadCountProvider { public init(accountsFolder: String) { self.accountsFolder = accountsFolder - + // The local "On My Mac" account must always exist, even if it's empty. let localAccountFolder = (accountsFolder as NSString).appendingPathComponent("OnMyMac") do { @@ -129,14 +129,14 @@ public final class AccountManager: UnreadCountProvider { } // MARK: - API - + public func createAccount(type: AccountType) -> Account { if type == .cloudKit { if let existingiCloudAccount = accounts.first(where: { $0.type == .cloudKit }) { return existingiCloudAccount } } - + let accountID = type == .cloudKit ? "iCloud" : UUID().uuidString let accountFolder = (accountsFolder as NSString).appendingPathComponent("\(type.rawValue)_\(accountID)") @@ -146,14 +146,14 @@ public final class AccountManager: UnreadCountProvider { assertionFailure("Could not create folder for \(accountID) account.") abort() } - + let account = Account(dataFolder: accountFolder, type: type, accountID: accountID) accountsDictionary[accountID] = account - + var userInfo = [String: Any]() userInfo[Account.UserInfoKey.account] = account NotificationCenter.default.post(name: .UserDidAddAccount, object: self, userInfo: userInfo) - + return account } @@ -161,12 +161,12 @@ public final class AccountManager: UnreadCountProvider { guard !account.refreshInProgress else { return } - + account.prepareForDeletion() - + accountsDictionary.removeValue(forKey: account.accountID) account.isDeleted = true - + do { try FileManager.default.removeItem(atPath: account.dataFolder) } @@ -174,14 +174,14 @@ public final class AccountManager: UnreadCountProvider { assertionFailure("Could not create folder for OnMyMac account.") abort() } - + updateUnreadCount() var userInfo = [String: Any]() userInfo[Account.UserInfoKey.account] = account NotificationCenter.default.post(name: .UserDidDeleteAccount, object: self, userInfo: userInfo) } - + public func duplicateServiceAccount(type: AccountType, username: String?) -> Bool { guard type != .onMyMac else { return false @@ -193,11 +193,11 @@ public final class AccountManager: UnreadCountProvider { } return false } - + public func existingAccount(with accountID: String) -> Account? { return accountsDictionary[accountID] } - + public func existingContainer(with containerID: ContainerIdentifier) -> Container? { switch containerID { case .account(let accountID): @@ -209,7 +209,7 @@ public final class AccountManager: UnreadCountProvider { } return nil } - + public func existingFeed(with sidebarItemID: SidebarItemIdentifier) -> SidebarItem? { switch sidebarItemID { case .folder(let accountID, let folderName): @@ -225,7 +225,7 @@ public final class AccountManager: UnreadCountProvider { } return nil } - + public func suspendNetworkAll() { isSuspended = true accounts.forEach { $0.suspendNetwork() } @@ -243,14 +243,14 @@ public final class AccountManager: UnreadCountProvider { public func receiveRemoteNotification(userInfo: [AnyHashable : Any], completion: (() -> Void)? = nil) { let group = DispatchGroup() - + activeAccounts.forEach { account in group.enter() account.receiveRemoteNotification(userInfo: userInfo) { group.leave() } } - + group.notify(queue: DispatchQueue.main) { completion?() } @@ -265,7 +265,7 @@ public final class AccountManager: UnreadCountProvider { combinedRefreshProgress.start() let group = DispatchGroup() - + for account in activeAccounts { group.enter() account.refreshAll() { result in @@ -278,7 +278,7 @@ public final class AccountManager: UnreadCountProvider { } } } - + group.notify(queue: DispatchQueue.main) { self.combinedRefreshProgress.stop() completion?() @@ -287,7 +287,7 @@ public final class AccountManager: UnreadCountProvider { public func sendArticleStatusAll(completion: (() -> Void)? = nil) { let group = DispatchGroup() - + activeAccounts.forEach { group.enter() $0.sendArticleStatus() { _ in @@ -302,7 +302,7 @@ public final class AccountManager: UnreadCountProvider { public func syncArticleStatusAll(completion: (() -> Void)? = nil) { let group = DispatchGroup() - + activeAccounts.forEach { group.enter() $0.syncArticleStatus() { _ in @@ -314,11 +314,11 @@ public final class AccountManager: UnreadCountProvider { completion?() } } - + public func saveAll() { accounts.forEach { $0.save() } } - + public func anyAccountHasAtLeastOneFeed() -> Bool { for account in activeAccounts { if account.hasAtLeastOneFeed() { @@ -328,7 +328,7 @@ public final class AccountManager: UnreadCountProvider { return false } - + public func anyAccountHasNetNewsWireNewsSubscription() -> Bool { return anyAccountHasFeedWithURL(Self.netNewsWireNewsURL) || anyAccountHasFeedWithURL(Self.jsonNetNewsWireNewsURL) } @@ -358,34 +358,34 @@ public final class AccountManager: UnreadCountProvider { public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { precondition(Thread.isMainThread) - + guard activeAccounts.count > 0 else { completion(.success(Set
())) return } - + var allFetchedArticles = Set
() var databaseError: DatabaseError? let dispatchGroup = DispatchGroup() - + for account in activeAccounts { - + dispatchGroup.enter() - + account.fetchArticlesAsync(fetchType) { (articleSetResult) in precondition(Thread.isMainThread) - + switch articleSetResult { case .success(let articles): allFetchedArticles.formUnion(articles) case .failure(let error): databaseError = error } - + dispatchGroup.leave() } } - + dispatchGroup.notify(queue: .main) { if let databaseError { completion(.failure(databaseError)) @@ -417,7 +417,7 @@ public final class AccountManager: UnreadCountProvider { } // MARK: - Notifications - + @objc func unreadCountDidInitialize(_ notification: Notification) { guard let _ = notification.object as? Account else { return @@ -426,14 +426,14 @@ public final class AccountManager: UnreadCountProvider { postUnreadCountDidInitializeNotification() } } - + @objc dynamic func unreadCountDidChange(_ notification: Notification) { guard let _ = notification.object as? Account else { return } updateUnreadCount() } - + @objc func accountStateDidChange(_ notification: Notification) { updateUnreadCount() } @@ -469,7 +469,7 @@ private extension AccountManager { print("Error reading Accounts folder: \(error)") return } - + filenames = filenames?.sorted() filenames?.forEach { (oneFilename) in @@ -483,14 +483,14 @@ private extension AccountManager { } } } - + func duplicateServiceAccount(_ account: Account) -> Bool { return duplicateServiceAccount(type: account.type, username: account.username) } func sortByName(_ accounts: [Account]) -> [Account] { // LocalAccount is first. - + return accounts.sorted { (account1, account2) -> Bool in if account1 === defaultAccount { return true @@ -516,14 +516,14 @@ private struct AccountSpecifier { if !FileManager.default.isFolder(atPath: folderPath) { return nil } - + let name = NSString(string: folderPath).lastPathComponent if name.hasPrefix(".") { return nil } - + let nameComponents = name.components(separatedBy: "_") - + guard nameComponents.count == 2, let rawType = Int(nameComponents[0]), let accountType = AccountType(rawValue: rawType) else { return nil } diff --git a/Modules/Account/Sources/Account/AccountMetadata.swift b/Modules/Account/Sources/Account/AccountMetadata.swift index 8d9ba4fc1..55a82a788 100644 --- a/Modules/Account/Sources/Account/AccountMetadata.swift +++ b/Modules/Account/Sources/Account/AccountMetadata.swift @@ -34,7 +34,7 @@ final class AccountMetadata: Codable { } } } - + var isActive: Bool = true { didSet { if isActive != oldValue { @@ -42,7 +42,7 @@ final class AccountMetadata: Codable { } } } - + var username: String? { didSet { if username != oldValue { @@ -50,7 +50,7 @@ final class AccountMetadata: Codable { } } } - + var conditionalGetInfo = [String: HTTPConditionalGetInfo]() { didSet { if conditionalGetInfo != oldValue { @@ -58,7 +58,7 @@ final class AccountMetadata: Codable { } } } - + var lastArticleFetchStartTime: Date? { didSet { if lastArticleFetchStartTime != oldValue { @@ -66,7 +66,7 @@ final class AccountMetadata: Codable { } } } - + var lastArticleFetchEndTime: Date? { didSet { if lastArticleFetchEndTime != oldValue { @@ -74,7 +74,7 @@ final class AccountMetadata: Codable { } } } - + var endpointURL: URL? { didSet { if endpointURL != oldValue { @@ -94,7 +94,7 @@ final class AccountMetadata: Codable { } weak var delegate: AccountMetadataDelegate? - + func valueDidChange(_ key: CodingKeys) { delegate?.valueDidChange(self, key: key) } diff --git a/Modules/Account/Sources/Account/AccountMetadataFile.swift b/Modules/Account/Sources/Account/AccountMetadataFile.swift index 8c4d19704..f0b5ff3cb 100644 --- a/Modules/Account/Sources/Account/AccountMetadataFile.swift +++ b/Modules/Account/Sources/Account/AccountMetadataFile.swift @@ -13,7 +13,7 @@ import RSCore final class AccountMetadataFile { private let fileURL: URL private let account: Account - + private var isDirty = false { didSet { queueSaveToDiskIfNeeded() @@ -26,11 +26,11 @@ final class AccountMetadataFile { self.fileURL = URL(fileURLWithPath: filename) self.account = account } - + func markAsDirty() { isDirty = true } - + func load() { if let fileData = try? Data(contentsOf: fileURL) { let decoder = PropertyListDecoder() @@ -38,10 +38,10 @@ final class AccountMetadataFile { } account.metadata.delegate = account } - + func save() { guard !account.isDeleted else { return } - + let encoder = PropertyListEncoder() encoder.outputFormat = .binary @@ -52,7 +52,7 @@ final class AccountMetadataFile { Self.logger.error("AccountMetadataFile accountID: \(self.account.accountID) save to disk failed: \(error.localizedDescription)") } } - + } private extension AccountMetadataFile { diff --git a/Modules/Account/Sources/Account/ArticleFetcher.swift b/Modules/Account/Sources/Account/ArticleFetcher.swift index 007c66e17..43bf58d68 100644 --- a/Modules/Account/Sources/Account/ArticleFetcher.swift +++ b/Modules/Account/Sources/Account/ArticleFetcher.swift @@ -19,7 +19,7 @@ public protocol ArticleFetcher { } extension Feed: ArticleFetcher { - + public func fetchArticles() throws -> Set
{ return try account?.fetchArticles(.feed(self)) ?? Set
() } @@ -55,7 +55,7 @@ extension Feed: ArticleFetcher { } extension Folder: ArticleFetcher { - + public func fetchArticles() throws -> Set
{ guard let account = account else { assertionFailure("Expected folder.account, but got nil.") diff --git a/Modules/Account/Sources/Account/CloudKit/CKRecord+Extensions.swift b/Modules/Account/Sources/Account/CloudKit/CKRecord+Extensions.swift index fc97d2dd7..08e127cd6 100644 --- a/Modules/Account/Sources/Account/CloudKit/CKRecord+Extensions.swift +++ b/Modules/Account/Sources/Account/CloudKit/CKRecord+Extensions.swift @@ -10,17 +10,17 @@ import Foundation import CloudKit extension CKRecord { - + var externalID: String { return recordID.externalID } - + } extension CKRecord.ID { - + var externalID: String { return recordName } - + } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 77671dfdb..830c945d3 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -88,7 +88,7 @@ final class CloudKitAccountDelegate: AccountDelegate { } syncProgress.reset() - + guard NetworkMonitor.shared.isConnected else { completion(.success(())) return @@ -172,7 +172,7 @@ final class CloudKitAccountDelegate: AccountDelegate { } let normalizedItems = OPMLNormalizer.normalize(opmlItems) - + syncProgress.addToNumberOfTasksAndRemaining(1) self.accountZone.importOPML(rootExternalID: rootExternalID, items: normalizedItems) { _ in self.syncProgress.completeTask() @@ -304,7 +304,7 @@ final class CloudKitAccountDelegate: AccountDelegate { } func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result) -> Void) { - + syncProgress.addToNumberOfTasksAndRemaining(2) accountZone.findFeedExternalIDs(for: folder) { result in self.syncProgress.completeTask() @@ -544,7 +544,7 @@ private extension CloudKitAccountDelegate { } func standardRefreshAll(for account: Account, completion: @escaping (Result) -> Void) { - + syncProgress.addToNumberOfTasksAndRemaining(3) func fail(_ error: Error) { @@ -556,7 +556,7 @@ private extension CloudKitAccountDelegate { accountZone.fetchChangesInZone() { result in switch result { case .success: - + self.syncProgress.completeTask() let feeds = account.flattenedFeeds() @@ -613,7 +613,7 @@ private extension CloudKitAccountDelegate { syncProgress.addToNumberOfTasksAndRemaining(5) FeedFinder.find(url: url) { result in - + self.syncProgress.completeTask() switch result { case .success(let feedSpecifiers): @@ -641,7 +641,7 @@ private extension CloudKitAccountDelegate { InitialFeedDownloader.download(url) { parsedFeed, _, response, _ in self.syncProgress.completeTask() feed.lastCheckDate = Date() - + if let parsedFeed { // Save conditional GET info so that first refresh uses conditional GET. if let httpResponse = response as? HTTPURLResponse, diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift index c2339e5d6..57d24887f 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift @@ -26,7 +26,7 @@ final class CloudKitAccountZone: CloudKitZone { weak var container: CKContainer? weak var database: CKDatabase? var delegate: CloudKitZoneDelegate? - + struct CloudKitFeed { static let recordType = "AccountWebFeed" struct Fields { @@ -37,7 +37,7 @@ final class CloudKitAccountZone: CloudKitZone { static let containerExternalIDs = "containerExternalIDs" } } - + struct CloudKitContainer { static let recordType = "AccountContainer" struct Fields { @@ -45,18 +45,18 @@ final class CloudKitAccountZone: CloudKitZone { static let name = "name" } } - + init(container: CKContainer) { self.container = container self.database = container.privateCloudDatabase self.zoneID = CKRecordZone.ID(zoneName: "Account", ownerName: CKCurrentUserDefaultName) migrateChangeToken() } - + func importOPML(rootExternalID: String, items: [RSOPMLItem], completion: @escaping (Result) -> Void) { var records = [CKRecord]() var feedRecords = [String: CKRecord]() - + func processFeed(feedSpecifier: RSOPMLFeedSpecifier, containerExternalID: String) { if let feedRecord = feedRecords[feedSpecifier.feedURL], var containerExternalIDs = feedRecord[CloudKitFeed.Fields.containerExternalIDs] as? [String] { containerExternalIDs.append(containerExternalID) @@ -67,7 +67,7 @@ final class CloudKitAccountZone: CloudKitZone { feedRecords[feedSpecifier.feedURL] = feedRecord } } - + for item in items { if let feedSpecifier = item.feedSpecifier { processFeed(feedSpecifier: feedSpecifier, containerExternalID: rootExternalID) @@ -86,7 +86,7 @@ final class CloudKitAccountZone: CloudKitZone { save(records, completion: completion) } - + /// Persist a web feed record to iCloud and return the external key func createFeed(url: String, name: String?, editedName: String?, homePageURL: String?, container: Container, completion: @escaping (Result) -> Void) { let recordID = CKRecord.ID(recordName: url.md5String, zoneID: zoneID) @@ -115,7 +115,7 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + /// Rename the given web feed func renameFeed(_ feed: Feed, editedName: String?, completion: @escaping (Result) -> Void) { guard let externalID = feed.externalID else { @@ -126,7 +126,7 @@ final class CloudKitAccountZone: CloudKitZone { let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) let record = CKRecord(recordType: CloudKitFeed.recordType, recordID: recordID) record[CloudKitFeed.Fields.editedName] = editedName - + save(record) { result in switch result { case .success: @@ -136,22 +136,22 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + /// Removes a web feed from a container and optionally deletes it, calling the completion with true if deleted func removeFeed(_ feed: Feed, from: Container, completion: @escaping (Result) -> Void) { guard let fromContainerExternalID = from.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } - + fetch(externalID: feed.externalID) { result in switch result { case .success(let record): - + if let containerExternalIDs = record[CloudKitFeed.Fields.containerExternalIDs] as? [String] { var containerExternalIDSet = Set(containerExternalIDs) containerExternalIDSet.remove(fromContainerExternalID) - + if containerExternalIDSet.isEmpty { self.delete(externalID: feed.externalID) { result in switch result { @@ -161,9 +161,9 @@ final class CloudKitAccountZone: CloudKitZone { completion(.failure(error)) } } - + } else { - + record[CloudKitFeed.Fields.containerExternalIDs] = Array(containerExternalIDSet) self.save(record) { result in switch result { @@ -173,10 +173,10 @@ final class CloudKitAccountZone: CloudKitZone { completion(.failure(error)) } } - + } } - + case .failure(let error): if let ckError = ((error as? CloudKitError)?.error as? CKError), ckError.code == .unknownItem { completion(.success(true)) @@ -186,13 +186,13 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + func moveFeed(_ feed: Feed, from: Container, to: Container, completion: @escaping (Result) -> Void) { guard let fromContainerExternalID = from.externalID, let toContainerExternalID = to.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } - + fetch(externalID: feed.externalID) { result in switch result { case .success(let record): @@ -208,13 +208,13 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + func addFeed(_ feed: Feed, to: Container, completion: @escaping (Result) -> Void) { guard let toContainerExternalID = to.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } - + fetch(externalID: feed.externalID) { result in switch result { case .success(let record): @@ -229,16 +229,16 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + func findFeedExternalIDs(for folder: Folder, completion: @escaping (Result<[String], Error>) -> Void) { guard let folderExternalID = folder.externalID else { completion(.failure(CloudKitAccountZoneError.unknown)) return } - + let predicate = NSPredicate(format: "containerExternalIDs CONTAINS %@", folderExternalID) let ckQuery = CKQuery(recordType: CloudKitFeed.recordType, predicate: predicate) - + query(ckQuery) { result in switch result { case .success(let records): @@ -249,11 +249,11 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + func findOrCreateAccount(completion: @escaping (Result) -> Void) { let predicate = NSPredicate(format: "isAccount = \"1\"") let ckQuery = CKQuery(recordType: CloudKitContainer.recordType, predicate: predicate) - + database?.fetch(withQuery: ckQuery, inZoneWith: zoneID, desiredKeys: nil, resultsLimit: CKQueryOperation.maximumResults) { [weak self] result in guard let self = self else { return } @@ -293,13 +293,13 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + } - + func createFolder(name: String, completion: @escaping (Result) -> Void) { createContainer(name: name, isAccount: false, completion: completion) } - + func renameFolder(_ folder: Folder, to name: String, completion: @escaping (Result) -> Void) { guard let externalID = folder.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) @@ -309,7 +309,7 @@ final class CloudKitAccountZone: CloudKitZone { let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: recordID) record[CloudKitContainer.Fields.name] = name - + save(record) { result in switch result { case .success: @@ -319,15 +319,15 @@ final class CloudKitAccountZone: CloudKitZone { } } } - + func removeFolder(_ folder: Folder, completion: @escaping (Result) -> Void) { delete(externalID: folder.externalID, completion: completion) } - + } private extension CloudKitAccountZone { - + func newFeedCKRecord(feedSpecifier: RSOPMLFeedSpecifier, containerExternalID: String) -> CKRecord { let record = CKRecord(recordType: CloudKitFeed.recordType, recordID: generateRecordID()) record[CloudKitFeed.Fields.url] = feedSpecifier.feedURL @@ -340,14 +340,14 @@ private extension CloudKitAccountZone { record[CloudKitFeed.Fields.containerExternalIDs] = [containerExternalID] return record } - + func newContainerCKRecord(name: String) -> CKRecord { let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: generateRecordID()) record[CloudKitContainer.Fields.name] = name record[CloudKitContainer.Fields.isAccount] = "0" return record } - + func createContainer(name: String, isAccount: Bool, completion: @escaping (Result) -> Void) { let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: generateRecordID()) record[CloudKitContainer.Fields.name] = name @@ -362,5 +362,5 @@ private extension CloudKitAccountZone { } } } - + } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift index 007b14d7f..f393e4141 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift @@ -14,7 +14,7 @@ import RSCore import Articles final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { - + private typealias UnclaimedFeed = (url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String) private var newUnclaimedFeeds = [String: [UnclaimedFeed]]() private var existingUnclaimedFeeds = [String: [Feed]]() @@ -26,7 +26,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { self.account = account self.articlesZone = articlesZone } - + func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey], completion: @escaping (Result) -> Void) { for deletedRecordKey in deleted { switch deletedRecordKey.recordType { @@ -38,7 +38,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { assertionFailure("Unknown record type: \(deletedRecordKey.recordType)") } } - + for changedRecord in changed { switch changedRecord.recordType { case CloudKitAccountZone.CloudKitFeed.recordType: @@ -49,10 +49,10 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { assertionFailure("Unknown record type: \(changedRecord.recordType)") } } - + completion(.success(())) } - + func addOrUpdateFeed(_ record: CKRecord) { guard let account = account, let urlString = record[CloudKitAccountZone.CloudKitFeed.Fields.url] as? String, @@ -60,7 +60,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { let url = URL(string: urlString) else { return } - + let name = record[CloudKitAccountZone.CloudKitFeed.Fields.name] as? String let editedName = record[CloudKitAccountZone.CloudKitFeed.Fields.editedName] as? String let homePageURL = record[CloudKitAccountZone.CloudKitFeed.Fields.homePageURL] as? String @@ -77,7 +77,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } } - + func removeFeed(_ externalID: String) { if let feed = account?.existingFeed(withExternalID: externalID), let containers = account?.existingContainers(withFeed: feed) { for container in containers { @@ -86,7 +86,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } } - + func addOrUpdateContainer(_ record: CKRecord) { guard let account = account, let name = record[CloudKitAccountZone.CloudKitContainer.Fields.name] as? String, @@ -94,17 +94,17 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { isAccount != "1" else { return } - + var folder = account.existingFolder(withExternalID: record.externalID) folder?.name = name - + if folder == nil { folder = account.ensureFolder(with: name) folder?.externalID = record.externalID } - + guard let container = folder, let containerExternalID = container.externalID else { return } - + if let newUnclaimedFeeds = newUnclaimedFeeds[containerExternalID] { for newUnclaimedFeed in newUnclaimedFeeds { createFeedIfNecessary(url: newUnclaimedFeed.url, @@ -117,7 +117,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { self.newUnclaimedFeeds.removeValue(forKey: containerExternalID) } - + if let existingUnclaimedFeeds = existingUnclaimedFeeds[containerExternalID] { for existingUnclaimedFeed in existingUnclaimedFeeds { container.addFeed(existingUnclaimedFeed) @@ -125,29 +125,29 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { self.existingUnclaimedFeeds.removeValue(forKey: containerExternalID) } } - + func removeContainer(_ externalID: String) { if let folder = account?.existingFolder(withExternalID: externalID) { account?.removeFolder(folder) } } - + } private extension CloudKitAcountZoneDelegate { - + func updateFeed(_ feed: Feed, name: String?, editedName: String?, homePageURL: String?, containerExternalIDs: [String]) { guard let account = account else { return } - + feed.name = name feed.editedName = editedName feed.homePageURL = homePageURL - + let existingContainers = account.existingContainers(withFeed: feed) let existingContainerExternalIds = existingContainers.compactMap { $0.externalID } let diff = containerExternalIDs.difference(from: existingContainerExternalIds) - + for change in diff { switch change { case .remove(_, let externalID, _): @@ -163,20 +163,20 @@ private extension CloudKitAcountZoneDelegate { } } } - + func createFeedIfNecessary(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, container: Container) { guard let account = account else { return } - + if account.existingFeed(withExternalID: feedExternalID) != nil { return } - + let feed = account.createFeed(with: name, url: url.absoluteString, feedID: url.absoluteString, homePageURL: homePageURL) feed.editedName = editedName feed.externalID = feedExternalID container.addFeed(feed) } - + func addNewUnclaimedFeed(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, containerExternalID: String) { if var unclaimedFeeds = self.newUnclaimedFeeds[containerExternalID] { unclaimedFeeds.append(UnclaimedFeed(url: url, name: name, editedName: editedName, homePageURL: homePageURL, feedExternalID: feedExternalID)) @@ -187,7 +187,7 @@ private extension CloudKitAcountZoneDelegate { self.newUnclaimedFeeds[containerExternalID] = unclaimedFeeds } } - + func addExistingUnclaimedFeed(_ feed: Feed, containerExternalID: String) { if var unclaimedFeeds = self.existingUnclaimedFeeds[containerExternalID] { unclaimedFeeds.append(feed) @@ -198,5 +198,5 @@ private extension CloudKitAcountZoneDelegate { self.existingUnclaimedFeeds[containerExternalID] = unclaimedFeeds } } - + } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticleStatusUpdate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticleStatusUpdate.swift index 9bad6d6d0..7cd1a2aec 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticleStatusUpdate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticleStatusUpdate.swift @@ -11,18 +11,18 @@ import SyncDatabase import Articles struct CloudKitArticleStatusUpdate { - + enum Record { case all case new case statusOnly case delete } - + var articleID: String var statuses: [SyncStatus] var article: Article? - + init?(articleID: String, statuses: [SyncStatus], article: Article?) { self.articleID = articleID self.statuses = statuses @@ -34,16 +34,16 @@ struct CloudKitArticleStatusUpdate { return nil } } - + var record: Record { if statuses.contains(where: { $0.key == .deleted }) { return .delete } - + if statuses.count == 1, statuses.first!.key == .new { return .new } - + if let article = article { if article.status.read == false || article.status.starred == true { return .all @@ -52,19 +52,19 @@ struct CloudKitArticleStatusUpdate { return .statusOnly } - + var isRead: Bool { if let article = article { return article.status.read } return true } - + var isStarred: Bool { if let article = article { return article.status.starred } return false } - + } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift index 1caa275ad..d478b6682 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift @@ -16,15 +16,15 @@ import Articles import SyncDatabase final class CloudKitArticlesZone: CloudKitZone { - + var zoneID: CKRecordZone.ID - + weak var container: CKContainer? weak var database: CKDatabase? var delegate: CloudKitZoneDelegate? = nil - + var compressionQueue = DispatchQueue(label: "Articles Zone Compression Queue") - + struct CloudKitArticle { static let recordType = "Article" struct Fields { @@ -61,7 +61,7 @@ final class CloudKitArticlesZone: CloudKitZone { self.zoneID = CKRecordZone.ID(zoneName: "Articles", ownerName: CKCurrentUserDefaultName) migrateChangeToken() } - + func refreshArticles(completion: @escaping ((Result) -> Void)) { fetchChangesInZone() { result in switch result { @@ -83,15 +83,15 @@ final class CloudKitArticlesZone: CloudKitZone { } } } - + func saveNewArticles(_ articles: Set
, completion: @escaping ((Result) -> Void)) { guard !articles.isEmpty else { completion(.success(())) return } - + var records = [CKRecord]() - + let saveArticles = articles.filter { $0.status.read == false || $0.status.starred == true } for saveArticle in saveArticles { records.append(makeStatusRecord(saveArticle)) @@ -103,23 +103,23 @@ final class CloudKitArticlesZone: CloudKitZone { self.save(compressedRecords, completion: completion) } } - + func deleteArticles(_ feedExternalID: String, completion: @escaping ((Result) -> Void)) { let predicate = NSPredicate(format: "webFeedExternalID = %@", feedExternalID) let ckQuery = CKQuery(recordType: CloudKitArticleStatus.recordType, predicate: predicate) delete(ckQuery: ckQuery, completion: completion) } - + func modifyArticles(_ statusUpdates: [CloudKitArticleStatusUpdate], completion: @escaping ((Result) -> Void)) { guard !statusUpdates.isEmpty else { completion(.success(())) return } - + var modifyRecords = [CKRecord]() var newRecords = [CKRecord]() var deleteRecordIDs = [CKRecord.ID]() - + for statusUpdate in statusUpdates { switch statusUpdate.record { case .all: @@ -155,9 +155,9 @@ final class CloudKitArticlesZone: CloudKitZone { } } } - + } - + } private extension CloudKitArticlesZone { @@ -176,15 +176,15 @@ private extension CloudKitArticlesZone { completion(.failure(error)) } } - + func statusID(_ id: String) -> String { return "s|\(id)" } - + func articleID(_ id: String) -> String { return "a|\(id)" } - + func makeStatusRecord(_ article: Article) -> CKRecord { let recordID = CKRecord.ID(recordName: statusID(article.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticleStatus.recordType, recordID: recordID) @@ -195,21 +195,21 @@ private extension CloudKitArticlesZone { record[CloudKitArticleStatus.Fields.starred] = article.status.starred ? "1" : "0" return record } - + func makeStatusRecord(_ statusUpdate: CloudKitArticleStatusUpdate) -> CKRecord { let recordID = CKRecord.ID(recordName: statusID(statusUpdate.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticleStatus.recordType, recordID: recordID) - + if let feedExternalID = statusUpdate.article?.feed?.externalID { record[CloudKitArticleStatus.Fields.feedExternalID] = feedExternalID } - + record[CloudKitArticleStatus.Fields.read] = statusUpdate.isRead ? "1" : "0" record[CloudKitArticleStatus.Fields.starred] = statusUpdate.isStarred ? "1" : "0" - + return record } - + func makeArticleRecord(_ article: Article) -> CKRecord { let recordID = CKRecord.ID(recordName: articleID(article.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticle.recordType, recordID: recordID) @@ -227,10 +227,10 @@ private extension CloudKitArticlesZone { record[CloudKitArticle.Fields.imageURL] = article.rawImageLink record[CloudKitArticle.Fields.datePublished] = article.datePublished record[CloudKitArticle.Fields.dateModified] = article.dateModified - + let encoder = JSONEncoder() var parsedAuthors = [String]() - + if let authors = article.authors, !authors.isEmpty { for author in authors { let parsedAuthor = ParsedAuthor(name: author.name, @@ -243,17 +243,17 @@ private extension CloudKitArticlesZone { } record[CloudKitArticle.Fields.parsedAuthors] = parsedAuthors } - + return record } func compressArticleRecords(_ records: [CKRecord]) -> [CKRecord] { var result = [CKRecord]() - + for record in records { - + if record.recordType == CloudKitArticle.recordType { - + if let contentHTML = record[CloudKitArticle.Fields.contentHTML] as? String { let data = Data(contentHTML.utf8) as NSData if let compressedData = try? data.compressed(using: .lzfse) { @@ -261,7 +261,7 @@ private extension CloudKitArticlesZone { record[CloudKitArticle.Fields.contentHTML] = nil } } - + if let contentText = record[CloudKitArticle.Fields.contentText] as? String { let data = Data(contentText.utf8) as NSData if let compressedData = try? data.compressed(using: .lzfse) { @@ -269,12 +269,12 @@ private extension CloudKitArticlesZone { record[CloudKitArticle.Fields.contentText] = nil } } - + } - + result.append(record) } - + return result } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index a1720f796..0952493ed 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -24,15 +24,15 @@ final class CloudKitArticlesZoneDelegate: CloudKitZoneDelegate { var database: SyncDatabase weak var articlesZone: CloudKitArticlesZone? var compressionQueue = DispatchQueue(label: "Articles Zone Delegate Compression Queue") - + init(account: Account, database: SyncDatabase, articlesZone: CloudKitArticlesZone) { self.account = account self.database = database self.articlesZone = articlesZone } - + func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey], completion: @escaping (Result) -> Void) { - + database.selectPendingReadStatusArticleIDs() { result in switch result { case .success(let pendingReadStatusArticleIDs): @@ -47,7 +47,7 @@ final class CloudKitArticlesZoneDelegate: CloudKitZoneDelegate { pendingStarredStatusArticleIDs: pendingStarredStatusArticleIDs, completion: completion) } - + case .failure(let error): Self.logger.error("CloudKit: Error getting pending starred records: \(error.localizedDescription)") completion(.failure(CloudKitZoneError.unknown)) @@ -67,12 +67,12 @@ private extension CloudKitArticlesZoneDelegate { let receivedRecordIDs = recordKeys.filter({ $0.recordType == CloudKitArticlesZone.CloudKitArticleStatus.recordType }).map({ $0.recordID }) let receivedArticleIDs = Set(receivedRecordIDs.map({ stripPrefix($0.externalID) })) let deletableArticleIDs = receivedArticleIDs.subtracting(pendingStarredStatusArticleIDs) - + guard !deletableArticleIDs.isEmpty else { completion() return } - + database.deleteSelectedForProcessing(Array(deletableArticleIDs)) { _ in self.account?.delete(articleIDs: deletableArticleIDs) { _ in completion() @@ -94,7 +94,7 @@ private extension CloudKitArticlesZoneDelegate { var errorOccurred = false let group = DispatchGroup() - + group.enter() account?.markAsUnread(updateableUnreadArticleIDs) { result in if case .failure(let databaseError) = result { @@ -103,7 +103,7 @@ private extension CloudKitArticlesZoneDelegate { } group.leave() } - + group.enter() account?.markAsRead(updateableReadArticleIDs) { result in if case .failure(let databaseError) = result { @@ -112,7 +112,7 @@ private extension CloudKitArticlesZoneDelegate { } group.leave() } - + group.enter() account?.markAsUnstarred(updateableUnstarredArticleIDs) { result in if case .failure(let databaseError) = result { @@ -121,7 +121,7 @@ private extension CloudKitArticlesZoneDelegate { } group.leave() } - + group.enter() account?.markAsStarred(updateableStarredArticleIDs) { result in if case .failure(let databaseError) = result { @@ -130,7 +130,7 @@ private extension CloudKitArticlesZoneDelegate { } group.leave() } - + group.enter() compressionQueue.async { let parsedItems = records.compactMap { self.makeParsedItem($0) } @@ -159,9 +159,9 @@ private extension CloudKitArticlesZoneDelegate { } group.leave() } - + } - + group.notify(queue: DispatchQueue.main) { if errorOccurred { completion(.failure(CloudKitZoneError.unknown)) @@ -170,7 +170,7 @@ private extension CloudKitArticlesZoneDelegate { } } } - + func stripPrefix(_ externalID: String) -> String { return String(externalID[externalID.index(externalID.startIndex, offsetBy: 2)..() - + let decoder = JSONDecoder() - + if let encodedParsedAuthors = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.parsedAuthors] as? [String] { for encodedParsedAuthor in encodedParsedAuthors { if let data = encodedParsedAuthor.data(using: .utf8), let parsedAuthor = try? decoder.decode(ParsedAuthor.self, from: data) { @@ -191,26 +191,26 @@ private extension CloudKitArticlesZoneDelegate { } } } - + guard let uniqueID = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.uniqueID] as? String, let feedURL = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.feedURL] as? String else { return nil } - + var contentHTML = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.contentHTML] as? String if let contentHTMLData = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.contentHTMLData] as? NSData { if let decompressedContentHTMLData = try? contentHTMLData.decompressed(using: .lzfse) { contentHTML = String(data: decompressedContentHTMLData as Data, encoding: .utf8) } } - + var contentText = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.contentText] as? String if let contentTextData = articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.contentTextData] as? NSData { if let decompressedContentTextData = try? contentTextData.decompressed(using: .lzfse) { contentText = String(data: decompressedContentTextData as Data, encoding: .utf8) } } - + let parsedItem = ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedURL, @@ -229,8 +229,8 @@ private extension CloudKitArticlesZoneDelegate { authors: parsedAuthors, tags: nil, attachments: nil) - + return parsedItem } - + } diff --git a/Modules/Account/Sources/Account/CombinedRefreshProgress.swift b/Modules/Account/Sources/Account/CombinedRefreshProgress.swift index 91eaed1c5..5982f8cab 100644 --- a/Modules/Account/Sources/Account/CombinedRefreshProgress.swift +++ b/Modules/Account/Sources/Account/CombinedRefreshProgress.swift @@ -47,7 +47,7 @@ public final class CombinedRefreshProgress { guard isStarted else { return } - + var updatedNumberOfTasks = 0 var updatedNumberRemaining = 0 var updatedNumberCompleted = 0 diff --git a/Modules/Account/Sources/Account/Container.swift b/Modules/Account/Sources/Account/Container.swift index a5d1714db..0f7f12448 100644 --- a/Modules/Account/Sources/Account/Container.swift +++ b/Modules/Account/Sources/Account/Container.swift @@ -12,7 +12,7 @@ import RSCore import Articles extension Notification.Name { - + public static let ChildrenDidChange = Notification.Name("ChildrenDidChange") } @@ -22,7 +22,7 @@ public protocol Container: AnyObject, ContainerIdentifiable { var topLevelFeeds: Set { get set } var folders: Set? { get set } var externalID: String? { get set } - + func hasAtLeastOneFeed() -> Bool func objectIsChild(_ object: AnyObject) -> Bool @@ -100,7 +100,7 @@ public extension Container { func has(_ feed: Feed) -> Bool { return flattenedFeeds().contains(feed) } - + func existingFeed(withFeedID feedID: String) -> Feed? { for feed in flattenedFeeds() { if feed.feedID == feedID { @@ -118,7 +118,7 @@ public extension Container { } return nil } - + func existingFeed(withExternalID externalID: String) -> Feed? { for feed in flattenedFeeds() { if feed.externalID == externalID { diff --git a/Modules/Account/Sources/Account/ContainerIdentifier.swift b/Modules/Account/Sources/Account/ContainerIdentifier.swift index 0db60e6d4..9a73fb16f 100644 --- a/Modules/Account/Sources/Account/ContainerIdentifier.swift +++ b/Modules/Account/Sources/Account/ContainerIdentifier.swift @@ -16,7 +16,7 @@ public enum ContainerIdentifier: Hashable, Equatable { case smartFeedController case account(String) // accountID case folder(String, String) // accountID, folderName - + public var userInfo: [AnyHashable: AnyHashable] { switch self { case .smartFeedController: @@ -36,10 +36,10 @@ public enum ContainerIdentifier: Hashable, Equatable { ] } } - + public init?(userInfo: [AnyHashable: AnyHashable]) { guard let type = userInfo["type"] as? String else { return nil } - + switch type { case "smartFeedController": self = ContainerIdentifier.smartFeedController @@ -53,7 +53,7 @@ public enum ContainerIdentifier: Hashable, Equatable { return nil } } - + } extension ContainerIdentifier: Encodable { @@ -80,11 +80,11 @@ extension ContainerIdentifier: Encodable { } extension ContainerIdentifier: Decodable { - + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(String.self, forKey: .type) - + switch type { case "smartFeedController": self = .smartFeedController @@ -97,5 +97,5 @@ extension ContainerIdentifier: Decodable { self = .folder(accountID, folderName) } } - + } diff --git a/Modules/Account/Sources/Account/DataExtensions.swift b/Modules/Account/Sources/Account/DataExtensions.swift index 3328cb3d0..15c445022 100644 --- a/Modules/Account/Sources/Account/DataExtensions.swift +++ b/Modules/Account/Sources/Account/DataExtensions.swift @@ -56,7 +56,7 @@ public extension Article { } return manager.existingAccount(with: accountID) } - + var feed: Feed? { return account?.existingFeed(withFeedID: feedID) } diff --git a/Modules/Account/Sources/Account/Feed.swift b/Modules/Account/Sources/Account/Feed.swift index 1b073ec10..67f373544 100644 --- a/Modules/Account/Sources/Account/Feed.swift +++ b/Modules/Account/Sources/Account/Feed.swift @@ -149,7 +149,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { metadata.cacheControlInfo = newValue } } - + public var contentHash: String? { get { return metadata.contentHash @@ -167,7 +167,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { metadata.isNotifyAboutNewArticles = newValue } } - + public var isArticleExtractorAlwaysOn: Bool? { get { metadata.isArticleExtractorAlwaysOn @@ -176,7 +176,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { metadata.isArticleExtractorAlwaysOn = newValue } } - + public var externalID: String? { get { return metadata.externalID @@ -226,7 +226,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { } // MARK: - UnreadCountProvider - + public var unreadCount: Int { get { return account?.unreadCount(for: self) ?? 0 @@ -239,7 +239,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { postUnreadCountDidChangeNotification() } } - + // MARK: - NotificationDisplayName public var notificationDisplayName: String { #if os(macOS) @@ -308,7 +308,7 @@ extension Feed: OPMLRepresentable { nameToUse = "" } let escapedName = nameToUse!.escapingSpecialXMLCharacters - + var escapedHomePageURL = "" if let homePageURL = homePageURL { escapedHomePageURL = homePageURL.escapingSpecialXMLCharacters @@ -327,7 +327,7 @@ extension Set where Element == Feed { func feedIDs() -> Set { return Set(map { $0.feedID }) } - + func sorted() -> Array { return sorted(by: { (feed1, feed2) -> Bool in if feed1.nameForDisplay.localizedStandardCompare(feed2.nameForDisplay) == .orderedSame { @@ -336,5 +336,5 @@ extension Set where Element == Feed { return feed1.nameForDisplay.localizedStandardCompare(feed2.nameForDisplay) == .orderedAscending }) } - + } diff --git a/Modules/Account/Sources/Account/FeedFinder/FeedSpecifier.swift b/Modules/Account/Sources/Account/FeedFinder/FeedSpecifier.swift index e7c2c2e87..09bada0c5 100644 --- a/Modules/Account/Sources/Account/FeedFinder/FeedSpecifier.swift +++ b/Modules/Account/Sources/Account/FeedFinder/FeedSpecifier.swift @@ -46,7 +46,7 @@ struct FeedSpecifier: Hashable { return FeedSpecifier(title: mergedTitle, urlString: urlString, source: mergedSource, orderFound: mergedOrderFound) } - + public static func bestFeed(in feedSpecifiers: Set) -> FeedSpecifier? { if feedSpecifiers.isEmpty { return nil @@ -54,10 +54,10 @@ struct FeedSpecifier: Hashable { if feedSpecifiers.count == 1 { return feedSpecifiers.anyObject() } - + var currentHighScore = Int.min var currentBestFeed: FeedSpecifier? = nil - + for oneFeedSpecifier in feedSpecifiers { let oneScore = oneFeedSpecifier.score if oneScore > currentHighScore { @@ -65,25 +65,25 @@ struct FeedSpecifier: Hashable { currentBestFeed = oneFeedSpecifier } } - + return currentBestFeed } } private extension FeedSpecifier { - + func calculatedScore() -> Int { var score = 0 - + if source == .UserEntered { return 1000 } else if source == .HTMLHead { score = score + 50 } - + score = score - ((orderFound - 1) * 5) - + if urlString.caseInsensitiveContains("comments") { score = score - 10 } @@ -105,13 +105,13 @@ private extension FeedSpecifier { if urlString.caseInsensitiveContains("json") { score = score + 3 } - + if let title = title { if title.caseInsensitiveContains("comments") { score = score - 10 } } - + return score } } diff --git a/Modules/Account/Sources/Account/FeedFinder/HTMLFeedFinder.swift b/Modules/Account/Sources/Account/FeedFinder/HTMLFeedFinder.swift index 912bd0a25..815d53f9f 100644 --- a/Modules/Account/Sources/Account/FeedFinder/HTMLFeedFinder.swift +++ b/Modules/Account/Sources/Account/FeedFinder/HTMLFeedFinder.swift @@ -12,17 +12,17 @@ import RSParser private let feedURLWordsToMatch = ["feed", "xml", "rss", "atom", "json"] final class HTMLFeedFinder { - + var feedSpecifiers: Set { return Set(feedSpecifiersDictionary.values) } - + private var feedSpecifiersDictionary = [String: FeedSpecifier]() - + init(parserData: ParserData) { let metadata = RSHTMLMetadataParser.htmlMetadata(with: parserData) var orderFound = 0 - + for oneFeedLink in metadata.feedLinks { if let oneURLString = oneFeedLink.urlString?.normalizedURL { orderFound = orderFound + 1 diff --git a/Modules/Account/Sources/Account/FeedMetadata.swift b/Modules/Account/Sources/Account/FeedMetadata.swift index 98f0d62e8..c0df8f5c3 100644 --- a/Modules/Account/Sources/Account/FeedMetadata.swift +++ b/Modules/Account/Sources/Account/FeedMetadata.swift @@ -41,7 +41,7 @@ final class FeedMetadata: Codable { } } } - + var homePageURL: String? { didSet { if homePageURL != oldValue { @@ -81,7 +81,7 @@ final class FeedMetadata: Codable { } } } - + var isNotifyAboutNewArticles: Bool? { didSet { if isNotifyAboutNewArticles != oldValue { @@ -142,7 +142,7 @@ final class FeedMetadata: Codable { } } } - + // Folder Name: Sync Service Relationship ID var folderRelationship: [String: String]? { didSet { diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinDate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinDate.swift index 7d35b66d9..08051fa2d 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinDate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinDate.swift @@ -9,7 +9,7 @@ import Foundation struct FeedbinDate { - + public static var formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'" @@ -17,5 +17,5 @@ struct FeedbinDate { formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift index 27e23a140..72b5e5f7f 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift @@ -58,7 +58,7 @@ struct FeedbinEntryJSONFeed: Decodable { case jsonFeedAuthor = "author" case jsonFeedExternalURL = "external_url" } - + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinImportResult.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinImportResult.swift index bce437960..dea2b331f 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinImportResult.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinImportResult.swift @@ -9,13 +9,13 @@ import Foundation struct FeedbinImportResult: Codable { - + let importResultID: Int let complete: Bool - + enum CodingKeys: String, CodingKey { case importResultID = "id" case complete } - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinStarredEntry.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinStarredEntry.swift index a070a89f6..a8c4dbb38 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinStarredEntry.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinStarredEntry.swift @@ -9,11 +9,11 @@ import Foundation struct FeedbinStarredEntry: Codable { - + let starredEntries: [Int] - + enum CodingKeys: String, CodingKey { case starredEntries = "starred_entries" } - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinSubscription.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinSubscription.swift index d789d1deb..db93027b2 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinSubscription.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinSubscription.swift @@ -31,11 +31,11 @@ struct FeedbinSubscription: Hashable, Codable { public func hash(into hasher: inout Hasher) { hasher.combine(subscriptionID) } - + static func == (lhs: FeedbinSubscription, rhs: FeedbinSubscription) -> Bool { return lhs.subscriptionID == rhs.subscriptionID } - + } struct FeedbinSubscriptionJSONFeed: Codable { @@ -62,13 +62,13 @@ struct FeedbinUpdateSubscription: Codable { } struct FeedbinSubscriptionChoice: Codable { - + let name: String? let url: String - + enum CodingKeys: String, CodingKey { case name = "title" case url = "feed_url" } - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinTag.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinTag.swift index b7aaa6f58..970b29f2d 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinTag.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinTag.swift @@ -9,35 +9,35 @@ import Foundation struct FeedbinTag: Codable { - + let tagID: Int let name: String - + enum CodingKeys: String, CodingKey { case tagID = "id" case name = "name" } - + } struct FeedbinRenameTag: Codable { - + let oldName: String let newName: String - + enum CodingKeys: String, CodingKey { case oldName = "old_name" case newName = "new_name" } - + } struct FeedbinDeleteTag: Codable { - + let name: String - + enum CodingKeys: String, CodingKey { case name } - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinTagging.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinTagging.swift index a3f830aec..b64103074 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinTagging.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinTagging.swift @@ -23,13 +23,13 @@ struct FeedbinTagging: Codable { } struct FeedbinCreateTagging: Codable { - + let feedID: Int let name: String - + enum CodingKeys: String, CodingKey { case feedID = "feed_id" case name = "name" } - + } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinUnreadEntry.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinUnreadEntry.swift index ff979a0e9..1883c12a4 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinUnreadEntry.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinUnreadEntry.swift @@ -9,11 +9,11 @@ import Foundation struct FeedbinUnreadEntry: Codable { - + let unreadEntries: [Int] - + enum CodingKeys: String, CodingKey { case unreadEntries = "unread_entries" } - + } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift index e84b801bd..f3d414f36 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift @@ -18,11 +18,11 @@ protocol FeedlyAPICallerDelegate: AnyObject { } final class FeedlyAPICaller { - + enum API { case sandbox case cloud - + var baseUrlComponents: URLComponents { var components = URLComponents() components.scheme = "https" @@ -36,7 +36,7 @@ final class FeedlyAPICaller { } return components } - + var oauthAuthorizationClient: OAuthAuthorizationClient { switch self { case .sandbox: @@ -46,83 +46,83 @@ final class FeedlyAPICaller { } } } - + private let transport: Transport private let baseUrlComponents: URLComponents private let uriComponentAllowed: CharacterSet - + init(transport: Transport, api: API) { self.transport = transport self.baseUrlComponents = api.baseUrlComponents - + var urlHostAllowed = CharacterSet.urlHostAllowed urlHostAllowed.remove("+") uriComponentAllowed = urlHostAllowed } - + weak var delegate: FeedlyAPICallerDelegate? - + var credentials: Credentials? - + var server: String? { return baseUrlComponents.host } - + func cancelAll() { transport.cancelAll() } - + private var isSuspended = false - + /// Cancels all pending requests rejects any that come in later func suspend() { transport.cancelAll() isSuspended = true } - + func resume() { isSuspended = false } - + func send(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) { transport.send(request: request, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding) { [weak self] result in assert(Thread.isMainThread) - + switch result { case .success: completion(result) case .failure(let error): switch error { case TransportError.httpError(let statusCode) where statusCode == 401: - + assert(self == nil ? true : self?.delegate != nil, "Check the delegate is set to \(FeedlyAccountDelegate.self).") - + guard let self = self, let delegate = self.delegate else { completion(result) return } - + /// Capture the credentials before the reauthorization to check for a change. let credentialsBefore = self.credentials - + delegate.reauthorizeFeedlyAPICaller(self) { [weak self] isReauthorizedAndShouldRetry in assert(Thread.isMainThread) - + guard isReauthorizedAndShouldRetry, let self = self else { completion(result) return } - + // Check for a change. Not only would it help debugging, but it'll also catch an infinitely recursive attempt to refresh. guard let accessToken = self.credentials?.secret, accessToken != credentialsBefore?.secret else { assertionFailure("Could not update the request with a new OAuth token. Did \(String(describing: self.delegate)) set them on \(self)?") completion(result) return } - + var reauthorizedRequest = request reauthorizedRequest.setValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + self.send(request: reauthorizedRequest, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding, completion: completion) } default: @@ -131,14 +131,14 @@ final class FeedlyAPICaller { } } } - + func importOpml(_ opmlData: Data, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -146,18 +146,18 @@ final class FeedlyAPICaller { } var components = baseUrlComponents components.path = "/v3/opml" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("text/xml", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) request.httpBody = opmlData - + send(request: request, resultType: String.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (httpResponse, _)): @@ -171,14 +171,14 @@ final class FeedlyAPICaller { } } } - + func createCollection(named label: String, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -186,17 +186,17 @@ final class FeedlyAPICaller { } var components = baseUrlComponents components.path = "/v3/collections" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + do { struct CreateCollectionBody: Encodable { var label: String @@ -209,7 +209,7 @@ final class FeedlyAPICaller { completion(.failure(error)) } } - + send(request: request, resultType: [FeedlyCollection].self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (httpResponse, collections)): @@ -223,14 +223,14 @@ final class FeedlyAPICaller { } } } - + func renameCollection(with id: String, to name: String, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -238,17 +238,17 @@ final class FeedlyAPICaller { } var components = baseUrlComponents components.path = "/v3/collections" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + do { struct RenameCollectionBody: Encodable { var id: String @@ -262,7 +262,7 @@ final class FeedlyAPICaller { completion(.failure(error)) } } - + send(request: request, resultType: [FeedlyCollection].self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (httpResponse, collections)): @@ -276,18 +276,18 @@ final class FeedlyAPICaller { } } } - + private func encodeForURLPath(_ pathComponent: String) -> String? { return pathComponent.addingPercentEncoding(withAllowedCharacters: uriComponentAllowed) } - + func deleteCollection(with id: String, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -300,17 +300,17 @@ final class FeedlyAPICaller { } var components = baseUrlComponents components.percentEncodedPath = "/v3/collections/\(encodedId)" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "DELETE" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: Optional.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (httpResponse, _)): @@ -324,14 +324,14 @@ final class FeedlyAPICaller { } } } - + func removeFeed(_ feedId: String, fromCollectionWith collectionId: String, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -343,20 +343,20 @@ final class FeedlyAPICaller { completion(.failure(FeedlyAccountDelegateError.unexpectedResourceId(collectionId))) } } - + var components = baseUrlComponents components.percentEncodedPath = "/v3/collections/\(encodedCollectionId)/feeds/.mdelete" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "DELETE" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + do { struct RemovableFeed: Encodable { let id: String @@ -369,7 +369,7 @@ final class FeedlyAPICaller { completion(.failure(error)) } } - + // `resultType` is optional because the Feedly API has gone from returning an array of removed feeds to returning `null`. // https://developer.feedly.com/v3/collections/#remove-multiple-feeds-from-a-personal-collection send(request: request, resultType: Optional<[FeedlyFeed]>.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in @@ -388,14 +388,14 @@ final class FeedlyAPICaller { } extension FeedlyAPICaller: FeedlyAddFeedToCollectionService { - + func addFeed(with feedId: FeedlyFeedResourceId, title: String? = nil, toCollectionWith collectionId: String, completion: @escaping (Result<[FeedlyFeed], Error>) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -409,17 +409,17 @@ extension FeedlyAPICaller: FeedlyAddFeedToCollectionService { } var components = baseUrlComponents components.percentEncodedPath = "/v3/collections/\(encodedId)/feeds" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "PUT" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + do { struct AddFeedBody: Encodable { var id: String @@ -433,7 +433,7 @@ extension FeedlyAPICaller: FeedlyAddFeedToCollectionService { completion(.failure(error)) } } - + send(request: request, resultType: [FeedlyFeed].self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success((_, let collectionFeeds)): @@ -450,45 +450,45 @@ extension FeedlyAPICaller: FeedlyAddFeedToCollectionService { } extension FeedlyAPICaller: OAuthAuthorizationCodeGrantRequesting { - + static func authorizationCodeUrlRequest(for request: OAuthAuthorizationRequest, baseUrlComponents: URLComponents) -> URLRequest { var components = baseUrlComponents components.path = "/v3/auth/auth" components.queryItems = request.queryItems - + guard let url = components.url else { assert(components.scheme != nil) assert(components.host != nil) fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") - + return request } - + typealias AccessTokenResponse = FeedlyOAuthAccessTokenResponse - + func requestAccessToken(_ authorizationRequest: OAuthAccessTokenRequest, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + var components = baseUrlComponents components.path = "/v3/auth/token" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept-Type") - + do { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase @@ -499,7 +499,7 @@ extension FeedlyAPICaller: OAuthAuthorizationCodeGrantRequesting { } return } - + send(request: request, resultType: AccessTokenResponse.self, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, tokenResponse)): @@ -516,26 +516,26 @@ extension FeedlyAPICaller: OAuthAuthorizationCodeGrantRequesting { } extension FeedlyAPICaller: OAuthAcessTokenRefreshRequesting { - + func refreshAccessToken(_ refreshRequest: OAuthRefreshAccessTokenRequest, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + var components = baseUrlComponents components.path = "/v3/auth/token" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept-Type") - + do { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase @@ -546,7 +546,7 @@ extension FeedlyAPICaller: OAuthAcessTokenRefreshRequesting { } return } - + send(request: request, resultType: AccessTokenResponse.self, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, tokenResponse)): @@ -563,14 +563,14 @@ extension FeedlyAPICaller: OAuthAcessTokenRefreshRequesting { } extension FeedlyAPICaller: FeedlyGetCollectionsService { - + func getCollections(completion: @escaping (Result<[FeedlyCollection], Error>) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -578,16 +578,16 @@ extension FeedlyAPICaller: FeedlyGetCollectionsService { } var components = baseUrlComponents components.path = "/v3/collections" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: [FeedlyCollection].self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, collections)): @@ -604,58 +604,58 @@ extension FeedlyAPICaller: FeedlyGetCollectionsService { } extension FeedlyAPICaller: FeedlyGetStreamContentsService { - + func getStreamContents(for resource: FeedlyResourceId, continuation: String? = nil, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) } } - + var components = baseUrlComponents components.path = "/v3/streams/contents" - + var queryItems = [URLQueryItem]() - + if let date = newerThan { let value = String(Int(date.timeIntervalSince1970 * 1000)) let queryItem = URLQueryItem(name: "newerThan", value: value) queryItems.append(queryItem) } - + if let flag = unreadOnly { let value = flag ? "true" : "false" let queryItem = URLQueryItem(name: "unreadOnly", value: value) queryItems.append(queryItem) } - + if let value = continuation, !value.isEmpty { let queryItem = URLQueryItem(name: "continuation", value: value) queryItems.append(queryItem) } - + queryItems.append(contentsOf: [ URLQueryItem(name: "count", value: "1000"), URLQueryItem(name: "streamId", value: resource.id), ]) - + components.queryItems = queryItems - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: FeedlyStream.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, collections)): @@ -672,58 +672,58 @@ extension FeedlyAPICaller: FeedlyGetStreamContentsService { } extension FeedlyAPICaller: FeedlyGetStreamIdsService { - + func getStreamIds(for resource: FeedlyResourceId, continuation: String? = nil, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) } } - + var components = baseUrlComponents components.path = "/v3/streams/ids" var queryItems = [URLQueryItem]() - + if let date = newerThan { let value = String(Int(date.timeIntervalSince1970 * 1000)) let queryItem = URLQueryItem(name: "newerThan", value: value) queryItems.append(queryItem) } - + if let flag = unreadOnly { let value = flag ? "true" : "false" let queryItem = URLQueryItem(name: "unreadOnly", value: value) queryItems.append(queryItem) } - + if let value = continuation, !value.isEmpty { let queryItem = URLQueryItem(name: "continuation", value: value) queryItems.append(queryItem) } - + queryItems.append(contentsOf: [ URLQueryItem(name: "count", value: "10000"), URLQueryItem(name: "streamId", value: resource.id), ]) - + components.queryItems = queryItems - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: FeedlyStreamIds.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, collections)): @@ -740,29 +740,29 @@ extension FeedlyAPICaller: FeedlyGetStreamIdsService { } extension FeedlyAPICaller: FeedlyGetEntriesService { - + func getEntries(for ids: Set, completion: @escaping (Result<[FeedlyEntry], Error>) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) } } - + var components = baseUrlComponents components.path = "/v3/entries/.mget" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) - + do { let body = Array(ids) let encoder = JSONEncoder() @@ -773,12 +773,12 @@ extension FeedlyAPICaller: FeedlyGetEntriesService { completion(.failure(error)) } } - + request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: [FeedlyEntry].self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, entries)): @@ -795,20 +795,20 @@ extension FeedlyAPICaller: FeedlyGetEntriesService { } extension FeedlyAPICaller: FeedlyMarkArticlesService { - + private struct MarkerEntriesBody: Encodable { let type = "entries" var action: String var entryIds: [String] } - + func mark(_ articleIds: Set, as action: FeedlyMarkAction, completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -816,23 +816,23 @@ extension FeedlyAPICaller: FeedlyMarkArticlesService { } var components = baseUrlComponents components.path = "/v3/markers" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + let articleIdChunks = Array(articleIds).chunked(into: 300) let dispatchGroup = DispatchGroup() var groupError: Error? = nil for articleIdChunk in articleIdChunks { - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + do { let body = MarkerEntriesBody(action: action.actionValue, entryIds: Array(articleIdChunk)) let encoder = JSONEncoder() @@ -843,7 +843,7 @@ extension FeedlyAPICaller: FeedlyMarkArticlesService { completion(.failure(error)) } } - + dispatchGroup.enter() send(request: request, resultType: String.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { @@ -857,7 +857,7 @@ extension FeedlyAPICaller: FeedlyMarkArticlesService { dispatchGroup.leave() } } - + dispatchGroup.notify(queue: .main) { if let groupError = groupError { completion(.failure(groupError)) @@ -869,34 +869,34 @@ extension FeedlyAPICaller: FeedlyMarkArticlesService { } extension FeedlyAPICaller: FeedlySearchService { - + func getFeeds(for query: String, count: Int, locale: String, completion: @escaping (Result) -> ()) { - + guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + var components = baseUrlComponents components.path = "/v3/search/feeds" - + components.queryItems = [ URLQueryItem(name: "query", value: query), URLQueryItem(name: "count", value: String(count)), URLQueryItem(name: "locale", value: locale) ] - - + + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") - + send(request: request, resultType: FeedlyFeedsSearchResponse.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (_, searchResponse)): @@ -913,14 +913,14 @@ extension FeedlyAPICaller: FeedlySearchService { } extension FeedlyAPICaller: FeedlyLogoutService { - + func logout(completion: @escaping (Result) -> ()) { guard !isSuspended else { return DispatchQueue.main.async { completion(.failure(TransportError.suspended)) } } - + guard let accessToken = credentials?.secret else { return DispatchQueue.main.async { completion(.failure(CredentialsError.incompleteCredentials)) @@ -928,17 +928,17 @@ extension FeedlyAPICaller: FeedlyLogoutService { } var components = baseUrlComponents components.path = "/v3/auth/logout" - + guard let url = components.url else { fatalError("\(components) does not produce a valid URL.") } - + var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: HTTPRequestHeader.contentType) request.addValue("application/json", forHTTPHeaderField: "Accept-Type") request.addValue("OAuth \(accessToken)", forHTTPHeaderField: HTTPRequestHeader.authorization) - + send(request: request, resultType: String.self, dateDecoding: .millisecondsSince1970, keyDecoding: .convertFromSnakeCase) { result in switch result { case .success(let (httpResponse, _)): diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate+OAuth.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate+OAuth.swift index 9e29bbbe2..ccb953e6a 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate+OAuth.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate+OAuth.swift @@ -25,9 +25,9 @@ public struct FeedlyOAuthAccessTokenResponse: Decodable, OAuthAccessTokenRespons } extension FeedlyAccountDelegate: OAuthAuthorizationGranting { - + private static let oauthAuthorizationGrantScope = "https://cloud.feedly.com/subscriptions" - + static func oauthAuthorizationCodeGrantRequest() -> URLRequest { let client = environment.oauthAuthorizationClient let authorizationRequest = OAuthAuthorizationRequest(clientId: client.id, @@ -37,7 +37,7 @@ extension FeedlyAccountDelegate: OAuthAuthorizationGranting { let baseURLComponents = environment.baseUrlComponents return FeedlyAPICaller.authorizationCodeUrlRequest(for: authorizationRequest, baseUrlComponents: baseURLComponents) } - + static func requestOAuthAccessToken(with response: OAuthAuthorizationResponse, transport: Transport, completion: @escaping (Result) -> ()) { let client = environment.oauthAuthorizationClient let request = OAuthAccessTokenRequest(authorizationResponse: response, @@ -48,18 +48,18 @@ extension FeedlyAccountDelegate: OAuthAuthorizationGranting { switch result { case .success(let response): let accessToken = Credentials(type: .oauthAccessToken, username: response.id, secret: response.accessToken) - + let refreshToken: Credentials? = { guard let token = response.refreshToken else { return nil } return Credentials(type: .oauthRefreshToken, username: response.id, secret: token) }() - + let grant = OAuthAuthorizationGrant(accessToken: accessToken, refreshToken: refreshToken) - + completion(.success(grant)) - + case .failure(let error): completion(.failure(error)) } @@ -70,23 +70,23 @@ extension FeedlyAccountDelegate: OAuthAuthorizationGranting { extension FeedlyAccountDelegate: OAuthAccessTokenRefreshing { func refreshAccessToken(with refreshToken: String, client: OAuthAuthorizationClient, completion: @escaping (Result) -> ()) { let request = OAuthRefreshAccessTokenRequest(refreshToken: refreshToken, scope: nil, client: client) - + caller.refreshAccessToken(request) { result in switch result { case .success(let response): let accessToken = Credentials(type: .oauthAccessToken, username: response.id, secret: response.accessToken) - + let refreshToken: Credentials? = { guard let token = response.refreshToken else { return nil } return Credentials(type: .oauthRefreshToken, username: response.id, secret: token) }() - + let grant = OAuthAuthorizationGrant(accessToken: accessToken, refreshToken: refreshToken) - + completion(.success(grant)) - + case .failure(let error): completion(.failure(error)) } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 39d0ecc55..d3799f73d 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -27,15 +27,15 @@ final class FeedlyAccountDelegate: AccountDelegate { // TODO: Kiel, if you decide not to support OPML import you will have to disallow it in the behaviors // See https://developer.feedly.com/v3/opml/ var behaviors: AccountBehaviors = [.disallowFeedInRootFolder, .disallowMarkAsUnreadAfterPeriod(31)] - + let isOPMLImportSupported = false - + var isOPMLImportInProgress = false - + var server: String? { return caller.server } - + var credentials: Credentials? { didSet { #if DEBUG @@ -48,36 +48,36 @@ final class FeedlyAccountDelegate: AccountDelegate { caller.credentials = credentials } } - + let oauthAuthorizationClient: OAuthAuthorizationClient - + var accountMetadata: AccountMetadata? - + var refreshProgress = DownloadProgress(numberOfTasks: 0) - + /// Set on `accountDidInitialize` for the purposes of refreshing OAuth tokens when they expire. /// See the implementation for `FeedlyAPICallerDelegate`. private weak var initializedAccount: Account? - + internal let caller: FeedlyAPICaller private static let logger = Feedly.logger private let database: SyncDatabase - + private weak var currentSyncAllOperation: MainThreadOperation? private let operationQueue = MainThreadOperationQueue() - + init(dataFolder: String, transport: Transport?, api: FeedlyAPICaller.API) { // Many operations have their own operation queues, such as the sync all operation. // Making this a serial queue at this higher level of abstraction means we can ensure, // for example, a `FeedlyRefreshAccessTokenOperation` occurs before a `FeedlySyncAllOperation`, // improving our ability to debug, reason about and predict the behaviour of the code. - + if let transport = transport { self.caller = FeedlyAPICaller(transport: transport, api: api) - + } else { - + let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData sessionConfiguration.timeoutIntervalForRequest = 60.0 @@ -86,24 +86,24 @@ final class FeedlyAccountDelegate: AccountDelegate { sessionConfiguration.httpMaximumConnectionsPerHost = 1 sessionConfiguration.httpCookieStorage = nil sessionConfiguration.urlCache = nil - + if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } - + let session = URLSession(configuration: sessionConfiguration) self.caller = FeedlyAPICaller(transport: session, api: api) } - + let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") self.database = SyncDatabase(databaseFilePath: databaseFilePath) self.oauthAuthorizationClient = api.oauthAuthorizationClient - + self.caller.delegate = self } - + // MARK: Account API - + func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) { completion() } @@ -121,19 +121,19 @@ final class FeedlyAccountDelegate: AccountDelegate { completion(.success(())) return } - + guard let credentials = credentials else { Self.logger.info("Feedly: Ignoring refreshAll: account has no credentials") completion(.failure(FeedlyAccountDelegateError.notLoggedIn)) return } - + refreshProgress.reset() let syncAllOperation = FeedlySyncAllOperation(account: account, feedlyUserId: credentials.username, caller: caller, database: database, lastSuccessfulFetchStartDate: accountMetadata?.lastArticleFetchStartTime, downloadProgress: refreshProgress) syncAllOperation.downloadProgress = refreshProgress - + let date = Date() syncAllOperation.syncCompletionHandler = { [weak self] result in if case .success = result { @@ -145,12 +145,12 @@ final class FeedlyAccountDelegate: AccountDelegate { completion(result) self?.refreshProgress.reset() } - + currentSyncAllOperation = syncAllOperation - + operationQueue.add(syncAllOperation) } - + func syncArticleStatus(for account: Account, completion: ((Result) -> Void)? = nil) { sendArticleStatus(for: account) { result in switch result { @@ -168,7 +168,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { // Ensure remote articles have the same status as they do locally. let send = FeedlySendArticleStatusesOperation(database: database, service: caller) @@ -180,7 +180,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } operationQueue.add(send) } - + /// Attempts to ensure local articles have the same status as they do remotely. /// So if the user is using another client roughly simultaneously with this app, /// this app does its part to ensure the articles have a consistent status between both. @@ -191,34 +191,34 @@ final class FeedlyAccountDelegate: AccountDelegate { guard let credentials = credentials else { return completion(.success(())) } - + let group = DispatchGroup() - + let ingestUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: database, newerThan: nil) - + group.enter() ingestUnread.completionBlock = { _ in group.leave() - + } - + let ingestStarred = FeedlyIngestStarredArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: database, newerThan: nil) - + group.enter() ingestStarred.completionBlock = { _ in group.leave() } - + group.notify(queue: .main) { completion(.success(())) } - + operationQueue.addOperations([ingestUnread, ingestStarred]) } - + func importOPML(for account: Account, opmlFile: URL, completion: @escaping (Result) -> Void) { let data: Data - + do { data = try Data(contentsOf: opmlFile) } catch { @@ -229,7 +229,7 @@ final class FeedlyAccountDelegate: AccountDelegate { Self.logger.info("Feedly: Begin importing OPML") isOPMLImportInProgress = true refreshProgress.addToNumberOfTasksAndRemaining(1) - + caller.importOpml(data) { result in switch result { case .success: @@ -250,15 +250,15 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) { - + let progress = refreshProgress progress.addToNumberOfTasksAndRemaining(1) - + caller.createCollection(named: name) { result in progress.completeTask() - + switch result { case .success(let collection): if let folder = account.ensureFolder(with: collection.label) { @@ -273,16 +273,16 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) { guard let id = folder.externalID else { return DispatchQueue.main.async { completion(.failure(FeedlyAccountDelegateError.unableToRenameFolder(folder.nameForDisplay, name))) } } - + let nameBefore = folder.name - + caller.renameCollection(with: id, to: name) { result in switch result { case .success(let collection): @@ -293,23 +293,23 @@ final class FeedlyAccountDelegate: AccountDelegate { completion(.failure(error)) } } - + folder.name = name } - + func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result) -> Void) { guard let id = folder.externalID else { return DispatchQueue.main.async { completion(.failure(FeedlyAccountDelegateError.unableToRemoveFolder(folder.nameForDisplay))) } } - + let progress = refreshProgress progress.addToNumberOfTasksAndRemaining(1) - + caller.deleteCollection(with: id) { result in progress.completeTask() - + switch result { case .success: account.removeFolder(folder) @@ -319,14 +319,14 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + func createFeed(for account: Account, url: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result) -> Void) { - + do { guard let credentials = credentials else { throw FeedlyAccountDelegateError.notLoggedIn } - + let addNewFeed = try FeedlyAddNewFeedOperation(account: account, credentials: credentials, url: url, @@ -342,50 +342,50 @@ final class FeedlyAccountDelegate: AccountDelegate { addNewFeed.addCompletionHandler = { result in completion(result) } - + operationQueue.add(addNewFeed) - + } catch { DispatchQueue.main.async { completion(.failure(error)) } } } - + func renameFeed(for account: Account, with feed: Feed, to name: String, completion: @escaping (Result) -> Void) { let folderCollectionIds = account.folders?.filter { $0.has(feed) }.compactMap { $0.externalID } guard let collectionIds = folderCollectionIds, let collectionId = collectionIds.first else { completion(.failure(FeedlyAccountDelegateError.unableToRenameFeed(feed.nameForDisplay, name))) return } - + let feedId = FeedlyFeedResourceId(id: feed.feedID) let editedNameBefore = feed.editedName - + // Adding an existing feed updates it. // Updating feed name in one folder/collection updates it for all folders/collections. caller.addFeed(with: feedId, title: name, toCollectionWith: collectionId) { result in switch result { case .success: completion(.success(())) - + case .failure(let error): feed.editedName = editedNameBefore completion(.failure(error)) } } - + // optimistically set the name feed.editedName = name } - + func addFeed(for account: Account, with feed: Feed, to container: Container, completion: @escaping (Result) -> Void) { - + do { guard let credentials = credentials else { throw FeedlyAccountDelegateError.notLoggedIn } - + let resource = FeedlyFeedResourceId(id: feed.feedID) let addExistingFeed = try FeedlyAddExistingFeedOperation(account: account, credentials: credentials, @@ -394,28 +394,28 @@ final class FeedlyAccountDelegate: AccountDelegate { container: container, progress: refreshProgress, customFeedName: feed.editedName) - - + + addExistingFeed.addCompletionHandler = { result in completion(result) } - + operationQueue.add(addExistingFeed) - + } catch { DispatchQueue.main.async { completion(.failure(error)) } } } - + func removeFeed(for account: Account, with feed: Feed, from container: Container, completion: @escaping (Result) -> Void) { guard let folder = container as? Folder, let collectionId = folder.externalID else { return DispatchQueue.main.async { completion(.failure(FeedlyAccountDelegateError.unableToRemoveFeed(feed))) } } - + caller.removeFeed(feed.feedID, fromCollectionWith: collectionId) { result in switch result { case .success: @@ -425,17 +425,17 @@ final class FeedlyAccountDelegate: AccountDelegate { completion(.failure(error)) } } - + folder.removeFeed(feed) } - + func moveFeed(for account: Account, with feed: Feed, from: Container, to: Container, completion: @escaping (Result) -> Void) { guard let from = from as? Folder, let to = to as? Folder else { return DispatchQueue.main.async { completion(.failure(FeedlyAccountDelegateError.addFeedChooseFolder)) } } - + addFeed(for: account, with: feed, to: to) { [weak self] addResult in switch addResult { // now that we have added the feed, remove it from the other collection @@ -454,14 +454,14 @@ final class FeedlyAccountDelegate: AccountDelegate { to.removeFeed(feed) completion(.failure(error)) } - + } - + // optimistically move the feed, undoing as appropriate to the failure from.removeFeed(feed) to.addFeed(feed) } - + func restoreFeed(for account: Account, feed: Feed, container: Container, completion: @escaping (Result) -> Void) { if let existingFeed = account.existingFeed(withURL: feed.url) { account.addFeed(existingFeed, to: container) { result in @@ -483,14 +483,14 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result) -> Void) { let group = DispatchGroup() - + for feed in folder.topLevelFeeds { - + folder.topLevelFeeds.remove(feed) - + group.enter() restoreFeed(for: account, feed: feed, container: folder) { result in group.leave() @@ -502,13 +502,13 @@ final class FeedlyAccountDelegate: AccountDelegate { } } } - + group.notify(queue: .main) { account.addFolder(folder) completion(.success(())) } } - + func markArticles(for account: Account, articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result) -> Void) { account.update(articles, statusKey: statusKey, flag: flag) { result in switch result { @@ -535,7 +535,7 @@ final class FeedlyAccountDelegate: AccountDelegate { initializedAccount = account credentials = try? account.retrieveCredentials(type: .oauthAccessToken) } - + func accountWillBeDeleted(_ account: Account) { let logout = FeedlyLogoutOperation(account: account, service: caller) // Dispatch on the shared queue because the lifetime of the account delegate is uncertain. @@ -554,12 +554,12 @@ final class FeedlyAccountDelegate: AccountDelegate { caller.suspend() operationQueue.cancelAllOperations() } - + /// Suspend the SQLLite databases func suspendDatabase() { database.suspend() } - + /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { database.resume() @@ -568,35 +568,35 @@ final class FeedlyAccountDelegate: AccountDelegate { } extension FeedlyAccountDelegate: FeedlyAPICallerDelegate { - + func reauthorizeFeedlyAPICaller(_ caller: FeedlyAPICaller, completionHandler: @escaping (Bool) -> ()) { guard let account = initializedAccount else { completionHandler(false) return } - + /// Captures a failure to refresh a token, assuming that it was refreshed unless told otherwise. final class RefreshAccessTokenOperationDelegate: FeedlyOperationDelegate { - + private(set) var didReauthorize = true - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { didReauthorize = false } } - + let refreshAccessToken = FeedlyRefreshAccessTokenOperation(account: account, service: self, oauthClient: oauthAuthorizationClient) refreshAccessToken.downloadProgress = refreshProgress - + /// This must be strongly referenced by the completionBlock of the `FeedlyRefreshAccessTokenOperation`. let refreshAccessTokenDelegate = RefreshAccessTokenOperationDelegate() refreshAccessToken.delegate = refreshAccessTokenDelegate - + refreshAccessToken.completionBlock = { operation in assert(Thread.isMainThread) completionHandler(refreshAccessTokenDelegate.didReauthorize && !operation.isCanceled) } - + MainThreadOperationQueue.shared.add(refreshAccessToken) } } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift index 0ed5cac99..efe28b73e 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift @@ -19,80 +19,80 @@ enum FeedlyAccountDelegateError: LocalizedError { case addFeedInvalidFolder(Folder) case unableToRenameFeed(String, String) case unableToRemoveFeed(Feed) - + var errorDescription: String? { switch self { case .notLoggedIn: return NSLocalizedString("Please add the Feedly account again. If this problem persists, open Keychain Access and delete all feedly.com entries, then try again.", comment: "Feedly – Credentials not found.") - + case .unexpectedResourceId(let resourceId): let template = NSLocalizedString("Could not encode the identifier “%@”.", comment: "Feedly – Could not encode resource id to send to Feedly.") return String(format: template, resourceId) - + case .unableToAddFolder(let name): let template = NSLocalizedString("Could not create a folder named “%@”.", comment: "Feedly – Could not create a folder/collection.") return String(format: template, name) - + case .unableToRenameFolder(let from, let to): let template = NSLocalizedString("Could not rename “%@” to “%@”.", comment: "Feedly – Could not rename a folder/collection.") return String(format: template, from, to) - + case .unableToRemoveFolder(let name): let template = NSLocalizedString("Could not remove the folder named “%@”.", comment: "Feedly – Could not remove a folder/collection.") return String(format: template, name) - + case .unableToMoveFeedBetweenFolders(let feed, _, let to): let template = NSLocalizedString("Could not move “%@” to “%@”.", comment: "Feedly – Could not move a feed between folders/collections.") return String(format: template, feed.nameForDisplay, to.nameForDisplay) - + case .addFeedChooseFolder: return NSLocalizedString("Please choose a folder to contain the feed.", comment: "Feedly – Feed can only be added to folders.") - + case .addFeedInvalidFolder(let invalidFolder): let template = NSLocalizedString("Feeds cannot be added to the “%@” folder.", comment: "Feedly – Feed can only be added to folders.") return String(format: template, invalidFolder.nameForDisplay) - + case .unableToRenameFeed(let from, let to): let template = NSLocalizedString("Could not rename “%@” to “%@”.", comment: "Feedly – Could not rename a feed.") return String(format: template, from, to) - + case .unableToRemoveFeed(let feed): let template = NSLocalizedString("Could not remove “%@”.", comment: "Feedly – Could not remove a feed.") return String(format: template, feed.nameForDisplay) } } - + var recoverySuggestion: String? { switch self { case .notLoggedIn: return nil - + case .unexpectedResourceId: let template = NSLocalizedString("Please contact NetNewsWire support.", comment: "Feedly – Recovery suggestion for not being able to encode a resource id to send to Feedly..") return String(format: template) - + case .unableToAddFolder: return nil - + case .unableToRenameFolder: return nil - + case .unableToRemoveFolder: return nil - + case .unableToMoveFeedBetweenFolders(let feed, let from, let to): let template = NSLocalizedString("“%@” may be in both “%@” and “%@”.", comment: "Feedly – Could not move a feed between folders/collections.") return String(format: template, feed.nameForDisplay, from.nameForDisplay, to.nameForDisplay) - + case .addFeedChooseFolder: return nil - + case .addFeedInvalidFolder: return NSLocalizedString("Please choose a different folder to contain the feed.", comment: "Feedly – Feed can only be added to folders recovery suggestion.") - + case .unableToRemoveFeed: return nil - + case .unableToRenameFeed: return nil } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift b/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift index da4e6fb81..1aa87d07f 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift @@ -10,16 +10,16 @@ import Foundation struct FeedlyFeedContainerValidator { var container: Container - + func getValidContainer() throws -> (Folder, String) { guard let folder = container as? Folder else { throw FeedlyAccountDelegateError.addFeedChooseFolder } - + guard let collectionId = folder.externalID else { throw FeedlyAccountDelegateError.addFeedInvalidFolder(folder) } - + return (folder, collectionId) } } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyResourceProviding.swift b/Modules/Account/Sources/Account/Feedly/FeedlyResourceProviding.swift index c58d25a28..3251f2d0f 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyResourceProviding.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyResourceProviding.swift @@ -13,7 +13,7 @@ protocol FeedlyResourceProviding { } extension FeedlyFeedResourceId: FeedlyResourceProviding { - + var resource: FeedlyResourceId { return self } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyCollectionParser.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyCollectionParser.swift index 229498592..c346b94f3 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyCollectionParser.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyCollectionParser.swift @@ -12,11 +12,11 @@ struct FeedlyCollectionParser { let collection: FeedlyCollection private let rightToLeftTextSantizer = FeedlyRTLTextSanitizer() - + var folderName: String { return rightToLeftTextSantizer.sanitize(collection.label) ?? "" } - + var externalID: String { return collection.id } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntry.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntry.swift index cb38fd2e6..18f4a5bce 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntry.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntry.swift @@ -11,30 +11,30 @@ import Foundation struct FeedlyEntry: Decodable { /// the unique, immutable ID for this particular article. let id: String - + /// the article’s title. This string does not contain any HTML markup. let title: String? - + struct Content: Decodable { - + enum Direction: String, Decodable { case leftToRight = "ltr" case rightToLeft = "rtl" } - + let content: String? let direction: Direction? } - + /// This object typically has two values: “content” for the content itself, and “direction” (“ltr” for left-to-right, “rtl” for right-to-left). The content itself contains sanitized HTML markup. let content: Content? - + /// content object the article summary. See the content object above. let summary: Content? - + /// the author’s name let author: String? - + /// the immutable timestamp, in ms, when this article was processed by the feedly Cloud servers. let crawled: Date @@ -43,7 +43,7 @@ struct FeedlyEntry: Decodable { /// the feed from which this article was crawled. If present, “streamId” will contain the feed id, “title” will contain the feed title, and “htmlUrl” will contain the feed’s website. let origin: FeedlyOrigin? - + /// Used to help find the URL to visit an article on a web site. /// See https://groups.google.com/forum/#!searchin/feedly-cloud/feed$20url%7Csort:date/feedly-cloud/Rx3dVd4aTFQ/Hf1ZfLJoCQAJ let canonical: [FeedlyLink]? diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift index 694ccd07b..0077e32d4 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift @@ -14,15 +14,15 @@ protocol FeedlyEntryIdentifierProviding: AnyObject { final class FeedlyEntryIdentifierProvider: FeedlyEntryIdentifierProviding { private(set) var entryIds: Set - + init(entryIds: Set = Set()) { self.entryIds = entryIds } - + func addEntryIds(from provider: FeedlyEntryIdentifierProviding) { entryIds.formUnion(provider.entryIds) } - + func addEntryIds(in articleIds: [String]) { entryIds.formUnion(articleIds) } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryParser.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryParser.swift index 51b5aa913..ce1609313 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryParser.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryParser.swift @@ -12,13 +12,13 @@ import RSParser struct FeedlyEntryParser { let entry: FeedlyEntry - + private let rightToLeftTextSantizer = FeedlyRTLTextSanitizer() - + var id: String { return entry.id } - + /// When ingesting articles, the feedURL must match a feed's `feedID` for the article to be reachable between it and its matching feed. It reminds me of a foreign key. var feedUrl: String? { guard let id = entry.origin?.streamId else { @@ -28,7 +28,7 @@ struct FeedlyEntryParser { } return id } - + /// Convoluted external URL logic "documented" here: /// https://groups.google.com/forum/#!searchin/feedly-cloud/feed$20url%7Csort:date/feedly-cloud/Rx3dVd4aTFQ/Hf1ZfLJoCQAJ var externalUrl: String? { @@ -38,39 +38,39 @@ struct FeedlyEntryParser { let webPageLinks = flattened.filter { $0.type == nil || $0.type == "text/html" } return webPageLinks.first?.href } - + var title: String? { return rightToLeftTextSantizer.sanitize(entry.title) } - + var contentHMTL: String? { return entry.content?.content ?? entry.summary?.content } - + var contentText: String? { // We could strip HTML from contentHTML? return nil } - + var summary: String? { return rightToLeftTextSantizer.sanitize(entry.summary?.content) } - + var datePublished: Date { return entry.crawled } - + var dateModified: Date? { return entry.recrawled } - + var authors: Set? { guard let name = entry.author else { return nil } return Set([ParsedAuthor(name: name, url: nil, avatarURL: nil, emailAddress: nil)]) } - + /// While there is not yet a tagging interface, articles can still be searched for by tags. var tags: Set? { guard let labels = entry.tags?.compactMap({ $0.label }), !labels.isEmpty else { @@ -78,7 +78,7 @@ struct FeedlyEntryParser { } return Set(labels) } - + var attachments: Set? { guard let enclosure = entry.enclosure, !enclosure.isEmpty else { return nil @@ -86,12 +86,12 @@ struct FeedlyEntryParser { let attachments = enclosure.compactMap { ParsedAttachment(url: $0.href, mimeType: $0.type, title: nil, sizeInBytes: nil, durationInSeconds: nil) } return attachments.isEmpty ? nil : Set(attachments) } - + var parsedItemRepresentation: ParsedItem? { guard let feedUrl = feedUrl else { return nil } - + return ParsedItem(syncServiceID: id, uniqueID: id, // This value seems to get ignored or replaced. feedURL: feedUrl, diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedParser.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedParser.swift index a9faf3f25..e69d2b5e8 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedParser.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedParser.swift @@ -12,20 +12,20 @@ struct FeedlyFeedParser { let feed: FeedlyFeed private let rightToLeftTextSantizer = FeedlyRTLTextSanitizer() - + var title: String? { return rightToLeftTextSantizer.sanitize(feed.title) ?? "" } - + var feedID: String { return feed.id } - + var url: String { let resource = FeedlyFeedResourceId(id: feed.id) return resource.url } - + var homePageURL: String? { return feed.website } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedsSearchResponse.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedsSearchResponse.swift index 8ddbd563b..ca54d7b3e 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedsSearchResponse.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyFeedsSearchResponse.swift @@ -9,11 +9,11 @@ import Foundation struct FeedlyFeedsSearchResponse: Decodable { - + struct Feed: Decodable { let title: String let feedId: String } - + let results: [Feed] } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyLink.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyLink.swift index 879341a08..74c009c6f 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyLink.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyLink.swift @@ -10,7 +10,7 @@ import Foundation struct FeedlyLink: Decodable { let href: String - + /// The mime type of the resource located by `href`. /// When `nil`, it's probably a web page? /// https://groups.google.com/forum/#!searchin/feedly-cloud/feed$20url%7Csort:date/feedly-cloud/Rx3dVd4aTFQ/Hf1ZfLJoCQAJ diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyRTLTextSanitizer.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyRTLTextSanitizer.swift index 11eb2dcb5..55400dd5c 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyRTLTextSanitizer.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyRTLTextSanitizer.swift @@ -11,16 +11,16 @@ import Foundation struct FeedlyRTLTextSanitizer { private let rightToLeftPrefix = "
" private let rightToLeftSuffix = "
" - + func sanitize(_ sourceText: String?) -> String? { guard let source = sourceText, !source.isEmpty else { return sourceText } - + guard source.hasPrefix(rightToLeftPrefix) && source.hasSuffix(rightToLeftSuffix) else { return source } - + let start = source.index(source.startIndex, offsetBy: rightToLeftPrefix.indices.count) let end = source.index(source.endIndex, offsetBy: -rightToLeftSuffix.indices.count) return String(source[start.. FeedlyCategoryResourceId { // https://developer.feedly.com/cloud/#global-resource-ids let id = "user/\(userId)/category/global.uncategorized" return FeedlyCategoryResourceId(id: id) } - + /// All articles from all the feeds the user subscribes to. static func all(for userId: String) -> FeedlyCategoryResourceId { // https://developer.feedly.com/cloud/#global-resource-ids let id = "user/\(userId)/category/global.all" return FeedlyCategoryResourceId(id: id) } - + /// All articles from all the feeds the user loves most. static func mustRead(for userId: String) -> FeedlyCategoryResourceId { // https://developer.feedly.com/cloud/#global-resource-ids @@ -73,9 +73,9 @@ struct FeedlyCategoryResourceId: FeedlyResourceId { struct FeedlyTagResourceId: FeedlyResourceId { let id: String - + enum Global { - + static func saved(for userId: String) -> FeedlyTagResourceId { // https://developer.feedly.com/cloud/#global-resource-ids let id = "user/\(userId)/tag/global.saved" diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyStream.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyStream.swift index fc3e92f38..38dece8a5 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyStream.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyStream.swift @@ -10,16 +10,16 @@ import Foundation struct FeedlyStream: Decodable { let id: String - + /// Of the most recent entry for this stream (regardless of continuation, newerThan, etc). let updated: Date? - + /// the continuation id to pass to the next stream call, for pagination. /// This id guarantees that no entry will be duplicated in a stream (meaning, there is no need to de-duplicate entries returned by this call). /// If this value is not returned, it means the end of the stream has been reached. let continuation: String? let items: [FeedlyEntry] - + var isStreamEnd: Bool { return continuation == nil } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyStreamIds.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyStreamIds.swift index a31e1005c..5e44fee50 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyStreamIds.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyStreamIds.swift @@ -11,7 +11,7 @@ import Foundation struct FeedlyStreamIds: Decodable { let continuation: String? let ids: [String] - + var isStreamEnd: Bool { return continuation == nil } diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift index f16029ce8..edd418874 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift @@ -17,7 +17,7 @@ public protocol OAuthAccountAuthorizationOperationDelegate: AnyObject { public enum OAuthAccountAuthorizationOperationError: LocalizedError { case duplicateAccount - + public var errorDescription: String? { return NSLocalizedString("There is already a Feedly account with that username created.", comment: "Duplicate Error") } @@ -38,44 +38,44 @@ public enum OAuthAccountAuthorizationOperationError: LocalizedError { public weak var presentationAnchor: ASPresentationAnchor? public weak var delegate: OAuthAccountAuthorizationOperationDelegate? - + private let accountType: AccountType private let oauthClient: OAuthAuthorizationClient private var session: ASWebAuthenticationSession? - + public init(accountType: AccountType) { self.accountType = accountType self.oauthClient = Account.oauthAuthorizationClient(for: accountType) } - + public func run() { assert(presentationAnchor != nil, "\(self) outlived presentation anchor.") - + let request = Account.oauthAuthorizationCodeGrantRequest(for: accountType) - + guard let url = request.url else { return DispatchQueue.main.async { self.didEndAuthentication(url: nil, error: URLError(.badURL)) } } - + guard let redirectUri = URL(string: oauthClient.redirectUri), let scheme = redirectUri.scheme else { assertionFailure("Could not get callback URL scheme from \(oauthClient.redirectUri)") return DispatchQueue.main.async { self.didEndAuthentication(url: nil, error: URLError(.badURL)) } } - + let session = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme) { url, error in DispatchQueue.main.async { [weak self] in self?.didEndAuthentication(url: url, error: error) } } - + session.presentationContextProvider = self - + guard session.start() else { - + /// Documentation does not say on why `ASWebAuthenticationSession.start` or `canStart` might return false. /// Perhaps it has something to do with an inter-process communication failure? No browsers installed? No browsers that support web authentication? struct UnableToStartASWebAuthenticationSessionError: LocalizedError { @@ -84,25 +84,25 @@ public enum OAuthAccountAuthorizationOperationError: LocalizedError { let recoverySuggestion: String? = NSLocalizedString("Check your default web browser in System Preferences or change it to Safari and try again.", comment: "OAuth - recovery suggestion - ensure browser selected supports web authentication.") } - + didFinish(UnableToStartASWebAuthenticationSessionError()) - + return } - + self.session = session } - + public func cancel() { session?.cancel() } - + private func didEndAuthentication(url: URL?, error: Error?) { guard !isCanceled else { didFinish() return } - + do { guard let url = url else { if let error = error { @@ -110,32 +110,32 @@ public enum OAuthAccountAuthorizationOperationError: LocalizedError { } throw URLError(.badURL) } - + let response = try OAuthAuthorizationResponse(url: url, client: oauthClient) - + Account.requestOAuthAccessToken(with: response, client: oauthClient, accountType: accountType, completion: didEndRequestingAccessToken(_:)) - + } catch is ASWebAuthenticationSessionError { didFinish() // Primarily, cancellation. - + } catch { didFinish(error) } } - + public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { guard let anchor = presentationAnchor else { fatalError("\(self) has outlived presentation anchor.") } return anchor } - + private func didEndRequestingAccessToken(_ result: Result) { guard !isCanceled else { didFinish() return } - + switch result { case .success(let tokenResponse): saveAccount(for: tokenResponse) @@ -143,39 +143,39 @@ public enum OAuthAccountAuthorizationOperationError: LocalizedError { didFinish(error) } } - + private func saveAccount(for grant: OAuthAuthorizationGrant) { guard !AccountManager.shared.duplicateServiceAccount(type: .feedly, username: grant.accessToken.username) else { didFinish(OAuthAccountAuthorizationOperationError.duplicateAccount) return } - + let account = AccountManager.shared.createAccount(type: .feedly) do { - + // Store the refresh token first because it sends this token to the account delegate. if let token = grant.refreshToken { try account.storeCredentials(token) } - + // Now store the access token because we want the account delegate to use it. try account.storeCredentials(grant.accessToken) - + delegate?.oauthAccountAuthorizationOperation(self, didCreate: account) - + didFinish() } catch { didFinish(error) } } - + // MARK: Managing Operation State - + private func didFinish() { assert(Thread.isMainThread) operationDelegate?.operationDidComplete(self) } - + private func didFinish(_ error: Error) { assert(Thread.isMainThread) delegate?.oauthAccountAuthorizationOperation(self, didFailWith: error) diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift b/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift index 306815c77..b2228c19f 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift @@ -15,11 +15,11 @@ public struct OAuthRefreshAccessTokenRequest: Encodable { public let grantType = "refresh_token" public var refreshToken: String public var scope: String? - + // Possibly not part of the standard but specific to certain implementations (e.g.: Feedly). public var clientId: String public var clientSecret: String - + public init(refreshToken: String, scope: String?, client: OAuthAuthorizationClient) { self.refreshToken = refreshToken self.scope = scope @@ -32,7 +32,7 @@ public struct OAuthRefreshAccessTokenRequest: Encodable { /// https://tools.ietf.org/html/rfc6749#section-6 public protocol OAuthAcessTokenRefreshRequesting { associatedtype AccessTokenResponse: OAuthAccessTokenResponse - + /// Access tokens expire. Perform a request for a fresh access token given the long life refresh token received when authorization was granted. /// - Parameter refreshRequest: The refresh token and other information the authorization server requires to grant the client fresh access tokens on the user's behalf. /// - Parameter completion: On success, the access token response appropriate for concrete type's service. Both the access and refresh token should be stored, preferably on the Keychain. On failure, possibly a `URLError` or `OAuthAuthorizationErrorResponse` value. @@ -41,6 +41,6 @@ public protocol OAuthAcessTokenRefreshRequesting { /// Implemented by concrete types to perform the actual request. protocol OAuthAccessTokenRefreshing: AnyObject { - + func refreshAccessToken(with refreshToken: String, client: OAuthAuthorizationClient, completion: @escaping (Result) -> ()) } diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationClient+Feedly.swift b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationClient+Feedly.swift index 627736317..3a74341ae 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationClient+Feedly.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationClient+Feedly.swift @@ -10,7 +10,7 @@ import Foundation import Secrets extension OAuthAuthorizationClient { - + static var feedlyCloudClient: OAuthAuthorizationClient { /// Models private NetNewsWire client secrets. /// These placeholders are substituted at build time using a Run Script phase with build settings. @@ -20,7 +20,7 @@ extension OAuthAuthorizationClient { state: nil, secret: SecretsManager.provider.feedlyClientSecret) } - + static var feedlySandboxClient: OAuthAuthorizationClient { /// We use this funky redirect URI because ASWebAuthenticationSession will try to load http://localhost URLs. /// See https://developer.feedly.com/v3/sandbox/ for more information. diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift index 713788fbd..4c7f7e324 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift @@ -17,7 +17,7 @@ public struct OAuthAuthorizationClient: Equatable { public var redirectUri: String public var state: String? public var secret: String - + public init(id: String, redirectUri: String, state: String?, secret: String) { self.id = id self.redirectUri = redirectUri @@ -34,14 +34,14 @@ public struct OAuthAuthorizationRequest { public var redirectUri: String public var scope: String public var state: String? - + public init(clientId: String, redirectUri: String, scope: String, state: String?) { self.clientId = clientId self.redirectUri = redirectUri self.scope = scope self.state = state } - + public var queryItems: [URLQueryItem] { return [ URLQueryItem(name: "response_type", value: responseType), @@ -60,7 +60,7 @@ public struct OAuthAuthorizationResponse { } public extension OAuthAuthorizationResponse { - + init(url: URL, client: OAuthAuthorizationClient) throws { guard let scheme = url.scheme, client.redirectUri.hasPrefix(scheme) else { throw URLError(.unsupportedURL) @@ -75,10 +75,10 @@ public extension OAuthAuthorizationResponse { guard let codeValue = code?.value, !codeValue.isEmpty else { throw URLError(.unsupportedURL) } - + let state = queryItems.first { $0.name.lowercased() == "state" } let stateValue = state?.value - + self.init(code: codeValue, state: stateValue) } } @@ -89,7 +89,7 @@ public struct OAuthAuthorizationErrorResponse: Error { public var error: OAuthAuthorizationError public var state: String? public var errorDescription: String? - + public var localizedDescription: String { return errorDescription ?? error.rawValue } @@ -115,11 +115,11 @@ public struct OAuthAccessTokenRequest: Encodable { public var redirectUri: String public var state: String? public var clientId: String - + // Possibly not part of the standard but specific to certain implementations (e.g.: Feedly). public var clientSecret: String public var scope: String - + public init(authorizationResponse: OAuthAuthorizationResponse, scope: String, client: OAuthAuthorizationClient) { self.code = authorizationResponse.code self.redirectUri = client.redirectUri @@ -152,13 +152,13 @@ public struct OAuthAuthorizationGrant: Equatable { /// https://tools.ietf.org/html/rfc6749#section-4.1 public protocol OAuthAuthorizationCodeGrantRequesting { associatedtype AccessTokenResponse: OAuthAccessTokenResponse - + /// Provides the URL request that allows users to consent to the client having access to their information. Typically loaded by a web view. /// - Parameter request: The information about the client requesting authorization to be granted access tokens. /// - Parameter baseUrlComponents: The scheme and host of the url except for the path. static func authorizationCodeUrlRequest(for request: OAuthAuthorizationRequest, baseUrlComponents: URLComponents) -> URLRequest - - + + /// Performs the request for the access token given an authorization code. /// - Parameter authorizationRequest: The authorization code and other information the authorization server requires to grant the client access tokens on the user's behalf. /// - Parameter completion: On success, the access token response appropriate for concrete type's service. On failure, possibly a `URLError` or `OAuthAuthorizationErrorResponse` value. @@ -166,8 +166,8 @@ public protocol OAuthAuthorizationCodeGrantRequesting { } protocol OAuthAuthorizationGranting: AccountDelegate { - + static func oauthAuthorizationCodeGrantRequest() -> URLRequest - + static func requestOAuthAccessToken(with response: OAuthAuthorizationResponse, transport: Transport, completion: @escaping (Result) -> ()) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddExistingFeedOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddExistingFeedOperation.swift index 100756b11..508548a2c 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddExistingFeedOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddExistingFeedOperation.swift @@ -18,33 +18,33 @@ final class FeedlyAddExistingFeedOperation: FeedlyOperation, FeedlyOperationDele var addCompletionHandler: ((Result) -> ())? init(account: Account, credentials: Credentials, resource: FeedlyFeedResourceId, service: FeedlyAddFeedToCollectionService, container: Container, progress: DownloadProgress, customFeedName: String? = nil) throws { - + let validator = FeedlyFeedContainerValidator(container: container) let (folder, collectionId) = try validator.getValidContainer() - + self.operationQueue.suspend() super.init() - + self.downloadProgress = progress - + let addRequest = FeedlyAddFeedToCollectionOperation(account: account, folder: folder, feedResource: resource, feedName: customFeedName, collectionId: collectionId, service: service) addRequest.delegate = self addRequest.downloadProgress = progress self.operationQueue.add(addRequest) - + let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: addRequest) createFeeds.downloadProgress = progress createFeeds.addDependency(addRequest) self.operationQueue.add(createFeeds) - + let finishOperation = FeedlyCheckpointOperation() finishOperation.checkpointDelegate = self finishOperation.downloadProgress = progress finishOperation.addDependency(createFeeds) self.operationQueue.add(finishOperation) } - + override func run() { operationQueue.resume() } @@ -54,22 +54,22 @@ final class FeedlyAddExistingFeedOperation: FeedlyOperation, FeedlyOperationDele addCompletionHandler = nil super.didCancel() } - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { addCompletionHandler?(.failure(error)) addCompletionHandler = nil - + cancel() } - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { guard !isCanceled else { return } - + addCompletionHandler?(.success(())) addCompletionHandler = nil - + didFinish() } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddFeedToCollectionOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddFeedToCollectionOperation.swift index ce749a83d..0ebae8c6b 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddFeedToCollectionOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddFeedToCollectionOperation.swift @@ -29,13 +29,13 @@ final class FeedlyAddFeedToCollectionOperation: FeedlyOperation, FeedlyFeedsAndF self.collectionId = collectionId self.service = service } - + private(set) var feedsAndFolders = [([FeedlyFeed], Folder)]() - + var resource: FeedlyResourceId { return feedResource } - + override func run() { service.addFeed(with: feedResource, title: feedName, toCollectionWith: collectionId) { [weak self] result in guard let self = self else { @@ -56,15 +56,15 @@ private extension FeedlyAddFeedToCollectionOperation { switch result { case .success(let feedlyFeeds): feedsAndFolders = [(feedlyFeeds, folder)] - + let feedsWithCreatedFeedId = feedlyFeeds.filter { $0.id == resource.id } - + if feedsWithCreatedFeedId.isEmpty { didFinish(with: AccountError.createErrorNotFound) } else { didFinish() } - + case .failure(let error): didFinish(with: error) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddNewFeedOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddNewFeedOperation.swift index de99cc228..25606f8e3 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddNewFeedOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyAddNewFeedOperation.swift @@ -30,11 +30,11 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, var addCompletionHandler: ((Result) -> ())? init(account: Account, credentials: Credentials, url: String, feedName: String?, searchService: FeedlySearchService, addToCollectionService: FeedlyAddFeedToCollectionService, syncUnreadIdsService: FeedlyGetStreamIdsService, getStreamContentsService: FeedlyGetStreamContentsService, database: SyncDatabase, container: Container, progress: DownloadProgress) throws { - + let validator = FeedlyFeedContainerValidator(container: container) (self.folder, self.collectionId) = try validator.getValidContainer() - + self.url = url self.operationQueue.suspend() self.account = account @@ -48,14 +48,14 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, super.init() self.downloadProgress = progress - + let search = FeedlySearchOperation(query: url, locale: .current, service: searchService) search.delegate = self search.searchDelegate = self search.downloadProgress = progress self.operationQueue.add(search) } - + override func run() { operationQueue.resume() } @@ -65,7 +65,7 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, addCompletionHandler = nil super.didCancel() } - + override func didFinish(with error: Error) { assert(Thread.isMainThread) addCompletionHandler?(.failure(error)) @@ -80,33 +80,33 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, guard let first = response.results.first else { return didFinish(with: AccountError.createErrorNotFound) } - + let feedResourceId = FeedlyFeedResourceId(id: first.feedId) self.feedResourceId = feedResourceId - + let addRequest = FeedlyAddFeedToCollectionOperation(account: account, folder: folder, feedResource: feedResourceId, feedName: feedName, collectionId: collectionId, service: addToCollectionService) addRequest.delegate = self addRequest.downloadProgress = downloadProgress operationQueue.add(addRequest) - + let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: addRequest) createFeeds.delegate = self createFeeds.addDependency(addRequest) createFeeds.downloadProgress = downloadProgress operationQueue.add(createFeeds) - + let syncUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: credentials.username, service: syncUnreadIdsService, database: database, newerThan: nil) syncUnread.addDependency(createFeeds) syncUnread.downloadProgress = downloadProgress syncUnread.delegate = self operationQueue.add(syncUnread) - + let syncFeed = FeedlySyncStreamContentsOperation(account: account, resource: feedResourceId, service: getStreamContentsService, isPagingEnabled: false, newerThan: nil) syncFeed.addDependency(syncUnread) syncFeed.downloadProgress = downloadProgress syncFeed.delegate = self operationQueue.add(syncFeed) - + let finishOperation = FeedlyCheckpointOperation() finishOperation.checkpointDelegate = self finishOperation.downloadProgress = downloadProgress @@ -114,7 +114,7 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, finishOperation.delegate = self operationQueue.add(finishOperation) } - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { addCompletionHandler?(.failure(error)) addCompletionHandler = nil @@ -123,7 +123,7 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, cancel() } - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { guard !isCanceled else { return @@ -131,7 +131,7 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate, defer { didFinish() } - + guard let handler = addCompletionHandler else { return } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyCreateFeedsForCollectionFoldersOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyCreateFeedsForCollectionFoldersOperation.swift index 08d4e6110..9806ab35b 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyCreateFeedsForCollectionFoldersOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyCreateFeedsForCollectionFoldersOperation.swift @@ -11,7 +11,7 @@ import os.log /// Single responsibility is to accurately reflect Collections and their Feeds as Folders and their Feeds. final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { - + let account: Account let feedsAndFoldersProvider: FeedlyFeedsAndFoldersProviding @@ -19,18 +19,18 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { self.feedsAndFoldersProvider = feedsAndFoldersProvider self.account = account } - + override func run() { defer { didFinish() } let pairs = feedsAndFoldersProvider.feedsAndFolders - + let feedsBefore = Set(pairs .map { $0.1 } .flatMap { $0.topLevelFeeds }) - + // Remove feeds in a folder which are not in the corresponding collection. for (collectionFeeds, folder) in pairs { let feedsInFolder = folder.topLevelFeeds @@ -40,12 +40,12 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { folder.removeFeeds(feedsToRemove) // os_log(.debug, log: log, "\"%@\" - removed: %@", collection.label, feedsToRemove.map { $0.feedID }, feedsInCollection) } - + } - + // Pair each Feed with its Folder. var feedsAdded = Set() - + let feedsAndFolders = pairs .map({ (collectionFeeds, folder) -> [(FeedlyFeed, Folder)] in return collectionFeeds.map { feed -> (FeedlyFeed, Folder) in @@ -57,11 +57,11 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { // find an existing feed previously added to the account if let feed = account.existingFeed(withFeedID: collectionFeed.id) { - + // If the feed was renamed on Feedly, ensure we ingest the new name. if feed.nameForDisplay != collectionFeed.title { feed.name = collectionFeed.title - + // Let the rest of the app (e.g.: the sidebar) know the feed name changed // `editedName` would post this if its value is changing. // Setting the `name` property has no side effects like this. @@ -85,10 +85,10 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { url: parser.url, feedID: parser.feedID, homePageURL: parser.homePageURL) - + // So the same feed isn't created more than once. feedsAdded.insert(feed) - + return (feed, folder) } @@ -98,12 +98,12 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation { folder.addFeed(feed) } } - + // Remove feeds without folders/collections. let feedsAfter = Set(feedsAndFolders.map { $0.0 }) let feedsWithoutCollections = feedsBefore.subtracting(feedsAfter) account.removeFeeds(feedsWithoutCollections) - + if !feedsWithoutCollections.isEmpty { Feedly.logger.info("Feedly: Removed \(feedsWithoutCollections.count) feeds") } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift index 0e64e6706..c901411a3 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift @@ -19,7 +19,7 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation { private let getEntriesService: FeedlyGetEntriesService private let operationQueue = MainThreadOperationQueue() private let finishOperation: FeedlyCheckpointOperation - + init(account: Account, missingArticleEntryIdProvider: FeedlyEntryIdentifierProviding, updatedArticleEntryIdProvider: FeedlyEntryIdentifierProviding, getEntriesService: FeedlyGetEntriesService) { self.account = account self.operationQueue.suspend() @@ -31,7 +31,7 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation { self.finishOperation.checkpointDelegate = self self.operationQueue.add(self.finishOperation) } - + override func run() { var articleIds = missingArticleEntryIdProvider.entryIds articleIds.formUnion(updatedArticleEntryIdProvider.entryIds) @@ -40,12 +40,12 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation { let feedlyAPILimitBatchSize = 1000 for articleIds in Array(articleIds).chunked(into: feedlyAPILimitBatchSize) { - + let provider = FeedlyEntryIdentifierProvider(entryIds: Set(articleIds)) let getEntries = FeedlyGetEntriesOperation(account: account, service: getEntriesService, provider: provider) getEntries.delegate = self self.operationQueue.add(getEntries) - + let organiseByFeed = FeedlyOrganiseParsedItemsByFeedOperation( account: account, parsedItemProvider: getEntries @@ -53,19 +53,19 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation { organiseByFeed.delegate = self organiseByFeed.addDependency(getEntries) self.operationQueue.add(organiseByFeed) - + let updateAccount = FeedlyUpdateAccountFeedsWithItemsOperation( account: account, organisedItemsProvider: organiseByFeed ) - + updateAccount.delegate = self updateAccount.addDependency(organiseByFeed) self.operationQueue.add(updateAccount) finishOperation.addDependency(updateAccount) } - + operationQueue.resume() } @@ -77,17 +77,17 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation { } extension FeedlyDownloadArticlesOperation: FeedlyCheckpointOperationDelegate { - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { didFinish() } } extension FeedlyDownloadArticlesOperation: FeedlyOperationDelegate { - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { assert(Thread.isMainThread) - + // Having this log is useful for debugging missing required JSON keys in the response from Feedly, for example. Feedly.logger.error("Feedly: FeedlyDownloadArticlesOperation did fail with error: \(error.localizedDescription)") cancel() diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift index 2e38ceb0a..d2de572c7 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift @@ -12,20 +12,20 @@ import os.log final class FeedlyFetchIdsForMissingArticlesOperation: FeedlyOperation, FeedlyEntryIdentifierProviding { private let account: Account - + private(set) var entryIds = Set() - + init(account: Account) { self.account = account } - + override func run() { account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in switch result { case .success(let articleIds): self.entryIds.formUnion(articleIds) self.didFinish() - + case .failure(let error): self.didFinish(with: error) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetCollectionsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetCollectionsOperation.swift index 117323794..e806fddc0 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetCollectionsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetCollectionsOperation.swift @@ -15,15 +15,15 @@ protocol FeedlyCollectionProviding: AnyObject { /// Get Collections from Feedly. final class FeedlyGetCollectionsOperation: FeedlyOperation, FeedlyCollectionProviding { - + let service: FeedlyGetCollectionsService - + private(set) var collections = [FeedlyCollection]() init(service: FeedlyGetCollectionsService) { self.service = service } - + override func run() { Feedly.logger.info("Feedly: Requesting collections") @@ -33,7 +33,7 @@ final class FeedlyGetCollectionsOperation: FeedlyOperation, FeedlyCollectionProv Feedly.logger.info("Feedly: Received collections \(collections.map { $0.id })") self.collections = collections self.didFinish() - + case .failure(let error): Feedly.logger.error("Feedly: Unable to request collections with error \(error.localizedDescription)") self.didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift index f795962e5..1e0dbd781 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift @@ -22,20 +22,20 @@ final class FeedlyGetEntriesOperation: FeedlyOperation, FeedlyEntryProviding, Fe self.service = service self.provider = provider } - + private(set) var entries = [FeedlyEntry]() - + private var storedParsedEntries: Set? - + var parsedEntries: Set { if let entries = storedParsedEntries { return entries } - + let parsed = Set(entries.compactMap { FeedlyEntryParser(entry: $0).parsedItemRepresentation }) - + // TODO: Fix the below. There’s an error on the os.log line: "Expression type '()' is ambiguous without more context" // if parsed.count != entries.count { // let entryIds = Set(entries.map { $0.id }) @@ -43,23 +43,23 @@ final class FeedlyGetEntriesOperation: FeedlyOperation, FeedlyEntryProviding, Fe // let difference = entryIds.subtracting(parsedIds) // os_log(.debug, log: log, "%{public}@ dropping articles with ids: %{public}@.", self, difference) // } - + storedParsedEntries = parsed - + return parsed } - + var parsedItemProviderName: String { return name ?? String(describing: Self.self) } - + override func run() { service.getEntries(for: provider.entryIds) { result in switch result { case .success(let entries): self.entries = entries self.didFinish() - + case .failure(let error): Feedly.logger.error("Feedly: Unable to get entries with error \(error.localizedDescription)") self.didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamContentsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamContentsOperation.swift index 93a013ac5..3d99b418d 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamContentsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamContentsOperation.swift @@ -25,17 +25,17 @@ protocol FeedlyGetStreamContentsOperationDelegate: AnyObject { /// Get the stream content of a Collection from Feedly. final class FeedlyGetStreamContentsOperation: FeedlyOperation, FeedlyEntryProviding, FeedlyParsedItemProviding { - + struct ResourceProvider: FeedlyResourceProviding { var resource: FeedlyResourceId } - + let resourceProvider: FeedlyResourceProviding - + var parsedItemProviderName: String { return resourceProvider.resource.id } - + var entries: [FeedlyEntry] { guard let entries = stream?.items else { // assert(isFinished, "This should only be called when the operation finishes without error.") @@ -44,42 +44,42 @@ final class FeedlyGetStreamContentsOperation: FeedlyOperation, FeedlyEntryProvid } return entries } - + var parsedEntries: Set { if let entries = storedParsedEntries { return entries } - + let parsed = Set(entries.compactMap { FeedlyEntryParser(entry: $0).parsedItemRepresentation }) - + if parsed.count != entries.count { let entryIds = Set(entries.map { $0.id }) let parsedIds = Set(parsed.map { $0.uniqueID }) let difference = entryIds.subtracting(parsedIds) Feedly.logger.info("Feedly: Dropping articles with IDs \(difference)") } - + storedParsedEntries = parsed - + return parsed } - + private(set) var stream: FeedlyStream? { didSet { storedParsedEntries = nil } } - + private var storedParsedEntries: Set? - + let account: Account let service: FeedlyGetStreamContentsService let unreadOnly: Bool? let newerThan: Date? let continuation: String? - + weak var streamDelegate: FeedlyGetStreamContentsOperationDelegate? init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamContentsService, continuation: String? = nil, newerThan: Date?, unreadOnly: Bool? = nil) { @@ -90,21 +90,21 @@ final class FeedlyGetStreamContentsOperation: FeedlyOperation, FeedlyEntryProvid self.unreadOnly = unreadOnly self.newerThan = newerThan } - + convenience init(account: Account, resourceProvider: FeedlyResourceProviding, service: FeedlyGetStreamContentsService, newerThan: Date?, unreadOnly: Bool? = nil) { self.init(account: account, resource: resourceProvider.resource, service: service, newerThan: newerThan, unreadOnly: unreadOnly) } - + override func run() { service.getStreamContents(for: resourceProvider.resource, continuation: continuation, newerThan: newerThan, unreadOnly: unreadOnly) { result in switch result { case .success(let stream): self.stream = stream - + self.streamDelegate?.feedlyGetStreamContentsOperation(self, didGetContentsOf: stream) - + self.didFinish() - + case .failure(let error): Feedly.logger.error("Feedly: Unable to get stream contents: \(error.localizedDescription)") self.didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift index 1cd58b2bc..d336b21fa 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift @@ -15,7 +15,7 @@ protocol FeedlyGetStreamIdsOperationDelegate: AnyObject { /// Single responsibility is to get the stream ids from Feedly. final class FeedlyGetStreamIdsOperation: FeedlyOperation, FeedlyEntryIdentifierProviding { - + var entryIds: Set { guard let ids = streamIds?.ids else { assertionFailure("Has this operation been addeded as a dependency on the caller?") @@ -23,9 +23,9 @@ final class FeedlyGetStreamIdsOperation: FeedlyOperation, FeedlyEntryIdentifierP } return Set(ids) } - + private(set) var streamIds: FeedlyStreamIds? - + let account: Account let service: FeedlyGetStreamIdsService let continuation: String? @@ -41,19 +41,19 @@ final class FeedlyGetStreamIdsOperation: FeedlyOperation, FeedlyEntryIdentifierP self.newerThan = newerThan self.unreadOnly = unreadOnly } - + weak var streamIdsDelegate: FeedlyGetStreamIdsOperationDelegate? - + override func run() { service.getStreamIds(for: resource, continuation: continuation, newerThan: newerThan, unreadOnly: unreadOnly) { result in switch result { case .success(let stream): self.streamIds = stream - + self.streamIdsDelegate?.feedlyGetStreamIdsOperation(self, didGet: stream) - + self.didFinish() - + case .failure(let error): Feedly.logger.error("Feedly: Unable to get stream IDs: \(error.localizedDescription)") self.didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift index aca73f01b..ae97fad05 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift @@ -20,57 +20,57 @@ final class FeedlyGetUpdatedArticleIdsOperation: FeedlyOperation, FeedlyEntryIde private let resource: FeedlyResourceId private let service: FeedlyGetStreamIdsService private let newerThan: Date? - + init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamIdsService, newerThan: Date?) { self.account = account self.resource = resource self.service = service self.newerThan = newerThan } - + convenience init(account: Account, userId: String, service: FeedlyGetStreamIdsService, newerThan: Date?) { let all = FeedlyCategoryResourceId.Global.all(for: userId) self.init(account: account, resource: all, service: service, newerThan: newerThan) } - + var entryIds: Set { return storedUpdatedArticleIds } - + private var storedUpdatedArticleIds = Set() - + override func run() { getStreamIds(nil) } - + private func getStreamIds(_ continuation: String?) { guard let date = newerThan else { Feedly.logger.debug("Feedly: No date provided so everything must be new (nothing is updated)") didFinish() return } - + service.getStreamIds(for: resource, continuation: continuation, newerThan: date, unreadOnly: nil, completion: didGetStreamIds(_:)) } - + private func didGetStreamIds(_ result: Result) { guard !isCanceled else { didFinish() return } - + switch result { case .success(let streamIds): storedUpdatedArticleIds.formUnion(streamIds.ids) - + guard let continuation = streamIds.continuation else { Feedly.logger.info("Feedly: Articles updated since last successful sync start date: \(self.storedUpdatedArticleIds.count)") didFinish() return } - + getStreamIds(continuation) - + case .failure(let error): didFinish(with: error) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift index 1f06ecb3d..fc74fe518 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift @@ -24,104 +24,104 @@ final class FeedlyIngestStarredArticleIdsOperation: FeedlyOperation { private let service: FeedlyGetStreamIdsService private let database: SyncDatabase private var remoteEntryIds = Set() - + convenience init(account: Account, userId: String, service: FeedlyGetStreamIdsService, database: SyncDatabase, newerThan: Date?) { let resource = FeedlyTagResourceId.Global.saved(for: userId) self.init(account: account, resource: resource, service: service, database: database, newerThan: newerThan) } - + init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamIdsService, database: SyncDatabase, newerThan: Date?) { self.account = account self.resource = resource self.service = service self.database = database } - + override func run() { getStreamIds(nil) } - + private func getStreamIds(_ continuation: String?) { service.getStreamIds(for: resource, continuation: continuation, newerThan: nil, unreadOnly: nil, completion: didGetStreamIds(_:)) } - + private func didGetStreamIds(_ result: Result) { guard !isCanceled else { didFinish() return } - + switch result { case .success(let streamIds): - + remoteEntryIds.formUnion(streamIds.ids) - + guard let continuation = streamIds.continuation else { removeEntryIdsWithPendingStatus() return } - + getStreamIds(continuation) - + case .failure(let error): didFinish(with: error) } } - + /// Do not override pending statuses with the remote statuses of the same articles, otherwise an article will temporarily re-acquire the remote status before the pending status is pushed and subseqently pulled. private func removeEntryIdsWithPendingStatus() { guard !isCanceled else { didFinish() return } - + database.selectPendingStarredStatusArticleIDs { result in switch result { case .success(let pendingArticleIds): self.remoteEntryIds.subtract(pendingArticleIds) - + self.updateStarredStatuses() - + case .failure(let error): self.didFinish(with: error) } } } - + private func updateStarredStatuses() { guard !isCanceled else { didFinish() return } - + account.fetchStarredArticleIDs { result in switch result { case .success(let localStarredArticleIDs): self.processStarredArticleIDs(localStarredArticleIDs) - + case .failure(let error): self.didFinish(with: error) } } } - + func processStarredArticleIDs(_ localStarredArticleIDs: Set) { guard !isCanceled else { didFinish() return } - + let remoteStarredArticleIDs = remoteEntryIds - + let group = DispatchGroup() - + final class StarredStatusResults { var markAsStarredError: Error? var markAsUnstarredError: Error? } - + let results = StarredStatusResults() - + group.enter() account.markAsStarred(remoteStarredArticleIDs) { result in if case .failure(let error) = result { diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift index 83e1dfc21..2b231fff2 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift @@ -20,47 +20,47 @@ final class FeedlyIngestStreamArticleIdsOperation: FeedlyOperation { private let account: Account private let resource: FeedlyResourceId private let service: FeedlyGetStreamIdsService - + init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamIdsService) { self.account = account self.resource = resource self.service = service } - + convenience init(account: Account, userId: String, service: FeedlyGetStreamIdsService) { let all = FeedlyCategoryResourceId.Global.all(for: userId) self.init(account: account, resource: all, service: service) } - + override func run() { getStreamIds(nil) } - + private func getStreamIds(_ continuation: String?) { service.getStreamIds(for: resource, continuation: continuation, newerThan: nil, unreadOnly: nil, completion: didGetStreamIds(_:)) } - + private func didGetStreamIds(_ result: Result) { guard !isCanceled else { didFinish() return } - + switch result { case .success(let streamIds): account.createStatusesIfNeeded(articleIDs: Set(streamIds.ids)) { databaseError in - + if let error = databaseError { self.didFinish(with: error) return } - + guard let continuation = streamIds.continuation else { Feedly.logger.info("Feedly: Reached end of stream for \(self.resource.id)") self.didFinish() return } - + self.getStreamIds(continuation) } case .failure(let error): diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift index fca023f26..9def852ad 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift @@ -25,87 +25,87 @@ final class FeedlyIngestUnreadArticleIdsOperation: FeedlyOperation { private let service: FeedlyGetStreamIdsService private let database: SyncDatabase private var remoteEntryIds = Set() - + convenience init(account: Account, userId: String, service: FeedlyGetStreamIdsService, database: SyncDatabase, newerThan: Date?) { let resource = FeedlyCategoryResourceId.Global.all(for: userId) self.init(account: account, resource: resource, service: service, database: database, newerThan: newerThan) } - + init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamIdsService, database: SyncDatabase, newerThan: Date?) { self.account = account self.resource = resource self.service = service self.database = database } - + override func run() { getStreamIds(nil) } - + private func getStreamIds(_ continuation: String?) { service.getStreamIds(for: resource, continuation: continuation, newerThan: nil, unreadOnly: true, completion: didGetStreamIds(_:)) } - + private func didGetStreamIds(_ result: Result) { guard !isCanceled else { didFinish() return } - + switch result { case .success(let streamIds): - + remoteEntryIds.formUnion(streamIds.ids) - + guard let continuation = streamIds.continuation else { removeEntryIdsWithPendingStatus() return } - + getStreamIds(continuation) - + case .failure(let error): didFinish(with: error) } } - + /// Do not override pending statuses with the remote statuses of the same articles, otherwise an article will temporarily re-acquire the remote status before the pending status is pushed and subseqently pulled. private func removeEntryIdsWithPendingStatus() { guard !isCanceled else { didFinish() return } - + database.selectPendingReadStatusArticleIDs { result in switch result { case .success(let pendingArticleIds): self.remoteEntryIds.subtract(pendingArticleIds) - + self.updateUnreadStatuses() - + case .failure(let error): self.didFinish(with: error) } } } - + private func updateUnreadStatuses() { guard !isCanceled else { didFinish() return } - + account.fetchUnreadArticleIDs { result in switch result { case .success(let localUnreadArticleIDs): self.processUnreadArticleIDs(localUnreadArticleIDs) - + case .failure(let error): self.didFinish(with: error) } } } - + private func processUnreadArticleIDs(_ localUnreadArticleIDs: Set) { guard !isCanceled else { didFinish() @@ -114,14 +114,14 @@ final class FeedlyIngestUnreadArticleIdsOperation: FeedlyOperation { let remoteUnreadArticleIDs = remoteEntryIds let group = DispatchGroup() - + final class ReadStatusResults { var markAsUnreadError: Error? var markAsReadError: Error? } - + let results = ReadStatusResults() - + group.enter() account.markAsUnread(remoteUnreadArticleIDs) { result in if case .failure(let error) = result { diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyLogoutOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyLogoutOperation.swift index f9af7c235..0a7fdaa3d 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyLogoutOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyLogoutOperation.swift @@ -17,17 +17,17 @@ final class FeedlyLogoutOperation: FeedlyOperation { let service: FeedlyLogoutService let account: Account - + init(account: Account, service: FeedlyLogoutService) { self.service = service self.account = account } - + override func run() { Feedly.logger.info("Feedly: Requesting logout \(self.account.accountID, privacy: .public)") service.logout(completion: didCompleteLogout(_:)) } - + func didCompleteLogout(_ result: Result) { assert(Thread.isMainThread) switch result { @@ -40,7 +40,7 @@ final class FeedlyLogoutOperation: FeedlyOperation { // oh well, we tried our best. } didFinish() - + case .failure(let error): Feedly.logger.error("Feedly: Logout failed: \(error.localizedDescription)") didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyMirrorCollectionsAsFoldersOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyMirrorCollectionsAsFoldersOperation.swift index 324bcee55..13cbd40d8 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyMirrorCollectionsAsFoldersOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyMirrorCollectionsAsFoldersOperation.swift @@ -15,25 +15,25 @@ protocol FeedlyFeedsAndFoldersProviding { /// Reflect Collections from Feedly as Folders. final class FeedlyMirrorCollectionsAsFoldersOperation: FeedlyOperation, FeedlyFeedsAndFoldersProviding { - + let account: Account let collectionsProvider: FeedlyCollectionProviding - + private(set) var feedsAndFolders = [([FeedlyFeed], Folder)]() init(account: Account, collectionsProvider: FeedlyCollectionProviding) { self.collectionsProvider = collectionsProvider self.account = account } - + override func run() { defer { didFinish() } - + let localFolders = account.folders ?? Set() let collections = collectionsProvider.collections - + feedsAndFolders = collections.compactMap { collection -> ([FeedlyFeed], Folder)? in let parser = FeedlyCollectionParser(collection: collection) guard let folder = account.ensureFolder(with: parser.folderName) else { @@ -49,7 +49,7 @@ final class FeedlyMirrorCollectionsAsFoldersOperation: FeedlyOperation, FeedlyFe // Remove folders without a corresponding collection let collectionFolders = Set(feedsAndFolders.map { $0.1 }) let foldersWithoutCollections = localFolders.subtracting(collectionFolders) - + if !foldersWithoutCollections.isEmpty { for unmatched in foldersWithoutCollections { account.removeFolder(unmatched) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyOrganiseParsedItemsByFeedOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyOrganiseParsedItemsByFeedOperation.swift index e6a9a6340..7e0fa99f7 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyOrganiseParsedItemsByFeedOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyOrganiseParsedItemsByFeedOperation.swift @@ -20,23 +20,23 @@ final class FeedlyOrganiseParsedItemsByFeedOperation: FeedlyOperation, FeedlyPar private let account: Account private let parsedItemProvider: FeedlyParsedItemProviding - + var parsedItemsByFeedProviderName: String { return name ?? String(describing: Self.self) } - + var parsedItemsKeyedByFeedId: [String : Set] { precondition(Thread.isMainThread) // Needs to be on main thread because Feed is a main-thread-only model type. return itemsKeyedByFeedId } - + private var itemsKeyedByFeedId = [String: Set]() - + init(account: Account, parsedItemProvider: FeedlyParsedItemProviding) { self.account = account self.parsedItemProvider = parsedItemProvider } - + override func run() { defer { didFinish() @@ -44,7 +44,7 @@ final class FeedlyOrganiseParsedItemsByFeedOperation: FeedlyOperation, FeedlyPar let items = parsedItemProvider.parsedEntries var dict = [String: Set](minimumCapacity: items.count) - + for item in items { let key = item.feedURL let value: Set = { diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift index 72d5512ee..7d317e2bd 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift @@ -16,24 +16,24 @@ final class FeedlyRefreshAccessTokenOperation: FeedlyOperation { let service: OAuthAccessTokenRefreshing let oauthClient: OAuthAuthorizationClient let account: Account - + init(account: Account, service: OAuthAccessTokenRefreshing, oauthClient: OAuthAuthorizationClient) { self.oauthClient = oauthClient self.service = service self.account = account } - + override func run() { let refreshToken: Credentials - + do { guard let credentials = try account.retrieveCredentials(type: .oauthRefreshToken) else { Feedly.logger.error("Feedly: Could not find a refresh token in the keychain. Check the refresh token is added to the Keychain, remove the account and add it again") throw TransportError.httpError(status: 403) } - + refreshToken = credentials - + } catch { didFinish(with: error) return @@ -46,10 +46,10 @@ final class FeedlyRefreshAccessTokenOperation: FeedlyOperation { self.didRefreshAccessToken(result) } } - + private func didRefreshAccessToken(_ result: Result) { assert(Thread.isMainThread) - + switch result { case .success(let grant): do { @@ -58,16 +58,16 @@ final class FeedlyRefreshAccessTokenOperation: FeedlyOperation { if let token = grant.refreshToken { try account.storeCredentials(token) } - + Feedly.logger.info("Feedly: Storing access token") // Now store the access token because we want the account delegate to use it. try account.storeCredentials(grant.accessToken) - + didFinish() } catch { didFinish(with: error) } - + case .failure(let error): didFinish(with: error) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRequestStreamsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRequestStreamsOperation.swift index 9a68986ab..e40e6e60e 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRequestStreamsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRequestStreamsOperation.swift @@ -16,9 +16,9 @@ protocol FeedlyRequestStreamsOperationDelegate: AnyObject { /// Create one stream request operation for one Feedly collection. /// This is the start of the process of refreshing the entire contents of a Folder. final class FeedlyRequestStreamsOperation: FeedlyOperation { - + weak var queueDelegate: FeedlyRequestStreamsOperationDelegate? - + let collectionsProvider: FeedlyCollectionProviding let service: FeedlyGetStreamContentsService let account: Account @@ -32,16 +32,16 @@ final class FeedlyRequestStreamsOperation: FeedlyOperation { self.newerThan = newerThan self.unreadOnly = unreadOnly } - + override func run() { defer { didFinish() } - + assert(queueDelegate != nil, "This is not particularly useful unless the `queueDelegate` is non-nil.") - + // TODO: Prioritise the must read collection/category before others so the most important content for the user loads first. - + for collection in collectionsProvider.collections { let resource = FeedlyCategoryResourceId(id: collection.id) let operation = FeedlyGetStreamContentsOperation( @@ -53,7 +53,7 @@ final class FeedlyRequestStreamsOperation: FeedlyOperation { ) queueDelegate?.feedlyRequestStreamsOperation(self, enqueue: operation) } - + Feedly.logger.info("Feedly: Requested \(self.collectionsProvider.collections.count) collection streams") } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySearchOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySearchOperation.swift index 5ef9bdc2c..80b022960 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySearchOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySearchOperation.swift @@ -30,7 +30,7 @@ final class FeedlySearchOperation: FeedlyOperation { self.locale = locale self.searchService = service } - + override func run() { searchService.getFeeds(for: query, count: 1, locale: locale.identifier) { result in switch result { @@ -38,7 +38,7 @@ final class FeedlySearchOperation: FeedlyOperation { assert(Thread.isMainThread) self.searchDelegate?.feedlySearchOperation(self, didGet: response) self.didFinish() - + case .failure(let error): self.didFinish(with: error) } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift index 983631d2c..a0b9078d0 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift @@ -22,7 +22,7 @@ final class FeedlySendArticleStatusesOperation: FeedlyOperation { self.database = database self.service = service } - + override func run() { Feedly.logger.info("Feedly: Sending article statuses") @@ -31,7 +31,7 @@ final class FeedlySendArticleStatusesOperation: FeedlyOperation { self.didFinish() return } - + switch result { case .success(let syncStatuses): self.processStatuses(syncStatuses) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift index a066c43a1..ea8b2364d 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift @@ -18,9 +18,9 @@ final class FeedlySyncAllOperation: FeedlyOperation { private let operationQueue = MainThreadOperationQueue() let syncUUID: UUID - + var syncCompletionHandler: ((Result) -> ())? - + /// These requests to Feedly determine which articles to download: /// 1. The set of all article ids we might need or show. /// 2. The set of all unread article ids we might need or show (a subset of 1). @@ -36,49 +36,49 @@ final class FeedlySyncAllOperation: FeedlyOperation { init(account: Account, feedlyUserId: String, lastSuccessfulFetchStartDate: Date?, markArticlesService: FeedlyMarkArticlesService, getUnreadService: FeedlyGetStreamIdsService, getCollectionsService: FeedlyGetCollectionsService, getStreamContentsService: FeedlyGetStreamContentsService, getStarredService: FeedlyGetStreamIdsService, getStreamIdsService: FeedlyGetStreamIdsService, getEntriesService: FeedlyGetEntriesService, database: SyncDatabase, downloadProgress: DownloadProgress) { self.syncUUID = UUID() self.operationQueue.suspend() - + super.init() - + self.downloadProgress = downloadProgress - + // Send any read/unread/starred article statuses to Feedly before anything else. let sendArticleStatuses = FeedlySendArticleStatusesOperation(database: database, service: markArticlesService) sendArticleStatuses.delegate = self sendArticleStatuses.downloadProgress = downloadProgress self.operationQueue.add(sendArticleStatuses) - + // Get all the Collections the user has. let getCollections = FeedlyGetCollectionsOperation(service: getCollectionsService) getCollections.delegate = self getCollections.downloadProgress = downloadProgress getCollections.addDependency(sendArticleStatuses) self.operationQueue.add(getCollections) - + // Ensure a folder exists for each Collection, removing Folders without a corresponding Collection. let mirrorCollectionsAsFolders = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: getCollections) mirrorCollectionsAsFolders.delegate = self mirrorCollectionsAsFolders.addDependency(getCollections) self.operationQueue.add(mirrorCollectionsAsFolders) - + // Ensure feeds are created and grouped by their folders. let createFeedsOperation = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: mirrorCollectionsAsFolders) createFeedsOperation.delegate = self createFeedsOperation.addDependency(mirrorCollectionsAsFolders) self.operationQueue.add(createFeedsOperation) - + let getAllArticleIds = FeedlyIngestStreamArticleIdsOperation(account: account, userId: feedlyUserId, service: getStreamIdsService) getAllArticleIds.delegate = self getAllArticleIds.downloadProgress = downloadProgress getAllArticleIds.addDependency(createFeedsOperation) self.operationQueue.add(getAllArticleIds) - + // Get each page of unread article ids in the global.all stream for the last 31 days (nil = Feedly API default). let getUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: feedlyUserId, service: getUnreadService, database: database, newerThan: nil) getUnread.delegate = self getUnread.addDependency(getAllArticleIds) getUnread.downloadProgress = downloadProgress self.operationQueue.add(getUnread) - + // Get each page of the article ids which have been update since the last successful fetch start date. // If the date is nil, this operation provides an empty set (everything is new, nothing is updated). let getUpdated = FeedlyGetUpdatedArticleIdsOperation(account: account, userId: feedlyUserId, service: getStreamIdsService, newerThan: lastSuccessfulFetchStartDate) @@ -86,14 +86,14 @@ final class FeedlySyncAllOperation: FeedlyOperation { getUpdated.downloadProgress = downloadProgress getUpdated.addDependency(createFeedsOperation) self.operationQueue.add(getUpdated) - + // Get each page of the article ids for starred articles. let getStarred = FeedlyIngestStarredArticleIdsOperation(account: account, userId: feedlyUserId, service: getStarredService, database: database, newerThan: nil) getStarred.delegate = self getStarred.downloadProgress = downloadProgress getStarred.addDependency(createFeedsOperation) self.operationQueue.add(getStarred) - + // Now all the possible article ids we need have a status, fetch the article ids for missing articles. let getMissingIds = FeedlyFetchIdsForMissingArticlesOperation(account: account) getMissingIds.delegate = self @@ -103,7 +103,7 @@ final class FeedlySyncAllOperation: FeedlyOperation { getMissingIds.addDependency(getStarred) getMissingIds.addDependency(getUpdated) self.operationQueue.add(getMissingIds) - + // Download all the missing and updated articles let downloadMissingArticles = FeedlyDownloadArticlesOperation( account: account, @@ -116,7 +116,7 @@ final class FeedlySyncAllOperation: FeedlyOperation { downloadMissingArticles.addDependency(getMissingIds) downloadMissingArticles.addDependency(getUpdated) self.operationQueue.add(downloadMissingArticles) - + // Once this operation's dependencies, their dependencies etc finish, we can finish. let finishOperation = FeedlyCheckpointOperation() finishOperation.checkpointDelegate = self @@ -124,11 +124,11 @@ final class FeedlySyncAllOperation: FeedlyOperation { finishOperation.addDependency(downloadMissingArticles) self.operationQueue.add(finishOperation) } - + convenience init(account: Account, feedlyUserId: String, caller: FeedlyAPICaller, database: SyncDatabase, lastSuccessfulFetchStartDate: Date?, downloadProgress: DownloadProgress) { self.init(account: account, feedlyUserId: feedlyUserId, lastSuccessfulFetchStartDate: lastSuccessfulFetchStartDate, markArticlesService: caller, getUnreadService: caller, getCollectionsService: caller, getStreamContentsService: caller, getStarredService: caller, getStreamIdsService: caller, getEntriesService: caller, database: database, downloadProgress: downloadProgress) } - + override func run() { Feedly.logger.info("Feedly: Starting sync \(self.syncUUID.uuidString, privacy: .public)") operationQueue.resume() @@ -143,29 +143,29 @@ final class FeedlySyncAllOperation: FeedlyOperation { } extension FeedlySyncAllOperation: FeedlyCheckpointOperationDelegate { - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { assert(Thread.isMainThread) Feedly.logger.info("Feedly: Sync finished \(self.syncUUID.uuidString, privacy: .public)") syncCompletionHandler?(.success(())) syncCompletionHandler = nil - + didFinish() } } extension FeedlySyncAllOperation: FeedlyOperationDelegate { - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { assert(Thread.isMainThread) - + // Having this log is useful for debugging missing required JSON keys in the response from Feedly, for example. Feedly.logger.error("Feedly: Sync \(self.syncUUID.uuidString, privacy: .public) failed with error: \(error.localizedDescription)") syncCompletionHandler?(.failure(error)) syncCompletionHandler = nil - + cancel() } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncStreamContentsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncStreamContentsOperation.swift index 71520778e..773190db5 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncStreamContentsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncStreamContentsOperation.swift @@ -22,7 +22,7 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD private let newerThan: Date? private let isPagingEnabled: Bool private let finishOperation: FeedlyCheckpointOperation - + init(account: Account, resource: FeedlyResourceId, service: FeedlyGetStreamContentsService, isPagingEnabled: Bool, newerThan: Date?) { self.account = account self.resource = resource @@ -31,19 +31,19 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD self.operationQueue.suspend() self.newerThan = newerThan self.finishOperation = FeedlyCheckpointOperation() - + super.init() - + self.operationQueue.add(self.finishOperation) self.finishOperation.checkpointDelegate = self enqueueOperations(for: nil) } - + convenience init(account: Account, credentials: Credentials, service: FeedlyGetStreamContentsService, newerThan: Date?) { let all = FeedlyCategoryResourceId.Global.all(for: credentials.username) self.init(account: account, resource: all, service: service, isPagingEnabled: true, newerThan: newerThan) } - + override func run() { operationQueue.resume() } @@ -59,7 +59,7 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD let operations = pageOperations(for: continuation) operationQueue.addOperations(operations) } - + func pageOperations(for continuation: String?) -> [MainThreadOperation] { let getPage = FeedlyGetStreamContentsOperation(account: account, resource: resource, @@ -67,11 +67,11 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD continuation: continuation, newerThan: newerThan) - + let organiseByFeed = FeedlyOrganiseParsedItemsByFeedOperation(account: account, parsedItemProvider: getPage) - + let updateAccount = FeedlyUpdateAccountFeedsWithItemsOperation(account: account, organisedItemsProvider: organiseByFeed) - + getPage.delegate = self getPage.streamDelegate = self @@ -85,7 +85,7 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD return [getPage, organiseByFeed, updateAccount] } - + func feedlyGetStreamContentsOperation(_ operation: FeedlyGetStreamContentsOperation, didGetContentsOf stream: FeedlyStream) { guard !isCanceled else { Feedly.logger.info("Feedly: Canceled requesting page for \(self.resource.id)") @@ -98,15 +98,15 @@ final class FeedlySyncStreamContentsOperation: FeedlyOperation, FeedlyOperationD Feedly.logger.info("Feedly: Reached end of stream for \(stream.id)") return } - + enqueueOperations(for: continuation) } - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { Feedly.logger.info("Feedly: Finished ingesting items from \(self.resource.id)") didFinish() } - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { operationQueue.cancelAllOperations() didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyUpdateAccountFeedsWithItemsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyUpdateAccountFeedsWithItemsOperation.swift index eb553e741..c40bd9a64 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyUpdateAccountFeedsWithItemsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyUpdateAccountFeedsWithItemsOperation.swift @@ -20,10 +20,10 @@ final class FeedlyUpdateAccountFeedsWithItemsOperation: FeedlyOperation { self.account = account self.organisedItemsProvider = organisedItemsProvider } - + override func run() { let feedIDsAndItems = organisedItemsProvider.parsedItemsKeyedByFeedId - + account.update(feedIDsAndItems: feedIDsAndItems, defaultRead: true) { databaseError in if let error = databaseError { self.didFinish(with: error) diff --git a/Modules/Account/Sources/Account/Feedly/Services/FeedlyMarkArticlesService.swift b/Modules/Account/Sources/Account/Feedly/Services/FeedlyMarkArticlesService.swift index 60a9263c2..6cd574479 100644 --- a/Modules/Account/Sources/Account/Feedly/Services/FeedlyMarkArticlesService.swift +++ b/Modules/Account/Sources/Account/Feedly/Services/FeedlyMarkArticlesService.swift @@ -13,7 +13,7 @@ enum FeedlyMarkAction: String { case unread case saved case unsaved - + /// These values are paired with the "action" key in POST requests to the markers API. /// See for example: https://developer.feedly.com/v3/markers/#mark-one-or-multiple-articles-as-read var actionValue: String { diff --git a/Modules/Account/Sources/Account/Folder.swift b/Modules/Account/Sources/Account/Folder.swift index f088e3a26..080c53ac3 100644 --- a/Modules/Account/Sources/Account/Folder.swift +++ b/Modules/Account/Sources/Account/Folder.swift @@ -15,7 +15,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { public var defaultReadFilterType: ReadFilterType { return .read } - + public var containerID: ContainerIdentifier? { guard let accountID = account?.accountID else { assertionFailure("Expected feed.account, but got nil.") @@ -23,7 +23,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { } return ContainerIdentifier.folder(accountID, nameForDisplay) } - + public var sidebarItemID: SidebarItemIdentifier? { guard let accountID = account?.accountID else { assertionFailure("Expected feed.account, but got nil.") @@ -35,13 +35,13 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { public weak var account: Account? public var topLevelFeeds: Set = Set() public var folders: Set? = nil // subfolders are not supported, so this is always nil - + public var name: String? { didSet { postDisplayNameDidChangeNotification() } } - + static let untitledName = NSLocalizedString("Untitled ƒ", comment: "Folder name") public let folderID: Int // not saved: per-run only public var externalID: String? = nil @@ -52,7 +52,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { public var nameForDisplay: String { return name ?? Folder.untitledName } - + // MARK: - UnreadCountProvider public var unreadCount = 0 { @@ -69,7 +69,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { guard let account = account else { return } account.renameFolder(self, to: name, completion: completion) } - + // MARK: - Init init(account: Account, name: String?) { @@ -117,7 +117,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { topLevelFeeds.insert(feed) postChildrenDidChangeNotification() } - + public func addFeeds(_ feeds: Set) { guard !feeds.isEmpty else { return @@ -125,12 +125,12 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { topLevelFeeds.formUnion(feeds) postChildrenDidChangeNotification() } - + public func removeFeed(_ feed: Feed) { topLevelFeeds.remove(feed) postChildrenDidChangeNotification() } - + public func removeFeeds(_ feeds: Set) { guard !feeds.isEmpty else { return @@ -174,7 +174,7 @@ private extension Folder { extension Folder: OPMLRepresentable { public func OPMLString(indentLevel: Int, allowCustomAttributes: Bool) -> String { - + let attrExternalID: String = { if allowCustomAttributes, let externalID = externalID { return " nnw_externalID=\"\(externalID.escapingSpecialXMLCharacters)\"" @@ -182,7 +182,7 @@ extension Folder: OPMLRepresentable { return "" } }() - + let escapedTitle = nameForDisplay.escapingSpecialXMLCharacters var s = "\n" s = s.prepending(tabCount: indentLevel) @@ -209,11 +209,11 @@ extension Folder: OPMLRepresentable { // MARK: Set extension Set where Element == Folder { - + func sorted() -> Array { return sorted(by: { (folder1, folder2) -> Bool in return folder1.nameForDisplay.localizedStandardCompare(folder2.nameForDisplay) == .orderedAscending }) } - + } diff --git a/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift b/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift index 4ef7f7b5d..1a9bb4853 100644 --- a/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift +++ b/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift @@ -19,7 +19,7 @@ struct InitialFeedDownloader { completion(nil, nil, response, error) return } - + let parserData = ParserData(url: url.absoluteString, data: data) FeedParser.parse(parserData) { (parsedFeed, error) in completion(parsedFeed, data, response, error) diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift index fbbb20728..f9bcbc391 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift @@ -21,14 +21,14 @@ public enum LocalAccountDelegateError: String, Error { final class LocalAccountDelegate: AccountDelegate { weak var account: Account? - + lazy var refreshProgress: DownloadProgress = { refresher.downloadProgress }() let behaviors: AccountBehaviors = [] let isOPMLImportInProgress = false - + let server: String? = nil var credentials: Credentials? var accountMetadata: AccountMetadata? @@ -42,7 +42,7 @@ final class LocalAccountDelegate: AccountDelegate { func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) { completion() } - + func refreshAll(for account: Account, completion: @escaping (Result) -> Void) { guard refreshProgress.isComplete, !Platform.isRunningUnitTests else { completion(.success(())) @@ -57,7 +57,7 @@ final class LocalAccountDelegate: AccountDelegate { refresher.refreshFeeds(feeds) { group.leave() } - + group.notify(queue: DispatchQueue.main) { account.metadata.lastArticleFetchEndTime = Date() completion(.success(())) @@ -67,11 +67,11 @@ final class LocalAccountDelegate: AccountDelegate { func syncArticleStatus(for account: Account, completion: ((Result) -> Void)? = nil) { completion?(.success(())) } - + func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { completion(.success(())) } - + func refreshArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { completion(.success(())) } @@ -90,17 +90,17 @@ final class LocalAccountDelegate: AccountDelegate { completion(.success(())) return } - + let parserData = ParserData(url: opmlFile.absoluteString, data: opmlData) var opmlDocument: RSOPMLDocument? - + do { opmlDocument = try RSOPMLParser.parseOPML(with: parserData) } catch { completion(.failure(error)) return } - + guard let loadDocument = opmlDocument else { completion(.success(())) return @@ -113,16 +113,16 @@ final class LocalAccountDelegate: AccountDelegate { BatchUpdate.shared.perform { account.loadOPMLItems(children) } - + completion(.success(())) } - + func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result) -> Void) { guard let url = URL(string: urlString) else { completion(.failure(LocalAccountDelegateError.invalidParameter)) return } - + createFeed(for: account, url: url, editedName: name, container: container, completion: completion) } @@ -135,23 +135,23 @@ final class LocalAccountDelegate: AccountDelegate { container.removeFeed(feed) completion(.success(())) } - + func moveFeed(for account: Account, with feed: Feed, from: Container, to: Container, completion: @escaping (Result) -> Void) { from.removeFeed(feed) to.addFeed(feed) completion(.success(())) } - + func addFeed(for account: Account, with feed: Feed, to container: Container, completion: @escaping (Result) -> Void) { container.addFeed(feed) completion(.success(())) } - + func restoreFeed(for account: Account, feed: Feed, container: Container, completion: @escaping (Result) -> Void) { container.addFeed(feed) completion(.success(())) } - + func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) { if let folder = account.ensureFolder(with: name) { completion(.success(folder)) @@ -159,17 +159,17 @@ final class LocalAccountDelegate: AccountDelegate { completion(.failure(FeedbinAccountDelegateError.invalidParameter)) } } - + func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) { folder.name = name completion(.success(())) } - + func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result) -> Void) { account.removeFolder(folder) completion(.success(())) } - + func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result) -> Void) { account.addFolder(folder) completion(.success(())) @@ -188,7 +188,7 @@ final class LocalAccountDelegate: AccountDelegate { func accountDidInitialize(_ account: Account) { self.account = account } - + func accountWillBeDeleted(_ account: Account) { } @@ -205,20 +205,20 @@ final class LocalAccountDelegate: AccountDelegate { func suspendDatabase() { // Nothing to do } - + func resume() { refresher.resume() } } extension LocalAccountDelegate: LocalAccountRefresherDelegate { - + func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges) { } } private extension LocalAccountDelegate { - + func createFeed(for account: Account, url: URL, editedName: String?, container: Container, completion: @escaping (Result) -> Void) { // We need to use a batch update here because we need to assign add the feed to the @@ -226,7 +226,7 @@ private extension LocalAccountDelegate { // with an Untitled name if we don't delay it being added to the sidebar. BatchUpdate.shared.start() FeedFinder.find(url: url) { result in - + switch result { case .success(let feedSpecifiers): guard let bestFeedSpecifier = FeedSpecifier.bestFeed(in: feedSpecifiers), @@ -235,13 +235,13 @@ private extension LocalAccountDelegate { completion(.failure(AccountError.createErrorNotFound)) return } - + if account.hasFeed(withURL: bestFeedSpecifier.urlString) { BatchUpdate.shared.end() completion(.failure(AccountError.createErrorAlreadySubscribed)) return } - + InitialFeedDownloader.download(url) { parsedFeed, _, response, _ in if let parsedFeed { @@ -253,7 +253,7 @@ private extension LocalAccountDelegate { let conditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse) { feed.conditionalGetInfo = conditionalGetInfo } - + feed.editedName = editedName container.addFeed(feed) @@ -266,7 +266,7 @@ private extension LocalAccountDelegate { completion(.failure(AccountError.createErrorNotFound)) } } - + case .failure: BatchUpdate.shared.end() completion(.failure(AccountError.createErrorNotFound)) diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift index b72dc53c1..009560ef8 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift @@ -175,7 +175,7 @@ extension LocalAccountRefresher: DownloadSessionDelegate { } return true } - + func downloadSessionDidComplete(_ downloadSession: DownloadSession) { Task { @MainActor in @@ -277,7 +277,7 @@ private extension LocalAccountRefresher { // MARK: - Utility private extension Data { - + func isDefinitelyNotFeed() -> Bool { // We only detect a few image types for now. This should get fleshed-out at some later date. return self.isImage diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index 0c75b13e9..69b355a36 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -16,7 +16,7 @@ import SyncDatabase import os.log extension NewsBlurAccountDelegate { - + func refreshFeeds(for account: Account, completion: @escaping (Result) -> Void) { Self.logger.info("NewsBlur: Refreshing feeds") @@ -177,7 +177,7 @@ extension NewsBlurAccountDelegate { } } } - + // Handle the account level feeds. If there isn't the special folder, that means all the feeds are // in folders and we need to remove them all from the account level. if let folderRelationships = newsBlurFolderDict[" "] { @@ -192,7 +192,7 @@ extension NewsBlurAccountDelegate { account.removeFeed(feed) } } - + } func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) { @@ -334,7 +334,7 @@ extension NewsBlurAccountDelegate { } let group = DispatchGroup() - + // Mark articles as unread let deltaUnreadArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs) group.enter() @@ -348,7 +348,7 @@ extension NewsBlurAccountDelegate { account.markAsRead(deltaReadArticleIDs) { _ in group.leave() } - + group.notify(queue: DispatchQueue.main) { completion() } @@ -382,7 +382,7 @@ extension NewsBlurAccountDelegate { } let group = DispatchGroup() - + // Mark articles as starred let deltaStarredArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentStarredArticleIDs) group.enter() @@ -474,7 +474,7 @@ extension NewsBlurAccountDelegate { completion(.success(())) return } - + self.downloadFeed(account: account, feed: feed, page: page + 1, completion: completion) } diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift index c6c7c48e1..4f4433282 100644 --- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift +++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift @@ -61,11 +61,11 @@ final class NewsBlurAccountDelegate: AccountDelegate { func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) { completion() } - + func refreshAll(for account: Account, completion: @escaping (Result) -> ()) { refreshProgress.reset() - + self.refreshProgress.addToNumberOfTasksAndRemaining(4) refreshFeeds(for: account) { result in @@ -134,7 +134,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { } } } - + func sendArticleStatus(for account: Account, completion: @escaping (Result) -> ()) { Self.logger.info("NewsBlur: Sending story statuses") @@ -513,7 +513,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { case .success: from.removeFeed(feed) to.addFeed(feed) - + completion(.success(())) case .failure(let error): completion(.failure(error)) diff --git a/Modules/Account/Sources/Account/OPMLFile.swift b/Modules/Account/Sources/Account/OPMLFile.swift index 07ff9c90d..0c73b2869 100644 --- a/Modules/Account/Sources/Account/OPMLFile.swift +++ b/Modules/Account/Sources/Account/OPMLFile.swift @@ -27,32 +27,32 @@ final class OPMLFile { self.fileURL = URL(fileURLWithPath: filename) self.account = account } - + func markAsDirty() { isDirty = true } - + func load() { guard let fileData = opmlFileData(), let opmlItems = parsedOPMLItems(fileData: fileData) else { return } - + BatchUpdate.shared.perform { account.loadOPMLItems(opmlItems) } } - + func save() { guard !account.isDeleted else { return } let opmlDocumentString = opmlDocument() - + do { try opmlDocumentString.write(to: fileURL, atomically: true, encoding: .utf8) } catch let error as NSError { Self.logger.error("OPML save to disk failed: \(error.localizedDescription)") } } - + } private extension OPMLFile { @@ -70,7 +70,7 @@ private extension OPMLFile { func opmlFileData() -> Data? { var fileData: Data? = nil - + do { fileData = try Data(contentsOf: fileURL) } catch { @@ -79,7 +79,7 @@ private extension OPMLFile { return fileData } - + func parsedOPMLItems(fileData: Data) -> [RSOPMLItem]? { let parserData = ParserData(url: fileURL.absoluteString, data: fileData) var opmlDocument: RSOPMLDocument? @@ -90,10 +90,10 @@ private extension OPMLFile { Self.logger.error("OPML import failed: \(error.localizedDescription)") return nil } - + return opmlDocument?.children } - + func opmlDocument() -> String { let escapedTitle = account.nameForDisplay.escapingSpecialXMLCharacters let openingText = diff --git a/Modules/Account/Sources/Account/OPMLNormalizer.swift b/Modules/Account/Sources/Account/OPMLNormalizer.swift index 77f6ee54b..2830ca857 100644 --- a/Modules/Account/Sources/Account/OPMLNormalizer.swift +++ b/Modules/Account/Sources/Account/OPMLNormalizer.swift @@ -10,15 +10,15 @@ import Foundation import RSParser final class OPMLNormalizer { - + var normalizedOPMLItems = [RSOPMLItem]() - + static func normalize(_ items: [RSOPMLItem]) -> [RSOPMLItem] { let opmlNormalizer = OPMLNormalizer() opmlNormalizer.normalize(items) return opmlNormalizer.normalizedOPMLItems } - + private func normalize(_ items: [RSOPMLItem], parentFolder: RSOPMLItem? = nil) { var feedsToAdd = [RSOPMLItem]() @@ -60,7 +60,7 @@ final class OPMLNormalizer { normalizedOPMLItems.append(feed) } } - + } - + } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index c47905ae7..a9319059e 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -19,7 +19,7 @@ public enum ReaderAPIAccountDelegateError: LocalizedError { case invalidParameter case invalidResponse case urlNotFound - + public var errorDescription: String? { switch self { case .unknown: @@ -35,11 +35,11 @@ public enum ReaderAPIAccountDelegateError: LocalizedError { } final class ReaderAPIAccountDelegate: AccountDelegate { - + private let variant: ReaderAPIVariant - + private let database: SyncDatabase - + private let caller: ReaderAPICaller private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ReaderAPI") @@ -56,15 +56,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate { return caller.server } } - + var isOPMLImportInProgress = false - + var credentials: Credentials? { didSet { caller.credentials = credentials } } - + weak var accountMetadata: AccountMetadata? { didSet { caller.accountMetadata = accountMetadata @@ -72,11 +72,11 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } var refreshProgress = DownloadProgress(numberOfTasks: 0) - + init(dataFolder: String, transport: Transport?, variant: ReaderAPIVariant) { let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") database = SyncDatabase(databaseFilePath: databaseFilePath) - + if transport != nil { caller = ReaderAPICaller(transport: transport!) } else { @@ -88,27 +88,27 @@ final class ReaderAPIAccountDelegate: AccountDelegate { sessionConfiguration.httpMaximumConnectionsPerHost = 1 sessionConfiguration.httpCookieStorage = nil sessionConfiguration.urlCache = nil - + if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } - + caller = ReaderAPICaller(transport: URLSession(configuration: sessionConfiguration)) } - + caller.variant = variant self.variant = variant } - + func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) { completion() } - + func refreshAll(for account: Account, completion: @escaping (Result) -> Void) { refreshProgress.reset() refreshProgress.addToNumberOfTasksAndRemaining(6) - + refreshAccount(account) { result in switch result { case .success(): @@ -139,11 +139,11 @@ final class ReaderAPIAccountDelegate: AccountDelegate { case .failure(let error): DispatchQueue.main.async { self.refreshProgress.reset() - + let wrappedError = AccountError.wrappedError(error: error, account: account) if wrappedError.isCredentialsError, let basicCredentials = try? account.retrieveCredentials(type: .readerBasic), let endpoint = account.endpointURL { self.caller.credentials = basicCredentials - + self.caller.validateCredentials(endpoint: endpoint) { result in switch result { case .success(let apiCredentials): @@ -164,15 +164,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + } else { completion(.failure(wrappedError)) } } } - + } - + } func syncArticleStatus(for account: Account, completion: ((Result) -> Void)? = nil) { @@ -180,7 +180,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { completion?(.success(())) return } - + sendArticleStatus(for: account) { result in switch result { case .success: @@ -197,7 +197,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { Self.logger.info("ReaderAPI: Sending article statuses") @@ -245,7 +245,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func refreshArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { Self.logger.info("ReaderAPI: Refreshing article statuses") @@ -264,9 +264,9 @@ final class ReaderAPIAccountDelegate: AccountDelegate { Self.logger.error("ReaderAPI: Retrieving unread entries failed: \(error.localizedDescription)") group.leave() } - + } - + group.enter() caller.retrieveItemIDs(type: .starred) { result in switch result { @@ -281,7 +281,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } - + group.notify(queue: DispatchQueue.main) { Self.logger.info("ReaderAPI: Finished refreshing article statuses") if errorOccurred { @@ -291,10 +291,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func importOPML(for account:Account, opmlFile: URL, completion: @escaping (Result) -> Void) { } - + func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) { if let folder = account.ensureFolder(with: name) { completion(.success(folder)) @@ -302,9 +302,9 @@ final class ReaderAPIAccountDelegate: AccountDelegate { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) } } - + func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) { - + refreshProgress.addToNumberOfTasksAndRemaining(1) caller.renameTag(oldName: folder.name ?? "", newName: name) { result in self.refreshProgress.completeTask() @@ -322,17 +322,17 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + } func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result) -> Void) { let group = DispatchGroup() - + for feed in folder.topLevelFeeds { - + if feed.folderRelationship?.count ?? 0 > 1 { - + if let feedExternalID = feed.externalID { group.enter() refreshProgress.addToNumberOfTasksAndRemaining(1) @@ -349,9 +349,9 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + } else { - + if let subscriptionID = feed.externalID { group.enter() refreshProgress.addToNumberOfTasksAndRemaining(1) @@ -370,7 +370,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + group.notify(queue: DispatchQueue.main) { if self.variant == .theOldReader { account.removeFolder(folder) @@ -388,15 +388,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func createFeed(for account: Account, url: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result) -> Void) { guard let url = URL(string: url) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + refreshProgress.addToNumberOfTasksAndRemaining(2) - + FeedFinder.find(url: url) { result in self.refreshProgress.completeTask() @@ -427,25 +427,25 @@ final class ReaderAPIAccountDelegate: AccountDelegate { completion(.failure(wrappedError)) } } - + } case .failure: self.refreshProgress.reset() completion(.failure(AccountError.createErrorNotFound)) } - + } - + } - + func renameFeed(for account: Account, with feed: Feed, to name: String, completion: @escaping (Result) -> Void) { - + // This error should never happen guard let subscriptionID = feed.externalID else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + refreshProgress.addToNumberOfTasksAndRemaining(1) caller.renameSubscription(subscriptionID: subscriptionID, newName: name) { result in self.refreshProgress.completeTask() @@ -462,15 +462,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + } - + func removeFeed(for account: Account, with feed: Feed, from container: Container, completion: @escaping (Result) -> Void) { guard let subscriptionID = feed.externalID else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + refreshProgress.addToNumberOfTasksAndRemaining(1) caller.deleteSubscription(subscriptionID: subscriptionID) { result in self.refreshProgress.completeTask() @@ -494,7 +494,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func moveFeed(for account: Account, with feed: Feed, from: Container, to: Container, completion: @escaping (Result) -> Void) { if from is Account { addFeed(for: account, with: feed, to: to, completion: completion) @@ -507,7 +507,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + refreshProgress.addToNumberOfTasksAndRemaining(1) caller.moveSubscription(subscriptionID: subscriptionId, fromTag: fromTag, toTag: toTag) { result in self.refreshProgress.completeTask() @@ -522,7 +522,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func addFeed(for account: Account, with feed: Feed, to container: Container, completion: @escaping (Result) -> Void) { if let folder = container as? Folder, let feedExternalID = feed.externalID { refreshProgress.addToNumberOfTasksAndRemaining(1) @@ -552,7 +552,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + func restoreFeed(for account: Account, feed: Feed, container: Container, completion: @escaping (Result) -> Void) { if let existingFeed = account.existingFeed(withURL: feed.url) { @@ -574,17 +574,17 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + } - + func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result) -> Void) { let group = DispatchGroup() - + for feed in folder.topLevelFeeds { - + folder.topLevelFeeds.remove(feed) - + group.enter() restoreFeed(for: account, feed: feed, container: folder) { result in group.leave() @@ -596,7 +596,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } } - + group.notify(queue: DispatchQueue.main) { account.addFolder(folder) completion(.success(())) @@ -628,7 +628,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { func accountDidInitialize(_ account: Account) { credentials = try? account.retrieveCredentials(type: .readerAPIKey) } - + func accountWillBeDeleted(_ account: Account) { } @@ -648,12 +648,12 @@ final class ReaderAPIAccountDelegate: AccountDelegate { func suspendNetwork() { caller.cancelAll() } - + /// Suspend the SQLLite databases func suspendDatabase() { database.suspend() } - + /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { database.resume() @@ -663,7 +663,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { // MARK: Private private extension ReaderAPIAccountDelegate { - + func refreshAccount(_ account: Account, completion: @escaping (Result) -> Void) { caller.retrieveTags { result in switch result { @@ -692,14 +692,14 @@ private extension ReaderAPIAccountDelegate { func syncFolders(_ account: Account, _ tags: [ReaderAPITag]?) { guard let tags = tags else { return } assert(Thread.isMainThread) - + let folderTags: [ReaderAPITag] if variant == .inoreader { folderTags = tags.filter{ $0.type == "folder" } } else { folderTags = tags.filter{ $0.tagID.contains("/label/") } } - + guard !folderTags.isEmpty else { return } Self.logger.info("ReaderAPI: Syncing folders with \(folderTags.count) tags") @@ -718,7 +718,7 @@ private extension ReaderAPIAccountDelegate { } } } - + let folderExternalIDs: [String] = { if let folders = account.folders { return folders.compactMap { $0.externalID } @@ -734,18 +734,18 @@ private extension ReaderAPIAccountDelegate { folder?.externalID = tag.tagID } } - + } - + func syncFeeds(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) { - + guard let subscriptions = subscriptions else { return } assert(Thread.isMainThread) Self.logger.info("ReaderAPI: Syncing feeds with \(subscriptions.count) subscriptions") let subFeedIds = subscriptions.map { $0.feedID } - + // Remove any feeds that are no longer in the subscriptions if let folders = account.folders { for folder in folders { @@ -756,17 +756,17 @@ private extension ReaderAPIAccountDelegate { } } } - + for feed in account.topLevelFeeds { if !subFeedIds.contains(feed.feedID) { account.clearFeedMetadata(feed) account.removeFeed(feed) } } - + // Add any feeds we don't have and update any we do subscriptions.forEach { subscription in - + if let feed = account.existingFeed(withFeedID: subscription.feedID) { feed.name = subscription.name feed.editedName = nil @@ -776,9 +776,9 @@ private extension ReaderAPIAccountDelegate { feed.externalID = subscription.feedID account.addFeed(feed) } - + } - + } func syncFeedFolderRelationship(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) { @@ -790,7 +790,7 @@ private extension ReaderAPIAccountDelegate { let folderDict = externalIDToFolderDictionary(with: account.folders) let taggingsDict = subscriptions.reduce([String: [ReaderAPISubscription]]()) { (dict, subscription) in var taggedFeeds = dict - + subscription.categories.forEach({ (category) in if var taggedFeed = taggedFeeds[category.categoryId] { taggedFeed.append(subscription) @@ -799,15 +799,15 @@ private extension ReaderAPIAccountDelegate { taggedFeeds[category.categoryId] = [subscription] } }) - + return taggedFeeds } - + // Sync the folders for (folderExternalID, groupedTaggings) in taggingsDict { guard let folder = folderDict[folderExternalID] else { return } let taggingFeedIDs = groupedTaggings.map { $0.feedID } - + // Move any feeds not in the folder to the account for feed in folder.topLevelFeeds { if !taggingFeedIDs.contains(feed.feedID) { @@ -816,10 +816,10 @@ private extension ReaderAPIAccountDelegate { account.addFeed(feed) } } - + // Add any feeds not in the folder let folderFeedIds = folder.topLevelFeeds.map { $0.feedID } - + for subscription in groupedTaggings { let taggingFeedID = subscription.feedID if !folderFeedIds.contains(taggingFeedID) { @@ -830,11 +830,11 @@ private extension ReaderAPIAccountDelegate { folder.addFeed(feed) } } - + } - + let taggedFeedIDs = Set(subscriptions.filter({ !$0.categories.isEmpty }).map { String($0.feedID) }) - + // Remove all feeds from the account container that have a tag for feed in account.topLevelFeeds { if taggedFeedIDs.contains(feed.feedID) { @@ -842,20 +842,20 @@ private extension ReaderAPIAccountDelegate { } } } - + func externalIDToFolderDictionary(with folders: Set?) -> [String: Folder] { guard let folders = folders else { return [String: Folder]() } var d = [String: Folder]() - + for folder in folders { if let externalID = folder.externalID, d[externalID] == nil { d[externalID] = folder } } - + return d } @@ -864,13 +864,13 @@ private extension ReaderAPIAccountDelegate { completion() return } - + let group = DispatchGroup() - + let articleIDs = statuses.compactMap { $0.articleID } let articleIDGroups = articleIDs.chunked(into: 1000) for articleIDGroup in articleIDGroups { - + group.enter() apiCall(articleIDGroup) { result in switch result { @@ -883,21 +883,21 @@ private extension ReaderAPIAccountDelegate { group.leave() } } - + } - + group.notify(queue: DispatchQueue.main) { completion() } - + } - + func clearFolderRelationship(for feed: Feed, folderExternalID: String?) { guard var folderRelationship = feed.folderRelationship, let folderExternalID = folderExternalID else { return } folderRelationship[folderExternalID] = nil feed.folderRelationship = folderRelationship } - + func saveFolderRelationship(for feed: Feed, folderExternalID: String?, feedExternalID: String) { guard let folderExternalID = folderExternalID else { return } if var folderRelationship = feed.folderRelationship { @@ -907,14 +907,14 @@ private extension ReaderAPIAccountDelegate { feed.folderRelationship = [folderExternalID: feedExternalID] } } - + func createFeed( account: Account, subscription sub: ReaderAPISubscription, name: String?, container: Container, completion: @escaping (Result) -> Void) { - + DispatchQueue.main.async { - + let feed = account.createFeed(with: sub.name, url: sub.url, feedID: String(sub.feedID), homePageURL: sub.homePageURL) feed.externalID = String(sub.feedID) - + account.addFeed(feed, to: container) { result in switch result { case .success: @@ -934,14 +934,14 @@ private extension ReaderAPIAccountDelegate { completion(.failure(error)) } } - + } - + } func initialFeedDownload( account: Account, feed: Feed, completion: @escaping (Result) -> Void) { refreshProgress.addToNumberOfTasksAndRemaining(5) - + // Download the initial articles self.caller.retrieveItemIDs(type: .allForFeed, feedID: feed.feedID) { result in self.refreshProgress.completeTask() @@ -964,11 +964,11 @@ private extension ReaderAPIAccountDelegate { case .failure(let error): completion(.failure(error)) } - + } - + } - + func refreshMissingArticles(_ account: Account, completion: @escaping VoidCompletionBlock) { account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { articleIDsResult in @@ -1028,13 +1028,13 @@ private extension ReaderAPIAccountDelegate { completion() } } - + func mapEntriesToParsedItems(account: Account, entries: [ReaderAPIEntry]?) -> Set { - + guard let entries = entries else { return Set() } - + let parsedItems: [ParsedItem] = entries.compactMap { entry in guard let streamID = entry.origin.streamId else { return nil @@ -1046,7 +1046,7 @@ private extension ReaderAPIAccountDelegate { } return Set([ParsedAuthor(name: name, url: nil, avatarURL: nil, emailAddress: nil)]) } - + return ParsedItem(syncServiceID: entry.uniqueID(variant: variant), uniqueID: entry.uniqueID(variant: variant), feedURL: streamID, @@ -1066,11 +1066,11 @@ private extension ReaderAPIAccountDelegate { tags: nil, attachments: nil) } - + return Set(parsedItems) - + } - + func syncArticleReadState(account: Account, articleIDs: [String]?, completion: @escaping (() -> Void)) { guard let articleIDs = articleIDs else { completion() @@ -1081,14 +1081,14 @@ private extension ReaderAPIAccountDelegate { func process(_ pendingArticleIDs: Set) { let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs) - + account.fetchUnreadArticleIDs { articleIDsResult in guard let currentUnreadArticleIDs = try? articleIDsResult.get() else { return } let group = DispatchGroup() - + // Mark articles as unread let deltaUnreadArticleIDs = updatableReaderUnreadArticleIDs.subtracting(currentUnreadArticleIDs) group.enter() @@ -1102,13 +1102,13 @@ private extension ReaderAPIAccountDelegate { account.markAsRead(deltaReadArticleIDs) { _ in group.leave() } - + group.notify(queue: DispatchQueue.main) { completion() } } } - + switch result { case .success(let pendingArticleIDs): process(pendingArticleIDs) @@ -1117,7 +1117,7 @@ private extension ReaderAPIAccountDelegate { } } } - + func syncArticleStarredState(account: Account, articleIDs: [String]?, completion: @escaping (() -> Void)) { guard let articleIDs = articleIDs else { completion() @@ -1135,7 +1135,7 @@ private extension ReaderAPIAccountDelegate { } let group = DispatchGroup() - + // Mark articles as starred let deltaStarredArticleIDs = updatableReaderUnreadArticleIDs.subtracting(currentStarredArticleIDs) group.enter() @@ -1155,7 +1155,7 @@ private extension ReaderAPIAccountDelegate { } } } - + switch result { case .success(let pendingArticleIDs): process(pendingArticleIDs) diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift index ee6214907..f7d6ef538 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift @@ -16,23 +16,23 @@ enum CreateReaderAPISubscriptionResult { } final class ReaderAPICaller: NSObject { - + enum ItemIDType { case unread case starred case allForAccount case allForFeed } - + private enum ReaderState: String { case read = "user/-/state/com.google/read" case starred = "user/-/state/com.google/starred" } - + private enum ReaderStreams: String { case readingList = "user/-/state/com.google/reading-list" } - + private enum ReaderAPIEndpoints: String { case login = "/accounts/ClientLogin" case token = "/reader/api/0/token" @@ -46,12 +46,12 @@ final class ReaderAPICaller: NSObject { case itemIds = "/reader/api/0/stream/items/ids" case editTag = "/reader/api/0/edit-tag" } - + private var transport: Transport! private let uriComponentAllowed: CharacterSet private var accessToken: String? - + weak var accountMetadata: AccountMetadata? var variant: ReaderAPIVariant = .generic @@ -62,7 +62,7 @@ final class ReaderAPICaller: NSObject { return apiBaseURL?.host } } - + private var apiBaseURL: URL? { get { switch variant { @@ -76,17 +76,17 @@ final class ReaderAPICaller: NSObject { } } } - + init(transport: Transport) { self.transport = transport - + var urlHostAllowed = CharacterSet.urlHostAllowed urlHostAllowed.remove("+") urlHostAllowed.remove("&") uriComponentAllowed = urlHostAllowed super.init() } - + func cancelAll() { transport.cancelAll() } @@ -104,7 +104,7 @@ final class ReaderAPICaller: NSObject { completion(.failure(CredentialsError.incompleteCredentials)) return } - + var request = URLRequest(url: endpoint.appendingPathComponent(ReaderAPIEndpoints.login.rawValue), credentials: credentials) addVariantHeaders(&request) @@ -115,13 +115,13 @@ final class ReaderAPICaller: NSObject { completion(.failure(TransportError.noData)) break } - + // Convert the return data to UTF8 and then parse out the Auth token guard let rawData = String(data: resultData, encoding: .utf8) else { completion(.failure(TransportError.noData)) break } - + var authData: [String: String] = [:] rawData.split(separator: "\n").forEach({ (line: Substring) in let items = line.split(separator: "=").map{String($0)} @@ -129,15 +129,15 @@ final class ReaderAPICaller: NSObject { authData[items[0]] = items[1] } }) - + guard let authString = authData["Auth"] else { completion(.failure(CredentialsError.incompleteCredentials)) break } - + // Save Auth Token for later use self.credentials = Credentials(type: .readerAPIKey, username: credentials.username, secret: authString) - + completion(.success(self.credentials)) case .failure(let error): if let transportError = error as? TransportError, case .httpError(let code) = transportError, code == 404 { @@ -147,25 +147,25 @@ final class ReaderAPICaller: NSObject { } } } - + } - + func requestAuthorizationToken(endpoint: URL, completion: @escaping (Result) -> Void) { // If we have a token already, use it if let accessToken = accessToken { completion(.success(accessToken)) return } - + // Otherwise request one. guard let credentials = credentials else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + var request = URLRequest(url: endpoint.appendingPathComponent(ReaderAPIEndpoints.token.rawValue), credentials: credentials) addVariantHeaders(&request) - + transport.send(request: request) { result in switch result { case .success(let (_, data)): @@ -173,13 +173,13 @@ final class ReaderAPICaller: NSObject { completion(.failure(TransportError.noData)) break } - + // Convert the return data to UTF8 and then parse out the Auth token guard let accessToken = String(data: resultData, encoding: .utf8) else { completion(.failure(TransportError.noData)) break } - + self.accessToken = accessToken completion(.success(accessToken)) case .failure(let error): @@ -187,22 +187,22 @@ final class ReaderAPICaller: NSObject { } } } - - + + func retrieveTags(completion: @escaping (Result<[ReaderAPITag]?, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + var url = baseURL .appendingPathComponent(ReaderAPIEndpoints.tagList.rawValue) .appendingQueryItem(URLQueryItem(name: "output", value: "json")) - + if variant == .inoreader { url = url?.appendingQueryItem(URLQueryItem(name: "types", value: "1")) } - + guard let callURL = url else { completion(.failure(TransportError.noURL)) return @@ -219,7 +219,7 @@ final class ReaderAPICaller: NSObject { completion(.failure(error)) } } - + } func renameTag(oldName: String, newName: String, completion: @escaping (Result) -> Void) { @@ -227,7 +227,7 @@ final class ReaderAPICaller: NSObject { completion(.failure(CredentialsError.incompleteCredentials)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -235,16 +235,16 @@ final class ReaderAPICaller: NSObject { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + guard let encodedOldName = self.encodeForURLPath(oldName), let encodedNewName = self.encodeForURLPath(newName) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + let oldTagName = "user/-/label/\(encodedOldName)" let newTagName = "user/-/label/\(encodedNewName)" let postData = "T=\(token)&s=\(oldTagName)&dest=\(newTagName)".data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: @@ -255,25 +255,25 @@ final class ReaderAPICaller: NSObject { break } }) - - + + case .failure(let error): completion(.failure(error)) } } } - + func deleteTag(folder: Folder, completion: @escaping (Result) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + guard let folderExternalID = folder.externalID else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -281,9 +281,9 @@ final class ReaderAPICaller: NSObject { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + let postData = "T=\(token)&s=\(folderExternalID)".data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: @@ -294,29 +294,29 @@ final class ReaderAPICaller: NSObject { break } }) - - + + case .failure(let error): completion(.failure(error)) } } } - + func retrieveSubscriptions(completion: @escaping (Result<[ReaderAPISubscription]?, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + let url = baseURL .appendingPathComponent(ReaderAPIEndpoints.subscriptionList.rawValue) .appendingQueryItem(URLQueryItem(name: "output", value: "json")) - + guard let callURL = url else { completion(.failure(TransportError.noURL)) return } - + var request = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) @@ -329,13 +329,13 @@ final class ReaderAPICaller: NSObject { } } } - + func createSubscription(url: String, name: String?, folder: Folder?, completion: @escaping (Result) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + func findSubscription(streamID: String, completion: @escaping (Result) -> Void) { // There is no call to get a single subscription entry, so we get them all, // look up the one we just subscribed to and return that @@ -361,19 +361,19 @@ final class ReaderAPICaller: NSObject { } }) } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): let callURL = baseURL .appendingPathComponent(ReaderAPIEndpoints.subscriptionAdd.rawValue) - + var request = URLRequest(url: callURL, credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + guard let encodedFeedURL = self.encodeForURLPath(url) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return @@ -395,7 +395,7 @@ final class ReaderAPICaller: NSObject { findSubscription(streamID: streamId, completion: completion) } - + case .failure(let error): completion(.failure(error)) } @@ -405,21 +405,21 @@ final class ReaderAPICaller: NSObject { case .failure(let error): completion(.failure(error)) } - + } } - + func renameSubscription(subscriptionID: String, newName: String, completion: @escaping (Result) -> Void) { changeSubscription(subscriptionID: subscriptionID, title: newName, completion: completion) } - + func deleteSubscription(subscriptionID: String, completion: @escaping (Result) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -427,9 +427,9 @@ final class ReaderAPICaller: NSObject { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + let postData = "T=\(token)&s=\(subscriptionID)&ac=unsubscribe".data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: @@ -440,36 +440,36 @@ final class ReaderAPICaller: NSObject { break } }) - + case .failure(let error): completion(.failure(error)) } } } - + func createTagging(subscriptionID: String, tagName: String, completion: @escaping (Result) -> Void) { changeSubscription(subscriptionID: subscriptionID, addTagName: tagName, completion: completion) } - + func deleteTagging(subscriptionID: String, tagName: String, completion: @escaping (Result) -> Void) { changeSubscription(subscriptionID: subscriptionID, removeTagName: tagName, completion: completion) } - + func moveSubscription(subscriptionID: String, fromTag: String, toTag: String, completion: @escaping (Result) -> Void) { changeSubscription(subscriptionID: subscriptionID, removeTagName: fromTag, addTagName: toTag, completion: completion) } - + private func changeSubscription(subscriptionID: String, removeTagName: String? = nil, addTagName: String? = nil, title: String? = nil, completion: @escaping (Result) -> Void) { guard removeTagName != nil || addTagName != nil || title != nil else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -477,7 +477,7 @@ final class ReaderAPICaller: NSObject { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + var postString = "T=\(token)&s=\(subscriptionID)&ac=edit" if let fromLabel = self.encodeForURLPath(removeTagName) { postString += "&r=user/-/label/\(fromLabel)" @@ -489,7 +489,7 @@ final class ReaderAPICaller: NSObject { postString += "&t=\(encodedTitle)" } let postData = postString.data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: @@ -500,25 +500,25 @@ final class ReaderAPICaller: NSObject { break } }) - + case .failure(let error): completion(.failure(error)) } } } - + func retrieveEntries(articleIDs: [String], completion: @escaping (Result<([ReaderAPIEntry]?), Error>) -> Void) { - + guard !articleIDs.isEmpty else { completion(.success(([ReaderAPIEntry]()))) return } - + guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -526,7 +526,7 @@ final class ReaderAPICaller: NSObject { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - + // Get ids from above into hex representation of value let idsToFetch = articleIDs.map({ articleID -> String in if self.variant == .theOldReader { @@ -537,9 +537,9 @@ final class ReaderAPICaller: NSObject { return "i=tag:google.com,2005:reader/item/\(idHexString)" } }).joined(separator:"&") - + let postData = "T=\(token)&output=json&\(idsToFetch)".data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, data: postData!, resultType: ReaderAPIEntryWrapper.self, completion: { (result) in switch result { case .success(let (_, entryWrapper)): @@ -547,32 +547,32 @@ final class ReaderAPICaller: NSObject { completion(.failure(ReaderAPIAccountDelegateError.invalidResponse)) return } - + completion(.success((entryWrapper.entries))) case .failure(let error): completion(.failure(error)) } }) - - + + case .failure(let error): completion(.failure(error)) } } } - + func retrieveItemIDs(type: ItemIDType, feedID: String? = nil, completion: @escaping ((Result<[String], Error>) -> Void)) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } - + var queryItems = [ URLQueryItem(name: "n", value: "1000"), URLQueryItem(name: "output", value: "json") ] - + switch type { case .allForAccount: let since: Date = { @@ -582,7 +582,7 @@ final class ReaderAPICaller: NSObject { return Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date() } }() - + let sinceTimeInterval = since.timeIntervalSince1970 queryItems.append(URLQueryItem(name: "ot", value: String(Int(sinceTimeInterval)))) queryItems.append(URLQueryItem(name: "s", value: ReaderStreams.readingList.rawValue)) @@ -600,16 +600,16 @@ final class ReaderAPICaller: NSObject { case .starred: queryItems.append(URLQueryItem(name: "s", value: ReaderState.starred.rawValue)) } - + let url = baseURL .appendingPathComponent(ReaderAPIEndpoints.itemIds.rawValue) .appendingQueryItems(queryItems) - + guard let callURL = url else { completion(.failure(TransportError.noURL)) return } - + var request: URLRequest = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) @@ -638,21 +638,21 @@ final class ReaderAPICaller: NSObject { completion(.success(itemIDs)) return } - + guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } - + var queryItems = urlComponents.queryItems!.filter({ $0.name != "c" }) queryItems.append(URLQueryItem(name: "c", value: continuation)) urlComponents.queryItems = queryItems - + guard let callURL = urlComponents.url else { completion(.failure(TransportError.noURL)) return } - + var request: URLRequest = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) @@ -671,34 +671,34 @@ final class ReaderAPICaller: NSObject { } } } - + func createUnreadEntries(entries: [String], completion: @escaping (Result) -> Void) { updateStateToEntries(entries: entries, state: .read, add: false, completion: completion) } - + func deleteUnreadEntries(entries: [String], completion: @escaping (Result) -> Void) { updateStateToEntries(entries: entries, state: .read, add: true, completion: completion) } - + func createStarredEntries(entries: [String], completion: @escaping (Result) -> Void) { updateStateToEntries(entries: entries, state: .starred, add: true, completion: completion) } - + func deleteStarredEntries(entries: [String], completion: @escaping (Result) -> Void) { updateStateToEntries(entries: entries, state: .starred, add: false, completion: completion) } - + } // MARK: Private private extension ReaderAPICaller { - + func encodeForURLPath(_ pathComponent: String?) -> String? { guard let pathComponent = pathComponent else { return nil } return pathComponent.addingPercentEncoding(withAllowedCharacters: uriComponentAllowed) } - + func addVariantHeaders(_ request: inout URLRequest) { if variant == .inoreader { request.addValue(SecretsManager.provider.inoreaderAppId, forHTTPHeaderField: "AppId") @@ -711,7 +711,7 @@ private extension ReaderAPICaller { completion(.failure(CredentialsError.incompleteCredentials)) return } - + self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): @@ -720,7 +720,7 @@ private extension ReaderAPICaller { self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", 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 { @@ -731,11 +731,11 @@ private extension ReaderAPICaller { return "i=tag:google.com,2005:reader/item/\(idHexString)" } }).joined(separator:"&") - + let actionIndicator = add ? "a" : "r" - + let postData = "T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".data(using: String.Encoding.utf8) - + self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: @@ -744,13 +744,13 @@ private extension ReaderAPICaller { completion(.failure(error)) } }) - - + + case .failure(let error): completion(.failure(error)) } } } - + } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift index 93de146f8..b6e3eb7a5 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift @@ -14,8 +14,8 @@ struct ReaderAPIEntryWrapper: Codable { let id: String let updated: Int let entries: [ReaderAPIEntry] - - + + enum CodingKeys: String, CodingKey { case id = "id" case updated = "updated" @@ -56,7 +56,7 @@ struct ReaderAPIEntry: Codable { let publishedTimestamp: Double? let crawledTimestamp: String? let timestampUsec: String? - + let summary: ReaderAPIArticleSummary let alternates: [ReaderAPIAlternateLocation]? let categories: [String] @@ -74,22 +74,22 @@ struct ReaderAPIEntry: Codable { case origin = "origin" case timestampUsec = "timestampUsec" } - + func parseDatePublished() -> Date? { guard let unixTime = publishedTimestamp else { return nil } return Date(timeIntervalSince1970: unixTime) } - + func uniqueID(variant: ReaderAPIVariant) -> String { // Should look something like "tag:google.com,2005:reader/item/00058b10ce338909" // REGEX feels heavy, I should be able to just split on / and take the last element - + guard let idPart = articleID.components(separatedBy: "/").last else { return articleID } - + guard variant != .theOldReader else { return idPart } @@ -98,15 +98,15 @@ struct ReaderAPIEntry: Codable { guard let idNumber = Int(idPart, radix: 16) else { return articleID } - + return String(idNumber, radix: 10, uppercase: false) } - + } struct ReaderAPIArticleSummary: Codable { let content: String? - + enum CodingKeys: String, CodingKey { case content = "content" } @@ -114,7 +114,7 @@ struct ReaderAPIArticleSummary: Codable { struct ReaderAPIAlternateLocation: Codable { let url: String? - + enum CodingKeys: String, CodingKey { case url = "href" } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPISubscription.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPISubscription.swift index e74491ca6..bc388574a 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPISubscription.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPISubscription.swift @@ -23,7 +23,7 @@ struct ReaderAPIQuickAddResult: Codable { let numResults: Int let error: String? let streamId: String? - + enum CodingKeys: String, CodingKey { case numResults = "numResults" case error = "error" @@ -33,7 +33,7 @@ struct ReaderAPIQuickAddResult: Codable { struct ReaderAPISubscriptionContainer: Codable { let subscriptions: [ReaderAPISubscription] - + enum CodingKeys: String, CodingKey { case subscriptions = "subscriptions" } @@ -84,7 +84,7 @@ struct ReaderAPISubscription: Codable { struct ReaderAPICategory: Codable { let categoryId: String let categoryLabel: String - + enum CodingKeys: String, CodingKey { case categoryId = "id" case categoryLabel = "label" @@ -99,13 +99,13 @@ struct ReaderAPICreateSubscription: Codable { } struct ReaderAPISubscriptionChoice: Codable { - + let name: String? let url: String - + enum CodingKeys: String, CodingKey { case name = "title" case url = "feed_url" } - + } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITag.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITag.swift index d64462701..345829a0e 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITag.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITag.swift @@ -10,27 +10,27 @@ import Foundation struct ReaderAPITagContainer: Codable { let tags: [ReaderAPITag] - + enum CodingKeys: String, CodingKey { case tags = "tags" } } struct ReaderAPITag: Codable { - + let tagID: String let type: String? - + enum CodingKeys: String, CodingKey { case tagID = "id" case type = "type" } - + var folderName: String? { guard let range = tagID.range(of: "/label/") else { return nil } return String(tagID.suffix(from: range.upperBound)) } - + } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITagging.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITagging.swift index d907ca445..4b6121fe3 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITagging.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPITagging.swift @@ -23,13 +23,13 @@ struct ReaderAPITagging: Codable { } struct ReaderAPICreateTagging: Codable { - + let feedID: Int let name: String - + enum CodingKeys: String, CodingKey { case feedID = "feed_id" case name = "name" } - + } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIUnreadEntry.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIUnreadEntry.swift index 4fe3fde89..a80597adf 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIUnreadEntry.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIUnreadEntry.swift @@ -11,7 +11,7 @@ import Foundation struct ReaderAPIReferenceWrapper: Codable { let itemRefs: [ReaderAPIReference]? let continuation: String? - + enum CodingKeys: String, CodingKey { case itemRefs = "itemRefs" case continuation = "continuation" @@ -20,7 +20,7 @@ struct ReaderAPIReferenceWrapper: Codable { struct ReaderAPIReference: Codable { let itemId: String? - + enum CodingKeys: String, CodingKey { case itemId = "id" } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIVariant.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIVariant.swift index a2cf5682c..74c5a155e 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIVariant.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIVariant.swift @@ -13,7 +13,7 @@ public enum ReaderAPIVariant { case inoreader case bazQux case theOldReader - + public var host: String { switch self { case .inoreader: @@ -26,5 +26,5 @@ public enum ReaderAPIVariant { return "" } } - + } diff --git a/Modules/Account/Sources/Account/SidebarItem.swift b/Modules/Account/Sources/Account/SidebarItem.swift index c3a5c8468..b46b45614 100644 --- a/Modules/Account/Sources/Account/SidebarItem.swift +++ b/Modules/Account/Sources/Account/SidebarItem.swift @@ -19,11 +19,11 @@ public protocol SidebarItem: SidebarItemIdentifiable, ArticleFetcher, DisplayNam var account: Account? { get } var defaultReadFilterType: ReadFilterType { get } - + } public extension SidebarItem { - + func readFiltered(readFilterEnabledTable: [SidebarItemIdentifier: Bool]) -> Bool { guard defaultReadFilterType != .alwaysRead else { return true @@ -35,5 +35,5 @@ public extension SidebarItem { } } - + } diff --git a/Modules/Account/Sources/Account/SidebarItemIdentifier.swift b/Modules/Account/Sources/Account/SidebarItemIdentifier.swift index 579d322c8..051a76e1b 100644 --- a/Modules/Account/Sources/Account/SidebarItemIdentifier.swift +++ b/Modules/Account/Sources/Account/SidebarItemIdentifier.swift @@ -13,12 +13,12 @@ public protocol SidebarItemIdentifiable { } public enum SidebarItemIdentifier: CustomStringConvertible, Hashable, Equatable { - + case smartFeed(String) // String is a unique identifier case script(String) // String is a unique identifier case feed(String, String) // accountID, feedID case folder(String, String) // accountID, folderName - + public var description: String { switch self { case .smartFeed(let id): @@ -31,7 +31,7 @@ public enum SidebarItemIdentifier: CustomStringConvertible, Hashable, Equatable return "folder: \(accountID)_\(folderName)" } } - + public var userInfo: [AnyHashable: AnyHashable] { switch self { case .smartFeed(let id): @@ -58,10 +58,10 @@ public enum SidebarItemIdentifier: CustomStringConvertible, Hashable, Equatable ] } } - + public init?(userInfo: [AnyHashable: AnyHashable]) { guard let type = userInfo["type"] as? String else { return nil } - + switch type { case "smartFeed": guard let id = userInfo["id"] as? String else { return nil } diff --git a/Modules/Account/Sources/Account/SingleArticleFetcher.swift b/Modules/Account/Sources/Account/SingleArticleFetcher.swift index f558fd5fa..78c28357e 100644 --- a/Modules/Account/Sources/Account/SingleArticleFetcher.swift +++ b/Modules/Account/Sources/Account/SingleArticleFetcher.swift @@ -11,29 +11,29 @@ import Articles import ArticlesDatabase public struct SingleArticleFetcher: ArticleFetcher { - + private let account: Account private let articleID: String - + public init(account: Account, articleID: String) { self.account = account self.articleID = articleID } - + public func fetchArticles() throws -> Set
{ return try account.fetchArticles(.articleIDs(Set([articleID]))) } - + public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) } - + public func fetchUnreadArticles() throws -> Set
{ return try account.fetchArticles(.articleIDs(Set([articleID]))) } - + public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) } - + } diff --git a/Modules/Account/Sources/Account/URLRequest+Account.swift b/Modules/Account/Sources/Account/URLRequest+Account.swift index 035106a7c..43ad63df5 100755 --- a/Modules/Account/Sources/Account/URLRequest+Account.swift +++ b/Modules/Account/Sources/Account/URLRequest+Account.swift @@ -11,15 +11,15 @@ import RSWeb import Secrets public extension URLRequest { - + init(url: URL, credentials: Credentials?, conditionalGet: HTTPConditionalGetInfo? = nil) { - + self.init(url: url) - + guard let credentials = credentials else { return } - + switch credentials.type { case .basic: let data = "\(credentials.username):\(credentials.secret)".data(using: .utf8) @@ -64,11 +64,11 @@ public extension URLRequest { assertionFailure("Refresh tokens are used to replace expired access tokens. Did you mean to use `accessToken` instead?") break } - + guard let conditionalGet = conditionalGet else { return } - + // Bug seen in the wild: lastModified with last possible 32-bit date, which is in 2038. Ignore those. // TODO: drop this check in late 2037. if let lastModified = conditionalGet.lastModified, !lastModified.contains("2038") { @@ -77,7 +77,7 @@ public extension URLRequest { if let etag = conditionalGet.etag { setValue(etag, forHTTPHeaderField: HTTPRequestHeader.ifNoneMatch) } - + } - + } diff --git a/Modules/Account/Sources/Account/UnreadCountProvider.swift b/Modules/Account/Sources/Account/UnreadCountProvider.swift index f6bc48d4a..4c5cfe06a 100644 --- a/Modules/Account/Sources/Account/UnreadCountProvider.swift +++ b/Modules/Account/Sources/Account/UnreadCountProvider.swift @@ -23,7 +23,7 @@ public protocol UnreadCountProvider { public extension UnreadCountProvider { - + func postUnreadCountDidInitializeNotification() { NotificationCenter.default.post(name: .UnreadCountDidInitialize, object: self, userInfo: nil) } diff --git a/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift b/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift index 1a99df599..665161613 100644 --- a/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift +++ b/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift @@ -14,7 +14,7 @@ import Secrets final class AccountCredentialsTest: XCTestCase { private var account: Account! - + override func setUp() { account = TestAccountManager.shared.createAccount(type: .feedbin, transport: TestTransport()) } @@ -24,7 +24,7 @@ final class AccountCredentialsTest: XCTestCase { } func testCreateRetrieveDelete() { - + // Make sure any left over from failed tests are gone do { try account.removeCredentials(type: .basic) @@ -33,14 +33,14 @@ final class AccountCredentialsTest: XCTestCase { } var credentials: Credentials? = Credentials(type: .basic, username: "maurice", secret: "hardpasswd") - + // Store the credentials do { try account.storeCredentials(credentials!) } catch { XCTFail(error.localizedDescription) } - + // Retrieve them credentials = nil do { @@ -48,7 +48,7 @@ final class AccountCredentialsTest: XCTestCase { } catch { XCTFail(error.localizedDescription) } - + switch credentials!.type { case .basic: XCTAssertEqual("maurice", credentials?.username) @@ -56,7 +56,7 @@ final class AccountCredentialsTest: XCTestCase { default: XCTFail("Expected \(CredentialsType.basic), received \(credentials!.type)") } - + // Update them credentials = Credentials(type: .basic, username: "maurice", secret: "easypasswd") do { @@ -64,7 +64,7 @@ final class AccountCredentialsTest: XCTestCase { } catch { XCTFail(error.localizedDescription) } - + // Retrieve them again credentials = nil do { @@ -94,7 +94,7 @@ final class AccountCredentialsTest: XCTestCase { } catch { XCTFail(error.localizedDescription) } - + XCTAssertNil(credentials) } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderContentsSyncTest.swift b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderContentsSyncTest.swift index 5aa095ad9..79bac84dd 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderContentsSyncTest.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderContentsSyncTest.swift @@ -18,24 +18,24 @@ final class AccountFeedbinFolderContentsSyncTest: XCTestCase { } func testDownloadSync() { - + let testTransport = TestTransport() testTransport.testFiles["https://api.feedbin.com/v2/tags.json"] = "JSON/tags_add.json" testTransport.testFiles["https://api.feedbin.com/v2/subscriptions.json"] = "JSON/subscriptions_initial.json" testTransport.testFiles["https://api.feedbin.com/v2/taggings.json"] = "JSON/taggings_initial.json" let account = TestAccountManager.shared.createAccount(type: .feedbin, transport: testTransport) - + // Test initial folders let initialExpection = self.expectation(description: "Initial contents") account.refreshAll() { _ in initialExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + let folder = account.folders?.filter { $0.name == "Developers" } .first! XCTAssertEqual(156, folder?.topLevelFeeds.count ?? 0) XCTAssertEqual(2, account.topLevelFeeds.count) - + // Test Adding a Feed to the folder testTransport.testFiles["https://api.feedbin.com/v2/taggings.json"] = "JSON/taggings_add.json" @@ -44,24 +44,24 @@ final class AccountFeedbinFolderContentsSyncTest: XCTestCase { addExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + XCTAssertEqual(157, folder?.topLevelFeeds.count ?? 0) XCTAssertEqual(1, account.topLevelFeeds.count) // Test Deleting some Feeds from the folder testTransport.testFiles["https://api.feedbin.com/v2/taggings.json"] = "JSON/taggings_delete.json" - + let deleteExpection = self.expectation(description: "Delete contents") account.refreshAll() { _ in deleteExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + XCTAssertEqual(153, folder?.topLevelFeeds.count ?? 0) XCTAssertEqual(5, account.topLevelFeeds.count) TestAccountManager.shared.deleteAccount(account) - + } - + } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderSyncTest.swift b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderSyncTest.swift index 51eb17928..82713ee73 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderSyncTest.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinFolderSyncTest.swift @@ -22,37 +22,37 @@ final class AccountFeedbinFolderSyncTest: XCTestCase { let testTransport = TestTransport() testTransport.testFiles["https://api.feedbin.com/v2/tags.json"] = "JSON/tags_initial.json" let account = TestAccountManager.shared.createAccount(type: .feedbin, transport: testTransport) - + // Test initial folders let initialExpection = self.expectation(description: "Initial tags") account.refreshAll() { _ in initialExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + guard let intialFolders = account.folders else { XCTFail() return } - + XCTAssertEqual(9, intialFolders.count) let initialFolderNames = intialFolders.map { $0.name ?? "" } XCTAssertTrue(initialFolderNames.contains("Outdoors")) // Test removing folders testTransport.testFiles["https://api.feedbin.com/v2/tags.json"] = "JSON/tags_delete.json" - + let deleteExpection = self.expectation(description: "Delete tags") account.refreshAll() { _ in deleteExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + guard let deleteFolders = account.folders else { XCTFail() return } - + XCTAssertEqual(8, deleteFolders.count) let deleteFolderNames = deleteFolders.map { $0.name ?? "" } XCTAssertTrue(deleteFolderNames.contains("Outdoors")) @@ -60,24 +60,24 @@ final class AccountFeedbinFolderSyncTest: XCTestCase { // Test Adding Folders testTransport.testFiles["https://api.feedbin.com/v2/tags.json"] = "JSON/tags_add.json" - + let addExpection = self.expectation(description: "Add tags") account.refreshAll() { _ in addExpection.fulfill() } waitForExpectations(timeout: 5, handler: nil) - + guard let addFolders = account.folders else { XCTFail() return } - + XCTAssertEqual(10, addFolders.count) let addFolderNames = addFolders.map { $0.name ?? "" } XCTAssertTrue(addFolderNames.contains("Vanlife")) TestAccountManager.shared.deleteAccount(account) - + } } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinSyncTest.swift b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinSyncTest.swift index 233ce133e..af2b08e1d 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinSyncTest.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/AccountFeedbinSyncTest.swift @@ -18,12 +18,12 @@ final class AccountFeedbinSyncTest: XCTestCase { } func testDownloadSync() { - + let testTransport = TestTransport() testTransport.testFiles["tags.json"] = "JSON/tags_add.json" testTransport.testFiles["subscriptions.json"] = "JSON/subscriptions_initial.json" let account = TestAccountManager.shared.createAccount(type: .feedbin, transport: testTransport) - + // Test initial folders let initialExpection = self.expectation(description: "Initial feeds") account.refreshAll() { result in @@ -35,7 +35,7 @@ final class AccountFeedbinSyncTest: XCTestCase { } } waitForExpectations(timeout: 5, handler: nil) - + XCTAssertEqual(224, account.flattenedFeeds().count) let daringFireball = account.idToFeedDictionary["1296379"] @@ -45,7 +45,7 @@ final class AccountFeedbinSyncTest: XCTestCase { // Test Adding a Feed testTransport.testFiles["subscriptions.json"] = "JSON/subscriptions_add.json" - + let addExpection = self.expectation(description: "Add feeds") account.refreshAll() { result in switch result { @@ -56,9 +56,9 @@ final class AccountFeedbinSyncTest: XCTestCase { } } waitForExpectations(timeout: 5, handler: nil) - + XCTAssertEqual(225, account.flattenedFeeds().count) - + let bPixels = account.idToFeedDictionary["1096623"] XCTAssertEqual("Beautiful Pixels", bPixels?.name) XCTAssertEqual("https://feedpress.me/beautifulpixels", bPixels?.url) @@ -67,5 +67,5 @@ final class AccountFeedbinSyncTest: XCTestCase { TestAccountManager.shared.deleteAccount(account) } - + } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCheckpointOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCheckpointOperationTests.swift index e63c1f1cc..bbf1709fb 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCheckpointOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCheckpointOperationTests.swift @@ -11,52 +11,52 @@ import XCTest import RSCore final class FeedlyCheckpointOperationTests: XCTestCase { - + final class TestDelegate: FeedlyCheckpointOperationDelegate { - + var didReachCheckpointExpectation: XCTestExpectation? - + func feedlyCheckpointOperationDidReachCheckpoint(_ operation: FeedlyCheckpointOperation) { didReachCheckpointExpectation?.fulfill() } } - + func testCallback() { let delegate = TestDelegate() delegate.didReachCheckpointExpectation = expectation(description: "Did Reach Checkpoint") - + let operation = FeedlyCheckpointOperation() operation.checkpointDelegate = delegate - + let didFinishExpectation = expectation(description: "Did Finish") operation.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(operation) - + waitForExpectations(timeout: 2) } - + func testCancellation() { let didReachCheckpointExpectation = expectation(description: "Did Reach Checkpoint") didReachCheckpointExpectation.isInverted = true - + let delegate = TestDelegate() delegate.didReachCheckpointExpectation = didReachCheckpointExpectation - + let operation = FeedlyCheckpointOperation() operation.checkpointDelegate = delegate - + let didFinishExpectation = expectation(description: "Did Finish") operation.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(operation) - + MainThreadOperationQueue.shared.cancelOperations([operation]) - + waitForExpectations(timeout: 1) } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCollectionParserTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCollectionParserTests.swift index 33583879c..ebc09951c 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCollectionParserTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCollectionParserTests.swift @@ -10,14 +10,14 @@ import XCTest @testable import Account final class FeedlyCollectionParserTests: XCTestCase { - + func testParsing() { let collection = FeedlyCollection(feeds: [], label: "Test Collection", id: "test/collection/1") let parser = FeedlyCollectionParser(collection: collection) XCTAssertEqual(parser.folderName, collection.label) XCTAssertEqual(parser.externalID, collection.id) } - + func testSanitization() { let name = "Test Collection" let collection = FeedlyCollection(feeds: [], label: "
\(name)
", id: "test/collection/1") diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCreateFeedsForCollectionFoldersOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCreateFeedsForCollectionFoldersOperationTests.swift index 8c82270bf..20196f1d5 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyCreateFeedsForCollectionFoldersOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyCreateFeedsForCollectionFoldersOperationTests.swift @@ -11,186 +11,186 @@ import XCTest import RSCore final class FeedlyCreateFeedsForCollectionFoldersOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + final class FeedsAndFoldersProvider: FeedlyFeedsAndFoldersProviding { var feedsAndFolders = [([FeedlyFeed], Folder)]() } - + func testAddFeeds() { let feedsForFolderOne = [ FeedlyFeed(id: "feed/1", title: "Feed One", updated: nil, website: nil), FeedlyFeed(id: "feed/2", title: "Feed Two", updated: nil, website: nil) ] - + let feedsForFolderTwo = [ FeedlyFeed(id: "feed/1", title: "Feed One", updated: nil, website: nil), FeedlyFeed(id: "feed/3", title: "Feed Three", updated: nil, website: nil), ] - + let folderOne: (name: String, id: String) = ("FolderOne", "folder/1") let folderTwo: (name: String, id: String) = ("FolderTwo", "folder/2") let namesAndFeeds = [(folderOne, feedsForFolderOne), (folderTwo, feedsForFolderTwo)] - + let provider = FeedsAndFoldersProvider() provider.feedsAndFolders = namesAndFeeds.map { (folder, feeds) in let accountFolder = account.ensureFolder(with: folder.name)! accountFolder.externalID = folder.id return (feeds, accountFolder) } - + let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: provider) let completionExpectation = expectation(description: "Did Finish") createFeeds.completionBlock = { _ in completionExpectation.fulfill() } - + XCTAssertTrue(account.flattenedFeeds().isEmpty, "Expected empty account.") - + MainThreadOperationQueue.shared.add(createFeeds) - + waitForExpectations(timeout: 2) - + let feedIds = Set([feedsForFolderOne, feedsForFolderTwo] .flatMap { $0 } .map { $0.id }) - + let feedTitles = Set([feedsForFolderOne, feedsForFolderTwo] .flatMap { $0 } .map { $0.title }) - + let accountFeeds = account.flattenedFeeds() let ingestedIds = Set(accountFeeds.map { $0.feedID }) let ingestedTitles = Set(accountFeeds.map { $0.nameForDisplay }) - + let missingIds = feedIds.subtracting(ingestedIds) let missingTitles = feedTitles.subtracting(ingestedTitles) - + XCTAssertTrue(missingIds.isEmpty, "Failed to ingest feeds with these ids.") XCTAssertTrue(missingTitles.isEmpty, "Failed to ingest feeds with these titles.") - + let expectedFolderAndFeedIds = namesAndFeeds .sorted { $0.0.id < $1.0.id } .map { folder, feeds -> [String: [String]] in return [folder.id: feeds.map { $0.id }.sorted(by: <)] } - + let ingestedFolderAndFeedIds = (account.folders ?? Set()) .sorted { $0.externalID! < $1.externalID! } .compactMap { folder -> [String: [String]]? in return [folder.externalID!: folder.topLevelFeeds.map { $0.feedID }.sorted(by: <)] } - + XCTAssertEqual(expectedFolderAndFeedIds, ingestedFolderAndFeedIds, "Did not ingest feeds in their corresponding folders.") } - + func testRemoveFeeds() { let folderOne: (name: String, id: String) = ("FolderOne", "folder/1") let folderTwo: (name: String, id: String) = ("FolderTwo", "folder/2") let feedToRemove = FeedlyFeed(id: "feed/1", title: "Feed One", updated: nil, website: nil) - + var feedsForFolderOne = [ feedToRemove, FeedlyFeed(id: "feed/2", title: "Feed Two", updated: nil, website: nil) ] - + var feedsForFolderTwo = [ feedToRemove, FeedlyFeed(id: "feed/3", title: "Feed Three", updated: nil, website: nil), ] - + // Add initial content. do { let namesAndFeeds = [(folderOne, feedsForFolderOne), (folderTwo, feedsForFolderTwo)] - + let provider = FeedsAndFoldersProvider() provider.feedsAndFolders = namesAndFeeds.map { (folder, feeds) in let accountFolder = account.ensureFolder(with: folder.name)! accountFolder.externalID = folder.id return (feeds, accountFolder) } - + let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: provider) let completionExpectation = expectation(description: "Did Finish") createFeeds.completionBlock = { _ in completionExpectation.fulfill() } - + XCTAssertTrue(account.flattenedFeeds().isEmpty, "Expected empty account.") - + MainThreadOperationQueue.shared.add(createFeeds) - + waitForExpectations(timeout: 2) } - + feedsForFolderOne.removeAll { $0.id == feedToRemove.id } feedsForFolderTwo.removeAll { $0.id == feedToRemove.id } let namesAndFeeds = [(folderOne, feedsForFolderOne), (folderTwo, feedsForFolderTwo)] - + let provider = FeedsAndFoldersProvider() provider.feedsAndFolders = namesAndFeeds.map { (folder, feeds) in let accountFolder = account.ensureFolder(with: folder.name)! accountFolder.externalID = folder.id return (feeds, accountFolder) } - + let removeFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: provider) let completionExpectation = expectation(description: "Did Finish") removeFeeds.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(removeFeeds) - + waitForExpectations(timeout: 2) - + let feedIds = Set([feedsForFolderOne, feedsForFolderTwo] .flatMap { $0 } .map { $0.id }) - + let feedTitles = Set([feedsForFolderOne, feedsForFolderTwo] .flatMap { $0 } .map { $0.title }) - + let accountFeeds = account.flattenedFeeds() let ingestedIds = Set(accountFeeds.map { $0.feedID }) let ingestedTitles = Set(accountFeeds.map { $0.nameForDisplay }) - + XCTAssertEqual(ingestedIds.count, feedIds.count) XCTAssertEqual(ingestedTitles.count, feedTitles.count) - + let missingIds = feedIds.subtracting(ingestedIds) let missingTitles = feedTitles.subtracting(ingestedTitles) - + XCTAssertTrue(missingIds.isEmpty, "Failed to ingest feeds with these ids.") XCTAssertTrue(missingTitles.isEmpty, "Failed to ingest feeds with these titles.") - + let expectedFolderAndFeedIds = namesAndFeeds .sorted { $0.0.id < $1.0.id } .map { folder, feeds -> [String: [String]] in return [folder.id: feeds.map { $0.id }.sorted(by: <)] } - + let ingestedFolderAndFeedIds = (account.folders ?? Set()) .sorted { $0.externalID! < $1.externalID! } .compactMap { folder -> [String: [String]]? in return [folder.externalID!: folder.topLevelFeeds.map { $0.feedID }.sorted(by: <)] } - + XCTAssertEqual(expectedFolderAndFeedIds, ingestedFolderAndFeedIds, "Did not ingest feeds to their corresponding folders.") } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift index f32f7380b..bbdf4fc23 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift @@ -10,7 +10,7 @@ import XCTest @testable import Account final class FeedlyEntryParserTests: XCTestCase { - + func testParsing() { let content = FeedlyEntry.Content(content: "Test Content", direction: .leftToRight) let summary = FeedlyEntry.Content(content: "Test Summary", direction: .leftToRight) @@ -34,9 +34,9 @@ final class FeedlyEntryParserTests: XCTestCase { tags: tags, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + XCTAssertEqual(parser.id, entry.id) XCTAssertEqual(parser.feedUrl, origin.streamId) XCTAssertEqual(parser.externalUrl, canonicalLink.href) @@ -45,15 +45,15 @@ final class FeedlyEntryParserTests: XCTestCase { XCTAssertEqual(parser.summary, summary.content) XCTAssertEqual(parser.datePublished, .distantPast) XCTAssertEqual(parser.dateModified, Date(timeIntervalSinceReferenceDate: 0)) - + guard let item = parser.parsedItemRepresentation else { XCTFail("Expected a parsed item representation.") return } - + XCTAssertEqual(item.syncServiceID, entry.id) XCTAssertEqual(item.uniqueID, entry.id) - + // The following is not an error. // The feedURL must match the feedID for the article to be connected to its matching feed. XCTAssertEqual(item.feedURL, origin.streamId) @@ -63,15 +63,15 @@ final class FeedlyEntryParserTests: XCTestCase { XCTAssertEqual(item.summary, summary.content) XCTAssertEqual(item.datePublished, entry.crawled) XCTAssertEqual(item.dateModified, entry.recrawled) - + let expectedTags = Set(tags.compactMap { $0.label }) XCTAssertEqual(item.tags, expectedTags) - + let expectedAuthors = Set([entry.author]) let calculatedAuthors = Set(item.authors?.compactMap { $0.name } ?? []) XCTAssertEqual(calculatedAuthors, expectedAuthors) } - + func testSanitization() { let content = FeedlyEntry.Content(content: "
Test Content
", direction: .rightToLeft) let summaryContent = "Test Summary" @@ -92,17 +92,17 @@ final class FeedlyEntryParserTests: XCTestCase { tags: nil, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + // These should be sanitized XCTAssertEqual(parser.title, title) XCTAssertEqual(parser.summary, summaryContent) - + // These should not be sanitized because it is supposed to be HTML content. XCTAssertEqual(parser.contentHMTL, content.content) } - + func testLocatesCanonicalExternalUrl() { let canonicalLink = FeedlyLink(href: "tests://feeds/1/entries/1", type: "text/html") let alternateLink = FeedlyLink(href: "tests://feeds/1/entries/alternate/1", type: "text/html") @@ -120,12 +120,12 @@ final class FeedlyEntryParserTests: XCTestCase { tags: nil, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + XCTAssertEqual(parser.externalUrl, canonicalLink.href) } - + func testLocatesAlternateExternalUrl() { let canonicalLink = FeedlyLink(href: "tests://feeds/1/entries/1", type: "text/json") let alternateLink = FeedlyLink(href: "tests://feeds/1/entries/alternate/1", type: nil) @@ -143,12 +143,12 @@ final class FeedlyEntryParserTests: XCTestCase { tags: nil, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + XCTAssertEqual(parser.externalUrl, alternateLink.href) } - + func testContentPreferredToSummary() { let content = FeedlyEntry.Content(content: "Test Content", direction: .leftToRight) let summary = FeedlyEntry.Content(content: "Test Summary", direction: .leftToRight) @@ -166,12 +166,12 @@ final class FeedlyEntryParserTests: XCTestCase { tags: nil, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + XCTAssertEqual(parser.contentHMTL, content.content) } - + func testSummaryUsedAsContentWhenContentMissing() { let summary = FeedlyEntry.Content(content: "Test Summary", direction: .leftToRight) let entry = FeedlyEntry(id: "tests/feeds/1/entries/1", @@ -188,9 +188,9 @@ final class FeedlyEntryParserTests: XCTestCase { tags: nil, categories: nil, enclosure: nil) - + let parser = FeedlyEntryParser(entry: entry) - + XCTAssertEqual(parser.contentHMTL, summary.content) } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyFeedParserTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyFeedParserTests.swift index 4ca0ede17..5cea337ad 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyFeedParserTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyFeedParserTests.swift @@ -10,7 +10,7 @@ import XCTest @testable import Account final class FeedlyFeedParserTests: XCTestCase { - + func testParsing() { let name = "Test Feed" let website = "tests://nnw/feed/1" @@ -24,7 +24,7 @@ final class FeedlyFeedParserTests: XCTestCase { XCTAssertEqual(parser.url, url) XCTAssertEqual(parser.feedID, id) } - + func testSanitization() { let name = "Test Feed" let website = "tests://nnw/feed/1" diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetCollectionsOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetCollectionsOperationTests.swift index 65b306cd3..fc2059f49 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetCollectionsOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetCollectionsOperationTests.swift @@ -12,42 +12,42 @@ import os.log import RSCore final class FeedlyGetCollectionsOperationTests: XCTestCase { - + func testGetCollections() { let support = FeedlyTestSupport() let (transport, caller) = support.makeMockNetworkStack() let jsonName = "JSON/feedly_collections_initial" transport.testFiles["/v3/collections"] = "\(jsonName).json" - + let getCollections = FeedlyGetCollectionsOperation(service: caller) let completionExpectation = expectation(description: "Did Finish") getCollections.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getCollections) - + waitForExpectations(timeout: 2) - + let collections = support.testJSON(named: jsonName) as! [[String:Any]] let labelsInJSON = Set(collections.map { $0["label"] as! String }) let idsInJSON = Set(collections.map { $0["id"] as! String }) - + let labels = Set(getCollections.collections.map { $0.label }) let ids = Set(getCollections.collections.map { $0.id }) - + let missingLabels = labelsInJSON.subtracting(labels) let missingIds = idsInJSON.subtracting(ids) - + XCTAssertEqual(getCollections.collections.count, collections.count, "Mismatch between collections provided by operation and test JSON collections.") XCTAssertTrue(missingLabels.isEmpty, "Collections with these labels did not have a corresponding \(FeedlyCollection.self) value with the same name.") XCTAssertTrue(missingIds.isEmpty, "Collections with these ids did not have a corresponding \(FeedlyCollection.self) with the same id.") - + for collection in collections { let collectionId = collection["id"] as! String let collectionFeeds = collection["feeds"] as! [[String: Any]] let collectionFeedIds = Set(collectionFeeds.map { $0["id"] as! String }) - + for operationCollection in getCollections.collections where operationCollection.id == collectionId { let feedIds = Set(operationCollection.feeds.map { $0.id }) let missingIds = collectionFeedIds.subtracting(feedIds) @@ -55,37 +55,37 @@ final class FeedlyGetCollectionsOperationTests: XCTestCase { } } } - + func testGetCollectionsError() { - + final class TestDelegate: FeedlyOperationDelegate { var errorExpectation: XCTestExpectation? var error: Error? - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { self.error = error errorExpectation?.fulfill() } } - + let delegate = TestDelegate() delegate.errorExpectation = expectation(description: "Did Fail With Expected Error") - + let service = TestGetCollectionsService() service.mockResult = .failure(URLError(.timedOut)) - + let getCollections = FeedlyGetCollectionsOperation(service: service) getCollections.delegate = delegate - + let completionExpectation = expectation(description: "Did Finish") getCollections.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getCollections) - + waitForExpectations(timeout: 2) - + XCTAssertNotNil(delegate.error) XCTAssertTrue(getCollections.collections.isEmpty, "Collections should be empty.") } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamContentsOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamContentsOperationTests.swift index 681b28274..41ee98498 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamContentsOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamContentsOperationTests.swift @@ -11,52 +11,52 @@ import XCTest import RSCore final class FeedlyGetStreamContentsOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + func testGetStreamContentsFailure() { let service = TestGetStreamContentsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") - + let getStreamContents = FeedlyGetStreamContentsOperation(account: account, resource: resource, service: service, continuation: nil, newerThan: nil, unreadOnly: nil) - + service.mockResult = .failure(URLError(.fileDoesNotExist)) - + let completionExpectation = expectation(description: "Did Finish") getStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamContents) - + waitForExpectations(timeout: 2) - + XCTAssertNil(getStreamContents.stream) } - + func testValuesPassingForGetStreamContents() { let service = TestGetStreamContentsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") - + let continuation: String? = "abcdefg" let newerThan: Date? = Date(timeIntervalSinceReferenceDate: 86) let unreadOnly: Bool? = true - + let getStreamContents = FeedlyGetStreamContentsOperation(account: account, resource: resource, service: service, continuation: continuation, newerThan: newerThan, unreadOnly: unreadOnly) - + let mockStream = FeedlyStream(id: "stream/1", updated: nil, continuation: nil, items: []) service.mockResult = .success(mockStream) service.getStreamContentsExpectation = expectation(description: "Did Call Service") @@ -67,65 +67,65 @@ final class FeedlyGetStreamContentsOperationTests: XCTestCase { XCTAssertEqual(serviceNewerThan, newerThan) XCTAssertEqual(serviceUnreadOnly, unreadOnly) } - + let completionExpectation = expectation(description: "Did Finish") getStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamContents) - + waitForExpectations(timeout: 2) - + guard let stream = getStreamContents.stream else { XCTFail("\(FeedlyGetStreamContentsOperation.self) did not store the stream.") return } - + XCTAssertEqual(stream.id, mockStream.id) XCTAssertEqual(stream.updated, mockStream.updated) XCTAssertEqual(stream.continuation, mockStream.continuation) - + let streamIds = stream.items.map { $0.id } let mockStreamIds = mockStream.items.map { $0.id } XCTAssertEqual(streamIds, mockStreamIds) } - + func testGetStreamContentsFromJSON() { let support = FeedlyTestSupport() let (transport, caller) = support.makeMockNetworkStack() let jsonName = "JSON/feedly_macintosh_initial" transport.testFiles["/v3/streams/contents"] = "\(jsonName).json" - + let resource = FeedlyCategoryResourceId(id: "user/f2f031bd-f3e3-4893-a447-467a291c6d1e/category/5ca4d61d-e55d-4999-a8d1-c3b9d8789815") let getStreamContents = FeedlyGetStreamContentsOperation(account: account, resource: resource, service: caller, continuation: nil, newerThan: nil, unreadOnly: nil) - + let completionExpectation = expectation(description: "Did Finish") getStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamContents) - + waitForExpectations(timeout: 2) - + // verify entry providing and parsed item providing guard let stream = getStreamContents.stream else { return XCTFail("Expected to have stream.") } - + let streamJSON = support.testJSON(named: jsonName) as! [String:Any] - + let id = streamJSON["id"] as! String XCTAssertEqual(stream.id, id) - + let milliseconds = streamJSON["updated"] as! Double let updated = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000)) XCTAssertEqual(stream.updated, updated) - + let continuation = streamJSON["continuation"] as! String XCTAssertEqual(stream.continuation, continuation) - + support.check(getStreamContents.entries, correspondToStreamItemsIn: streamJSON) support.check(stream.items, correspondToStreamItemsIn: streamJSON) } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamIdsOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamIdsOperationTests.swift index 4b740a86a..af6aefbe4 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamIdsOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyGetStreamIdsOperationTests.swift @@ -11,52 +11,52 @@ import XCTest import RSCore final class FeedlyGetStreamIdsOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + func testGetStreamIdsFailure() { let service = TestGetStreamIdsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") - + let getStreamIds = FeedlyGetStreamIdsOperation(account: account, resource: resource, service: service, continuation: nil, newerThan: nil, unreadOnly: nil) - + service.mockResult = .failure(URLError(.fileDoesNotExist)) - + let completionExpectation = expectation(description: "Did Finish") getStreamIds.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamIds) - + waitForExpectations(timeout: 2) - + XCTAssertNil(getStreamIds.streamIds) } - + func testValuesPassingForGetStreamIds() { let service = TestGetStreamIdsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") - + let continuation: String? = "gfdsa" let newerThan: Date? = Date(timeIntervalSinceReferenceDate: 1000) let unreadOnly: Bool? = false - + let getStreamIds = FeedlyGetStreamIdsOperation(account: account, resource: resource, service: service, continuation: continuation, newerThan: newerThan, unreadOnly: unreadOnly) - + let mockStreamIds = FeedlyStreamIds(continuation: "1234", ids: ["item/1", "item/2", "item/3"]) service.mockResult = .success(mockStreamIds) service.getStreamIdsExpectation = expectation(description: "Did Call Service") @@ -67,49 +67,49 @@ final class FeedlyGetStreamIdsOperationTests: XCTestCase { XCTAssertEqual(serviceNewerThan, newerThan) XCTAssertEqual(serviceUnreadOnly, unreadOnly) } - + let completionExpectation = expectation(description: "Did Finish") getStreamIds.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamIds) - + waitForExpectations(timeout: 2) - + guard let streamIds = getStreamIds.streamIds else { XCTFail("\(FeedlyGetStreamIdsOperation.self) did not store the stream.") return } - + XCTAssertEqual(streamIds.continuation, mockStreamIds.continuation) XCTAssertEqual(streamIds.ids, mockStreamIds.ids) } - + func testGetStreamIdsFromJSON() { let support = FeedlyTestSupport() let (transport, caller) = support.makeMockNetworkStack() let jsonName = "JSON/feedly_unreads_1000" transport.testFiles["/v3/streams/ids"] = "\(jsonName).json" - + let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") let getStreamIds = FeedlyGetStreamIdsOperation(account: account, resource: resource, service: caller, continuation: nil, newerThan: nil, unreadOnly: nil) - + let completionExpectation = expectation(description: "Did Finish") getStreamIds.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(getStreamIds) - + waitForExpectations(timeout: 2) - + guard let streamIds = getStreamIds.streamIds else { return XCTFail("Expected to have a stream of identifiers.") } - + let streamIdsJSON = support.testJSON(named: jsonName) as! [String:Any] - + let continuation = streamIdsJSON["continuation"] as! String XCTAssertEqual(streamIds.continuation, continuation) XCTAssertEqual(streamIds.ids, streamIdsJSON["ids"] as! [String]) diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift index e49419f23..d0c887c51 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift @@ -15,19 +15,19 @@ final class FeedlyLogoutOperationTests: XCTestCase { private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + private func getTokens(for account: Account) throws -> (accessToken: Credentials, refreshToken: Credentials) { guard let accessToken = try account.retrieveCredentials(type: .oauthAccessToken), let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) else { XCTFail("Unable to retrieve access and/or refresh token from account.") @@ -35,11 +35,11 @@ final class FeedlyLogoutOperationTests: XCTestCase { } return (accessToken, refreshToken) } - + final class TestFeedlyLogoutService: FeedlyLogoutService { var mockResult: Result? var logoutExpectation: XCTestExpectation? - + func logout(completion: @escaping (Result) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") @@ -51,12 +51,12 @@ final class FeedlyLogoutOperationTests: XCTestCase { } } } - + func testCancel() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.logoutExpectation?.isInverted = true - + let accessToken: Credentials let refreshToken: Credentials do { @@ -65,106 +65,106 @@ final class FeedlyLogoutOperationTests: XCTestCase { XCTFail("Could not retrieve credentials to verify their integrity later.") return } - + let logout = FeedlyLogoutOperation(account: account, service: service) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(logout) - + MainThreadOperationQueue.shared.cancelOperations([logout]) - + waitForExpectations(timeout: 1) - + XCTAssertTrue(logout.isCanceled) - + do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) - + XCTAssertEqual(accountAccessToken, accessToken) XCTAssertEqual(accountRefreshToken, refreshToken) } catch { XCTFail("Could not verify tokens were left intact. Did the operation delete them?") } } - + func testLogoutSuccess() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.mockResult = .success(()) - + let logout = FeedlyLogoutOperation(account: account, service: service) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(logout) - + waitForExpectations(timeout: 1) - + XCTAssertFalse(logout.isCanceled) - + do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) - + XCTAssertNil(accountAccessToken) XCTAssertNil(accountRefreshToken) } catch { XCTFail("Could not verify tokens were deleted.") } } - + final class TestLogoutDelegate: FeedlyOperationDelegate { var error: Error? var didFailExpectation: XCTestExpectation? - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { self.error = error didFailExpectation?.fulfill() } } - + func testLogoutMissingAccessToken() { support.removeCredentials(matching: .oauthAccessToken, from: account) - + let (_, service) = support.makeMockNetworkStack() service.credentials = nil - + let logout = FeedlyLogoutOperation(account: account, service: service) - + let delegate = TestLogoutDelegate() delegate.didFailExpectation = expectation(description: "Did Fail") - + logout.delegate = delegate - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(logout) - + waitForExpectations(timeout: 1) - + XCTAssertFalse(logout.isCanceled) - + do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) XCTAssertNil(accountAccessToken) } catch { XCTFail("Could not verify tokens were deleted.") } - + XCTAssertNotNil(delegate.error, "Should have failed with error.") if let error = delegate.error { switch error { @@ -175,12 +175,12 @@ final class FeedlyLogoutOperationTests: XCTestCase { } } } - + func testLogoutFailure() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.mockResult = .failure(URLError(.timedOut)) - + let accessToken: Credentials let refreshToken: Credentials do { @@ -189,25 +189,25 @@ final class FeedlyLogoutOperationTests: XCTestCase { XCTFail("Could not retrieve credentials to verify their integrity later.") return } - + let logout = FeedlyLogoutOperation(account: account, service: service) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(logout) - + waitForExpectations(timeout: 1) - + XCTAssertFalse(logout.isCanceled) - + do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) - + XCTAssertEqual(accountAccessToken, accessToken) XCTAssertEqual(accountRefreshToken, refreshToken) } catch { diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyMirrorCollectionsAsFoldersOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyMirrorCollectionsAsFoldersOperationTests.swift index ec75c6f68..7552003f3 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyMirrorCollectionsAsFoldersOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyMirrorCollectionsAsFoldersOperationTests.swift @@ -11,29 +11,29 @@ import XCTest import RSCore final class FeedlyMirrorCollectionsAsFoldersOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + final class CollectionsProvider: FeedlyCollectionProviding { var collections = [ FeedlyCollection(feeds: [], label: "One", id: "collections/1"), FeedlyCollection(feeds: [], label: "Two", id: "collections/2") ] } - + func testAddsFolders() { let provider = CollectionsProvider() let mirrorOperation = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) @@ -41,81 +41,81 @@ final class FeedlyMirrorCollectionsAsFoldersOperationTests: XCTestCase { mirrorOperation.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(mirrorOperation) - + waitForExpectations(timeout: 2) - + let folders = account.folders ?? Set() let folderNames = Set(folders.compactMap { $0.nameForDisplay }) let folderExternalIds = Set(folders.compactMap { $0.externalID }) - + let collectionLabels = Set(provider.collections.map { $0.label }) let collectionIds = Set(provider.collections.map { $0.id }) - + let missingNames = collectionLabels.subtracting(folderNames) let missingIds = collectionIds.subtracting(folderExternalIds) - + XCTAssertTrue(missingNames.isEmpty, "Collections with these labels have no corresponding folder.") XCTAssertTrue(missingIds.isEmpty, "Collections with these ids have no corresponding folder.") // XCTAssertEqual(mirrorOperation.collectionsAndFolders.count, provider.collections.count, "Mismatch between collections and folders.") } - + func testRemovesFolders() { let provider = CollectionsProvider() - + do { let addFolders = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) let completionExpectation = expectation(description: "Did Finish") addFolders.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(addFolders) - + waitForExpectations(timeout: 2) } - + // Now that the folders are added, remove them all. provider.collections = [] - + let removeFolders = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) let completionExpectation = expectation(description: "Did Finish") removeFolders.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(removeFolders) - + waitForExpectations(timeout: 2) - + let folders = account.folders ?? Set() let folderNames = Set(folders.compactMap { $0.nameForDisplay }) let folderExternalIds = Set(folders.compactMap { $0.externalID }) - + let collectionLabels = Set(provider.collections.map { $0.label }) let collectionIds = Set(provider.collections.map { $0.id }) - + let remainingNames = folderNames.subtracting(collectionLabels) let remainingIds = folderExternalIds.subtracting(collectionIds) - + XCTAssertTrue(remainingNames.isEmpty, "Folders with these names remain with no corresponding collection.") XCTAssertTrue(remainingIds.isEmpty, "Folders with these ids remain with no corresponding collection.") - + XCTAssertTrue(removeFolders.feedsAndFolders.isEmpty) } - + final class CollectionsAndFeedsProvider: FeedlyCollectionProviding { var feedsForCollectionOne = [ FeedlyFeed(id: "feed/1", title: "Feed One", updated: nil, website: nil), FeedlyFeed(id: "feed/2", title: "Feed Two", updated: nil, website: nil) ] - + var feedsForCollectionTwo = [ FeedlyFeed(id: "feed/1", title: "Feed One", updated: nil, website: nil), FeedlyFeed(id: "feed/3", title: "Feed Three", updated: nil, website: nil), ] - + var collections: [FeedlyCollection] { return [ FeedlyCollection(feeds: feedsForCollectionOne, label: "One", id: "collections/1"), @@ -123,7 +123,7 @@ final class FeedlyMirrorCollectionsAsFoldersOperationTests: XCTestCase { ] } } - + func testFeedMappedToFolders() { let provider = CollectionsAndFeedsProvider() let mirrorOperation = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) @@ -131,74 +131,74 @@ final class FeedlyMirrorCollectionsAsFoldersOperationTests: XCTestCase { mirrorOperation.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(mirrorOperation) - + waitForExpectations(timeout: 2) - + let folders = account.folders ?? Set() let folderNames = Set(folders.compactMap { $0.nameForDisplay }) let folderExternalIds = Set(folders.compactMap { $0.externalID }) - + let collectionLabels = Set(provider.collections.map { $0.label }) let collectionIds = Set(provider.collections.map { $0.id }) - + let missingNames = collectionLabels.subtracting(folderNames) let missingIds = collectionIds.subtracting(folderExternalIds) - + XCTAssertTrue(missingNames.isEmpty, "Collections with these labels have no corresponding folder.") XCTAssertTrue(missingIds.isEmpty, "Collections with these ids have no corresponding folder.") - + let collectionIdsAndFeedIds = provider.collections.map { collection -> [String:[String]] in return [collection.id: collection.feeds.map { $0.id }.sorted(by: <)] } - + let folderIdsAndFeedIds = mirrorOperation.feedsAndFolders.compactMap { feeds, folder -> [String:[String]]? in guard let id = folder.externalID else { return nil } return [id: feeds.map { $0.id }.sorted(by: <)] } - + XCTAssertEqual(collectionIdsAndFeedIds, folderIdsAndFeedIds, "Did not map folders to feeds correctly.") } - + func testRemovingFolderRemovesFeeds() { do { let provider = CollectionsAndFeedsProvider() let addFoldersAndFeeds = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) - + let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: addFoldersAndFeeds) MainThreadOperationQueue.shared.make(createFeeds, dependOn: addFoldersAndFeeds) - + let completionExpectation = expectation(description: "Did Finish") createFeeds.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.addOperations([addFoldersAndFeeds, createFeeds]) - + waitForExpectations(timeout: 2) - + XCTAssertFalse(account.flattenedFeeds().isEmpty, "Expected account to have feeds.") } - + // Now that the folders are added, remove them all. let provider = CollectionsProvider() provider.collections = [] - + let removeFolders = FeedlyMirrorCollectionsAsFoldersOperation(account: account, collectionsProvider: provider) let completionExpectation = expectation(description: "Did Finish") removeFolders.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(removeFolders) - + waitForExpectations(timeout: 2) - + let feeds = account.flattenedFeeds() - + XCTAssertTrue(feeds.isEmpty) } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyOperationTests.swift index 096c0defe..bbbd9d55f 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyOperationTests.swift @@ -12,23 +12,23 @@ import RSWeb import RSCore final class FeedlyOperationTests: XCTestCase { - + enum TestOperationError: Error, Equatable { case mockError case anotherMockError } - + final class TestOperation: FeedlyOperation { var didCallMainExpectation: XCTestExpectation? var mockError: Error? - + override func run() { super.run() // Should always call on main thread. XCTAssertTrue(Thread.isMainThread) - + didCallMainExpectation?.fulfill() - + if let error = mockError { didFinish(with: error) } else { @@ -36,12 +36,12 @@ final class FeedlyOperationTests: XCTestCase { } } } - + final class TestDelegate: FeedlyOperationDelegate { - + var error: Error? var didFailExpectation: XCTestExpectation? - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { didFailExpectation?.fulfill() self.error = error @@ -51,9 +51,9 @@ final class FeedlyOperationTests: XCTestCase { func testDoesCallMain() { let testOperation = TestOperation() testOperation.didCallMainExpectation = expectation(description: "Did Call Main") - + MainThreadOperationQueue.shared.add(testOperation) - + waitForExpectations(timeout: 2) } @@ -61,63 +61,63 @@ final class FeedlyOperationTests: XCTestCase { let testOperation = TestOperation() testOperation.didCallMainExpectation = expectation(description: "Did Call Main") testOperation.mockError = TestOperationError.mockError - + let delegate = TestDelegate() delegate.didFailExpectation = expectation(description: "Operation Failed As Expected") - + testOperation.delegate = delegate - + MainThreadOperationQueue.shared.add(testOperation) - + waitForExpectations(timeout: 2) - + if let error = delegate.error as? TestOperationError { XCTAssertEqual(error, TestOperationError.mockError) } else { XCTFail("Expected \(TestOperationError.self) but got \(String(describing: delegate.error)).") } } - + func testOperationFlags() { let testOperation = TestOperation() testOperation.didCallMainExpectation = expectation(description: "Did Call Main") - + let completionExpectation = expectation(description: "Operation Completed") testOperation.completionBlock = { _ in completionExpectation.fulfill() } - + XCTAssertFalse(testOperation.isCanceled) - + MainThreadOperationQueue.shared.add(testOperation) - + waitForExpectations(timeout: 2) - + XCTAssertFalse(testOperation.isCanceled) } - + func testOperationCancellationFlags() { let testOperation = TestOperation() testOperation.didCallMainExpectation = expectation(description: "Did Call Main") testOperation.didCallMainExpectation?.isInverted = true - + let completionExpectation = expectation(description: "Operation Completed") testOperation.completionBlock = { _ in completionExpectation.fulfill() } - + XCTAssertFalse(testOperation.isCanceled) - + MainThreadOperationQueue.shared.add(testOperation) - + MainThreadOperationQueue.shared.cancelOperations([testOperation]) - + waitForExpectations(timeout: 2) - + XCTAssertTrue(testOperation.isCanceled) } - + func testDependency() { // let testOperation = TestOperation() // testOperation.didCallMainExpectation = expectation(description: "Did Call Main") diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyOrganiseParsedItemsByFeedOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyOrganiseParsedItemsByFeedOperationTests.swift index 550b14cba..2064c079a 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyOrganiseParsedItemsByFeedOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyOrganiseParsedItemsByFeedOperationTests.swift @@ -12,87 +12,87 @@ import RSParser import RSCore final class FeedlyOrganiseParsedItemsByFeedOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + struct TestParsedItemsProvider: FeedlyParsedItemProviding { let parsedItemProviderName = "TestParsedItemsProvider" var resource: FeedlyResourceId var parsedEntries: Set } - + func testNoEntries() { let entries = support.makeParsedItemTestDataFor(numberOfFeeds: 0, numberOfItemsInFeeds: 0) let resource = FeedlyCategoryResourceId(id: "user/12345/category/6789") let parsedEntries = Set(entries.values.flatMap { $0 }) let provider = TestParsedItemsProvider(resource: resource, parsedEntries: parsedEntries) - + let organise = FeedlyOrganiseParsedItemsByFeedOperation(account: account, parsedItemProvider: provider) - + let completionExpectation = expectation(description: "Did Finish") organise.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(organise) - + waitForExpectations(timeout: 2) - + let itemsAndFeedIds = organise.parsedItemsKeyedByFeedId XCTAssertEqual(itemsAndFeedIds, entries) } - + func testGroupsOneEntryByFeedId() { let entries = support.makeParsedItemTestDataFor(numberOfFeeds: 1, numberOfItemsInFeeds: 1) let resource = FeedlyCategoryResourceId(id: "user/12345/category/6789") let parsedEntries = Set(entries.values.flatMap { $0 }) let provider = TestParsedItemsProvider(resource: resource, parsedEntries: parsedEntries) - + let organise = FeedlyOrganiseParsedItemsByFeedOperation(account: account, parsedItemProvider: provider) - + let completionExpectation = expectation(description: "Did Finish") organise.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(organise) - + waitForExpectations(timeout: 2) - + let itemsAndFeedIds = organise.parsedItemsKeyedByFeedId XCTAssertEqual(itemsAndFeedIds, entries) } - + func testGroupsManyEntriesByFeedId() { let entries = support.makeParsedItemTestDataFor(numberOfFeeds: 100, numberOfItemsInFeeds: 100) let resource = FeedlyCategoryResourceId(id: "user/12345/category/6789") let parsedEntries = Set(entries.values.flatMap { $0 }) let provider = TestParsedItemsProvider(resource: resource, parsedEntries: parsedEntries) - + let organise = FeedlyOrganiseParsedItemsByFeedOperation(account: account, parsedItemProvider: provider) - + let completionExpectation = expectation(description: "Did Finish") organise.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(organise) - + waitForExpectations(timeout: 2) - + let itemsAndFeedIds = organise.parsedItemsKeyedByFeedId XCTAssertEqual(itemsAndFeedIds, entries) } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyRefreshAccessTokenOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyRefreshAccessTokenOperationTests.swift index 7c4e25dd4..5f6272b8a 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyRefreshAccessTokenOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyRefreshAccessTokenOperationTests.swift @@ -13,29 +13,29 @@ import RSCore import Secrets final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + final class TestRefreshTokenService: OAuthAccessTokenRefreshing { var mockResult: Result? var refreshAccessTokenExpectation: XCTestExpectation? var parameterTester: ((String, OAuthAuthorizationClient) -> ())? - + func refreshAccessToken(with refreshToken: String, client: OAuthAuthorizationClient, completion: @escaping (Result) -> ()) { - + guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") return @@ -47,64 +47,64 @@ final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { } } } - + func testCancel() { let service = TestRefreshTokenService() service.refreshAccessTokenExpectation = expectation(description: "Did Call Refresh") service.refreshAccessTokenExpectation?.isInverted = true - + let client = support.makeMockOAuthClient() let refresh = FeedlyRefreshAccessTokenOperation(account: account, service: service, oauthClient: client) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") refresh.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(refresh) - + MainThreadOperationQueue.shared.cancelOperations([refresh]) - + waitForExpectations(timeout: 1) - + XCTAssertTrue(refresh.isCanceled) } - + final class TestRefreshTokenDelegate: FeedlyOperationDelegate { var error: Error? var didFailExpectation: XCTestExpectation? - + func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { self.error = error didFailExpectation?.fulfill() } } - + func testMissingRefreshToken() { support.removeCredentials(matching: .oauthRefreshToken, from: account) - + let service = TestRefreshTokenService() service.refreshAccessTokenExpectation = expectation(description: "Did Call Refresh") service.refreshAccessTokenExpectation?.isInverted = true - + let client = support.makeMockOAuthClient() let refresh = FeedlyRefreshAccessTokenOperation(account: account, service: service, oauthClient: client) let delegate = TestRefreshTokenDelegate() delegate.didFailExpectation = expectation(description: "Did Fail") refresh.delegate = delegate - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") refresh.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(refresh) - + waitForExpectations(timeout: 1) - + XCTAssertNotNil(delegate.error, "Should have failed with error.") if let error = delegate.error { switch error { @@ -120,16 +120,16 @@ final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { } } } - + func testRefreshTokenSuccess() { let service = TestRefreshTokenService() service.refreshAccessTokenExpectation = expectation(description: "Did Call Refresh") - + let mockAccessToken = Credentials(type: .oauthAccessToken, username: "Test", secret: UUID().uuidString) let mockRefreshToken = Credentials(type: .oauthRefreshToken, username: "Test", secret: UUID().uuidString) let grant = OAuthAuthorizationGrant(accessToken: mockAccessToken, refreshToken: mockRefreshToken) service.mockResult = .success(grant) - + let client = support.makeMockOAuthClient() service.parameterTester = { serviceRefreshToken, serviceClient in if let accountRefreshToken = try! self.account.retrieveCredentials(type: .oauthRefreshToken) { @@ -139,34 +139,34 @@ final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { } XCTAssertEqual(serviceClient, client) } - + let refresh = FeedlyRefreshAccessTokenOperation(account: account, service: service, oauthClient: client) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") refresh.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(refresh) - + waitForExpectations(timeout: 1) - + do { let accessToken = try account.retrieveCredentials(type: .oauthAccessToken) XCTAssertEqual(accessToken, mockAccessToken) - + let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) XCTAssertEqual(refreshToken, mockRefreshToken) } catch { XCTFail("Could not verify refresh and access tokens because \(error).") } } - + func testRefreshTokenFailure() { let accessTokenBefore: Credentials let refreshTokenBefore: Credentials - + do { guard let accessToken = try account.retrieveCredentials(type: .oauthAccessToken), let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) else { @@ -179,11 +179,11 @@ final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { XCTFail("Caught error getting initial refresh and access tokens because \(error).") return } - + let service = TestRefreshTokenService() service.refreshAccessTokenExpectation = expectation(description: "Did Call Refresh") service.mockResult = .failure(URLError(.timedOut)) - + let client = support.makeMockOAuthClient() service.parameterTester = { serviceRefreshToken, serviceClient in if let accountRefreshToken = try! self.account.retrieveCredentials(type: .oauthRefreshToken) { @@ -193,23 +193,23 @@ final class FeedlyRefreshAccessTokenOperationTests: XCTestCase { } XCTAssertEqual(serviceClient, client) } - + let refresh = FeedlyRefreshAccessTokenOperation(account: account, service: service, oauthClient: client) - + // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") refresh.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(refresh) - + waitForExpectations(timeout: 1) - + do { let accessToken = try account.retrieveCredentials(type: .oauthAccessToken) XCTAssertEqual(accessToken, accessTokenBefore) - + let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) XCTAssertEqual(refreshToken, refreshTokenBefore) } catch { diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyResourceIdTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyResourceIdTests.swift index ad7387f28..7761af0cb 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyResourceIdTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyResourceIdTests.swift @@ -10,15 +10,15 @@ import XCTest @testable import Account final class FeedlyResourceIdTests: XCTestCase { - + func testFeedResourceId() { let expectedUrl = "http://ranchero.com/blog/atom.xml" - + let feedResource = FeedlyFeedResourceId(id: "feed/\(expectedUrl)") let urlResource = FeedlyFeedResourceId(id: expectedUrl) let otherResource = FeedlyFeedResourceId(id: "whiskey/\(expectedUrl)") let invalidResource = FeedlyFeedResourceId(id: "") - + XCTAssertEqual(feedResource.url, expectedUrl) XCTAssertEqual(urlResource.url, expectedUrl) XCTAssertEqual(otherResource.url, otherResource.id) diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlySendArticleStatusesOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlySendArticleStatusesOperationTests.swift index 7520d3c97..eceec4f12 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlySendArticleStatusesOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlySendArticleStatusesOperationTests.swift @@ -13,17 +13,17 @@ import Articles import RSCore final class FeedlySendArticleStatusesOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() private var container: FeedlyTestSupport.TestDatabaseContainer! - + override func setUp() { super.setUp() account = support.makeTestAccount() container = support.makeTestDatabaseContainer() } - + override func tearDown() { container = nil if let account = account { @@ -31,51 +31,51 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } super.tearDown() } - + func testSendEmpty() { let service = TestMarkArticlesService() let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) } - + func testSendUnreadSuccess() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .read, flag: false) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .success(()) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .unread) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -88,37 +88,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendUnreadFailure() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .read, flag: false) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .failure(URLError(.timedOut)) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .unread) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -131,37 +131,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendReadSuccess() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .read, flag: true) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .success(()) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .read) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -174,37 +174,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendReadFailure() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .read, flag: true) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .failure(URLError(.timedOut)) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .read) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -217,37 +217,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendStarredSuccess() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .starred, flag: true) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .success(()) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .saved) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -260,37 +260,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendStarredFailure() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .starred, flag: true) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .failure(URLError(.timedOut)) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .saved) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -303,37 +303,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendUnstarredSuccess() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .starred, flag: false) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .success(()) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .unsaved) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -346,37 +346,37 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendUnstarredFailure() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let statuses = articleIds.map { SyncStatus(articleID: $0, key: .starred, flag: false) } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .failure(URLError(.timedOut)) service.parameterTester = { serviceArticleIds, action in XCTAssertEqual(serviceArticleIds, articleIds) XCTAssertEqual(action, .unsaved) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -389,7 +389,7 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendAllSuccess() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let keys = [SyncStatus.Key.read, .starred] @@ -400,15 +400,15 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { let status = SyncStatus(articleID: articleId, key: key, flag: flag) return status } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .success(()) service.parameterTester = { serviceArticleIds, action in @@ -427,16 +427,16 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { XCTAssertEqual(serviceArticleIds, expectedArticleIds) } let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { @@ -449,7 +449,7 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { } waitForExpectations(timeout: 2) } - + func testSendAllFailure() { let articleIds = Set((0..<100).map { "feed/0/article/\($0)" }) let keys = [SyncStatus.Key.read, .starred] @@ -460,15 +460,15 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { let status = SyncStatus(articleID: articleId, key: key, flag: flag) return status } - + let insertExpectation = expectation(description: "Inserted Statuses") container.database.insertStatuses(statuses) { error in XCTAssertNil(error) insertExpectation.fulfill() } - + waitForExpectations(timeout: 2) - + let service = TestMarkArticlesService() service.mockResult = .failure(URLError(.timedOut)) service.parameterTester = { serviceArticleIds, action in @@ -486,18 +486,18 @@ final class FeedlySendArticleStatusesOperationTests: XCTestCase { let expectedArticleIds = Set(syncStatuses.map { $0.articleID }) XCTAssertEqual(serviceArticleIds, expectedArticleIds) } - + let send = FeedlySendArticleStatusesOperation(database: container.database, service: service) - + let didFinishExpectation = expectation(description: "Did Finish") send.completionBlock = { _ in didFinishExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(send) - + waitForExpectations(timeout: 2) - + let selectPendingCountExpectation = expectation(description: "Did Select Pending Count") container.database.selectPendingCount { result in do { diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncAllMockResponseProvider.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncAllMockResponseProvider.swift index 5695a9dde..d017ec120 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncAllMockResponseProvider.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncAllMockResponseProvider.swift @@ -9,62 +9,62 @@ import Foundation final class FeedlyMockResponseProvider: TestTransportMockResponseProviding { - + let subdirectory: String - + init(findingMocksIn subdirectory: String) { self.subdirectory = subdirectory } - + func mockResponseFileUrl(for components: URLComponents) -> URL? { let bundle = Bundle(for: FeedlyMockResponseProvider.self) - + // Match request for collections to build a list of folders. if components.path.contains("v3/collections") { return bundle.url(forResource: "collections", withExtension: "json", subdirectory: subdirectory) } - + guard let queryItems = components.queryItems else { return nil } - + // Match requests for starred articles from global.saved. if components.path.contains("streams/contents") && queryItems.contains(where: { ($0.value ?? "").contains("global.saved") }) { return bundle.url(forResource: "starred", withExtension: "json", subdirectory: subdirectory) } - + let continuation = queryItems.first(where: { $0.name.contains("continuation") })?.value - + // Match requests for unread article ids. if components.path.contains("streams/ids") && queryItems.contains(where: { $0.name.contains("unreadOnly") }) { - + // if there is a continuation, return the page for it if let continuation = continuation, let data = continuation.data(using: .utf8) { let base64 = data.base64EncodedString() // at least base64 can be used as a path component. return bundle.url(forResource: "unreadIds@\(base64)", withExtension: "json", subdirectory: subdirectory) - + } else { // return first page return bundle.url(forResource: "unreadIds", withExtension: "json", subdirectory: subdirectory) } } - + // Match requests for the contents of global.all. if components.path.contains("streams/contents") && queryItems.contains(where: { ($0.value ?? "").contains("global.all") }){ - + // if there is a continuation, return the page for it if let continuation = continuation, let data = continuation.data(using: .utf8) { let base64 = data.base64EncodedString() // at least base64 can be used as a path component. return bundle.url(forResource: "global.all@\(base64)", withExtension: "json", subdirectory: subdirectory) - + } else { // return first page return bundle.url(forResource: "global.all", withExtension: "json", subdirectory: subdirectory) } } - + return nil } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncStreamContentsOperationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncStreamContentsOperationTests.swift index daa392eae..70c6bf335 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncStreamContentsOperationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlySyncStreamContentsOperationTests.swift @@ -11,32 +11,32 @@ import XCTest import RSCore final class FeedlySyncStreamContentsOperationTests: XCTestCase { - + private var account: Account! private let support = FeedlyTestSupport() - + override func setUp() { super.setUp() account = support.makeTestAccount() } - + override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } - + func testIngestsOnePageSuccess() throws { let service = TestGetStreamContentsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") let newerThan: Date? = Date(timeIntervalSinceReferenceDate: 0) let items = service.makeMockFeedlyEntryItem() service.mockResult = .success(FeedlyStream(id: resource.id, updated: nil, continuation: nil, items: items)) - + let getStreamContentsExpectation = expectation(description: "Did Get Page of Stream Contents") getStreamContentsExpectation.expectedFulfillmentCount = 1 - + service.getStreamContentsExpectation = getStreamContentsExpectation service.parameterTester = { serviceResource, continuation, serviceNewerThan, serviceUnreadOnly in XCTAssertEqual(serviceResource.id, resource.id) @@ -44,33 +44,33 @@ final class FeedlySyncStreamContentsOperationTests: XCTestCase { XCTAssertNil(continuation) XCTAssertNil(serviceUnreadOnly) } - + let syncStreamContents = FeedlySyncStreamContentsOperation(account: account, resource: resource, service: service, isPagingEnabled: true, newerThan: newerThan) - + let completionExpectation = expectation(description: "Did Finish") syncStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(syncStreamContents) - + waitForExpectations(timeout: 2) - + let expectedArticleIds = Set(items.map { $0.id }) let expectedArticles = try account.fetchArticles(.articleIDs(expectedArticleIds)) XCTAssertEqual(expectedArticles.count, expectedArticleIds.count, "Did not fetch all the articles.") } - + func testIngestsOnePageFailure() { let service = TestGetStreamContentsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") let newerThan: Date? = Date(timeIntervalSinceReferenceDate: 0) - + service.mockResult = .failure(URLError(.timedOut)) - + let getStreamContentsExpectation = expectation(description: "Did Get Page of Stream Contents") getStreamContentsExpectation.expectedFulfillmentCount = 1 - + service.getStreamContentsExpectation = getStreamContentsExpectation service.parameterTester = { serviceResource, continuation, serviceNewerThan, serviceUnreadOnly in XCTAssertEqual(serviceResource.id, resource.id) @@ -78,59 +78,59 @@ final class FeedlySyncStreamContentsOperationTests: XCTestCase { XCTAssertNil(continuation) XCTAssertNil(serviceUnreadOnly) } - + let syncStreamContents = FeedlySyncStreamContentsOperation(account: account, resource: resource, service: service, isPagingEnabled: true, newerThan: newerThan) - + let completionExpectation = expectation(description: "Did Finish") syncStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(syncStreamContents) - + waitForExpectations(timeout: 2) } - + func testIngestsManyPagesSuccess() throws { let service = TestGetPagedStreamContentsService() let resource = FeedlyCategoryResourceId(id: "user/1234/category/5678") let newerThan: Date? = Date(timeIntervalSinceReferenceDate: 0) - + let continuations = (1...10).map { "\($0)" } service.addAtLeastOnePage(for: resource, continuations: continuations, numberOfEntriesPerPage: 1000) - + let getStreamContentsExpectation = expectation(description: "Did Get Page of Stream Contents") getStreamContentsExpectation.expectedFulfillmentCount = 1 + continuations.count - + var remainingContinuations = Set(continuations) let getStreamPageExpectation = expectation(description: "Did Request Page") getStreamPageExpectation.expectedFulfillmentCount = 1 + continuations.count - + service.getStreamContentsExpectation = getStreamContentsExpectation service.parameterTester = { serviceResource, continuation, serviceNewerThan, serviceUnreadOnly in XCTAssertEqual(serviceResource.id, resource.id) XCTAssertEqual(serviceNewerThan, newerThan) XCTAssertNil(serviceUnreadOnly) - + if let continuation = continuation { XCTAssertTrue(remainingContinuations.contains(continuation)) remainingContinuations.remove(continuation) } - + getStreamPageExpectation.fulfill() } - + let syncStreamContents = FeedlySyncStreamContentsOperation(account: account, resource: resource, service: service, isPagingEnabled: true, newerThan: newerThan) - + let completionExpectation = expectation(description: "Did Finish") syncStreamContents.completionBlock = { _ in completionExpectation.fulfill() } - + MainThreadOperationQueue.shared.add(syncStreamContents) - + waitForExpectations(timeout: 30) - + // Find articles inserted. let articleIds = Set(service.pages.values.map { $0.items }.flatMap { $0 }.map { $0.id }) let articles = try account.fetchArticles(.articleIDs(articleIds)) diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift index 29dc69a0d..c26d98dc5 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift @@ -18,17 +18,17 @@ final class FeedlyTestSupport { var accessToken = Credentials(type: .oauthAccessToken, username: "Test", secret: "t3st-access-tok3n") var refreshToken = Credentials(type: .oauthRefreshToken, username: "Test", secret: "t3st-refresh-tok3n") var transport = TestTransport() - + init() { SecretsManager.provider = FeedlyTestSecrets() } - + func makeMockNetworkStack() -> (TestTransport, FeedlyAPICaller) { let caller = FeedlyAPICaller(transport: transport, api: .sandbox) caller.credentials = accessToken return (transport, caller) } - + func makeTestAccount() -> Account { let manager = TestAccountManager() let account = manager.createAccount(type: .feedly, transport: transport) @@ -41,11 +41,11 @@ final class FeedlyTestSupport { } return account } - + func makeMockOAuthClient() -> OAuthAuthorizationClient { return OAuthAuthorizationClient(id: "test", redirectUri: "test://test/auth", state: nil, secret: "password") } - + func removeCredentials(matching type: CredentialsType, from account: Account) { do { try account.removeCredentials(type: type) @@ -53,21 +53,21 @@ final class FeedlyTestSupport { XCTFail("Unable to remove \(type)") } } - + func makeTestDatabaseContainer() -> TestDatabaseContainer { return TestDatabaseContainer() } - + final class TestDatabaseContainer { private let path: String private(set) var database: SyncDatabase! - + init() { let dataFolder = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) path = dataFolder.appendingPathComponent("\(UUID().uuidString)-Sync.sqlite3").path database = SyncDatabase(databaseFilePath: path) } - + deinit { // We should close the database before removing the database. database = nil @@ -79,7 +79,7 @@ final class FeedlyTestSupport { } } } - + func destroy(_ testAccount: Account) { do { // These should not throw when the keychain items are not found. @@ -88,44 +88,44 @@ final class FeedlyTestSupport { } catch { XCTFail("Unable to clean up mock credentials because \(error)") } - + let manager = TestAccountManager() manager.deleteAccount(testAccount) } - + func testJSON(named: String, subdirectory: String? = nil) -> Any { let url = Bundle.module.url(forResource: named, withExtension: "json", subdirectory: subdirectory)! let data = try! Data(contentsOf: url) let json = try! JSONSerialization.jsonObject(with: data) return json } - + func checkFoldersAndFeeds(in account: Account, againstCollectionsAndFeedsInJSONNamed name: String, subdirectory: String? = nil) { let collections = testJSON(named: name, subdirectory: subdirectory) as! [[String:Any]] let collectionNames = Set(collections.map { $0["label"] as! String }) let collectionIds = Set(collections.map { $0["id"] as! String }) - + let folders = account.folders ?? Set() let folderNames = Set(folders.compactMap { $0.name }) let folderIds = Set(folders.compactMap { $0.externalID }) - + let missingNames = collectionNames.subtracting(folderNames) let missingIds = collectionIds.subtracting(folderIds) - + XCTAssertEqual(folders.count, collections.count, "Mismatch between collections and folders.") XCTAssertTrue(missingNames.isEmpty, "Collections with these names did not have a corresponding folder with the same name.") XCTAssertTrue(missingIds.isEmpty, "Collections with these ids did not have a corresponding folder with the same id.") - + for collection in collections { checkSingleFolderAndFeeds(in: account, againstOneCollectionAndFeedsInJSONPayload: collection) } } - + func checkSingleFolderAndFeeds(in account: Account, againstOneCollectionAndFeedsInJSONNamed name: String) { let collection = testJSON(named: name) as! [String:Any] checkSingleFolderAndFeeds(in: account, againstOneCollectionAndFeedsInJSONPayload: collection) } - + func checkSingleFolderAndFeeds(in account: Account, againstOneCollectionAndFeedsInJSONPayload collection: [String: Any]) { let label = collection["label"] as! String guard let folder = account.existingFolder(with: label) else { @@ -135,32 +135,32 @@ final class FeedlyTestSupport { } let collectionFeeds = collection["feeds"] as! [[String: Any]] let folderFeeds = folder.topLevelFeeds - + XCTAssertEqual(collectionFeeds.count, folderFeeds.count) - + let collectionFeedIds = Set(collectionFeeds.map { $0["id"] as! String }) let folderFeedIds = Set(folderFeeds.map { $0.feedID }) let missingFeedIds = collectionFeedIds.subtracting(folderFeedIds) - + XCTAssertTrue(missingFeedIds.isEmpty, "Feeds with these ids were not found in the \"\(label)\" folder.") } - + func checkArticles(in account: Account, againstItemsInStreamInJSONNamed name: String, subdirectory: String? = nil) throws { let stream = testJSON(named: name, subdirectory: subdirectory) as! [String:Any] try checkArticles(in: account, againstItemsInStreamInJSONPayload: stream) } - + func checkArticles(in account: Account, againstItemsInStreamInJSONPayload stream: [String: Any]) throws { try checkArticles(in: account, correspondToStreamItemsIn: stream) } - + private struct ArticleItem { var id: String var feedId: String var content: String var JSON: [String: Any] var unread: Bool - + /// Convoluted external URL logic "documented" here: /// https://groups.google.com/forum/#!searchin/feedly-cloud/feed$20url%7Csort:date/feedly-cloud/Rx3dVd4aTFQ/Hf1ZfLJoCQAJ var externalUrl: String? { @@ -175,37 +175,37 @@ final class FeedlyTestSupport { return href }.first } - + init(item: [String: Any]) { self.JSON = item self.id = item["id"] as! String - + let origin = item["origin"] as! [String: Any] self.feedId = origin["streamId"] as! String - + let content = item["content"] as? [String: Any] let summary = item["summary"] as? [String: Any] self.content = ((content ?? summary)?["content"] as? String) ?? "" - + self.unread = item["unread"] as! Bool } } - + /// Awkwardly titled to make it clear the JSON given is from a stream response. func checkArticles(in testAccount: Account, correspondToStreamItemsIn stream: [String: Any]) throws { let items = stream["items"] as! [[String: Any]] let articleItems = items.map { ArticleItem(item: $0) } let itemIds = Set(articleItems.map { $0.id }) - + let articles = try testAccount.fetchArticles(.articleIDs(itemIds)) let articleIds = Set(articles.map { $0.articleID }) - + let missing = itemIds.subtracting(articleIds) - + XCTAssertEqual(items.count, articles.count) XCTAssertTrue(missing.isEmpty, "Items with these ids did not have a corresponding article with the same id.") - + for article in articles { for item in articleItems where item.id == article.articleID { XCTAssertEqual(article.uniqueID, item.id) @@ -215,12 +215,12 @@ final class FeedlyTestSupport { } } } - + func checkUnreadStatuses(in account: Account, againstIdsInStreamInJSONNamed name: String, subdirectory: String? = nil, testCase: XCTestCase) { let streamIds = testJSON(named: name, subdirectory: subdirectory) as! [String:Any] checkUnreadStatuses(in: account, correspondToIdsInJSONPayload: streamIds, testCase: testCase) } - + func checkUnreadStatuses(in testAccount: Account, correspondToIdsInJSONPayload streamIds: [String: Any], testCase: XCTestCase) { let ids = Set(streamIds["ids"] as! [String]) let fetchIdsExpectation = testCase.expectation(description: "Fetch Article Ids") @@ -238,12 +238,12 @@ final class FeedlyTestSupport { } testCase.wait(for: [fetchIdsExpectation], timeout: 2) } - + func checkStarredStatuses(in account: Account, againstItemsInStreamInJSONNamed name: String, subdirectory: String? = nil, testCase: XCTestCase) { let streamIds = testJSON(named: name, subdirectory: subdirectory) as! [String:Any] checkStarredStatuses(in: account, correspondToStreamItemsIn: streamIds, testCase: testCase) } - + func checkStarredStatuses(in testAccount: Account, correspondToStreamItemsIn stream: [String: Any], testCase: XCTestCase) { let items = stream["items"] as! [[String: Any]] let ids = Set(items.map { $0["id"] as! String }) @@ -262,27 +262,27 @@ final class FeedlyTestSupport { } testCase.wait(for: [fetchIdsExpectation], timeout: 2) } - + func check(_ entries: [FeedlyEntry], correspondToStreamItemsIn stream: [String: Any]) { - + let items = stream["items"] as! [[String: Any]] let itemIds = Set(items.map { $0["id"] as! String }) - + let articleIds = Set(entries.map { $0.id }) - + let missing = itemIds.subtracting(articleIds) - + XCTAssertEqual(items.count, entries.count) XCTAssertTrue(missing.isEmpty, "Failed to create \(FeedlyEntry.self) values from objects in the JSON with these ids.") } - + func makeParsedItemTestDataFor(numberOfFeeds: Int, numberOfItemsInFeeds: Int) -> [String: Set] { let ids = (0.. (String, [Int]) in return (feedId, (0.. (String, Set) in let items = pair.1.map { index -> ParsedItem in ParsedItem(syncServiceID: "\(pair.0)/articles/\(index)", @@ -310,7 +310,7 @@ final class FeedlyTestSupport { mutant[pair.0] = pair.1 return mutant } - + return entries } } diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTextSanitizationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTextSanitizationTests.swift index aece9a909..15b751ff8 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTextSanitizationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTextSanitizationTests.swift @@ -10,9 +10,9 @@ import XCTest @testable import Account final class FeedlyTextSanitizationTests: XCTestCase { - + func testRTLSanitization() { - + let targetsAndExpectations: [(target: String?, expectation: String?)] = [ (nil, nil), ("", ""), @@ -27,9 +27,9 @@ final class FeedlyTextSanitizationTests: XCTestCase { ("
", "
"), ("
text
", "text"), ] - + let sanitizer = FeedlyRTLTextSanitizer() - + for (target, expectation) in targetsAndExpectations { let calculated = sanitizer.sanitize(target) XCTAssertEqual(expectation, calculated) diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetCollectionsService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetCollectionsService.swift index 7f6b89813..24236e4a9 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetCollectionsService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetCollectionsService.swift @@ -12,7 +12,7 @@ import XCTest final class TestGetCollectionsService: FeedlyGetCollectionsService { var mockResult: Result<[FeedlyCollection], Error>? var getCollectionsExpectation: XCTestExpectation? - + func getCollections(completion: @escaping (Result<[FeedlyCollection], Error>) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetEntriesService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetEntriesService.swift index 7af98b393..46125781e 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetEntriesService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetEntriesService.swift @@ -12,7 +12,7 @@ import XCTest final class TestGetEntriesService: FeedlyGetEntriesService { var mockResult: Result<[FeedlyEntry], Error>? var getEntriesExpectation: XCTestExpectation? - + func getEntries(for ids: Set, completion: @escaping (Result<[FeedlyEntry], Error>) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamContentsService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamContentsService.swift index 979134404..1dccaa06b 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamContentsService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamContentsService.swift @@ -10,14 +10,14 @@ import XCTest @testable import Account final class TestGetPagedStreamContentsService: FeedlyGetStreamContentsService { - + var parameterTester: ((FeedlyResourceId, String?, Date?, Bool?) -> ())? var getStreamContentsExpectation: XCTestExpectation? var pages = [String: FeedlyStream]() - + func addAtLeastOnePage(for resource: FeedlyResourceId, continuations: [String], numberOfEntriesPerPage count: Int) { pages = [String: FeedlyStream](minimumCapacity: continuations.count + 1) - + // A continuation is an identifier for the next page. // The first page has a nil identifier. // The last page has no next page, so the next continuation value for that page is nil. @@ -30,16 +30,16 @@ final class TestGetPagedStreamContentsService: FeedlyGetStreamContentsService { pages[key] = page } } - + private func makeStreamContents(for resource: FeedlyResourceId, continuation: String?, between range: Range) -> FeedlyStream { let entries = range.map { index -> FeedlyEntry in let content = FeedlyEntry.Content(content: "Content \(index)", direction: .leftToRight) - + let origin = FeedlyOrigin(title: "Origin \(index)", streamId: resource.id, htmlUrl: "http://localhost/feedly/origin/\(index)") - + return FeedlyEntry(id: "/articles/\(index)", title: "Article \(index)", content: content, @@ -55,16 +55,16 @@ final class TestGetPagedStreamContentsService: FeedlyGetStreamContentsService { categories: nil, enclosure: nil) } - + let stream = FeedlyStream(id: resource.id, updated: nil, continuation: continuation, items: entries) - + return stream } - + static func getPagingKey(for stream: FeedlyResourceId, continuation: String?) -> String { return "\(stream.id)@\(continuation ?? "")" } - + func getStreamContents(for resource: FeedlyResourceId, continuation: String?, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { let key = TestGetPagedStreamContentsService.getPagingKey(for: resource, continuation: continuation) guard let page = pages[key] else { diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamIdsService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamIdsService.swift index da09e094b..e3fc41ba2 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamIdsService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetPagedStreamIdsService.swift @@ -10,14 +10,14 @@ import XCTest @testable import Account final class TestGetPagedStreamIdsService: FeedlyGetStreamIdsService { - + var parameterTester: ((FeedlyResourceId, String?, Date?, Bool?) -> ())? var getStreamIdsExpectation: XCTestExpectation? var pages = [String: FeedlyStreamIds]() - + func addAtLeastOnePage(for resource: FeedlyResourceId, continuations: [String], numberOfEntriesPerPage count: Int) { pages = [String: FeedlyStreamIds](minimumCapacity: continuations.count + 1) - + // A continuation is an identifier for the next page. // The first page has a nil identifier. // The last page has no next page, so the next continuation value for that page is nil. @@ -30,17 +30,17 @@ final class TestGetPagedStreamIdsService: FeedlyGetStreamIdsService { pages[key] = page } } - + private func makeStreamIds(for resource: FeedlyResourceId, continuation: String?, between range: Range) -> FeedlyStreamIds { let entryIds = range.map { _ in UUID().uuidString } let stream = FeedlyStreamIds(continuation: continuation, ids: entryIds) return stream } - + static func getPagingKey(for stream: FeedlyResourceId, continuation: String?) -> String { return "\(stream.id)@\(continuation ?? "")" } - + func getStreamIds(for resource: FeedlyResourceId, continuation: String?, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { let key = TestGetPagedStreamIdsService.getPagingKey(for: resource, continuation: continuation) guard let page = pages[key] else { diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamContentsService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamContentsService.swift index c62fba4c5..75c959d2d 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamContentsService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamContentsService.swift @@ -10,11 +10,11 @@ import XCTest @testable import Account final class TestGetStreamContentsService: FeedlyGetStreamContentsService { - + var mockResult: Result? var parameterTester: ((FeedlyResourceId, String?, Date?, Bool?) -> ())? var getStreamContentsExpectation: XCTestExpectation? - + func getStreamContents(for resource: FeedlyResourceId, continuation: String?, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") @@ -26,7 +26,7 @@ final class TestGetStreamContentsService: FeedlyGetStreamContentsService { self.getStreamContentsExpectation?.fulfill() } } - + func makeMockFeedlyEntryItem() -> [FeedlyEntry] { let origin = FeedlyOrigin(title: "XCTest@localhost", streamId: "user/12345/category/67890", htmlUrl: "http://localhost/nnw/xctest") let content = FeedlyEntry.Content(content: "In the beginning...", direction: .leftToRight) diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamIdsService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamIdsService.swift index 5ae0de1c4..f240c3846 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamIdsService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestGetStreamIdsService.swift @@ -10,11 +10,11 @@ import XCTest @testable import Account final class TestGetStreamIdsService: FeedlyGetStreamIdsService { - + var mockResult: Result? var parameterTester: ((FeedlyResourceId, String?, Date?, Bool?) -> ())? var getStreamIdsExpectation: XCTestExpectation? - + func getStreamIds(for resource: FeedlyResourceId, continuation: String?, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") diff --git a/Modules/Account/Tests/AccountTests/Feedly/TestMarkArticlesService.swift b/Modules/Account/Tests/AccountTests/Feedly/TestMarkArticlesService.swift index d45418a96..ab734c475 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/TestMarkArticlesService.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/TestMarkArticlesService.swift @@ -10,13 +10,13 @@ import XCTest @testable import Account final class TestMarkArticlesService: FeedlyMarkArticlesService { - + var didMarkExpectation: XCTestExpectation? var parameterTester: ((Set, FeedlyMarkAction) -> ())? var mockResult: Result = .success(()) - + func mark(_ articleIds: Set, as action: FeedlyMarkAction, completion: @escaping (Result) -> ()) { - + DispatchQueue.main.async { self.parameterTester?(articleIds, action) completion(self.mockResult) diff --git a/Modules/Account/Tests/AccountTests/TestAccountManager.swift b/Modules/Account/Tests/AccountTests/TestAccountManager.swift index f4cacb006..f2e8e04f7 100644 --- a/Modules/Account/Tests/AccountTests/TestAccountManager.swift +++ b/Modules/Account/Tests/AccountTests/TestAccountManager.swift @@ -12,45 +12,45 @@ import RSWeb @testable import Account final class TestAccountManager { - + static let shared = TestAccountManager() - + var accountsFolder: URL { return try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) } - + func createAccount(type: AccountType, username: String? = nil, password: String? = nil, transport: Transport) -> Account { - + let accountID = UUID().uuidString let accountFolder = accountsFolder.appendingPathComponent("\(type.rawValue)_\(accountID)") - + do { try FileManager.default.createDirectory(at: accountFolder, withIntermediateDirectories: true, attributes: nil) } catch { assertionFailure("Could not create folder for \(accountID) account.") abort() } - + let account = Account(dataFolder: accountFolder.absoluteString, type: type, accountID: accountID, transport: transport) - + return account - + } - + func deleteAccount(_ account: Account) { - + do { try FileManager.default.removeItem(atPath: account.dataFolder) } catch let error as CocoaError where error.code == .fileNoSuchFile { - + } catch { assertionFailure("Could not delete folder at: \(account.dataFolder) because \(error)") abort() } - + } - + } diff --git a/Modules/Account/Tests/AccountTests/TestTransport.swift b/Modules/Account/Tests/AccountTests/TestTransport.swift index ed433abfe..8f7bdf010 100644 --- a/Modules/Account/Tests/AccountTests/TestTransport.swift +++ b/Modules/Account/Tests/AccountTests/TestTransport.swift @@ -15,23 +15,23 @@ protocol TestTransportMockResponseProviding: AnyObject { } final class TestTransport: Transport { - + enum TestTransportError: String, Error { case invalidState = "The test wasn't set up correctly." } - + var testFiles = [String: String]() var testStatusCodes = [String: Int]() - + weak var mockResponseFileUrlProvider: TestTransportMockResponseProviding? - + private func httpResponse(for request: URLRequest, statusCode: Int = 200) -> HTTPURLResponse { guard let url = request.url else { fatalError("Attempting to mock a http response for a request without a URL \(request).") } return HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: nil)! } - + func cancelAll() { } @discardableResult @@ -44,26 +44,26 @@ final class TestTransport: Transport { } func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) { - + guard let url = request.url, let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { completion(.failure(TestTransportError.invalidState)) return } - + let urlString = url.absoluteString let response = httpResponse(for: request, statusCode: testStatusCodes[urlString] ?? 200) let testFileURL: URL - + if let provider = mockResponseFileUrlProvider { guard let providerUrl = provider.mockResponseFileUrl(for: components) else { XCTFail("Test behaviour undefined. Mock provider failed to provide non-nil URL for \(components).") return } testFileURL = providerUrl - + } else if let testKeyAndFileName = testFiles.first(where: { urlString.contains($0.key) }) { testFileURL = Bundle.module.resourceURL!.appendingPathComponent(testKeyAndFileName.value) - + } else { // XCTFail("Missing mock response for: \(urlString)") print("***\nWARNING: \(self) missing mock response for:\n\(urlString)\n***") @@ -72,7 +72,7 @@ final class TestTransport: Transport { } return } - + do { let data = try Data(contentsOf: testFileURL) DispatchQueue.global(qos: .background).async { @@ -89,7 +89,7 @@ final class TestTransport: Transport { func send(request: URLRequest, method: String, completion: @escaping (Result) -> Void) { fatalError("Unimplemented.") } - + func send(request: URLRequest, method: String, payload: Data, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) { fatalError("Unimplemented.") } diff --git a/Modules/Articles/Sources/Articles/Article.swift b/Modules/Articles/Sources/Articles/Article.swift index 30ec95d2f..0280bd756 100644 --- a/Modules/Articles/Sources/Articles/Article.swift +++ b/Modules/Articles/Sources/Articles/Article.swift @@ -45,7 +45,7 @@ public final class Article: Hashable { self.dateModified = dateModified self.authors = authors self.status = status - + if let articleID = articleID { self.articleID = articleID } @@ -72,7 +72,7 @@ public final class Article: Hashable { } public extension Set where Element == Article { - + func articleIDs() -> Set { return Set(map { $0.articleID }) } @@ -85,11 +85,11 @@ public extension Set where Element == Article { func contains(accountID: String, articleID: String) -> Bool { return contains(where: { $0.accountID == accountID && $0.articleID == articleID}) } - + } public extension Array where Element == Article { - + func articleIDs() -> [String] { return map { $0.articleID } } diff --git a/Modules/Articles/Sources/Articles/ArticleStatus.swift b/Modules/Articles/Sources/Articles/ArticleStatus.swift index eb2d5b572..c974d9c30 100644 --- a/Modules/Articles/Sources/Articles/ArticleStatus.swift +++ b/Modules/Articles/Sources/Articles/ArticleStatus.swift @@ -15,7 +15,7 @@ public final class ArticleStatus: Hashable { case read = "read" case starred = "starred" } - + public let articleID: String public let dateArrived: Date @@ -59,7 +59,7 @@ public final class ArticleStatus: Hashable { return starred } } - + public func setBoolStatus(_ status: Bool, forKey key: ArticleStatus.Key) { switch key { case .read: @@ -83,14 +83,14 @@ public final class ArticleStatus: Hashable { } public extension Set where Element == ArticleStatus { - + func articleIDs() -> Set { return Set(map { $0.articleID }) } } public extension Array where Element == ArticleStatus { - + func articleIDs() -> [String] { return map { $0.articleID } } diff --git a/Modules/Articles/Sources/Articles/Author.swift b/Modules/Articles/Sources/Articles/Author.swift index 3bedce5bd..99d11bb39 100644 --- a/Modules/Articles/Sources/Articles/Author.swift +++ b/Modules/Articles/Sources/Articles/Author.swift @@ -15,7 +15,7 @@ public struct Author: Codable, Hashable { public let url: String? public let avatarURL: String? public let emailAddress: String? - + public init?(authorID: String?, name: String?, url: String?, avatarURL: String?, emailAddress: String?) { if name == nil && url == nil && emailAddress == nil { return nil diff --git a/Modules/Articles/Sources/Articles/DatabaseID.swift b/Modules/Articles/Sources/Articles/DatabaseID.swift index 1ad269cc3..8105d16cf 100644 --- a/Modules/Articles/Sources/Articles/DatabaseID.swift +++ b/Modules/Articles/Sources/Articles/DatabaseID.swift @@ -20,11 +20,11 @@ public func databaseIDWithString(_ s: String) -> String { defer { databaseIDCacheLock.unlock() } - + if let identifier = databaseIDCache[s] { return identifier } - + let identifier = s.md5String databaseIDCache[s] = identifier return identifier diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 27933e082..e90c444ee 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -35,7 +35,7 @@ public struct ArticleChanges { self.updatedArticles = Set
() self.deletedArticles = Set
() } - + public init(newArticles: Set
?, updatedArticles: Set
?, deletedArticles: Set
?) { self.newArticles = newArticles self.updatedArticles = updatedArticles @@ -105,7 +105,7 @@ public final class ArticlesDatabase { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticles(feedID) } - + public func fetchArticles(_ feedIDs: Set) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticles(feedIDs) @@ -268,7 +268,7 @@ public final class ArticlesDatabase { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") articlesTable.fetchUnreadArticleIDsAsync(completion) } - + /// Fetch the articleIDs of starred articles. public func fetchStarredArticleIDsAsync(completion: @escaping ArticleIDsCompletionBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") @@ -323,7 +323,7 @@ public final class ArticlesDatabase { operationQueue.resume() } #endif - + // MARK: - Caches /// Call to free up some memory. Should be done when the app is backgrounded, for instance. diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index bdfc7f353..91f60a15c 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -41,13 +41,13 @@ final class ArticlesTable: DatabaseTable { self.queue = queue self.statusesTable = StatusesTable(queue: queue) self.retentionStyle = retentionStyle - + let authorsTable = AuthorsTable(name: DatabaseTableName.authors) self.authorsLookupTable = DatabaseLookupTable(name: DatabaseTableName.authorsLookup, objectIDKey: DatabaseKey.articleID, relatedObjectIDKey: DatabaseKey.authorID, relatedTable: authorsTable, relationshipName: RelationshipName.authors) } // MARK: - Fetching Articles for Feed - + func fetchArticles(_ feedID: String) throws -> Set
{ return try fetchArticles{ self.fetchArticlesForFeedID(feedID, $0) } } @@ -113,7 +113,7 @@ final class ArticlesTable: DatabaseTable { func fetchArticlesMatching(_ searchString: String) throws -> Set
{ var articles: Set
= Set
() var error: DatabaseError? = nil - + queue.runInDatabaseSync { (databaseResult) in switch databaseResult { case .success(let database): @@ -364,20 +364,20 @@ final class ArticlesTable: DatabaseTable { completion?(databaseError) } } - + } - + } - + // MARK: - Unread Counts - + func fetchUnreadCount(_ feedIDs: Set, _ since: Date, _ completion: @escaping SingleUnreadCountCompletionBlock) { // Get unread count for today, for instance. if feedIDs.isEmpty { completion(.success(0)) return } - + queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { @@ -439,7 +439,7 @@ final class ArticlesTable: DatabaseTable { } // MARK: - Statuses - + func fetchUnreadArticleIDsAsync(_ completion: @escaping ArticleIDsCompletionBlock) { statusesTable.fetchArticleIDsAsync(.read, false, completion) } @@ -451,7 +451,7 @@ final class ArticlesTable: DatabaseTable { func fetchStarredArticleIDs() throws -> Set { return try statusesTable.fetchStarredArticleIDs() } - + func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { statusesTable.fetchArticleIDsForStatusesWithoutArticlesNewerThan(articleCutoffDate, completion) } @@ -591,7 +591,7 @@ final class ArticlesTable: DatabaseTable { let sql: String let cutoffDate: Date - + switch self.retentionStyle { case .syncSystem: sql = "delete from statuses where dateArrived?, _ updatedArticles: Set
?, _ deletedArticles: Set
?, _ completion: @escaping UpdateArticlesCompletionBlock) { let articleChanges = ArticleChanges(newArticles: newArticles, updatedArticles: updatedArticles, deletedArticles: deletedArticles) DispatchQueue.main.async { completion(.success(articleChanges)) } } - + // MARK: - Saving New Articles func findNewArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article]) -> Set
? { let newArticles = Set(incomingArticles.filter { fetchedArticlesDictionary[$0.articleID] == nil }) return newArticles.isEmpty ? nil : newArticles } - + func findAndSaveNewArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { //5 guard let newArticles = findNewArticles(incomingArticles, fetchedArticlesDictionary) else { return nil @@ -935,7 +935,7 @@ private extension ArticlesTable { self.saveNewArticles(newArticles, database) return newArticles } - + func saveNewArticles(_ articles: Set
, _ database: FMDatabase) { saveRelatedObjectsForNewArticles(articles, database) @@ -984,7 +984,7 @@ private extension ArticlesTable { return updatedArticles.isEmpty ? nil : updatedArticles } - + func findAndSaveUpdatedArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { //6 guard let updatedArticles = findUpdatedArticles(incomingArticles, fetchedArticlesDictionary) else { return nil @@ -992,11 +992,11 @@ private extension ArticlesTable { saveUpdatedArticles(Set(updatedArticles), fetchedArticlesDictionary, database) return updatedArticles } - + func saveUpdatedArticles(_ updatedArticles: Set
, _ fetchedArticles: [String: Article], _ database: FMDatabase) { saveUpdatedRelatedObjects(updatedArticles, fetchedArticles, database) - + for updatedArticle in updatedArticles { saveUpdatedArticle(updatedArticle, fetchedArticles, database) } @@ -1005,7 +1005,7 @@ private extension ArticlesTable { func saveUpdatedArticle(_ updatedArticle: Article, _ fetchedArticles: [String: Article], _ database: FMDatabase) { // Only update exactly what has changed in the Article (if anything). // Untested theory: this gets us better performance and less database fragmentation. - + guard let fetchedArticle = fetchedArticles[updatedArticle.articleID] else { assertionFailure("Expected to find matching fetched article."); saveNewArticles(Set([updatedArticle]), database) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsTable.swift index ad447ddaa..afd307e44 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/AuthorsTable.swift @@ -19,7 +19,7 @@ import Articles final class AuthorsTable: DatabaseRelatedObjectsTable { - + let name: String let databaseIDKey = DatabaseKey.authorID var cache = DatabaseObjectCache() @@ -27,7 +27,7 @@ final class AuthorsTable: DatabaseRelatedObjectsTable { init(name: String) { self.name = name } - + // MARK: - DatabaseRelatedObjectsTable func objectWithRow(_ row: FMResultSet) -> DatabaseObject? { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift index 240c1eeb3..9847d7cbf 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift @@ -11,7 +11,7 @@ import Foundation // MARK: - Database structure struct DatabaseTableName { - + static let articles = "articles" static let authors = "authors" static let authorsLookup = "authorsLookup" @@ -19,12 +19,12 @@ struct DatabaseTableName { } struct DatabaseKey { - + // Shared static let articleID = "articleID" static let url = "url" static let title = "title" - + // Article static let feedID = "feedID" static let uniqueID = "uniqueID" @@ -39,7 +39,7 @@ struct DatabaseKey { static let dateModified = "dateModified" static let authors = "authors" static let searchRowID = "searchRowID" - + // ArticleStatus static let read = "read" static let starred = "starred" @@ -47,7 +47,7 @@ struct DatabaseKey { // Tag static let tagName = "tagName" - + // Author static let authorID = "authorID" static let name = "name" @@ -60,6 +60,6 @@ struct DatabaseKey { } struct RelationshipName { - + static let authors = "authors" } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift index 9660d3187..ff045c7a6 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift @@ -79,7 +79,7 @@ extension Article { if self == existingArticle { return nil } - + var d = DatabaseDictionary() if uniqueID != existingArticle.uniqueID { d[DatabaseKey.uniqueID] = uniqueID @@ -178,7 +178,7 @@ extension Article: @retroactive DatabaseObject { } return d } - + public var databaseID: String { return articleID } @@ -205,7 +205,7 @@ extension Set where Element == Article { func statuses() -> Set { return Set(map { $0.status }) } - + func dictionary() -> [String: Article] { var d = [String: Article]() for article in self { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift index 4dc1e0c39..60a500c73 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift @@ -12,14 +12,14 @@ import RSDatabaseObjC import Articles extension ArticleStatus { - + convenience init(articleID: String, dateArrived: Date, row: FMResultSet) { let read = row.bool(forColumn: DatabaseKey.read) let starred = row.bool(forColumn: DatabaseKey.starred) self.init(articleID: articleID, read: read, starred: starred, dateArrived: dateArrived) } - + } extension ArticleStatus: @retroactive DatabaseObject { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Author+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Author+Database.swift index 069642702..71f6a0b6b 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Author+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Author+Database.swift @@ -15,26 +15,26 @@ import RSParser // MARK: - DatabaseObject extension Author { - + init?(row: FMResultSet) { let authorID = row.string(forColumn: DatabaseKey.authorID) let name = row.string(forColumn: DatabaseKey.name) let url = row.string(forColumn: DatabaseKey.url) let avatarURL = row.string(forColumn: DatabaseKey.avatarURL) let emailAddress = row.string(forColumn: DatabaseKey.emailAddress) - + self.init(authorID: authorID, name: name, url: url, avatarURL: avatarURL, emailAddress: emailAddress) } - + init?(parsedAuthor: ParsedAuthor) { self.init(authorID: nil, name: parsedAuthor.name, url: parsedAuthor.url, avatarURL: parsedAuthor.avatarURL, emailAddress: parsedAuthor.emailAddress) } - + public static func authorsWithParsedAuthors(_ parsedAuthors: Set?) -> Set? { guard let parsedAuthors = parsedAuthors else { return nil } - + let authors = Set(parsedAuthors.compactMap { Author(parsedAuthor: $0) }) return authors.isEmpty ? nil: authors } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/DatabaseObject+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/DatabaseObject+Database.swift index af25c013a..e31344780 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/DatabaseObject+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/DatabaseObject+Database.swift @@ -11,7 +11,7 @@ import RSDatabase import Articles extension Array where Element == DatabaseObject { - + func asAuthors() -> Set? { let authors = Set(self.map { $0 as! Author }) return authors.isEmpty ? nil : authors diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ParsedArticle+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ParsedArticle+Database.swift index 271876057..ded5cc246 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ParsedArticle+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ParsedArticle+Database.swift @@ -11,7 +11,7 @@ import RSParser import Articles extension ParsedItem { - + var articleID: String { if let s = syncServiceID { return s diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/RelatedObjectsMap+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/RelatedObjectsMap+Database.swift index 00a42d41d..49325b62a 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/RelatedObjectsMap+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/RelatedObjectsMap+Database.swift @@ -11,7 +11,7 @@ import RSDatabase import Articles extension RelatedObjectsMap { - + func authors(for articleID: String) -> Set? { if let objects = self[articleID] { return objects.asAuthors() diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift index 2b49db38f..e22edc59a 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift @@ -27,7 +27,7 @@ public final class FetchAllUnreadCountsOperation: MainThreadOperation { init(databaseQueue: DatabaseQueue) { self.queue = databaseQueue } - + public func run() { queue.runInDatabase { databaseResult in if self.isCanceled { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift index a26fe04eb..083391cf3 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift @@ -22,7 +22,7 @@ final class ArticleSearchInfo: Hashable { let summary: String? let authorsNames: String? let searchRowID: Int? - + var preferredText: String { if let body = contentHTML, !body.isEmpty { return body diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift index bb53a36a2..8d32835c2 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift @@ -21,7 +21,7 @@ final class StatusesTable: DatabaseTable { let name = DatabaseTableName.statuses private let cache = StatusCache() private let queue: DatabaseQueue - + init(queue: DatabaseQueue) { self.queue = queue } @@ -46,10 +46,10 @@ final class StatusesTable: DatabaseTable { if articleIDsMissingCachedStatus.isEmpty { return (statusesDictionary(articleIDs), Set()) } - + // Check database. fetchAndCacheStatusesForArticleIDs(articleIDsMissingCachedStatus, database) - + let articleIDsNeedingStatus = self.articleIDsWithNoCachedStatus(articleIDs) if !articleIDsNeedingStatus.isEmpty { // Create new statuses. @@ -79,9 +79,9 @@ final class StatusesTable: DatabaseTable { return nil } let articleIDs = updatedStatuses.articleIDs() - + self.markArticleIDs(articleIDs, statusKey, flag, database) - + return updatedStatuses } @@ -101,7 +101,7 @@ final class StatusesTable: DatabaseTable { func fetchStarredArticleIDs() throws -> Set { return try fetchArticleIDs("select articleID from statuses where starred=1;") } - + func fetchArticleIDsAsync(_ statusKey: ArticleStatus.Key, _ value: Bool, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in @@ -136,24 +136,24 @@ final class StatusesTable: DatabaseTable { func fetchArticleIDsForStatusesWithoutArticlesNewerThan(_ cutoffDate: Date, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in - + var error: DatabaseError? var articleIDs = Set() - + func makeDatabaseCall(_ database: FMDatabase) { let sql = "select articleID from statuses s where (starred=1 or dateArrived>?) and not exists (select 1 from articles a where a.articleID = s.articleID);" if let resultSet = database.executeQuery(sql, withArgumentsIn: [cutoffDate]) { articleIDs = resultSet.mapToSet(self.articleIDWithRow) } } - + switch databaseResult { case .success(let database): makeDatabaseCall(database) case .failure(let databaseError): error = databaseError } - + if let error = error { DispatchQueue.main.async { completion(.failure(error)) @@ -166,7 +166,7 @@ final class StatusesTable: DatabaseTable { } } } - + func fetchArticleIDs(_ sql: String) throws -> Set { var error: DatabaseError? var articleIDs = Set() @@ -186,11 +186,11 @@ final class StatusesTable: DatabaseTable { } return articleIDs } - + func articleIDWithRow(_ row: FMResultSet) -> String? { return row.string(forColumn: DatabaseKey.articleID) } - + func statusWithRow(_ row: FMResultSet) -> ArticleStatus? { guard let articleID = row.string(forColumn: DatabaseKey.articleID) else { return nil @@ -237,7 +237,7 @@ final class StatusesTable: DatabaseTable { private extension StatusesTable { // MARK: - Cache - + func articleIDsWithNoCachedStatus(_ articleIDs: Set) -> Set { return Set(articleIDs.filter { cache[$0] == nil }) } @@ -253,7 +253,7 @@ private extension StatusesTable { let now = Date() let statuses = Set(articleIDs.map { ArticleStatus(articleID: $0, read: read, dateArrived: now) }) cache.addIfNotCached(statuses) - + saveStatuses(statuses, database) } @@ -261,7 +261,7 @@ private extension StatusesTable { guard let resultSet = self.selectRowsWhere(key: DatabaseKey.articleID, inValues: Array(articleIDs), in: database) else { return } - + let statuses = resultSet.mapToSet(self.statusWithRow) self.cache.addIfNotCached(statuses) } @@ -294,10 +294,10 @@ private final class StatusCache { func addStatusIfNotCached(_ status: ArticleStatus) { addIfNotCached(Set([status])) } - + func addIfNotCached(_ statuses: Set) { // Does not replace already cached statuses. - + for status in statuses { let articleID = status.articleID if let _ = self[articleID] { diff --git a/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift b/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift index ccfbe7fa2..1dc626038 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift @@ -11,7 +11,7 @@ import AppKit //let keypadEnter: unichar = 3 @objc public protocol KeyboardDelegate: AnyObject { - + // Return true if handled. func keydown(_: NSEvent, in view: NSView) -> Bool } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSAppearance+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSAppearance+RSCore.swift index fd2ed73de..207cc4885 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSAppearance+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSAppearance+RSCore.swift @@ -10,7 +10,7 @@ import AppKit extension NSAppearance { - + @objc(rsIsDarkMode) public var isDarkMode: Bool { if #available(macOS 10.14, *) { diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSResponder-Extensions.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSResponder-Extensions.swift index 80e4dcc6f..73c6889d1 100755 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSResponder-Extensions.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSResponder-Extensions.swift @@ -9,9 +9,9 @@ import AppKit public extension NSResponder { - + func hasAncestor(_ ancestor: NSResponder) -> Bool { - + var nomad: NSResponder = self while(true) { if nomad === ancestor { @@ -24,7 +24,7 @@ public extension NSResponder { break } } - + return false } } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift index bfffba77b..d6a8485ab 100755 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift @@ -9,11 +9,11 @@ import AppKit public extension NSTableView { - + var selectionIsEmpty: Bool { return selectedRowIndexes.startIndex == selectedRowIndexes.endIndex } - + func indexesOfAvailableRowsPassingTest(_ test: (Int) -> Bool) -> IndexSet? { // Checks visible and in-flight rows. diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSView+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSView+RSCore.swift index 3ad4601bf..b9b515389 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSView+RSCore.swift @@ -9,16 +9,16 @@ import AppKit extension NSView { - + public func asImage() -> NSImage { let rep = bitmapImageRepForCachingDisplay(in: bounds)! cacheDisplay(in: bounds, to: rep) - + let img = NSImage(size: bounds.size) img.addRepresentation(rep) return img } - + } public extension NSView { diff --git a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift index 66eb30f90..c42f7c6e3 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift @@ -139,7 +139,7 @@ public final class RSAppMovementMonitor: NSObject { let quitAlert = NSAlert() quitAlert.alertStyle = .critical quitAlert.addButton(withTitle: self.alertRelaunchButtonText) - + quitAlert.messageText = self.alertMessageText quitAlert.informativeText = self.alertInformativeText diff --git a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitError.swift b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitError.swift index 2d0e1ded7..2e0f4b0b3 100644 --- a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitError.swift +++ b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitError.swift @@ -13,16 +13,16 @@ import CloudKit public class CloudKitError: LocalizedError { public let error: Error - + public init(_ error: Error) { self.error = error } - + public var errorDescription: String? { guard let ckError = error as? CKError else { return error.localizedDescription } - + switch ckError.code { case .alreadyShared: return NSLocalizedString("Already Shared: a record or share cannot be saved because doing so would cause the same hierarchy of records to exist in multiple shares.", comment: "Known iCloud Error") @@ -94,5 +94,5 @@ public class CloudKitError: LocalizedError { return NSLocalizedString("Unhandled Error.", comment: "Unknown iCloud Error") } } - + } diff --git a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZone.swift b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZone.swift index 4726dc37b..ae0b60315 100644 --- a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZone.swift +++ b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZone.swift @@ -13,7 +13,7 @@ public enum CloudKitZoneError: LocalizedError { case userDeletedZone case corruptAccount case unknown - + public var errorDescription: String? { switch self { case .userDeletedZone: @@ -33,7 +33,7 @@ public protocol CloudKitZoneDelegate: AnyObject { public typealias CloudKitRecordKey = (recordType: CKRecord.RecordType, recordID: CKRecord.ID) public protocol CloudKitZone: AnyObject { - + static var qualityOfService: QualityOfService { get } var zoneID: CKRecordZone.ID { get } @@ -47,17 +47,17 @@ public protocol CloudKitZone: AnyObject { /// Generates a new CKRecord.ID using a UUID for the record's name func generateRecordID() -> CKRecord.ID - + /// Subscribe to changes at a zone level func subscribeToZoneChanges() - + /// Process a remove notification func receiveRemoteNotification(userInfo: [AnyHashable : Any], completion: @escaping () -> Void) - + } public extension CloudKitZone { - + // My observation has been that QoS is treated differently for CloudKit operations on macOS vs iOS. // .userInitiated is too aggressive on iOS and can lead the UI slowing down and appearing to block. // .default (or lower) on macOS will sometimes hang for extended periods of time and appear to hang. @@ -103,12 +103,12 @@ public extension CloudKitZone { UserDefaults.standard.removeObject(forKey: oldChangeTokenKey) } } - + /// Reset the change token used to determine what point in time we are doing changes fetches func resetChangeToken() { changeToken = nil } - + func generateRecordID() -> CKRecord.ID { return CKRecord.ID(recordName: UUID().uuidString, zoneID: zoneID) } @@ -119,14 +119,14 @@ public extension CloudKitZone { block() }) } - + func receiveRemoteNotification(userInfo: [AnyHashable : Any], completion: @escaping () -> Void) { let note = CKRecordZoneNotification(fromRemoteNotificationDictionary: userInfo) guard note?.recordZoneID?.zoneName == zoneID.zoneName else { completion() return } - + fetchChangesInZone() { result in if case .failure(let error) = result { Self.logger.error("CloudKit: \(self.zoneID.zoneName) remote notification fetch error: \(error.localizedDescription)") @@ -162,25 +162,25 @@ public extension CloudKitZone { let info = CKSubscription.NotificationInfo() info.shouldSendContentAvailable = true subscription.notificationInfo = info - + save(subscription) { result in if case .failure(let error) = result { Self.logger.error("CloudKit: \(self.zoneID.zoneName) zone subscribe to changes error: \(error.localizedDescription)") } } } - + /// Issue a CKQuery and return the resulting CKRecords. func query(_ ckQuery: CKQuery, desiredKeys: [String]? = nil, completion: @escaping (Result<[CKRecord], Error>) -> Void) { var records = [CKRecord]() - + let op = CKQueryOperation(query: ckQuery) op.qualityOfService = Self.qualityOfService - + if let desiredKeys = desiredKeys { op.desiredKeys = desiredKeys } - + op.recordMatchedBlock = { recordID, result in if let record = try? result.get() { records.append(record) @@ -235,21 +235,21 @@ public extension CloudKitZone { } } } - + database?.add(op) } - + /// Query CKRecords using a CKQuery Cursor func query(cursor: CKQueryOperation.Cursor, desiredKeys: [String]? = nil, carriedRecords: [CKRecord], completion: @escaping (Result<[CKRecord], Error>) -> Void) { var records = carriedRecords - + let op = CKQueryOperation(cursor: cursor) op.qualityOfService = Self.qualityOfService - + if let desiredKeys = desiredKeys { op.desiredKeys = desiredKeys } - + op.recordMatchedBlock = { recordID, result in if let record = try? result.get() { records.append(record) @@ -307,7 +307,7 @@ public extension CloudKitZone { database?.add(op) } - + /// Fetch a CKRecord by using its externalID func fetch(externalID: String?, completion: @escaping (Result) -> Void) { @@ -317,7 +317,7 @@ public extension CloudKitZone { } let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) - + database?.fetch(withRecordID: recordID) { [weak self] record, error in guard let self = self else { completion(.failure(CloudKitZoneError.unknown)) @@ -360,24 +360,24 @@ public extension CloudKitZone { } } } - + /// Save the CKRecord func save(_ record: CKRecord, completion: @escaping (Result) -> Void) { modify(recordsToSave: [record], recordIDsToDelete: [], completion: completion) } - + /// Save the CKRecords func save(_ records: [CKRecord], completion: @escaping (Result) -> Void) { modify(recordsToSave: records, recordIDsToDelete: [], completion: completion) } - + /// Saves or modifies the records as long as they are unchanged relative to the local version func saveIfNew(_ records: [CKRecord], completion: @escaping (Result) -> Void) { let op = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: [CKRecord.ID]()) op.savePolicy = .ifServerRecordUnchanged op.isAtomic = false op.qualityOfService = Self.qualityOfService - + op.modifyRecordsResultBlock = { [weak self] result in guard let self = self else { return } @@ -485,12 +485,12 @@ public extension CloudKitZone { } } } - + /// Delete CKRecords using a CKQuery func delete(ckQuery: CKQuery, completion: @escaping (Result) -> Void) { - + var records = [CKRecord]() - + let op = CKQueryOperation(query: ckQuery) op.qualityOfService = Self.qualityOfService op.recordMatchedBlock = { recordID, result in @@ -526,15 +526,15 @@ public extension CloudKitZone { } } } - + database?.add(op) } - + /// Delete CKRecords using a CKQuery func delete(cursor: CKQueryOperation.Cursor, carriedRecords: [CKRecord], completion: @escaping (Result) -> Void) { - + var records = [CKRecord]() - + let op = CKQueryOperation(cursor: cursor) op.qualityOfService = Self.qualityOfService op.recordMatchedBlock = { recordID, result in @@ -565,20 +565,20 @@ public extension CloudKitZone { } } } - + database?.add(op) } - + /// Delete a CKRecord using its recordID func delete(recordID: CKRecord.ID, completion: @escaping (Result) -> Void) { modify(recordsToSave: [], recordIDsToDelete: [recordID], completion: completion) } - + /// Delete CKRecords func delete(recordIDs: [CKRecord.ID], completion: @escaping (Result) -> Void) { modify(recordsToSave: [], recordIDsToDelete: recordIDs, completion: completion) } - + /// Delete a CKRecord using its externalID func delete(externalID: String?, completion: @escaping (Result) -> Void) { guard let externalID = externalID else { @@ -589,7 +589,7 @@ public extension CloudKitZone { let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) modify(recordsToSave: [], recordIDsToDelete: [recordID], completion: completion) } - + /// Delete a CKSubscription func delete(subscriptionID: String, completion: @escaping (Result) -> Void) { database?.delete(withSubscriptionID: subscriptionID) { [weak self] _, error in @@ -736,10 +736,10 @@ public extension CloudKitZone { func fetchChangesInZone(completion: @escaping (Result) -> Void) { var savedChangeToken = changeToken - + var changedRecords = [CKRecord]() var deletedRecordKeys = [CloudKitRecordKey]() - + let zoneConfig = CKFetchRecordZoneChangesOperation.ZoneConfiguration() zoneConfig.previousServerChangeToken = changeToken let op = CKFetchRecordZoneChangesOperation(recordZoneIDs: [zoneID], configurationsByRecordZoneID: [zoneID: zoneConfig]) @@ -835,5 +835,5 @@ public extension CloudKitZone { database?.add(op) } - + } diff --git a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZoneResult.swift b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZoneResult.swift index 30efa7b5a..72da91b86 100644 --- a/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZoneResult.swift +++ b/Modules/RSCore/Sources/RSCore/CloudKit/CloudKitZoneResult.swift @@ -19,15 +19,15 @@ public enum CloudKitZoneResult { case zoneNotFound case userDeletedZone case failure(error: Error) - + public static func resolve(_ error: Error?) -> CloudKitZoneResult { - + guard error != nil else { return .success } - + guard let ckError = error as? CKError else { return .failure(error: error!) } - + switch ckError.code { case .serviceUnavailable, .requestRateLimited, .zoneBusy: if let retry = ckError.userInfo[CKErrorRetryAfterKey] as? NSNumber { @@ -60,11 +60,11 @@ public enum CloudKitZoneResult { } } - + } private extension CloudKitZoneResult { - + static func anyRequestErrors(_ errors: [AnyHashable: CKError]) -> CloudKitZoneResult? { if errors.values.contains(where: { $0.code == .changeTokenExpired } ) { return .changeTokenExpired @@ -77,5 +77,5 @@ private extension CloudKitZoneResult { } return nil } - + } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift index e583824f3..146c997f1 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift @@ -15,7 +15,7 @@ public extension Array { Array(self[$0 ..< Swift.min($0 + size, count)]) } } - + } public extension Array where Element: Equatable { diff --git a/Modules/RSCore/Sources/RSCore/Shared/BatchUpdate.swift b/Modules/RSCore/Sources/RSCore/Shared/BatchUpdate.swift index 1396eda22..fdfdabae7 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/BatchUpdate.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/BatchUpdate.swift @@ -23,7 +23,7 @@ public final class BatchUpdate { /// The shared batch update object. public static let shared = BatchUpdate() - + private var count = 0 /// Is updating in progress? @@ -54,11 +54,11 @@ public final class BatchUpdate { } private extension BatchUpdate { - + func incrementCount() { count = count + 1 } - + func decrementCount() { count = count - 1 if count < 1 { @@ -67,7 +67,7 @@ private extension BatchUpdate { postBatchUpdateDidPerform() } } - + func postBatchUpdateDidPerform() { if !Thread.isMainThread { DispatchQueue.main.sync { @@ -77,5 +77,5 @@ private extension BatchUpdate { NotificationCenter.default.post(name: .BatchUpdateDidPerform, object: nil, userInfo: nil) } } - + } diff --git a/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift b/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift index 11373c37f..e2537bc1f 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift @@ -43,7 +43,7 @@ public struct BinaryDiskCache { catch {} return nil } - + set { if let data = newValue { do { diff --git a/Modules/RSCore/Sources/RSCore/Shared/Calendar+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Calendar+RSCore.swift index 9de5e199d..b083a40ce 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Calendar+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Calendar+RSCore.swift @@ -26,5 +26,5 @@ public extension Calendar { static var startOfToday: Date { cached.startOfDay(for: Date()) } - + } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Character+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Character+RSCore.swift index 233de03ee..49da17164 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Character+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Character+RSCore.swift @@ -9,7 +9,7 @@ import Foundation public extension Character { - + var isSimpleEmoji: Bool { guard let firstScalar = unicodeScalars.first else { return false } return firstScalar.properties.isEmoji && firstScalar.value > 0x238C diff --git a/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift b/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift index ec2271fe0..116655a14 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift @@ -61,12 +61,12 @@ struct QueueCall: Equatable { resetCalls() callsToMake.forEach { $0.perform() } } - + @objc func timerDidFire(_ sender: Any?) { lastCallTime = Date() performCallsImmediately() } - + } private extension CoalescingQueue { diff --git a/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift index 3a484dce7..3e4d26d18 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift @@ -212,19 +212,19 @@ public extension Data { self.range(of: RSSearch.UTF16.lowercaseDiv) != nil || self.range(of: RSSearch.UTF16.uppercaseDiv) != nil { return true } - + // Check for p tags if self.range(of: RSSearch.UTF8.lowercaseP) != nil || self.range(of: RSSearch.UTF8.uppercaseP) != nil || self.range(of: RSSearch.UTF16.lowercaseP) != nil || self.range(of: RSSearch.UTF16.uppercaseP) != nil { return true } - + // Check for span tags if self.range(of: RSSearch.UTF8.lowercaseSpan) != nil || self.range(of: RSSearch.UTF8.uppercaseSpan) != nil || self.range(of: RSSearch.UTF16.lowercaseSpan) != nil || self.range(of: RSSearch.UTF16.uppercaseSpan) != nil { return true } - + return false }() diff --git a/Modules/RSCore/Sources/RSCore/Shared/DisplayNameProvider.swift b/Modules/RSCore/Sources/RSCore/Shared/DisplayNameProvider.swift index 05525a815..1edf87d43 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/DisplayNameProvider.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/DisplayNameProvider.swift @@ -16,7 +16,7 @@ extension Notification.Name { /// A type that provides a name for display to the user. public protocol DisplayNameProvider { - + var nameForDisplay: String { get } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift index 21759ee56..a96d51ff6 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift @@ -82,7 +82,7 @@ public extension FileManager { guard let filenames = self.filenames(inFolder: folder) else { return nil } - + let url = URL(fileURLWithPath: folder) return filenames.map { url.appendingPathComponent($0).path } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperationQueue.swift b/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperationQueue.swift index be7d225dd..00e09751d 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperationQueue.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperationQueue.swift @@ -247,7 +247,7 @@ private extension MainThreadOperationQueue { guard !operationIDs.isEmpty else { return } - + let operationIDsToCancel = operationIDsByAddingChildOperationIDs(operationIDs) setCanceledAndRemoveDelegate(for: operationIDsToCancel) callCompletionBlockForOperationIDs(operationIDsToCancel) diff --git a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift index fe323fcef..5e9324c88 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift @@ -12,12 +12,12 @@ import os public enum Platform { private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Platform") - + /// Returns true if the app is currently running unit tests. public static var isRunningUnitTests: Bool { return _isRunningUnitTests } - + private static let _isRunningUnitTests: Bool = { func checkIfRunningUnitTests() -> Bool { @@ -51,7 +51,7 @@ public enum Platform { Self.logger.info("Not running unit tests") return false }() - + /// Get the path to a subfolder of the application's data folder (often `Application Support`). /// - Parameters: /// - appName: The name of the application. diff --git a/Modules/RSCore/Sources/RSCore/Shared/PropertyList.swift b/Modules/RSCore/Sources/RSCore/Shared/PropertyList.swift index 2246b0e5b..75eff3cce 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/PropertyList.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/PropertyList.swift @@ -11,7 +11,7 @@ import Foundation // These functions eat errors. public func propertyList(withData data: Data) -> Any? { - + do { return try PropertyListSerialization.propertyList(from: data, options: [], format: nil) } catch { @@ -22,7 +22,7 @@ public func propertyList(withData data: Data) -> Any? { // Create a binary plist. public func data(withPropertyList plist: Any) -> Data? { - + do { return try PropertyListSerialization.data(fromPropertyList: plist, format: .binary, options: 0) } diff --git a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift index aa7e4220b..df01fd9c4 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift @@ -29,25 +29,25 @@ public extension RSImage { /// - Parameter color: The color with which to fill the mask image. /// - Returns: A new masked image. func maskWithColor(color: CGColor) -> RSImage? { - + #if os(macOS) guard let maskImage = cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil } #else guard let maskImage = cgImage else { return nil } #endif - + let width = size.width let height = size.height let bounds = CGRect(x: 0, y: 0, width: width, height: height) - + let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! - + context.clip(to: bounds, mask: maskImage) context.setFillColor(color) context.fill(bounds) - + if let cgImage = context.makeImage() { #if os(macOS) let coloredImage = RSImage(cgImage: cgImage, size: CGSize(width: cgImage.width, height: cgImage.height)) @@ -58,7 +58,7 @@ public extension RSImage { } else { return nil } - + } #if os(iOS) @@ -131,7 +131,7 @@ public extension RSImage { } return nil } - + let numberOfImages = CGImageSourceGetCount(imageSource) if debugLoggingEnabled { RSImageLogger.debug("RSImageLogger: numberOfImages == \(numberOfImages, privacy: .public)") @@ -139,11 +139,11 @@ public extension RSImage { guard numberOfImages > 0 else { return nil } - + var exactMatch: (index: Int, maxDimension: Int)? = nil var goodMatch: (index: Int, maxDimension: Int)? = nil var smallMatch: (index: Int, maxDimension: Int)? = nil - + // Single pass through all images to find the best match for i in 0.. maxPixelSize && maxDimension <= maxPixelSize * 4 { if let currentGoodMatch = goodMatch { @@ -187,7 +187,7 @@ public extension RSImage { RSImageLogger.debug("RSImageLogger: found good match \(maxDimension, privacy: .public) for maxPixelSize: \(maxPixelSize, privacy: .public)") } } - + // Check for small match (smaller than maxPixelSize) if maxDimension < maxPixelSize { if let currentSmallMatch = smallMatch { @@ -202,12 +202,12 @@ public extension RSImage { } } } - + // Return best match in order of preference: exact > good > small if let match = exactMatch ?? goodMatch ?? smallMatch { return CGImageSourceCreateImageAtIndex(imageSource, match.index, nil) } - + // Fallback to creating a thumbnail if debugLoggingEnabled { RSImageLogger.debug("RSImageLogger: found no match — calling createThumbnail") diff --git a/Modules/RSCore/Sources/RSCore/Shared/Renamable.swift b/Modules/RSCore/Sources/RSCore/Shared/Renamable.swift index e65816b20..ce8dc9887 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Renamable.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Renamable.swift @@ -18,6 +18,6 @@ public protocol Renamable { /// - completion: A block called when the renaming completes or fails. /// - result: The result of the renaming. func rename(to: String, completion: @escaping (_ result: Result) -> Void) - + } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Set+Extensions.swift b/Modules/RSCore/Sources/RSCore/Shared/Set+Extensions.swift index 4e127e0bb..2efda344b 100755 --- a/Modules/RSCore/Sources/RSCore/Shared/Set+Extensions.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Set+Extensions.swift @@ -18,9 +18,9 @@ public extension Set { return self[index] } - + func anyObject() -> Element? { - + if self.isEmpty { return nil } diff --git a/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift index b0e4ee2d7..d29002db2 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift @@ -26,14 +26,14 @@ public extension String { static func htmlWithLink(_ link: String) -> String { return link.htmlByAddingLink(link) } - + func hmacUsingSHA1(key: String) -> String { var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, self, self.count, &digest) let data = Data(digest) return data.map { String(format: "%02hhx", $0) }.joined() } - + } public extension String { diff --git a/Modules/RSCore/Sources/RSCore/Shared/UndoableCommand.swift b/Modules/RSCore/Sources/RSCore/Shared/UndoableCommand.swift index 5594151ff..cd9b7da57 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/UndoableCommand.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/UndoableCommand.swift @@ -29,7 +29,7 @@ extension UndoableCommand { } public func registerRedo() { - + undoManager.setActionName(redoActionName) undoManager.registerUndo(withTarget: self) { (target) in self.perform() @@ -40,33 +40,33 @@ extension UndoableCommand { // Useful for view controllers. public protocol UndoableCommandRunner: AnyObject { - + var undoableCommands: [UndoableCommand] { get set } var undoManager: UndoManager? { get } - + func runCommand(_ undoableCommand: UndoableCommand) func clearUndoableCommands() } public extension UndoableCommandRunner { - + func runCommand(_ undoableCommand: UndoableCommand) { - + pushUndoableCommand(undoableCommand) undoableCommand.perform() } - + func pushUndoableCommand(_ undoableCommand: UndoableCommand) { - + undoableCommands += [undoableCommand] } - + func clearUndoableCommands() { - + // Useful, for example, when timeline is reloaded and the list of articles changes. // Otherwise things like Redo Mark Read are ambiguous. // (Do they apply to the previous articles or to the current articles?) - + guard let undoManager = undoManager else { return } diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UIResponder+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UIResponder+RSCore.swift index a4f334321..1244f4511 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UIResponder+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UIResponder+RSCore.swift @@ -10,7 +10,7 @@ import UIKit extension UIResponder { - + private weak static var _currentFirstResponder: UIResponder? = nil public static var isFirstResponderTextField: Bool { @@ -27,7 +27,7 @@ extension UIResponder { UIApplication.shared.sendAction(#selector(findFirstResponder(sender:)), to: nil, from: nil, for: nil) return UIResponder._currentFirstResponder } - + public static func resignCurrentFirstResponder() { if let responder = currentFirstResponder { responder.resignFirstResponder() @@ -37,6 +37,6 @@ extension UIResponder { @objc internal func findFirstResponder(sender: AnyObject) { UIResponder._currentFirstResponder = self } - + } #endif diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UIView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UIView+RSCore.swift index f3b2892b4..267e047a6 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UIView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UIView+RSCore.swift @@ -10,32 +10,32 @@ import UIKit extension UIView { - + public func setFrameIfNotEqual(_ rect: CGRect) { if !self.frame.equalTo(rect) { self.frame = rect } } - + public func addChildAndPin(_ view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) - + NSLayoutConstraint.activate([ safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor), safeAreaLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor), safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) - + } - + public func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } - + } #endif diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UIViewController+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UIViewController+RSCore.swift index a4945c594..f329705c8 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UIViewController+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UIViewController+RSCore.swift @@ -10,22 +10,22 @@ import UIKit import SwiftUI extension UIViewController { - + // MARK: Autolayout - + public func addChildAndPinView(_ controller: UIViewController) { view.addChildAndPin(controller.view) addChild(controller) } - + public func replaceChildAndPinView(_ controller: UIViewController) { view.subviews.forEach { $0.removeFromSuperview() } children.forEach { $0.removeFromParent() } addChildAndPinView(controller) } - + // MARK: Error Handling - + public func presentError(title: String, message: String, dismiss: (() -> Void)? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let dismissTitle = NSLocalizedString("OK", comment: "OK") @@ -35,7 +35,7 @@ extension UIViewController { alertController.addAction(dismissAction) self.present(alertController, animated: true, completion: nil) } - + } // MARK: SwiftUI diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UIWindow+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UIWindow+RSCore.swift index 5c45f8fc1..a5df7ac6b 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UIWindow+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UIWindow+RSCore.swift @@ -9,9 +9,9 @@ import UIKit extension UIWindow { - + public var topViewController: UIViewController? { - + var top = self.rootViewController while true { if let presented = top?.presentedViewController { @@ -33,10 +33,10 @@ extension UIWindow { break } } - + return top - + } - + } #endif diff --git a/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift b/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift index 3bac4f456..f58f3054a 100644 --- a/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift +++ b/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift @@ -13,7 +13,7 @@ public final class WebViewWindowController: NSWindowController { @IBOutlet private var webview: WKWebView! private var title: String! - + public convenience init(title: String) { self.init(window: nil) self.title = title diff --git a/Modules/RSCore/Tests/RSCoreTests/MainThreadOperationTests.swift b/Modules/RSCore/Tests/RSCoreTests/MainThreadOperationTests.swift index dada307f6..b9bf1dbf9 100644 --- a/Modules/RSCore/Tests/RSCoreTests/MainThreadOperationTests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/MainThreadOperationTests.swift @@ -212,9 +212,9 @@ final class MainThreadOperationTests: XCTestCase { waitForExpectations(timeout: 1.0, handler: nil) XCTAssertTrue(queue.pendingOperationsCount == 0) } - + func testCancelingDisownsOperation() { - + final class SlowFinishingOperation: MainThreadOperation { let didCancelExpectation: XCTestExpectation @@ -231,7 +231,7 @@ final class MainThreadOperationTests: XCTestCase { var operationDelegate: MainThreadOperationDelegate? var name: String? var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock? - + var didStartRunBlock: (() -> ())? init(didCancelExpectation: XCTestExpectation) { @@ -252,7 +252,7 @@ final class MainThreadOperationTests: XCTestCase { } } } - + let queue = MainThreadOperationQueue() let didCancelExpectation = expectation(description: "Did Cancel Operation") let completionBlockDidRunExpectation = expectation(description: "Completion Block Did Run") @@ -273,10 +273,10 @@ final class MainThreadOperationTests: XCTestCase { } return operation }() - + // The queue should take ownership of the operation (asserted below). queue.add(operation!) - + // Verify something other than this scope has ownership of the operation. weak var addedOperation = operation! operation = nil diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift index cc86201d3..517b65b31 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift @@ -20,9 +20,9 @@ public protocol DatabaseObject { } public extension DatabaseObject { - + func relatedObjectsWithName(_ name: String) -> [DatabaseObject]? { - + return nil } } @@ -37,14 +37,14 @@ extension Array where Element == DatabaseObject { } return d } - + func databaseIDs() -> Set { - + return Set(self.map { $0.databaseID }) } - + func includesObjectWithDatabaseID(_ databaseID: String) -> Bool { - + for object in self { if object.databaseID == databaseID { return true diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift index 45ad0e69c..bbb93f64d 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift @@ -15,11 +15,11 @@ public protocol DatabaseTable { } public extension DatabaseTable { - + // MARK: Fetching func selectRowsWhere(key: String, equals value: Any, in database: FMDatabase) -> FMResultSet? { - + return database.rs_selectRowsWhereKey(key, equalsValue: value, tableName: name) } @@ -39,7 +39,7 @@ public extension DatabaseTable { // MARK: Deleting func deleteRowsWhere(key: String, equalsAnyValue values: [Any], in database: FMDatabase) { - + if values.isEmpty { return } @@ -49,15 +49,15 @@ public extension DatabaseTable { // MARK: Updating func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, matches: [Any], database: FMDatabase) { - + let _ = database.rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: matches, tableName: self.name) } - + func updateRowsWithDictionary(_ dictionary: DatabaseDictionary, whereKey: String, matches: Any, database: FMDatabase) { - + let _ = database.rs_updateRows(with: dictionary, whereKey: whereKey, equalsValue: matches, tableName: self.name) } - + // MARK: Saving func insertRows(_ dictionaries: [DatabaseDictionary], insertType: RSDatabaseInsertType, in database: FMDatabase) { diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift index defd66fcb..e5e0f90ce 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift @@ -21,7 +21,7 @@ public final class DatabaseLookupTable { private let relationshipName: String private let relatedTable: DatabaseRelatedObjectsTable private var objectIDsWithNoRelatedObjects = Set() - + public init(name: String, objectIDKey: String, relatedObjectIDKey: String, relatedTable: DatabaseRelatedObjectsTable, relationshipName: String) { self.name = name @@ -32,32 +32,32 @@ public final class DatabaseLookupTable { } public func fetchRelatedObjects(for objectIDs: Set, in database: FMDatabase) -> RelatedObjectsMap? { - + let objectIDsThatMayHaveRelatedObjects = objectIDs.subtracting(objectIDsWithNoRelatedObjects) if objectIDsThatMayHaveRelatedObjects.isEmpty { return nil } - + guard let relatedObjectIDsMap = fetchRelatedObjectIDsMap(objectIDsThatMayHaveRelatedObjects, database) else { objectIDsWithNoRelatedObjects.formUnion(objectIDsThatMayHaveRelatedObjects) return nil } - + if let relatedObjects = fetchRelatedObjectsWithIDs(relatedObjectIDsMap.relatedObjectIDs(), database) { - + let relatedObjectsMap = RelatedObjectsMap(relatedObjects: relatedObjects, relatedObjectIDsMap: relatedObjectIDsMap) - + let objectIDsWithNoFetchedRelatedObjects = objectIDsThatMayHaveRelatedObjects.subtracting(relatedObjectsMap.objectIDs()) objectIDsWithNoRelatedObjects.formUnion(objectIDsWithNoFetchedRelatedObjects) - + return relatedObjectsMap } - + return nil } - + public func saveRelatedObjects(for objects: [DatabaseObject], in database: FMDatabase) { - + var objectsWithNoRelationships = [DatabaseObject]() var objectsWithRelationships = [DatabaseObject]() @@ -69,10 +69,10 @@ public final class DatabaseLookupTable { objectsWithNoRelationships += [object] } } - + removeRelationships(for: objectsWithNoRelationships, database) updateRelationships(for: objectsWithRelationships, database) - + objectIDsWithNoRelatedObjects.formUnion(objectsWithNoRelationships.databaseIDs()) objectIDsWithNoRelatedObjects.subtract(objectsWithRelationships.databaseIDs()) } @@ -83,7 +83,7 @@ public final class DatabaseLookupTable { private extension DatabaseLookupTable { // MARK: Removing - + func removeRelationships(for objects: [DatabaseObject], _ database: FMDatabase) { let objectIDs = objects.databaseIDs() @@ -91,52 +91,52 @@ private extension DatabaseLookupTable { if objectIDsToRemove.isEmpty { return } - + database.rs_deleteRowsWhereKey(objectIDKey, inValues: Array(objectIDsToRemove), tableName: name) } - + func deleteLookups(for objectID: String, _ relatedObjectIDs: Set, _ database: FMDatabase) { - + guard !relatedObjectIDs.isEmpty else { assertionFailure("deleteLookups: expected non-empty relatedObjectIDs") return } - + // delete from authorLookup where articleID=? and authorID in (?,?,?) let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(relatedObjectIDs.count))! let sql = "delete from \(name) where \(objectIDKey)=? and \(relatedObjectIDKey) in \(placeholders)" - + let parameters: [Any] = [objectID] + Array(relatedObjectIDs) let _ = database.executeUpdate(sql, withArgumentsIn: parameters) } - + // MARK: Saving/Updating - + func updateRelationships(for objects: [DatabaseObject], _ database: FMDatabase) { if objects.isEmpty { return } - + if let lookupTable = fetchRelatedObjectIDsMap(objects.databaseIDs(), database) { for object in objects { syncRelatedObjectsAndLookupTable(object, lookupTable, database) } } - + // Save the actual related objects. - + let relatedObjectsToSave = uniqueArrayOfRelatedObjects(with: objects) if relatedObjectsToSave.isEmpty { assertionFailure("updateRelationships: expected relatedObjectsToSave would not be empty. This should be unreachable.") return } - + relatedTable.save(relatedObjectsToSave, in: database) } func uniqueArrayOfRelatedObjects(with objects: [DatabaseObject]) -> [DatabaseObject] { - + // Can’t create a Set, because we can’t make a Set, because protocol-conforming objects can’t be made Hashable or even Equatable. // We still want the array to include only one copy of each object, but we have to do it the slow way. Instruments will tell us if this is a performance problem. @@ -154,48 +154,48 @@ private extension DatabaseLookupTable { } return relatedObjectsUniqueArray } - + func syncRelatedObjectsAndLookupTable(_ object: DatabaseObject, _ lookupTable: RelatedObjectIDsMap, _ database: FMDatabase) { - + guard let relatedObjects = object.relatedObjectsWithName(relationshipName) else { assertionFailure("syncRelatedObjectsAndLookupTable should be called only on objects with related objects.") return } - + let relatedObjectIDs = relatedObjects.databaseIDs() let lookupTableRelatedObjectIDs = lookupTable[object.databaseID] ?? Set() - + let relatedObjectIDsToDelete = lookupTableRelatedObjectIDs.subtracting(relatedObjectIDs) if !relatedObjectIDsToDelete.isEmpty { deleteLookups(for: object.databaseID, relatedObjectIDsToDelete, database) } - + let relatedObjectIDsToSave = relatedObjectIDs.subtracting(lookupTableRelatedObjectIDs) if !relatedObjectIDsToSave.isEmpty { saveLookups(for: object.databaseID, relatedObjectIDsToSave, database) } } - + func saveLookups(for objectID: String, _ relatedObjectIDs: Set, _ database: FMDatabase) { - + for relatedObjectID in relatedObjectIDs { let d: [NSObject: Any] = [(objectIDKey as NSString): objectID, (relatedObjectIDKey as NSString): relatedObjectID] let _ = database.rs_insertRow(with: d, insertType: .orIgnore, tableName: name) } } - + // MARK: Fetching - + func fetchRelatedObjectsWithIDs(_ relatedObjectIDs: Set, _ database: FMDatabase) -> [DatabaseObject]? { - + guard let relatedObjects = relatedTable.fetchObjectsWithIDs(relatedObjectIDs, in: database), !relatedObjects.isEmpty else { return nil } return relatedObjects } - + func fetchRelatedObjectIDsMap(_ objectIDs: Set, _ database: FMDatabase) -> RelatedObjectIDsMap? { - + guard let lookupValues = fetchLookupValues(objectIDs, database) else { return nil } @@ -203,20 +203,20 @@ private extension DatabaseLookupTable { } func fetchLookupValues(_ objectIDs: Set, _ database: FMDatabase) -> Set? { - + guard !objectIDs.isEmpty, let resultSet = database.rs_selectRowsWhereKey(objectIDKey, inValues: Array(objectIDs), tableName: name) else { return nil } return lookupValuesWithResultSet(resultSet) } - + func lookupValuesWithResultSet(_ resultSet: FMResultSet) -> Set { - + return resultSet.mapToSet(lookupValueWithRow) } - + func lookupValueWithRow(_ row: FMResultSet) -> LookupValue? { - + guard let objectID = row.string(forColumn: objectIDKey) else { return nil } diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift index 18e84ac75..4bf1611d8 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift @@ -15,7 +15,7 @@ public protocol DatabaseRelatedObjectsTable: DatabaseTable { var databaseIDKey: String { get} var cache: DatabaseObjectCache { get } - + func fetchObjectsWithIDs(_ databaseIDs: Set, in database: FMDatabase) -> [DatabaseObject]? func objectsWithResultSet(_ resultSet: FMResultSet) -> [DatabaseObject] func objectWithRow(_ row: FMResultSet) -> DatabaseObject? diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift index c15e4bde8..6ed4154dd 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift @@ -11,18 +11,18 @@ import Foundation // Maps objectIDs to Set where the Strings are relatedObjectIDs. struct RelatedObjectIDsMap { - + private let dictionary: [String: Set] // objectID: Set - + init(dictionary: [String: Set]) { - + self.dictionary = dictionary } - + init(lookupValues: Set) { - + var d = [String: Set]() - + for lookupValue in lookupValues { let objectID = lookupValue.objectID let relatedObjectID: String = lookupValue.relatedObjectID @@ -33,24 +33,24 @@ struct RelatedObjectIDsMap { d[objectID]!.insert(relatedObjectID) } } - + self.init(dictionary: d) } - + func objectIDs() -> Set { - + return Set(dictionary.keys) } - + func relatedObjectIDs() -> Set { - + var ids = Set() for (_, relatedObjectIDs) in dictionary { ids.formUnion(relatedObjectIDs) } return ids } - + subscript(_ objectID: String) -> Set? { return dictionary[objectID] } diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift index 5afd9b54c..181583ff1 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift @@ -12,16 +12,16 @@ import Foundation // It’s used as the return value for DatabaseLookupTable.fetchRelatedObjects. public struct RelatedObjectsMap { - + private let dictionary: [String: [DatabaseObject]] // objectID: relatedObjects - + init(relatedObjects: [DatabaseObject], relatedObjectIDsMap: RelatedObjectIDsMap) { - + var d = [String: [DatabaseObject]]() let relatedObjectsDictionary = relatedObjects.dictionary() - + for objectID in relatedObjectIDsMap.objectIDs() { - + if let relatedObjectIDs = relatedObjectIDsMap[objectID] { let relatedObjects = relatedObjectIDs.compactMap{ relatedObjectsDictionary[$0] } if !relatedObjects.isEmpty { @@ -29,15 +29,15 @@ public struct RelatedObjectsMap { } } } - + self.dictionary = d } - + public func objectIDs() -> Set { - + return Set(dictionary.keys) } - + public subscript(_ objectID: String) -> [DatabaseObject]? { return dictionary[objectID] } diff --git a/Modules/RSMarkdown/Sources/RSMarkdown/RSMarkdown.swift b/Modules/RSMarkdown/Sources/RSMarkdown/RSMarkdown.swift index ed39b8440..331f6f680 100644 --- a/Modules/RSMarkdown/Sources/RSMarkdown/RSMarkdown.swift +++ b/Modules/RSMarkdown/Sources/RSMarkdown/RSMarkdown.swift @@ -9,7 +9,7 @@ import Foundation import Markdown public struct RSMarkdown { - + /// Converts Markdown text to HTML string /// - Parameter markdown: The Markdown text to convert /// - Returns: HTML string representation of the Markdown diff --git a/Modules/RSMarkdown/Tests/RSMarkdownTests/RSMarkdownTests.swift b/Modules/RSMarkdown/Tests/RSMarkdownTests/RSMarkdownTests.swift index 29422399e..72906782d 100644 --- a/Modules/RSMarkdown/Tests/RSMarkdownTests/RSMarkdownTests.swift +++ b/Modules/RSMarkdown/Tests/RSMarkdownTests/RSMarkdownTests.swift @@ -56,7 +56,7 @@ final class RSMarkdownTests: XCTestCase { measure { let html = RSMarkdown.markdownToHTML(markdown) - + // Verify the output is valid HTML (inside measure block to ensure correctness) XCTAssertFalse(html.isEmpty) XCTAssertTrue(html.contains("<")) @@ -124,7 +124,7 @@ final class RSMarkdownTests: XCTestCase { func testLineBreaksAndParagraphs() throws { let markdown = """ First paragraph. - + Second paragraph with line break. """ @@ -206,17 +206,17 @@ final class RSMarkdownTests: XCTestCase { func testComplexNestedStructures() throws { let markdown = """ # Main Header - + ## Sub Header - + Here's a list with **bold** items: - + 1. First item with [a link](https://example.com) 2. Second item with `inline code` 3. Third item with *emphasis* - + And a code block: - + ``` function test() { return "hello"; @@ -251,17 +251,17 @@ final class RSMarkdownTests: XCTestCase { // Create a very large markdown document let section = """ ## Section Header - + This is a paragraph with **bold**, *italic*, and `code` formatting. - + - List item 1 - List item 2 with [link](https://example.com) - + ```swift let code = "example" print(code) ``` - + """ let largeMarkdown = String(repeating: section, count: 500) diff --git a/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift b/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift index 39c2706bb..d7f2f95c7 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift @@ -17,7 +17,7 @@ public typealias FeedParserCallback = (_ parsedFeed: ParsedFeed?, _ error: Error public struct FeedParser { private static let parseQueue = DispatchQueue(label: "FeedParser parse queue") - + public static func canParse(_ parserData: ParserData) -> Bool { let type = feedType(parserData) diff --git a/Modules/RSParser/Sources/Swift/Feeds/ParsedAttachment.swift b/Modules/RSParser/Sources/Swift/Feeds/ParsedAttachment.swift index 529f773cb..d4c1ebdf2 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/ParsedAttachment.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/ParsedAttachment.swift @@ -20,7 +20,7 @@ public struct ParsedAttachment: Hashable { if url.isEmpty { return nil } - + self.url = url self.mimeType = mimeType self.title = title diff --git a/Modules/RSParser/Sources/Swift/Feeds/ParsedAuthor.swift b/Modules/RSParser/Sources/Swift/Feeds/ParsedAuthor.swift index f7b9e9136..51381f569 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/ParsedAuthor.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/ParsedAuthor.swift @@ -14,7 +14,7 @@ public struct ParsedAuthor: Hashable, Codable { public let url: String? public let avatarURL: String? public let emailAddress: String? - + public init(name: String?, url: String?, avatarURL: String?, emailAddress: String?) { self.name = name self.url = url diff --git a/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift b/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift index 97b187a78..70ec4af51 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift @@ -29,12 +29,12 @@ public struct ParsedItem: Hashable { public let authors: Set? public let tags: Set? public let attachments: Set? - + public init(syncServiceID: String?, uniqueID: String, feedURL: String, url: String?, externalURL: String?, title: String?, language: String?, contentHTML: String?, contentText: String?, markdown: String?, summary: String?, imageURL: String?, bannerImageURL: String?,datePublished: Date?, dateModified: Date?, authors: Set?, tags: Set?, attachments: Set?) { - + self.syncServiceID = syncServiceID self.uniqueID = uniqueID self.feedURL = feedURL diff --git a/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift b/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift index 7347c04dd..12dde3803 100644 --- a/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift @@ -84,7 +84,7 @@ final class AtomParserTests: XCTestCase { d = parserData("neverworkintheory", "atom", "https://neverworkintheory.org/atom.xml") parsedFeed = try! FeedParser.parse(d)! - + foundTestArticle = false for item in parsedFeed.items { if item.title == "Andreas Zeller on Creating Nasty Test Inputs" { @@ -177,7 +177,7 @@ final class AtomParserTests: XCTestCase { guard let attachments = article.attachments else { continue } - + XCTAssertEqual(attachments.count, 1) let attachment = attachments.first! diff --git a/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift b/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift index 444102ea0..627ba8f74 100644 --- a/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift @@ -27,7 +27,7 @@ final class FeedParserTypeTests: XCTestCase { let type = feedType(d) XCTAssertTrue(type == .notAFeed) } - + func testInessentialHTMLType() { let d = parserData("inessential", "html", "http://inessential.com/") @@ -41,7 +41,7 @@ final class FeedParserTypeTests: XCTestCase { let type = feedType(d) XCTAssertTrue(type == .notAFeed) } - + // MARK: RSS func testEMarleyRSSType() { @@ -57,7 +57,7 @@ final class FeedParserTypeTests: XCTestCase { let type = feedType(d) XCTAssertTrue(type == .rss) } - + func testKatieFloydRSSType() { let d = parserData("KatieFloyd", "rss", "https://katiefloyd.com/") @@ -187,14 +187,14 @@ final class FeedParserTypeTests: XCTestCase { // In the case of this feed, the partial data isn’t enough to detect that it’s a JSON Feed. // The type detector should return .unknown rather than .notAFeed. - + let d = parserData("allthis-partial", "json", "http://leancrew.com/allthis/") let type = feedType(d, isPartialData: true) XCTAssertEqual(type, .unknown) } // MARK: Performance - + func testFeedTypePerformance() { // 0.000 on my 2012 iMac. diff --git a/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift b/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift index 71f0c148b..7de63ffed 100644 --- a/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift @@ -47,7 +47,7 @@ final class JSONFeedParserTests: XCTestCase { } func testCurt() { - + let d = parserData("curt", "json", "http://curtclifton.net/") let parsedFeed = try! FeedParser.parse(d)! @@ -83,7 +83,7 @@ final class JSONFeedParserTests: XCTestCase { let parsedFeed = try! FeedParser.parse(d)! XCTAssertEqual(parsedFeed.items.count, 20) XCTAssertEqual(parsedFeed.language, "de-DE") - + for item in parsedFeed.items { XCTAssertEqual(item.language, "de-DE") } diff --git a/Modules/RSParser/Tests/RSParserTests/RSDateParserTests.swift b/Modules/RSParser/Tests/RSParserTests/RSDateParserTests.swift index 281daf5f6..e7ff4f2e9 100644 --- a/Modules/RSParser/Tests/RSParserTests/RSDateParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/RSDateParserTests.swift @@ -10,25 +10,25 @@ import XCTest import RSParser final class RSDateParserTests: XCTestCase { - + static func dateWithValues(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int, _ second: Int) -> Date { var dateComponents = DateComponents() dateComponents.calendar = Calendar.current dateComponents.timeZone = TimeZone(secondsFromGMT: 0) - + dateComponents.year = year dateComponents.month = month dateComponents.day = day dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = second - + return dateComponents.date! } - + func testDateWithString() { var expectedDateResult = Self.dateWithValues(2010, 5, 28, 21, 3, 38) - + var d = RSDateWithString("Fri, 28 May 2010 21:03:38 +0000") XCTAssertEqual(d, expectedDateResult) @@ -93,7 +93,7 @@ final class RSDateParserTests: XCTestCase { let d = RSDateWithString("2010-11-17 08:40:07-05:00") XCTAssertEqual(d, expectedDateResult) } - + func testFeedbinDate() { let expectedDateResult = Self.dateWithValues(2019, 9, 27, 21, 01, 48) let d = RSDateWithString("2019-09-27T21:01:48.000000Z") diff --git a/Modules/RSTree/Sources/RSTree/NSOutlineView+RSTree.swift b/Modules/RSTree/Sources/RSTree/NSOutlineView+RSTree.swift index bd26475c9..bfb0071d3 100644 --- a/Modules/RSTree/Sources/RSTree/NSOutlineView+RSTree.swift +++ b/Modules/RSTree/Sources/RSTree/NSOutlineView+RSTree.swift @@ -21,7 +21,7 @@ public extension NSOutlineView { if numberOfNodes < 2 { return false } - + let indexOfNodeToSelect = numberOfNodes - 1 for i in 1...indexOfNodeToSelect { // Start at 1 to skip root node. diff --git a/Modules/RSTree/Sources/RSTree/Node.swift b/Modules/RSTree/Sources/RSTree/Node.swift index 0c70265fe..3ae17e89d 100644 --- a/Modules/RSTree/Sources/RSTree/Node.swift +++ b/Modules/RSTree/Sources/RSTree/Node.swift @@ -11,7 +11,7 @@ import Foundation // Main thread only. public final class Node: Hashable { - + public weak var parent: Node? public let representedObject: AnyObject public var canHaveChildNodes = false @@ -26,11 +26,11 @@ public final class Node: Hashable { } return true } - + public var numberOfChildNodes: Int { return childNodes.count } - + public var indexPath: IndexPath { if let parent = parent { let parentPath = parent.indexPath @@ -41,20 +41,20 @@ public final class Node: Hashable { } return IndexPath(index: 0) //root node } - + public var level: Int { if let parent = parent { return parent.level + 1 } return 0 } - + public var isLeaf: Bool { return numberOfChildNodes < 1 } - + public init(representedObject: AnyObject, parent: Node?) { - + precondition(Thread.isMainThread) self.representedObject = representedObject @@ -63,9 +63,9 @@ public final class Node: Hashable { self.uniqueID = Node.incrementingID Node.incrementingID += 1 } - + public class func genericRootNode() -> Node { - + let node = Node(representedObject: TopLevelRepresentedObject(), parent: nil) node.canHaveChildNodes = true return node @@ -86,7 +86,7 @@ public final class Node: Hashable { } public func childAtIndex(_ index: Int) -> Node? { - + if index >= childNodes.count || index < 0 { return nil } @@ -94,12 +94,12 @@ public final class Node: Hashable { } public func indexOfChild(_ node: Node) -> Int? { - + return childNodes.firstIndex{ (oneChildNode) -> Bool in oneChildNode === node } } - + public func childNodeRepresentingObject(_ obj: AnyObject) -> Node? { return findNodeRepresentingObject(obj, recursively: false) } diff --git a/Modules/RSTree/Sources/RSTree/TreeController.swift b/Modules/RSTree/Sources/RSTree/TreeController.swift index 84178243e..56ae68032 100644 --- a/Modules/RSTree/Sources/RSTree/TreeController.swift +++ b/Modules/RSTree/Sources/RSTree/TreeController.swift @@ -21,32 +21,32 @@ public final class TreeController { public let rootNode: Node public init(delegate: TreeControllerDelegate, rootNode: Node) { - + self.delegate = delegate self.rootNode = rootNode rebuild() } public convenience init(delegate: TreeControllerDelegate) { - + self.init(delegate: delegate, rootNode: Node.genericRootNode()) } - + @discardableResult public func rebuild() -> Bool { // Rebuild and re-sort. Return true if any changes in the entire tree. - + return rebuildChildNodes(node: rootNode) } - + public func visitNodes(_ visitBlock: NodeVisitBlock) { - + visitNode(rootNode, visitBlock) } - + public func nodeInArrayRepresentingObject(nodes: [Node], representedObject: AnyObject, recurse: Bool = false) -> Node? { - + for oneNode in nodes { if oneNode.representedObject === representedObject { @@ -85,17 +85,17 @@ public final class TreeController { } private extension TreeController { - + func visitNode(_ node: Node, _ visitBlock: NodeVisitBlock) { - + visitBlock(node) node.childNodes.forEach{ (oneChildNode) in visitNode(oneChildNode, visitBlock) } } - + func nodeArraysAreEqual(_ nodeArray1: [Node]?, _ nodeArray2: [Node]?) -> Bool { - + if nodeArray1 == nil && nodeArray2 == nil { return true } @@ -105,25 +105,25 @@ private extension TreeController { if nodeArray1 == nil && nodeArray2 != nil { return false } - + return nodeArray1! == nodeArray2! } - + func rebuildChildNodes(node: Node) -> Bool { - + if !node.canHaveChildNodes { return false } - + var childNodesDidChange = false - + let childNodes = delegate?.treeController(treeController: self, childNodesFor: node) ?? [Node]() - + childNodesDidChange = !nodeArraysAreEqual(childNodes, node.childNodes) if (childNodesDidChange) { node.childNodes = childNodes } - + childNodes.forEach{ (oneChildNode) in if rebuildChildNodes(node: oneChildNode) { childNodesDidChange = true diff --git a/Modules/RSWeb/Sources/RSWeb/CacheControlInfo.swift b/Modules/RSWeb/Sources/RSWeb/CacheControlInfo.swift index d6de46d38..b17b567dd 100644 --- a/Modules/RSWeb/Sources/RSWeb/CacheControlInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/CacheControlInfo.swift @@ -21,7 +21,7 @@ public struct CacheControlInfo: Codable, Equatable { public var canResume: Bool { Date() >= resumeDate } - + public init?(urlResponse: HTTPURLResponse) { guard let cacheControlValue = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.cacheControl) else { return nil @@ -35,7 +35,7 @@ public struct CacheControlInfo: Codable, Equatable { guard let maxAge = Self.parseMaxAge(value) else { return nil } - + let d = Date() self.dateCreated = d self.maxAge = maxAge diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift b/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift index 1a3444e76..3dae384ad 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift @@ -11,12 +11,12 @@ import Foundation // Main thread only. public extension Notification.Name { - + static let DownloadProgressDidChange = Notification.Name(rawValue: "DownloadProgressDidChange") } public final class DownloadProgress { - + public var numberOfTasks = 0 { didSet { if numberOfTasks == 0 && numberRemaining != 0 { @@ -27,7 +27,7 @@ public final class DownloadProgress { } } } - + public var numberRemaining = 0 { didSet { if numberRemaining != oldValue { @@ -46,22 +46,22 @@ public final class DownloadProgress { } return n } - + public var isComplete: Bool { assert(Thread.isMainThread) return numberRemaining < 1 } - + public init(numberOfTasks: Int) { assert(Thread.isMainThread) self.numberOfTasks = numberOfTasks } - + public func addToNumberOfTasks(_ n: Int) { assert(Thread.isMainThread) numberOfTasks = numberOfTasks + n } - + public func addToNumberOfTasksAndRemaining(_ n: Int) { assert(Thread.isMainThread) numberOfTasks = numberOfTasks + n @@ -74,14 +74,14 @@ public final class DownloadProgress { numberRemaining = numberRemaining - 1 } } - + public func completeTasks(_ tasks: Int) { assert(Thread.isMainThread) if numberRemaining >= tasks { numberRemaining = numberRemaining - tasks } } - + public func reset() { assert(Thread.isMainThread) numberRemaining = 0 @@ -92,7 +92,7 @@ public final class DownloadProgress { // MARK: - Private private extension DownloadProgress { - + func postDidChangeNotification() { DispatchQueue.main.async { NotificationCenter.default.post(name: .DownloadProgressDidChange, object: self) diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift index e86c00b76..094261659 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift @@ -59,7 +59,7 @@ struct HTTP4xxResponse { self.delegate = delegate super.init() - + let sessionConfiguration = URLSessionConfiguration.ephemeral sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData sessionConfiguration.timeoutIntervalForRequest = 15.0 @@ -75,7 +75,7 @@ struct HTTP4xxResponse { urlSession = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: OperationQueue.main) } - + deinit { urlSession.invalidateAndCancel() } @@ -192,7 +192,7 @@ extension DownloadSession: URLSessionDataDelegate { addDataTaskFromQueueIfNecessary() completionHandler(.allow) } - + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let info = infoForTask(dataTask) else { @@ -490,7 +490,7 @@ extension URLSessionTask { // MARK: - DownloadInfo private final class DownloadInfo { - + let url: URL let data = NSMutableData() var urlResponse: URLResponse? @@ -499,9 +499,9 @@ private final class DownloadInfo { self.url = url } - + func addData(_ d: Data) { - + data.append(d) } } diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index 998422381..dc6161041 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -21,7 +21,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> private let urlSession: URLSession private var callbacks = [URL: [DownloadCallback]]() private let cache = DownloadCache.shared - + nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Downloader") private init() { @@ -31,7 +31,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> sessionConfiguration.httpCookieAcceptPolicy = .never sessionConfiguration.httpMaximumConnectionsPerHost = 1 sessionConfiguration.httpCookieStorage = nil - + if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } diff --git a/Modules/RSWeb/Sources/RSWeb/HTMLMetadataCache.swift b/Modules/RSWeb/Sources/RSWeb/HTMLMetadataCache.swift index 310ac1e2d..f8bc23bf2 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTMLMetadataCache.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTMLMetadataCache.swift @@ -17,7 +17,7 @@ public extension Notification.Name { public final class HTMLMetadataCache: Sendable { static let shared = HTMLMetadataCache() - + // Sent along with .htmlMetadataAvailable notification public struct UserInfoKey { public static let htmlMetadata = "htmlMetadata" diff --git a/Modules/RSWeb/Sources/RSWeb/HTMLMetadataDownloader.swift b/Modules/RSWeb/Sources/RSWeb/HTMLMetadataDownloader.swift index 541d91a07..afed0b4cf 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTMLMetadataDownloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTMLMetadataDownloader.swift @@ -94,11 +94,11 @@ private extension HTMLMetadataDownloader { self.cache[url] = htmlMetadata return } - + if let statusCode = response?.forcedStatusCode, (400...499).contains(statusCode) { self.noteURLDidReturn4xx(url) } - + Self.logger.debug("HTMLMetadataDownloader failed download for \(url)") } } diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift b/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift index c62a382d4..c66647cf8 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift @@ -9,10 +9,10 @@ import Foundation public struct HTTPConditionalGetInfo: Codable, Equatable { - + public let lastModified: String? public let etag: String? - + public init?(lastModified: String?, etag: String?) { if lastModified == nil && etag == nil { return nil @@ -20,7 +20,7 @@ public struct HTTPConditionalGetInfo: Codable, Equatable { self.lastModified = lastModified self.etag = etag } - + public init?(urlResponse: HTTPURLResponse) { let lastModified = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.lastModified) let etag = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.etag) @@ -32,7 +32,7 @@ public struct HTTPConditionalGetInfo: Codable, Equatable { let etag = headers[HTTPResponseHeader.etag] as? String self.init(lastModified: lastModified, etag: etag) } - + public func addRequestHeadersToURLRequest(_ urlRequest: inout URLRequest) { // Bug seen in the wild: lastModified with last possible 32-bit date, which is in 2038. Ignore those. // TODO: drop this check in late 2037. diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPDateInfo.swift b/Modules/RSWeb/Sources/RSWeb/HTTPDateInfo.swift index 06d95f811..be5c2c649 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTTPDateInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPDateInfo.swift @@ -9,15 +9,15 @@ import Foundation public struct HTTPDateInfo: Codable, Equatable { - + private static let formatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE, dd LLL yyyy HH:mm:ss zzz" return dateFormatter }() - + public let date: Date? - + public init?(urlResponse: HTTPURLResponse) { if let headerDate = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.date) { date = HTTPDateInfo.formatter.date(from: headerDate) @@ -25,5 +25,5 @@ public struct HTTPDateInfo: Codable, Equatable { date = nil } } - + } diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift b/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift index 38f4ed774..c3cbe1b24 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift @@ -9,33 +9,33 @@ import Foundation public struct HTTPLinkPagingInfo { - + public let nextPage: String? public let lastPage: String? - + public init(nextPage: String?, lastPage: String?) { self.nextPage = nextPage self.lastPage = lastPage } public init(urlResponse: HTTPURLResponse) { - + guard let linkHeader = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.link) else { self.init(nextPage: nil, lastPage: nil) return } let links = linkHeader.components(separatedBy: ",") - + var dict: [String: String] = [:] links.forEach({ let components = $0.components(separatedBy:"; ") let page = components[0].trimmingCharacters(in: CharacterSet(charactersIn: " <>")) dict[components[1]] = page }) - + self.init(nextPage: dict["rel=\"next\""], lastPage: dict["rel=\"last\""]) - + } } diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift b/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift index 7021a6fcc..48e659854 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift @@ -13,9 +13,9 @@ public struct HTTPRequestHeader { public static let userAgent = "User-Agent" public static let authorization = "Authorization" public static let contentType = "Content-Type" - + // Conditional GET - + public static let ifModifiedSince = "If-Modified-Since" public static let ifNoneMatch = "If-None-Match" //Etag } diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift b/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift index e983ced2f..6e9bf46e7 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift @@ -12,10 +12,10 @@ public struct HTTPResponseCode { // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // Not an enum because the main interest is the actual values. - + public static let responseContinue = 100 //"continue" is a language keyword, hence the weird name public static let switchingProtocols = 101 - + public static let OK = 200 public static let created = 201 public static let accepted = 202 @@ -23,7 +23,7 @@ public struct HTTPResponseCode { public static let noContent = 204 public static let resetContent = 205 public static let partialContent = 206 - + public static let redirectMultipleChoices = 300 public static let redirectPermanent = 301 public static let redirectTemporary = 302 diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPResponseHeader.swift b/Modules/RSWeb/Sources/RSWeb/HTTPResponseHeader.swift index cfdd588ce..ba86cd3a1 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPResponseHeader.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPResponseHeader.swift @@ -17,7 +17,7 @@ public struct HTTPResponseHeader { // Conditional GET. See: // http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/ - + public static let lastModified = "Last-Modified" // Changed to the canonical case for lookups against a case sensitive dictionary // https://developer.apple.com/documentation/foundation/httpurlresponse/1417930-allheaderfields diff --git a/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift b/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift index 1e8a1298f..d6ac8a8f0 100755 --- a/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift +++ b/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift @@ -14,11 +14,11 @@ public class MacWebBrowser { /// Opens a URL in the default browser. @discardableResult public class func openURL(_ url: URL, inBackground: Bool = false) -> Bool { - + guard let preparedURL = url.preparedForOpeningInBrowser() else { return false } - + if inBackground { let configuration = NSWorkspace.OpenConfiguration() diff --git a/Modules/RSWeb/Sources/RSWeb/MimeType.swift b/Modules/RSWeb/Sources/RSWeb/MimeType.swift index 36225b718..4b384facf 100755 --- a/Modules/RSWeb/Sources/RSWeb/MimeType.swift +++ b/Modules/RSWeb/Sources/RSWeb/MimeType.swift @@ -9,9 +9,9 @@ import Foundation public struct MimeType { - + // This could certainly use expansion. - + public static let png = "image/png" public static let jpeg = "image/jpeg" public static let jpg = "image/jpg" @@ -20,29 +20,29 @@ public struct MimeType { } public extension String { - + func isMimeTypeImage() -> Bool { - + return self.isOfGeneralMimeType("image") } - + func isMimeTypeAudio() -> Bool { - + return self.isOfGeneralMimeType("audio") } - + func isMimeTypeVideo() -> Bool { - + return self.isOfGeneralMimeType("video") } - + func isMimeTypeTimeBasedMedia() -> Bool { - + return self.isMimeTypeAudio() || self.isMimeTypeVideo() } - + private func isOfGeneralMimeType(_ type: String) -> Bool { - + let lower = self.lowercased() if lower.hasPrefix(type) { return true diff --git a/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift index 3bed1da06..198bba279 100644 --- a/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift @@ -35,5 +35,5 @@ public extension String { return escaped } - + } diff --git a/Modules/RSWeb/Sources/RSWeb/URLComponents+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/URLComponents+RSWeb.swift index 7ab2ccb9c..78c4cf864 100644 --- a/Modules/RSWeb/Sources/RSWeb/URLComponents+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/URLComponents+RSWeb.swift @@ -8,7 +8,7 @@ import Foundation public extension URLComponents { - + // `+` is a valid character in query component as per RFC 3986 (https://developer.apple.com/documentation/foundation/nsurlcomponents/1407752-queryitems) // workaround: // - http://www.openradar.me/24076063 @@ -17,18 +17,18 @@ public extension URLComponents { guard !(queryItems?.isEmpty ?? true) else { return nil } - + var allowedCharacters = CharacterSet.urlQueryAllowed allowedCharacters.remove(charactersIn: "!*'();:@&=+$,/?%#[]") - + var queries = [String]() for queryItem in queryItems! { if let value = queryItem.value?.addingPercentEncoding(withAllowedCharacters: allowedCharacters)?.replacingOccurrences(of: "%20", with: "+") { queries.append("\(queryItem.name)=\(value)") } } - + return queries.joined(separator: "&") } - + } diff --git a/Modules/RSWeb/Sources/RSWeb/URLRequest+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/URLRequest+RSWeb.swift index 348f9d140..654663bf3 100755 --- a/Modules/RSWeb/Sources/RSWeb/URLRequest+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/URLRequest+RSWeb.swift @@ -11,18 +11,18 @@ import Foundation public extension URLRequest { @discardableResult mutating func addBasicAuthorization(username: String, password: String) -> Bool { - + // Do this *only* with https. And not even then if you can help it. - + let s = "\(username):\(password)" guard let d = s.data(using: .utf8, allowLossyConversion: false) else { return false } - + let base64EncodedString = d.base64EncodedString() let authorization = "Basic \(base64EncodedString)" setValue(authorization, forHTTPHeaderField: HTTPRequestHeader.authorization) - + return true } } diff --git a/Modules/RSWeb/Sources/RSWeb/URLResponse+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/URLResponse+RSWeb.swift index 9e00b2cbb..a9f219f58 100755 --- a/Modules/RSWeb/Sources/RSWeb/URLResponse+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/URLResponse+RSWeb.swift @@ -9,15 +9,15 @@ import Foundation public extension URLResponse { - + var statusIsOK: Bool { return forcedStatusCode >= 200 && forcedStatusCode <= 299 } - + var forcedStatusCode: Int { - + // Return actual statusCode or 0 if there isn’t one. - + if let response = self as? HTTPURLResponse { return response.statusCode } @@ -26,20 +26,20 @@ public extension URLResponse { } public extension HTTPURLResponse { - + func valueForHTTPHeaderField(_ headerField: String) -> String? { - + // Case-insensitive. HTTP headers may not be in the case you expect. - + let lowerHeaderField = headerField.lowercased() - + for (key, value) in allHeaderFields { - + if lowerHeaderField == (key as? String)?.lowercased() { return value as? String } } - + return nil } } diff --git a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift index 0a851c51d..dcced5503 100755 --- a/Modules/RSWeb/Sources/RSWeb/UserAgent.swift +++ b/Modules/RSWeb/Sources/RSWeb/UserAgent.swift @@ -9,7 +9,7 @@ import Foundation public struct UserAgent { - + public static func fromInfoPlist() -> String? { return Bundle.main.object(forInfoDictionaryKey: "UserAgent") as? String diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift index b1a8b1a3e..9991bd08e 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift @@ -14,7 +14,7 @@ public enum TransportError: LocalizedError { case noURL case suspended case httpError(status: Int) - + public var errorDescription: String? { switch self { case .httpError(let status): @@ -111,11 +111,11 @@ public enum TransportError: LocalizedError { return NSLocalizedString("An unknown network error occurred.", comment: "Unknown error") } } - + } public protocol Transport { - + /// Cancels all pending requests func cancelAll() @@ -125,17 +125,17 @@ public protocol Transport { /// Sends URLRequest and returns the HTTP headers and the data payload. func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) - + /// Sends URLRequest that doesn't require any result information. func send(request: URLRequest, method: String, completion: @escaping (Result) -> Void) - + /// Sends URLRequest with a data payload and returns the HTTP headers and the data payload. func send(request: URLRequest, method: String, payload: Data, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) - + } extension URLSession: Transport { - + public func cancelAll() { getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in dataTasks.forEach { $0.cancel() } @@ -175,10 +175,10 @@ extension URLSession: Transport { } public func send(request: URLRequest, method: String, completion: @escaping (Result) -> Void) { - + var sendRequest = request sendRequest.httpMethod = method - + let task = self.dataTask(with: sendRequest) { (data, response, error) in DispatchQueue.main.async { if let error = error { @@ -199,12 +199,12 @@ extension URLSession: Transport { } task.resume() } - + public func send(request: URLRequest, method: String, payload: Data, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) { - + var sendRequest = request sendRequest.httpMethod = method - + let task = self.uploadTask(with: sendRequest, from: payload) { (data, response, error) in DispatchQueue.main.async { if let error = error { @@ -221,14 +221,14 @@ extension URLSession: Transport { default: completion(.failure(TransportError.httpError(status: response.forcedStatusCode))) } - + } } task.resume() } - + public static func webserviceTransport() -> Transport { - + let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData sessionConfiguration.timeoutIntervalForRequest = 60.0 @@ -237,11 +237,11 @@ extension URLSession: Transport { sessionConfiguration.httpMaximumConnectionsPerHost = 2 sessionConfiguration.httpCookieStorage = nil sessionConfiguration.urlCache = nil - + if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } - + return URLSession(configuration: sessionConfiguration) } } diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift index 8d11954a1..ec780a118 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift @@ -9,12 +9,12 @@ import Foundation extension Transport { - + /** Sends an HTTP get and returns JSON object(s) */ public func send(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) { - + send(request: request) { result in DispatchQueue.main.async { @@ -51,12 +51,12 @@ extension Transport { } } } - + /** Sends the specified HTTP method with a JSON payload. */ public func send(request: URLRequest, method: String, payload: P, completion: @escaping (Result) -> Void) { - + var postRequest = request postRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType) @@ -79,12 +79,12 @@ extension Transport { } } } - + /** Sends the specified HTTP method with a JSON payload and returns JSON object(s). */ public func send(request: URLRequest, method: String, payload: P, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) { - + var postRequest = request postRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType) @@ -95,7 +95,7 @@ extension Transport { completion(.failure(error)) return } - + send(request: postRequest, method: method, payload: data) { result in DispatchQueue.main.async { diff --git a/Modules/Secrets/Sources/Secrets/Credentials.swift b/Modules/Secrets/Sources/Secrets/Credentials.swift index e7d0f0262..7571b7260 100644 --- a/Modules/Secrets/Sources/Secrets/Credentials.swift +++ b/Modules/Secrets/Sources/Secrets/Credentials.swift @@ -28,7 +28,7 @@ public struct Credentials: Equatable { public let type: CredentialsType public let username: String public let secret: String - + public init(type: CredentialsType, username: String, secret: String) { self.type = type self.username = username diff --git a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift index 1043d9f6d..c220c21bd 100644 --- a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift +++ b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift @@ -9,7 +9,7 @@ import Foundation public struct CredentialsManager { - + private static var keychainGroup: String? = { guard let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String else { return nil @@ -29,7 +29,7 @@ public struct CredentialsManager { if credentials.type != .basic { query[kSecAttrSecurityDomain as String] = credentials.type.rawValue } - + if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } @@ -47,27 +47,27 @@ public struct CredentialsManager { default: throw CredentialsError.unhandledError(status: status) } - + var deleteQuery = query deleteQuery.removeValue(forKey: kSecAttrAccessible as String) SecItemDelete(deleteQuery as CFDictionary) - + let addStatus = SecItemAdd(query as CFDictionary, nil) if addStatus != errSecSuccess { throw CredentialsError.unhandledError(status: status) } } - + public static func retrieveCredentials(type: CredentialsType, server: String, username: String) throws -> Credentials? { - + var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, kSecAttrAccount as String: username, kSecAttrServer as String: server, kSecMatchLimit as String: kSecMatchLimitOne, kSecReturnAttributes as String: true, kSecReturnData as String: true] - + if type != .basic { query[kSecAttrSecurityDomain as String] = type.rawValue } @@ -75,37 +75,37 @@ public struct CredentialsManager { if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } - + var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) - + guard status != errSecItemNotFound else { return nil } - + guard status == errSecSuccess else { throw CredentialsError.unhandledError(status: status) } - + guard let existingItem = item as? [String : Any], let secretData = existingItem[kSecValueData as String] as? Data, let secret = String(data: secretData, encoding: String.Encoding.utf8) else { return nil } - + return Credentials(type: type, username: username, secret: secret) - + } - + public static func removeCredentials(type: CredentialsType, server: String, username: String) throws { - + var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, kSecAttrAccount as String: username, kSecAttrServer as String: server, kSecMatchLimit as String: kSecMatchLimitOne, kSecReturnAttributes as String: true, kSecReturnData as String: true] - + if type != .basic { query[kSecAttrSecurityDomain as String] = type.rawValue } @@ -113,12 +113,12 @@ public struct CredentialsManager { if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } - + let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw CredentialsError.unhandledError(status: status) } - + } - + } diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/Constants.swift b/Modules/SyncDatabase/Sources/SyncDatabase/Constants.swift index 86d01b923..a80e5c0a7 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/Constants.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/Constants.swift @@ -9,13 +9,13 @@ import Foundation struct DatabaseTableName { - + static let syncStatus = "syncStatus" - + } struct DatabaseKey { - + // Sync Status static let articleID = "articleID" static let key = "key" diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift index 93726a113..036c1e69a 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift @@ -35,7 +35,7 @@ public struct SyncDatabase { public func insertStatuses(_ statuses: [SyncStatus], completion: @escaping DatabaseCompletionBlock) { syncStatusTable.insertStatuses(statuses, completion: completion) } - + public func selectForProcessing(limit: Int? = nil, completion: @escaping SyncStatusesCompletionBlock) { return syncStatusTable.selectForProcessing(limit: limit, completion: completion) } @@ -47,11 +47,11 @@ public struct SyncDatabase { public func selectPendingReadStatusArticleIDs(completion: @escaping SyncStatusArticleIDsCompletionBlock) { syncStatusTable.selectPendingReadStatusArticleIDs(completion: completion) } - + public func selectPendingStarredStatusArticleIDs(completion: @escaping SyncStatusArticleIDsCompletionBlock) { syncStatusTable.selectPendingStarredStatusArticleIDs(completion: completion) } - + public func resetAllSelectedForProcessing(completion: DatabaseCompletionBlock? = nil) { syncStatusTable.resetAllSelectedForProcessing(completion: completion) } @@ -59,7 +59,7 @@ public struct SyncDatabase { public func resetSelectedForProcessing(_ articleIDs: [String], completion: DatabaseCompletionBlock? = nil) { syncStatusTable.resetSelectedForProcessing(articleIDs, completion: completion) } - + public func deleteSelectedForProcessing(_ articleIDs: [String], completion: DatabaseCompletionBlock? = nil) { syncStatusTable.deleteSelectedForProcessing(articleIDs, completion: completion) } @@ -81,7 +81,7 @@ public struct SyncDatabase { // MARK: - Private private extension SyncDatabase { - + static let tableCreationStatements = """ CREATE TABLE if not EXISTS syncStatus (articleID TEXT NOT NULL, key TEXT NOT NULL, flag BOOL NOT NULL DEFAULT 0, selected BOOL NOT NULL DEFAULT 0, PRIMARY KEY (articleID, key)); """ diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift index cb6c71a45..34a7c091d 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift @@ -11,13 +11,13 @@ import Articles import RSDatabase public struct SyncStatus: Hashable, Equatable { - + public enum Key: String { case read = "read" case starred = "starred" case deleted = "deleted" case new = "new" - + public init(_ articleStatusKey: ArticleStatus.Key) { switch articleStatusKey { case .read: @@ -26,23 +26,23 @@ public struct SyncStatus: Hashable, Equatable { self = Self.starred } } - + } public let articleID: String public let key: SyncStatus.Key public let flag: Bool public let selected: Bool - + public init(articleID: String, key: SyncStatus.Key, flag: Bool, selected: Bool = false) { self.articleID = articleID self.key = key self.flag = flag self.selected = selected } - + public func databaseDictionary() -> DatabaseDictionary { return [DatabaseKey.articleID: articleID, DatabaseKey.key: key.rawValue, DatabaseKey.flag: flag, DatabaseKey.selected: selected] } - + } diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift index 0ab0d80cb..40df3e560 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatusTable.swift @@ -56,7 +56,7 @@ struct SyncStatusTable: DatabaseTable { } } } - + func selectPendingCount(_ completion: @escaping DatabaseIntCompletionBlock) { queue.runInDatabase { databaseResult in var count: Int = 0 @@ -90,11 +90,11 @@ struct SyncStatusTable: DatabaseTable { func selectPendingReadStatusArticleIDs(completion: @escaping SyncStatusArticleIDsCompletionBlock) { selectPendingArticleIDsAsync(.read, completion) } - + func selectPendingStarredStatusArticleIDs(completion: @escaping SyncStatusArticleIDsCompletionBlock) { selectPendingArticleIDsAsync(.starred, completion) } - + func resetAllSelectedForProcessing(completion: DatabaseCompletionBlock? = nil) { queue.runInTransaction { databaseResult in @@ -118,7 +118,7 @@ struct SyncStatusTable: DatabaseTable { callCompletion(completion, nil) return } - + queue.runInTransaction { databaseResult in func makeDatabaseCall(_ database: FMDatabase) { @@ -137,13 +137,13 @@ struct SyncStatusTable: DatabaseTable { } } } - + func deleteSelectedForProcessing(_ articleIDs: [String], completion: DatabaseCompletionBlock? = nil) { guard !articleIDs.isEmpty else { callCompletion(completion, nil) return } - + queue.runInTransaction { databaseResult in func makeDatabaseCall(_ database: FMDatabase) { @@ -162,7 +162,7 @@ struct SyncStatusTable: DatabaseTable { } } } - + func insertStatuses(_ statuses: [SyncStatus], completion: @escaping DatabaseCompletionBlock) { queue.runInTransaction { databaseResult in @@ -180,7 +180,7 @@ struct SyncStatusTable: DatabaseTable { } } } - + } private extension SyncStatusTable { @@ -191,13 +191,13 @@ private extension SyncStatusTable { let key = SyncStatus.Key(rawValue: rawKey) else { return nil } - + let flag = row.bool(forColumn: DatabaseKey.flag) let selected = row.bool(forColumn: DatabaseKey.selected) - + return SyncStatus(articleID: articleID, key: key, flag: flag, selected: selected) } - + func selectPendingArticleIDsAsync(_ statusKey: ArticleStatus.Key, _ completion: @escaping SyncStatusArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in @@ -228,7 +228,7 @@ private extension SyncStatusTable { } } } - + } private func callCompletion(_ completion: DatabaseCompletionBlock?, _ databaseError: DatabaseError?) { diff --git a/Shared/AccountType+Helpers.swift b/Shared/AccountType+Helpers.swift index 3c88d5d75..e047b6bb9 100644 --- a/Shared/AccountType+Helpers.swift +++ b/Shared/AccountType+Helpers.swift @@ -16,11 +16,11 @@ import UIKit import SwiftUI extension AccountType { - + // TODO: Move this to the Account Package. - + func localizedAccountName() -> String { - + switch self { case .onMyMac: return NSLocalizedString("account.name.on-my-device", tableName: "DefaultAccountNames", comment: "Device specific default account name, e.g: On my iPhone") @@ -42,7 +42,7 @@ extension AccountType { return NSLocalizedString("The Old Reader", comment: "Account name") } } - + // MARK: - SwiftUI Images func image() -> Image { switch self { diff --git a/Shared/Activity/ActivityManager.swift b/Shared/Activity/ActivityManager.swift index 582cad871..172c806cb 100644 --- a/Shared/Activity/ActivityManager.swift +++ b/Shared/Activity/ActivityManager.swift @@ -16,7 +16,7 @@ import Intents import UniformTypeIdentifiers final class ActivityManager { - + private var nextUnreadActivity: NSUserActivity? private var selectingActivity: NSUserActivity? private var readingActivity: NSUserActivity? @@ -26,11 +26,11 @@ final class ActivityManager { if let activity = readingActivity { return activity } - + if let activity = selectingActivity { return activity } - + let activity = NSUserActivity(activityType: ActivityType.restoration.rawValue) #if os(iOS) activity.persistentIdentifier = UUID().uuidString @@ -38,40 +38,40 @@ final class ActivityManager { activity.becomeCurrent() return activity } - + init() { NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) } - + func invalidateCurrentActivities() { invalidateReading() invalidateSelecting() invalidateNextUnread() } - + func selecting(sidebarItem: SidebarItem) { invalidateCurrentActivities() - + selectingActivity = makeSelectFeedActivity(sidebarItem: sidebarItem) - + if let feed = sidebarItem as? Feed { updateSelectingActivityFeedSearchAttributes(with: feed) } - + donate(selectingActivity!) } - + func invalidateSelecting() { selectingActivity?.invalidate() selectingActivity = nil } - + func selectingNextUnread() { guard nextUnreadActivity == nil else { return } nextUnreadActivity = NSUserActivity(activityType: ActivityType.nextUnread.rawValue) nextUnreadActivity!.title = NSLocalizedString("See first unread article", comment: "First Unread") - + #if os(iOS) nextUnreadActivity!.suggestedInvocationPhrase = nextUnreadActivity!.title nextUnreadActivity!.isEligibleForPrediction = true @@ -81,60 +81,60 @@ final class ActivityManager { donate(nextUnreadActivity!) } - + func invalidateNextUnread() { nextUnreadActivity?.invalidate() nextUnreadActivity = nil } - + func reading(feed: SidebarItem?, article: Article?) { invalidateReading() invalidateNextUnread() - + guard let article = article else { return } readingActivity = makeReadArticleActivity(sidebarItem: feed, article: article) - + #if os(iOS) updateReadArticleSearchAttributes(with: article) #endif - + donate(readingActivity!) } - + func invalidateReading() { readingActivity?.invalidate() readingActivity = nil readingArticle = nil } - + #if os(iOS) static func cleanUp(_ account: Account) { var ids = [String]() - + if let folders = account.folders { for folder in folders { ids.append(identifier(for: folder)) } } - + for feed in account.flattenedFeeds() { ids.append(contentsOf: identifiers(for: feed)) } - + CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ids) } - + static func cleanUp(_ folder: Folder) { var ids = [String]() ids.append(identifier(for: folder)) - + for feed in folder.flattenedFeeds() { ids.append(contentsOf: identifiers(for: feed)) } - + CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ids) } - + static func cleanUp(_ feed: Feed) { CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: identifiers(for: feed)) } @@ -144,13 +144,13 @@ final class ActivityManager { guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed, let activityFeedId = selectingActivity?.userInfo?[ArticlePathKey.feedID] as? String else { return } - + #if os(iOS) if let article = readingArticle, activityFeedId == article.feedID { updateReadArticleSearchAttributes(with: article) } #endif - + if activityFeedId == feed.feedID { updateSelectingActivityFeedSearchAttributes(with: feed) } @@ -161,17 +161,17 @@ final class ActivityManager { // MARK: Private private extension ActivityManager { - + func makeSelectFeedActivity(sidebarItem: SidebarItem) -> NSUserActivity { let activity = NSUserActivity(activityType: ActivityType.selectFeed.rawValue) - + let localizedText = NSLocalizedString("See articles in “%@”", comment: "See articles in Folder") let title = NSString.localizedStringWithFormat(localizedText as NSString, sidebarItem.nameForDisplay) as String activity.title = title - + activity.keywords = Set(makeKeywords(title)) activity.isEligibleForSearch = true - + let articleFetcherIdentifierUserInfo = sidebarItem.sidebarItemID?.userInfo ?? [AnyHashable: Any]() activity.userInfo = [UserInfoKey.feedIdentifier: articleFetcherIdentifierUserInfo] activity.requiredUserInfoKeys = Set(activity.userInfo!.keys.map { $0 as! String }) @@ -186,11 +186,11 @@ private extension ActivityManager { return activity } - + func makeReadArticleActivity(sidebarItem: SidebarItem?, article: Article) -> NSUserActivity { let activity = NSUserActivity(activityType: ActivityType.readArticle.rawValue) activity.title = ArticleStringFormatter.truncatedTitle(article) - + if let sidebarItem { let articleFetcherIdentifierUserInfo = sidebarItem.sidebarItemID?.userInfo ?? [AnyHashable: Any]() let articlePathUserInfo = article.pathUserInfo @@ -199,9 +199,9 @@ private extension ActivityManager { activity.userInfo = [UserInfoKey.articlePath: article.pathUserInfo] } activity.requiredUserInfoKeys = Set(activity.userInfo!.keys.map { $0 as! String }) - + activity.isEligibleForHandoff = true - + activity.persistentIdentifier = ActivityManager.identifier(for: article) #if os(iOS) @@ -212,13 +212,13 @@ private extension ActivityManager { #endif readingArticle = article - + return activity } - + #if os(iOS) func updateReadArticleSearchAttributes(with article: Article) { - + let attributeSet = CSSearchableItemAttributeSet(itemContentType: UTType.compositeContent.identifier) attributeSet.title = ArticleStringFormatter.truncatedTitle(article) attributeSet.contentDescription = article.summary @@ -228,25 +228,25 @@ private extension ActivityManager { if let iconImage = article.iconImage() { attributeSet.thumbnailData = iconImage.image.pngData() } - + readingActivity?.contentAttributeSet = attributeSet readingActivity?.needsSave = true - + } #endif - + func makeKeywords(_ article: Article) -> [String] { let feedNameKeywords = makeKeywords(article.feed?.nameForDisplay) let articleTitleKeywords = makeKeywords(ArticleStringFormatter.truncatedTitle(article)) return feedNameKeywords + articleTitleKeywords } - + func makeKeywords(_ value: String?) -> [String] { return value?.components(separatedBy: " ").filter { $0.count > 2 } ?? [] } - + func updateSelectingActivityFeedSearchAttributes(with feed: Feed) { - + let attributeSet = CSSearchableItemAttributeSet(contentType: UTType.compositeContent) attributeSet.title = feed.nameForDisplay attributeSet.keywords = makeKeywords(feed.nameForDisplay) @@ -258,9 +258,9 @@ private extension ActivityManager { selectingActivity!.contentAttributeSet = attributeSet selectingActivity!.needsSave = true - + } - + func donate(_ activity: NSUserActivity) { // You have to put the search item in the index or the activity won't index // itself because the relatedUniqueIdentifier on the activity attributeset is populated. @@ -270,22 +270,22 @@ private extension ActivityManager { let searchableItem = CSSearchableItem(uniqueIdentifier: identifier, domainIdentifier: nil, attributeSet: tempAttributeSet) CSSearchableIndex.default().indexSearchableItems([searchableItem]) } - + activity.becomeCurrent() } - + static func identifier(for folder: Folder) -> String { return "account_\(folder.account!.accountID)_folder_\(folder.nameForDisplay)" } - + static func identifier(for feed: Feed) -> String { return "account_\(feed.account!.accountID)_feed_\(feed.feedID)" } - + static func identifier(for article: Article) -> String { return "account_\(article.accountID)_feed_\(article.feedID)_article_\(article.articleID)" } - + static func identifiers(for feed: Feed) -> [String] { var ids = [String]() ids.append(identifier(for: feed)) diff --git a/Shared/Article Extractor/ArticleExtractor.swift b/Shared/Article Extractor/ArticleExtractor.swift index 0d43d9eb2..ebe75f443 100644 --- a/Shared/Article Extractor/ArticleExtractor.swift +++ b/Shared/Article Extractor/ArticleExtractor.swift @@ -24,23 +24,23 @@ protocol ArticleExtractorDelegate { } final class ArticleExtractor { - + private var dataTask: URLSessionDataTask? = nil - + var state: ArticleExtractorState! var article: ExtractedArticle? var delegate: ArticleExtractorDelegate? var articleLink: String? - + private var url: URL! - + public init?(_ articleLink: String) { self.articleLink = articleLink - + let clientURL = "https://extract.feedbin.com/parser" let username = SecretsManager.provider.mercuryClientId let signature = articleLink.hmacUsingSHA1(key: SecretsManager.provider.mercuryClientSecret) - + if let base64URL = articleLink.data(using: .utf8)?.base64EncodedString() { let fullURL = "\(clientURL)/\(username)/\(signature)?base64_url=\(base64URL)" if let url = URL(string: fullURL) { @@ -48,18 +48,18 @@ final class ArticleExtractor { return } } - + return nil } - + public func process() { - + state = .processing dataTask = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in - + guard let self = self else { return } - + if let error = error { self.state = .failedToParse DispatchQueue.main.async { @@ -67,7 +67,7 @@ final class ArticleExtractor { } return } - + guard let data = data else { self.state = .failedToParse DispatchQueue.main.async { @@ -75,12 +75,12 @@ final class ArticleExtractor { } return } - + do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 self.article = try decoder.decode(ExtractedArticle.self, from: data) - + DispatchQueue.main.async { if self.article?.content == nil { self.state = .failedToParse @@ -96,16 +96,16 @@ final class ArticleExtractor { self.delegate?.articleExtractionDidFail(with: error) } } - + } - + dataTask!.resume() - + } - + public func cancel() { state = .cancelled dataTask?.cancel() } - + } diff --git a/Shared/Article Extractor/ExtractedArticle.swift b/Shared/Article Extractor/ExtractedArticle.swift index 460302477..40c45820c 100644 --- a/Shared/Article Extractor/ExtractedArticle.swift +++ b/Shared/Article Extractor/ExtractedArticle.swift @@ -24,7 +24,7 @@ struct ExtractedArticle: Codable, Equatable { let direction: String? let totalPages: Int? let renderedPages: Int? - + enum CodingKeys: String, CodingKey { case title = "title" case author = "author" @@ -41,5 +41,5 @@ struct ExtractedArticle: Codable, Equatable { case totalPages = "total_pages" case renderedPages = "rendered_pages" } - + } diff --git a/Shared/Article Rendering/ArticleRenderer.swift b/Shared/Article Rendering/ArticleRenderer.swift index 9513a8fc9..29f21e56a 100644 --- a/Shared/Article Rendering/ArticleRenderer.swift +++ b/Shared/Article Rendering/ArticleRenderer.swift @@ -17,12 +17,12 @@ import Account struct ArticleRenderer { typealias Rendering = (style: String, html: String, title: String, baseURL: String) - + struct Page { let url: URL let baseURL: URL let html: String - + init(name: String) { url = Bundle.main.url(forResource: name, withExtension: "html")! baseURL = url.deletingLastPathComponent() @@ -31,17 +31,17 @@ struct ArticleRenderer { } static var imageIconScheme = "nnwImageIcon" - + static var blank = Page(name: "blank") static var page = Page(name: "page") - + private let article: Article? private let extractedArticle: ExtractedArticle? private let articleTheme: ArticleTheme private let title: String private let body: String private let baseURL: String? - + private static let longDateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long @@ -140,7 +140,7 @@ struct ArticleRenderer { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) return (renderer.articleCSS, renderer.noSelectionHTML, renderer.title, renderer.baseURL ?? "") } - + static func noContentHTML(theme: ArticleTheme) -> Rendering { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) return (renderer.articleCSS, renderer.noContentHTML, renderer.title, renderer.baseURL ?? "") @@ -173,7 +173,7 @@ private extension ArticleRenderer { private var noContentHTML: String { return "" } - + private var articleCSS: String { return try! MacroProcessor.renderedText(withTemplate: styleString(), substitutions: styleSubstitutions()) } @@ -205,10 +205,10 @@ private extension ArticleRenderer { assertionFailure("Article should have been set before calling this function.") return d } - + d["title"] = title d["preferred_link"] = article.preferredLink ?? "" - + if let externalLink = article.externalLink, externalLink != article.preferredLink { d["external_link_label"] = NSLocalizedString("Link:", comment: "Link") d["external_link_stripped"] = externalLink.strippingHTTPOrHTTPSScheme @@ -218,13 +218,13 @@ private extension ArticleRenderer { d["external_link_stripped"] = "" d["external_link"] = "" } - + d["body"] = body - + #if os(macOS) d["text_size_class"] = AppDefaults.shared.articleTextSize.cssClass #endif - + var components = URLComponents() components.scheme = Self.imageIconScheme components.path = article.articleID @@ -234,7 +234,7 @@ private extension ArticleRenderer { else { d["avatar_src"] = "" } - + if self.title.isEmpty { d["dateline_style"] = "articleDatelineTitle" } else { @@ -273,7 +273,7 @@ private extension ArticleRenderer { return "" } } - + var byline = "" var isFirstAuthor = true diff --git a/Shared/Article Rendering/ArticleRenderingSpecialCases.swift b/Shared/Article Rendering/ArticleRenderingSpecialCases.swift index 184a3d7a1..0a1edce2d 100644 --- a/Shared/Article Rendering/ArticleRenderingSpecialCases.swift +++ b/Shared/Article Rendering/ArticleRenderingSpecialCases.swift @@ -14,7 +14,7 @@ struct ArticleRenderingSpecialCases { guard let url = URL(string: baseURL) else { return html } - + if isVergeSpecialCase(url) { return filterVergeHTML(html) } diff --git a/Shared/Article Rendering/ArticleTextSize.swift b/Shared/Article Rendering/ArticleTextSize.swift index bbc433974..456bee65d 100644 --- a/Shared/Article Rendering/ArticleTextSize.swift +++ b/Shared/Article Rendering/ArticleTextSize.swift @@ -14,9 +14,9 @@ enum ArticleTextSize: Int, CaseIterable, Identifiable { case large = 3 case xlarge = 4 case xxlarge = 5 - + var id: String { description() } - + var cssClass: String { switch self { case .small: @@ -31,7 +31,7 @@ enum ArticleTextSize: Int, CaseIterable, Identifiable { return "xxLargeText" } } - + func description() -> String { switch self { case .small: @@ -46,5 +46,5 @@ enum ArticleTextSize: Int, CaseIterable, Identifiable { return NSLocalizedString("Extra Extra Large", comment: "XX-Large") } } - + } diff --git a/Shared/Article Rendering/WebViewConfiguration.swift b/Shared/Article Rendering/WebViewConfiguration.swift index b67f05ac9..9af763677 100644 --- a/Shared/Article Rendering/WebViewConfiguration.swift +++ b/Shared/Article Rendering/WebViewConfiguration.swift @@ -13,7 +13,7 @@ final class WebViewConfiguration { static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { assert(Thread.isMainThread) - + let configuration = WKWebViewConfiguration() configuration.preferences = preferences @@ -46,7 +46,7 @@ private extension WebViewConfiguration { static var webpagePreferences: WKWebpagePreferences { assert(Thread.isMainThread) - + let preferences = WKWebpagePreferences() preferences.allowsContentJavaScript = AppDefaults.shared.isArticleContentJavascriptEnabled return preferences diff --git a/Shared/ArticleStyles/ArticleTheme.swift b/Shared/ArticleStyles/ArticleTheme.swift index 4edb376b8..9c1e031a1 100644 --- a/Shared/ArticleStyles/ArticleTheme.swift +++ b/Shared/ArticleStyles/ArticleTheme.swift @@ -9,58 +9,58 @@ import Foundation struct ArticleTheme: Equatable { - + static let defaultTheme = ArticleTheme() static let nnwThemeSuffix = ".nnwtheme" - + private static let defaultThemeName = NSLocalizedString("Default", comment: "Default") private static let unknownValue = NSLocalizedString("Unknown", comment: "Unknown Value") - + let url: URL? let template: String? let css: String? let isAppTheme: Bool - + var name: String { guard let url else { return Self.defaultThemeName } return Self.themeNameForPath(url.path) } - + var creatorHomePage: String { return info?.creatorHomePage ?? Self.unknownValue } - + var creatorName: String { return info?.creatorName ?? Self.unknownValue } - + var version: String { return String(describing: info?.version ?? 0) } - + private let info: ArticleThemePlist? - + init() { self.url = nil self.info = ArticleThemePlist(name: "Article Theme", themeIdentifier: "com.ranchero.netnewswire.theme.article", creatorHomePage: "https://netnewswire.com/", creatorName: "Ranchero Software", version: 1) - + let corePath = Bundle.main.path(forResource: "core", ofType: "css")! let stylesheetPath = Bundle.main.path(forResource: "stylesheet", ofType: "css")! css = Self.stringAtPath(corePath)! + "\n" + Self.stringAtPath(stylesheetPath)! - + let templatePath = Bundle.main.path(forResource: "template", ofType: "html")! template = Self.stringAtPath(templatePath)! - + isAppTheme = true } - + init(url: URL, isAppTheme: Bool) throws { _ = url.startAccessingSecurityScopedResource() defer { url.stopAccessingSecurityScopedResource() } - + self.url = url let coreURL = Bundle.main.url(forResource: "core", withExtension: "css")! @@ -92,19 +92,19 @@ struct ArticleTheme: Equatable { } return nil } - + static func filenameWithThemeSuffixRemoved(_ filename: String) -> String { return filename.stripping(suffix: Self.nnwThemeSuffix) } - + static func themeNameForPath(_ f: String) -> String { let filename = (f as NSString).lastPathComponent return filenameWithThemeSuffixRemoved(filename) } - + static func pathIsPathForThemeName(_ themeName: String, path: String) -> Bool { let filename = (path as NSString).lastPathComponent return filenameWithThemeSuffixRemoved(filename) == themeName } - + } diff --git a/Shared/ArticleStyles/ArticleThemeDownloader.swift b/Shared/ArticleStyles/ArticleThemeDownloader.swift index 43ee04567..28f33e039 100644 --- a/Shared/ArticleStyles/ArticleThemeDownloader.swift +++ b/Shared/ArticleStyles/ArticleThemeDownloader.swift @@ -10,10 +10,10 @@ import Foundation import Zip public class ArticleThemeDownloader { - + public enum ArticleThemeDownloaderError: LocalizedError { case noThemeFile - + public var errorDescription: String? { switch self { case .noThemeFile: @@ -21,23 +21,23 @@ public class ArticleThemeDownloader { } } } - + public static let shared = ArticleThemeDownloader() private init() {} - + public func handleFile(at location: URL) throws { createDownloadDirectoryIfRequired() let movedFileLocation = try moveTheme(from: location) let unzippedFileLocation = try unzipFile(at: movedFileLocation) NotificationCenter.default.post(name: .didEndDownloadingTheme, object: nil, userInfo: ["url" : unzippedFileLocation]) } - - + + /// Creates `Application Support/NetNewsWire/Downloads` if needed. private func createDownloadDirectoryIfRequired() { try? FileManager.default.createDirectory(at: downloadDirectory(), withIntermediateDirectories: true, attributes: nil) } - + /// Moves the downloaded `.tmp` file to the `downloadDirectory` and renames it a `.zip` /// - Parameter location: The temporary file location. /// - Returns: Destination `URL`. @@ -48,7 +48,7 @@ public class ArticleThemeDownloader { try FileManager.default.moveItem(at: location, to: fileUrl) return fileUrl } - + /// Unzips the zip file /// - Parameter location: Location of the zip archive. /// - Returns: Enclosed `.nnwtheme` file. @@ -67,8 +67,8 @@ public class ArticleThemeDownloader { throw error } } - - + + /// Performs a deep search of the unzipped directory to find the theme file. /// - Parameter searchPath: directory to search /// - Returns: optional `String` @@ -84,16 +84,16 @@ public class ArticleThemeDownloader { } } } - + return nil } - + /// The download directory used by the theme downloader: `Application Support/NetNewsWire/Downloads` /// - Returns: `URL` private func downloadDirectory() -> URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!.appendingPathComponent("NetNewsWire/Downloads", isDirectory: true) } - + /// Removes downloaded themes, where themes == folders, from `Application Support/NetNewsWire/Downloads`. public func cleanUp() { guard let filenames = try? FileManager.default.contentsOfDirectory(atPath: downloadDirectory().path) else { diff --git a/Shared/ArticleStyles/ArticleThemePlist.swift b/Shared/ArticleStyles/ArticleThemePlist.swift index f324cdbde..306b1dc8a 100644 --- a/Shared/ArticleStyles/ArticleThemePlist.swift +++ b/Shared/ArticleStyles/ArticleThemePlist.swift @@ -14,7 +14,7 @@ public struct ArticleThemePlist: Codable, Equatable { public var creatorHomePage: String public var creatorName: String public var version: Int - + enum CodingKeys: String, CodingKey { case name = "Name" case themeIdentifier = "ThemeIdentifier" diff --git a/Shared/ArticleStyles/ArticleThemesManager.swift b/Shared/ArticleStyles/ArticleThemesManager.swift index 3075235d0..1a5938700 100644 --- a/Shared/ArticleStyles/ArticleThemesManager.swift +++ b/Shared/ArticleStyles/ArticleThemesManager.swift @@ -54,49 +54,49 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { self.currentTheme = ArticleTheme.defaultTheme super.init() - + do { try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil) } catch { assertionFailure("Could not create folder for Themes.") abort() } - + updateThemeNames() updateCurrentTheme() NSFileCoordinator.addFilePresenter(self) } - + func presentedSubitemDidChange(at url: URL) { updateThemeNames() updateCurrentTheme() } // MARK: API - + func themeExists(filename: String) -> Bool { let filenameLastPathComponent = (filename as NSString).lastPathComponent let toFilename = (folderPath as NSString).appendingPathComponent(filenameLastPathComponent) return FileManager.default.fileExists(atPath: toFilename) } - + func importTheme(filename: String) throws { let filenameLastPathComponent = (filename as NSString).lastPathComponent let toFilename = (folderPath as NSString).appendingPathComponent(filenameLastPathComponent) - + if FileManager.default.fileExists(atPath: toFilename) { try FileManager.default.removeItem(atPath: toFilename) } - + try FileManager.default.copyItem(atPath: filename, toPath: toFilename) } - + func articleThemeWithThemeName(_ themeName: String) -> ArticleTheme? { if themeName == AppDefaults.defaultThemeName { return ArticleTheme.defaultTheme } - + let url: URL let isAppTheme: Bool if let appThemeURL = Bundle.main.url(forResource: themeName, withExtension: ArticleTheme.nnwThemeSuffix) { @@ -108,14 +108,14 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { } else { return nil } - + do { return try ArticleTheme(url: url, isAppTheme: isAppTheme) } catch { NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) return nil } - + } func deleteTheme(themeName: String) { @@ -123,7 +123,7 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { try? FileManager.default.removeItem(atPath: filename) } } - + } // MARK : Private @@ -137,7 +137,7 @@ private extension ArticleThemesManager { let installedThemeNames = Set(allThemePaths(folderPath).map { ArticleTheme.themeNameForPath($0) }) let allThemeNames = appThemeNames.union(installedThemeNames) - + let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending }) if sortedThemeNames != themeNames { themeNames = sortedThemeNames @@ -179,5 +179,5 @@ private extension ArticleThemesManager { } return nil } - + } diff --git a/Shared/Commands/DeleteCommand.swift b/Shared/Commands/DeleteCommand.swift index 9e37fe69f..f09652160 100644 --- a/Shared/Commands/DeleteCommand.swift +++ b/Shared/Commands/DeleteCommand.swift @@ -46,7 +46,7 @@ final class DeleteCommand: UndoableCommand { } func perform() { - + let group = DispatchGroup() itemSpecifiers.forEach { group.enter() @@ -54,14 +54,14 @@ final class DeleteCommand: UndoableCommand { group.leave() } } - + group.notify(queue: DispatchQueue.main) { self.treeController?.rebuild() self.registerUndo() } - + } - + func undo() { itemSpecifiers.forEach { $0.restore() } registerRedo() @@ -137,9 +137,9 @@ private struct SidebarItemSpecifier { self.account = account! self.path = ContainerPath(account: account!, folders: node.containingFolders()) - + self.errorHandler = errorHandler - + } func delete(completion: @escaping () -> Void) { @@ -150,23 +150,23 @@ private struct SidebarItemSpecifier { completion() return } - + BatchUpdate.shared.start() account?.removeFeed(feed, from: container) { result in BatchUpdate.shared.end() completion() self.checkResult(result) } - + } else if let folder = folder { - + BatchUpdate.shared.start() account?.removeFolder(folder) { result in BatchUpdate.shared.end() completion() self.checkResult(result) } - + } } @@ -185,13 +185,13 @@ private struct SidebarItemSpecifier { guard let account = account, let feed = feed, let container = path.resolveContainer() else { return } - + BatchUpdate.shared.start() account.restoreFeed(feed, container: container) { result in BatchUpdate.shared.end() self.checkResult(result) } - + } private func restoreFolder() { @@ -199,17 +199,17 @@ private struct SidebarItemSpecifier { guard let account = account, let folder = folder else { return } - + BatchUpdate.shared.start() account.restoreFolder(folder) { result in BatchUpdate.shared.end() self.checkResult(result) } - + } private func checkResult(_ result: Result) { - + switch result { case .success: break @@ -218,11 +218,11 @@ private struct SidebarItemSpecifier { } } - + } private extension Node { - + func parentFolder() -> Folder? { guard let parentNode = self.parent else { diff --git a/Shared/Commands/MarkStatusCommand.swift b/Shared/Commands/MarkStatusCommand.swift index 79cf9777c..a21a0c9fe 100644 --- a/Shared/Commands/MarkStatusCommand.swift +++ b/Shared/Commands/MarkStatusCommand.swift @@ -13,7 +13,7 @@ import Articles // Mark articles read/unread, starred/unstarred, deleted/undeleted. final class MarkStatusCommand: UndoableCommand { - + let undoActionName: String let redoActionName: String let articles: Set
@@ -23,7 +23,7 @@ final class MarkStatusCommand: UndoableCommand { var completion: (() -> Void)? = nil init?(initialArticles: [Article], statusKey: ArticleStatus.Key, flag: Bool, undoManager: UndoManager, completion: (() -> Void)? = nil) { - + // Filter out articles that already have the desired status or can't be marked. let articlesToMark = MarkStatusCommand.filteredArticles(initialArticles, statusKey, flag) if articlesToMark.isEmpty { @@ -54,7 +54,7 @@ final class MarkStatusCommand: UndoableCommand { mark(statusKey, flag) registerUndo() } - + func undo() { mark(statusKey, !flag) registerRedo() @@ -62,7 +62,7 @@ final class MarkStatusCommand: UndoableCommand { } private extension MarkStatusCommand { - + func mark(_ statusKey: ArticleStatus.Key, _ flag: Bool) { markArticles(articles, statusKey: statusKey, flag: flag, completion: completion) completion = nil @@ -91,6 +91,6 @@ private extension MarkStatusCommand { guard !article.status.read || article.isAvailableToMarkUnread else { return false } return true } - + } } diff --git a/Shared/Exporters/OPMLExporter.swift b/Shared/Exporters/OPMLExporter.swift index cba135a17..5cf027c9f 100644 --- a/Shared/Exporters/OPMLExporter.swift +++ b/Shared/Exporters/OPMLExporter.swift @@ -24,7 +24,7 @@ struct OPMLExporter { \(escapedTitle) - + """ let middleText = account.OPMLString(indentLevel: 0) diff --git a/Shared/ExtensionPoints/SendToMarsEditCommand.swift b/Shared/ExtensionPoints/SendToMarsEditCommand.swift index 49576b1c7..19093a351 100644 --- a/Shared/ExtensionPoints/SendToMarsEditCommand.swift +++ b/Shared/ExtensionPoints/SendToMarsEditCommand.swift @@ -59,7 +59,7 @@ private extension SendToMarsEditCommand { 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) let _ = sender.send() } - + func appToUse() -> UserApp? { for app in marsEditApps { diff --git a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift index 342bec319..dbecdc77d 100644 --- a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift +++ b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift @@ -28,7 +28,7 @@ final class SendToMicroBlogCommand: SendToCommand { return true } - + func sendObject(_ object: Any?, selectedText: String?) { guard canSendObject(object, selectedText: selectedText) else { diff --git a/Shared/Extensions/AddFeedDefaultContainer.swift b/Shared/Extensions/AddFeedDefaultContainer.swift index 6bf7fa880..cd0c8abd6 100644 --- a/Shared/Extensions/AddFeedDefaultContainer.swift +++ b/Shared/Extensions/AddFeedDefaultContainer.swift @@ -10,9 +10,9 @@ import Foundation import Account struct AddFeedDefaultContainer { - + static var defaultContainer: Container? { - + if let accountID = AppDefaults.shared.addFeedAccountID, let account = AccountManager.shared.activeAccounts.first(where: { $0.accountID == accountID }) { if let folderName = AppDefaults.shared.addFeedFolderName, let folder = account.existingFolder(withDisplayName: folderName) { return folder @@ -24,9 +24,9 @@ struct AddFeedDefaultContainer { } else { return nil } - + } - + static func saveDefaultContainer(_ container: Container) { AppDefaults.shared.addFeedAccountID = container.account?.accountID if let folder = container as? Folder { @@ -35,7 +35,7 @@ struct AddFeedDefaultContainer { AppDefaults.shared.addFeedFolderName = nil } } - + private static func substituteContainerIfNeeded(account: Account) -> Container? { if !account.behaviors.contains(.disallowFeedInRootFolder) { return account @@ -47,5 +47,5 @@ struct AddFeedDefaultContainer { } } } - + } diff --git a/Shared/Extensions/ArticleUtilities.swift b/Shared/Extensions/ArticleUtilities.swift index 280c51563..79a3b4a21 100644 --- a/Shared/Extensions/ArticleUtilities.swift +++ b/Shared/Extensions/ArticleUtilities.swift @@ -14,11 +14,11 @@ import Account // These handle multiple accounts. func markArticles(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: (() -> Void)? = nil) { - + let d: [String: Set
] = accountAndArticlesDictionary(articles) let group = DispatchGroup() - + for (accountID, accountArticles) in d { guard let account = AccountManager.shared.existingAccount(with: accountID) else { continue @@ -28,42 +28,42 @@ func markArticles(_ articles: Set
, statusKey: ArticleStatus.Key, flag: group.leave() } } - + group.notify(queue: .main) { completion?() } } private func accountAndArticlesDictionary(_ articles: Set
) -> [String: Set
] { - + let d = Dictionary(grouping: articles, by: { $0.accountID }) return d.mapValues{ Set($0) } } extension Article { - + var feed: Feed? { return account?.existingFeed(withFeedID: feedID) } - + var url: URL? { return URL.encodeSpacesIfNeeded(rawLink) } - + var externalURL: URL? { return URL.encodeSpacesIfNeeded(rawExternalLink) } - + var imageURL: URL? { return URL.encodeSpacesIfNeeded(rawImageLink) } - + var link: String? { // Prefer link from URL, if one can be created, as these are repaired if required. // Provide the raw link if URL creation fails. return url?.absoluteString ?? rawLink } - + var externalLink: String? { // Prefer link from externalURL, if one can be created, as these are repaired if required. // Provide the raw link if URL creation fails. @@ -85,19 +85,19 @@ extension Article { } return nil } - + var preferredURL: URL? { return url ?? externalURL } - + var body: String? { return contentHTML ?? contentText ?? summary } - + var logicalDatePublished: Date { return datePublished ?? dateModified ?? status.dateArrived } - + var isAvailableToMarkUnread: Bool { guard let markUnreadWindow = account?.behaviors.compactMap( { behavior -> Int? in switch behavior { @@ -109,7 +109,7 @@ extension Article { }).first else { return true } - + if logicalDatePublished.byAdding(days: markUnreadWindow) > Date() { return true } else { @@ -120,7 +120,7 @@ extension Article { func iconImage() -> IconImage? { return IconImageCache.shared.imageForArticle(self) } - + func iconImageUrl(feed: Feed) -> URL? { if let image = iconImage() { let fm = FileManager.default @@ -133,7 +133,7 @@ extension Article { return nil } } - + func byline() -> String { guard let authors = authors ?? feed?.authors, !authors.isEmpty else { return "" @@ -147,7 +147,7 @@ extension Article { return "" } } - + var byline = "" var isFirstAuthor = true @@ -156,7 +156,7 @@ extension Article { byline += ", " } isFirstAuthor = false - + var authorEmailAddress: String? = nil if let emailAddress = author.emailAddress, !(emailAddress.contains("noreply@") || emailAddress.contains("no-reply@")) { authorEmailAddress = emailAddress @@ -181,7 +181,7 @@ extension Article { return byline } - + } // MARK: Path @@ -209,21 +209,21 @@ extension Article { // MARK: SortableArticle extension Article: SortableArticle { - + var sortableName: String { return feed?.name ?? "" } - + var sortableDate: Date { return logicalDatePublished } - + var sortableArticleID: String { return articleID } - + var sortableFeedID: String { return feedID } - + } diff --git a/Shared/Extensions/IconImage.swift b/Shared/Extensions/IconImage.swift index aa0a4f3e9..3a813d68f 100644 --- a/Shared/Extensions/IconImage.swift +++ b/Shared/Extensions/IconImage.swift @@ -15,15 +15,15 @@ import UIKit import RSCore final class IconImage { - + lazy var isDark: Bool = { return image.isDark() }() - + lazy var isBright: Bool = { return image.isBright() }() - + let image: RSImage let isSymbol: Bool let isBackgroundSuppressed: Bool @@ -35,7 +35,7 @@ final class IconImage { self.preferredColor = preferredColor self.isBackgroundSuppressed = isBackgroundSuppressed } - + } #if os(macOS) @@ -43,7 +43,7 @@ final class IconImage { func isDark() -> Bool { return self.cgImage(forProposedRect: nil, context: nil, hints: nil)?.isDark() ?? false } - + func isBright() -> Bool { return self.cgImage(forProposedRect: nil, context: nil, hints: nil)?.isBright() ?? false } @@ -53,7 +53,7 @@ final class IconImage { func isDark() -> Bool { return self.cgImage?.isDark() ?? false } - + func isBright() -> Bool { return self.cgImage?.isBright() ?? false } @@ -72,18 +72,18 @@ extension CGImage { } return luminanceType == .bright } - + func isDark() -> Bool { guard let luminanceType = getLuminanceType() else { return false } return luminanceType == .dark } - + fileprivate func getLuminanceType() -> ImageLuminanceType? { - + // This has been rewritten with information from https://christianselig.com/2021/04/efficient-average-color/ - + // First, resize the image. We do this for two reasons, 1) less pixels to deal with means faster // calculation and a resized image still has the "gist" of the colors, and 2) the image we're dealing // with may come in any of a variety of color formats (CMYK, ARGB, RGBA, etc.) which complicates things, @@ -91,32 +91,32 @@ extension CGImage { // 40x40 is a good size to resize to still preserve quite a bit of detail but not have too many pixels // to deal with. Aspect ratio is irrelevant for just finding average color. let size = CGSize(width: 40, height: 40) - + let width = Int(size.width) let height = Int(size.height) let totalPixels = width * height - + let colorSpace = CGColorSpaceCreateDeviceRGB() - + // ARGB format let bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue - + // 8 bits for each color channel, we're doing ARGB so 32 bits (4 bytes) total, and thus if the image is n pixels wide, // and has 4 bytes per pixel, the total bytes per row is 4n. That gives us 2^8 = 256 color variations for each RGB channel // or 256 * 256 * 256 = ~16.7M color options in total. That seems like a lot, but lots of HDR movies are in 10 bit, which // is (2^10)^3 = 1 billion color options! guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil } - + // Draw our resized image context.draw(self, in: CGRect(origin: .zero, size: size)) - + guard let pixelBuffer = context.data else { return nil } - + // Bind the pixel buffer's memory location to a pointer we can use/access let pointer = pixelBuffer.bindMemory(to: UInt32.self, capacity: width * height) - + var totalLuminance = 0.0 - + // Column of pixels in image for x in 0 ..< width { // Row of pixels in image @@ -126,17 +126,17 @@ extension CGImage { // columns in to our "long row", we'd offset ourselves 15 times the width in pixels of the image, and // then offset by the amount of columns let pixel = pointer[(y * width) + x] - + let r = red(for: pixel) let g = green(for: pixel) let b = blue(for: pixel) - + let luminance = (0.299 * Double(r) + 0.587 * Double(g) + 0.114 * Double(b)) - + totalLuminance += luminance } } - + let avgLuminance = totalLuminance / Double(totalPixels) if totalLuminance == 0 || avgLuminance < 40 { return .dark @@ -146,19 +146,19 @@ extension CGImage { return .regular } } - + private func red(for pixelData: UInt32) -> UInt8 { return UInt8((pixelData >> 16) & 255) } - + private func green(for pixelData: UInt32) -> UInt8 { return UInt8((pixelData >> 8) & 255) } - + private func blue(for pixelData: UInt32) -> UInt8 { return UInt8((pixelData >> 0) & 255) } - + } @@ -166,7 +166,7 @@ enum IconSize: Int, CaseIterable { case small = 1 case medium = 2 case large = 3 - + private static let smallDimension = CGFloat(integerLiteral: 24) private static let mediumDimension = CGFloat(integerLiteral: 36) private static let largeDimension = CGFloat(integerLiteral: 48) diff --git a/Shared/Extensions/Node-Extensions.swift b/Shared/Extensions/Node-Extensions.swift index 14839f8e9..6280583a8 100644 --- a/Shared/Extensions/Node-Extensions.swift +++ b/Shared/Extensions/Node-Extensions.swift @@ -27,38 +27,38 @@ extension Array where Element == Node { private extension Node { class func nodesSortedAlphabetically(_ nodes: [Node]) -> [Node] { - + return nodes.sorted { (node1, node2) -> Bool in - + guard let obj1 = node1.representedObject as? DisplayNameProvider, let obj2 = node2.representedObject as? DisplayNameProvider else { return false } - + let name1 = obj1.nameForDisplay let name2 = obj2.nameForDisplay - + return name1.localizedStandardCompare(name2) == .orderedAscending } } - + class func nodesSortedAlphabeticallyWithFoldersAtEnd(_ nodes: [Node]) -> [Node] { - + return nodes.sorted { (node1, node2) -> Bool in - + if node1.canHaveChildNodes != node2.canHaveChildNodes { if node1.canHaveChildNodes { return false } return true } - + guard let obj1 = node1.representedObject as? DisplayNameProvider, let obj2 = node2.representedObject as? DisplayNameProvider else { return false } - + let name1 = obj1.nameForDisplay let name2 = obj2.nameForDisplay - + return name1.localizedStandardCompare(name2) == .orderedAscending } } diff --git a/Shared/Extensions/RSImage-Extensions.swift b/Shared/Extensions/RSImage-Extensions.swift index 1d6e57f47..a7dcee82d 100644 --- a/Shared/Extensions/RSImage-Extensions.swift +++ b/Shared/Extensions/RSImage-Extensions.swift @@ -16,9 +16,9 @@ import UIKit import RSCore extension RSImage { - + static let maxIconSize = 48 - + static func scaledForIcon(_ data: Data, imageResultBlock: @escaping ImageResultBlock) { IconScalerQueue.shared.scaledForIcon(data, imageResultBlock) } diff --git a/Shared/Extensions/URL-Extensions.swift b/Shared/Extensions/URL-Extensions.swift index 8676a4b29..54ad6f742 100644 --- a/Shared/Extensions/URL-Extensions.swift +++ b/Shared/Extensions/URL-Extensions.swift @@ -9,12 +9,12 @@ import Foundation extension URL { - + /// Extracts email address from a `URL` with a `mailto` scheme, otherwise `nil`. var emailAddress: String? { scheme == "mailto" ? URLComponents(url: self, resolvingAgainstBaseURL: false)?.path : nil } - + /// Percent encoded `mailto` URL for use with `canOpenUrl`. If the URL doesn't contain the `mailto` scheme, this is `nil`. var percentEncodedEmailAddress: URL? { guard scheme == "mailto" else { @@ -25,7 +25,7 @@ extension URL { } return URL(string: urlString) } - + func valueFor(_ parameter: String) -> String? { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, @@ -33,7 +33,7 @@ extension URL { return nil } return value - + } /// Percent-encode spaces in links that may contain spaces but are otherwise already percent-encoded. diff --git a/Shared/Favicons/ColorHash.swift b/Shared/Favicons/ColorHash.swift index 5cd55d05a..33f5b62d9 100644 --- a/Shared/Favicons/ColorHash.swift +++ b/Shared/Favicons/ColorHash.swift @@ -17,10 +17,10 @@ import AppKit #endif public class ColorHash { - + public static let defaultSaturation = [CGFloat(0.35), CGFloat(0.5), CGFloat(0.65)] public static let defaultBrightness = [CGFloat(0.5), CGFloat(0.65), CGFloat(0.80)] - + let seed = CGFloat(131.0) let seed2 = CGFloat(137.0) let maxSafeInteger = 9007199254740991.0 / CGFloat(137.0) @@ -29,13 +29,13 @@ public class ColorHash { public private(set) var str: String public private(set) var brightness: [CGFloat] public private(set) var saturation: [CGFloat] - + public init(_ str: String, _ saturation: [CGFloat] = defaultSaturation, _ brightness: [CGFloat] = defaultBrightness) { self.str = str self.saturation = saturation self.brightness = brightness } - + public var bkdrHash: CGFloat { var hash = CGFloat(0) for char in "\(str)x" { @@ -48,7 +48,7 @@ public class ColorHash { } return hash } - + public var HSB: (CGFloat, CGFloat, CGFloat) { var hash = CGFloat(bkdrHash) let H = hash.truncatingRemainder(dividingBy: (full - 1.0)) / full @@ -58,7 +58,7 @@ public class ColorHash { let B = brightness[Int((full * hash).truncatingRemainder(dividingBy: CGFloat(brightness.count)))] return (H, S, B) } - + #if os(iOS) || os(tvOS) || os(watchOS) public var color: UIColor { let (H, S, B) = HSB @@ -70,5 +70,5 @@ public class ColorHash { return NSColor(hue: H, saturation: S, brightness: B, alpha: 1.0) } #endif - + } diff --git a/Shared/Favicons/FaviconDownloader.swift b/Shared/Favicons/FaviconDownloader.swift index 77be10e6c..cce0a3a83 100644 --- a/Shared/Favicons/FaviconDownloader.swift +++ b/Shared/Favicons/FaviconDownloader.swift @@ -75,7 +75,7 @@ final class FaviconDownloader { func resetCache() { cache = [Feed: IconImage]() } - + func favicon(for feed: Feed) -> IconImage? { assert(Thread.isMainThread) @@ -100,7 +100,7 @@ final class FaviconDownloader { return nil } - + func faviconAsIcon(for feed: Feed) -> IconImage? { if let image = cache[feed] { @@ -201,7 +201,7 @@ final class FaviconDownloader { saveHomePageToFaviconURLCache() } } - + @objc func saveHomePageURLsWithNoFaviconURLCacheIfNeeded() { if homePageURLsWithNoFaviconURLCacheDirty { saveHomePageURLsWithNoFaviconURLCache() @@ -240,7 +240,7 @@ private extension FaviconDownloader { func faviconDownloader(withURL faviconURL: String, homePageURL: String?) -> SingleFaviconDownloader { var firstTimeSeeingHomepageURL = false - + if let homePageURL = homePageURL, self.homePageToFaviconURLCache[homePageURL] == nil { self.homePageToFaviconURLCache[homePageURL] = faviconURL self.homePageToFaviconURLCacheDirty = true @@ -311,7 +311,7 @@ private extension FaviconDownloader { assertionFailure(error.localizedDescription) } } - + func saveHomePageURLsWithNoFaviconURLCache() { homePageURLsWithNoFaviconURLCacheDirty = false diff --git a/Shared/Favicons/FaviconGenerator.swift b/Shared/Favicons/FaviconGenerator.swift index b405ea195..6c3cacb68 100644 --- a/Shared/Favicons/FaviconGenerator.swift +++ b/Shared/Favicons/FaviconGenerator.swift @@ -15,11 +15,11 @@ final class FaviconGenerator { private static var faviconGeneratorCache = [String: IconImage]() // feedURL: RSImage static func favicon(_ feed: Feed) -> IconImage { - + if let favicon = FaviconGenerator.faviconGeneratorCache[feed.url] { return favicon } - + let colorHash = ColorHash(feed.url) if let favicon = AppAssets.faviconTemplateImage.maskWithColor(color: colorHash.color.cgColor) { let iconImage = IconImage(favicon, isBackgroundSuppressed: true) @@ -28,7 +28,7 @@ final class FaviconGenerator { } else { return IconImage(AppAssets.faviconTemplateImage, isBackgroundSuppressed: true) } - + } - + } diff --git a/Shared/IconImageCache.swift b/Shared/IconImageCache.swift index eb99ba2a3..9f1370fe2 100644 --- a/Shared/IconImageCache.swift +++ b/Shared/IconImageCache.swift @@ -34,7 +34,7 @@ final class IconImageCache { guard let sidebarItemID = sidebarItem.sidebarItemID else { return nil } - + if let smartFeed = sidebarItem as? PseudoFeed { return imageForSmartFeed(smartFeed, sidebarItemID) } @@ -68,7 +68,7 @@ final class IconImageCache { } private extension IconImageCache { - + func imageForSmartFeed(_ smartFeed: PseudoFeed, _ feedID: SidebarItemIdentifier) -> IconImage? { if let iconImage = smartFeedIconImageCache[feedID] { return iconImage diff --git a/Shared/Images/AuthorAvatarDownloader.swift b/Shared/Images/AuthorAvatarDownloader.swift index 471325d05..ac25ae8ab 100644 --- a/Shared/Images/AuthorAvatarDownloader.swift +++ b/Shared/Images/AuthorAvatarDownloader.swift @@ -31,17 +31,17 @@ final class AuthorAvatarDownloader { func resetCache() { cache = [String: IconImage]() } - + func image(for author: Author) -> IconImage? { guard let avatarURL = author.avatarURL else { return nil } - + if let cachedImage = cache[avatarURL] { return cachedImage } - + if let imageData = imageDownloader.image(for: avatarURL) { scaleAndCacheImageData(imageData, avatarURL) } diff --git a/Shared/Images/FeedIconDownloader.swift b/Shared/Images/FeedIconDownloader.swift index 2ff0de464..6115d19e9 100644 --- a/Shared/Images/FeedIconDownloader.swift +++ b/Shared/Images/FeedIconDownloader.swift @@ -49,7 +49,7 @@ public final class FeedIconDownloader { if let cachedImage = cache[feed] { return cachedImage } - + if let homePageURLString = feed.homePageURL, let homePageURL = URL(string: homePageURLString), (homePageURL.host == "nnw.ranchero.com" || homePageURL.host == "netnewswire.blog") { return IconImage.nnwFeedIcon } @@ -72,7 +72,7 @@ public final class FeedIconDownloader { } } } - + func checkFeedIconURL() { if let iconURL = feed.iconURL { icon(forURL: iconURL, feed: feed) { (image) in diff --git a/Shared/Images/RSHTMLMetadata+Extension.swift b/Shared/Images/RSHTMLMetadata+Extension.swift index 05970cf40..3e494c6cf 100644 --- a/Shared/Images/RSHTMLMetadata+Extension.swift +++ b/Shared/Images/RSHTMLMetadata+Extension.swift @@ -79,7 +79,7 @@ extension RSHTMLMetadata { if let appleTouchIcon = largestAppleTouchIcon() { return appleTouchIcon } - + if let openGraphImageURL = largestOpenGraphImageURL() { return openGraphImageURL } diff --git a/Shared/Importers/DefaultFeedsImporter.swift b/Shared/Importers/DefaultFeedsImporter.swift index 8ed67d3b9..afccbf301 100644 --- a/Shared/Importers/DefaultFeedsImporter.swift +++ b/Shared/Importers/DefaultFeedsImporter.swift @@ -11,11 +11,11 @@ import Account import RSCore struct DefaultFeedsImporter { - + static func importDefaultFeeds(account: Account) { let defaultFeedsURL = Bundle.main.url(forResource: "DefaultFeeds", withExtension: "opml")! AccountManager.shared.defaultAccount.importOPML(defaultFeedsURL) { result in } } - + } diff --git a/Shared/Settings/AddCloudKitAccount.swift b/Shared/Settings/AddCloudKitAccount.swift index 8e2e6878c..ae2974e38 100644 --- a/Shared/Settings/AddCloudKitAccount.swift +++ b/Shared/Settings/AddCloudKitAccount.swift @@ -15,13 +15,13 @@ import UIKit #endif enum AddCloudKitAccountError: LocalizedError, RecoverableError { - + case iCloudDriveMissing var errorDescription: String? { NSLocalizedString("Can’t Add iCloud Account", comment: "CloudKit account setup failure description — iCloud Drive not enabled.") } - + var recoverySuggestion: String? { #if os(macOS) NSLocalizedString("Open System Settings to configure iCloud and enable iCloud Drive.", comment: "CloudKit account setup recovery suggestion") @@ -29,7 +29,7 @@ enum AddCloudKitAccountError: LocalizedError, RecoverableError { NSLocalizedString("Open Settings to configure iCloud and enable iCloud Drive.", comment: "CloudKit account setup recovery suggestion") #endif } - + var recoveryOptions: [String] { #if os(macOS) [NSLocalizedString("Open System Settings", comment: "Open System Settings button"), NSLocalizedString("Cancel", comment: "Cancel button")] @@ -37,7 +37,7 @@ enum AddCloudKitAccountError: LocalizedError, RecoverableError { [NSLocalizedString("Open Settings", comment: "Open Settings button"), NSLocalizedString("Cancel", comment: "Cancel button")] #endif } - + func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool { guard recoveryOptionIndex == 0 else { return false diff --git a/Shared/ShareExtension/ExtensionContainers.swift b/Shared/ShareExtension/ExtensionContainers.swift index b283f177a..641c02c68 100644 --- a/Shared/ShareExtension/ExtensionContainers.swift +++ b/Shared/ShareExtension/ExtensionContainers.swift @@ -15,13 +15,13 @@ protocol ExtensionContainer: ContainerIdentifiable, Codable { } struct ExtensionContainers: Codable { - + enum CodingKeys: String, CodingKey { case accounts } let accounts: [ExtensionAccount] - + var flattened: [ExtensionContainer] { return accounts.reduce([ExtensionContainer](), { (containers, account) in var result = containers @@ -30,11 +30,11 @@ struct ExtensionContainers: Codable { return result }) } - + func findAccount(forName name: String) -> ExtensionAccount? { return accounts.first(where: { $0.name == name }) } - + } struct ExtensionAccount: ExtensionContainer { @@ -67,7 +67,7 @@ struct ExtensionAccount: ExtensionContainer { func findFolder(forName name: String) -> ExtensionFolder? { return folders.first(where: { $0.name == name }) } - + } struct ExtensionFolder: ExtensionContainer { @@ -90,5 +90,5 @@ struct ExtensionFolder: ExtensionContainer { self.name = folder.nameForDisplay self.containerID = folder.containerID } - + } diff --git a/Shared/ShareExtension/ExtensionContainersFile.swift b/Shared/ShareExtension/ExtensionContainersFile.swift index 87abea84c..c27ee667e 100644 --- a/Shared/ShareExtension/ExtensionContainersFile.swift +++ b/Shared/ShareExtension/ExtensionContainersFile.swift @@ -37,7 +37,7 @@ final class ExtensionContainersFile { return } isActive = true - + if !FileManager.default.fileExists(atPath: ExtensionContainersFile.filePath) { save() } diff --git a/Shared/ShareExtension/ExtensionFeedAddRequest.swift b/Shared/ShareExtension/ExtensionFeedAddRequest.swift index 86e54a7d6..99f0e00aa 100644 --- a/Shared/ShareExtension/ExtensionFeedAddRequest.swift +++ b/Shared/ShareExtension/ExtensionFeedAddRequest.swift @@ -10,7 +10,7 @@ import Foundation import Account struct ExtensionFeedAddRequest: Codable { - + enum CodingKeys: String, CodingKey { case name case feedURL @@ -20,5 +20,5 @@ struct ExtensionFeedAddRequest: Codable { let name: String? let feedURL: URL let destinationContainerID: ContainerIdentifier - + } diff --git a/Shared/ShareExtension/ShareDefaultContainer.swift b/Shared/ShareExtension/ShareDefaultContainer.swift index 5cc5ef24e..aabbe0c6e 100644 --- a/Shared/ShareExtension/ShareDefaultContainer.swift +++ b/Shared/ShareExtension/ShareDefaultContainer.swift @@ -9,9 +9,9 @@ import Foundation struct ShareDefaultContainer { - + static func defaultContainer(containers: ExtensionContainers) -> ExtensionContainer? { - + if let accountID = AppDefaults.shared.addFeedAccountID, let account = containers.accounts.first(where: { $0.accountID == accountID }) { if let folderName = AppDefaults.shared.addFeedFolderName, let folder = account.folders.first(where: { $0.name == folderName }) { return folder @@ -23,9 +23,9 @@ struct ShareDefaultContainer { } else { return nil } - + } - + static func saveDefaultContainer(_ container: ExtensionContainer) { AppDefaults.shared.addFeedAccountID = container.accountID if let folder = container as? ExtensionFolder { @@ -34,7 +34,7 @@ struct ShareDefaultContainer { AppDefaults.shared.addFeedFolderName = nil } } - + private static func substituteContainerIfNeeded(account: ExtensionAccount) -> ExtensionContainer? { if !account.disallowFeedInRootFolder { return account diff --git a/Shared/SmartFeeds/PseudoFeed.swift b/Shared/SmartFeeds/PseudoFeed.swift index 94436c66b..2126cd808 100644 --- a/Shared/SmartFeeds/PseudoFeed.swift +++ b/Shared/SmartFeeds/PseudoFeed.swift @@ -25,7 +25,7 @@ import Account import RSCore protocol PseudoFeed: AnyObject, SidebarItem, SmallIconProvider { - + } #endif diff --git a/Shared/SmartFeeds/SmartFeed.swift b/Shared/SmartFeeds/SmartFeed.swift index a31473f19..5c130c1c8 100644 --- a/Shared/SmartFeeds/SmartFeed.swift +++ b/Shared/SmartFeeds/SmartFeed.swift @@ -39,7 +39,7 @@ final class SmartFeed: PseudoFeed { var smallIcon: IconImage? { return delegate.smallIcon } - + #if os(macOS) var pasteboardWriter: NSPasteboardWriting { return SmartFeedPasteboardWriter(smartFeed: self) @@ -63,7 +63,7 @@ final class SmartFeed: PseudoFeed { @objc func fetchUnreadCounts() { let activeAccounts = AccountManager.shared.activeAccounts - + // Remove any accounts that are no longer active or have been deleted let activeAccountIDs = activeAccounts.map { $0.accountID } unreadCounts.keys.forEach { accountID in @@ -71,14 +71,14 @@ final class SmartFeed: PseudoFeed { unreadCounts.removeValue(forKey: accountID) } } - + if activeAccounts.isEmpty { updateUnreadCount() } else { activeAccounts.forEach { self.fetchUnreadCount(for: $0) } } } - + } extension SmartFeed: ArticleFetcher { diff --git a/Shared/SmartFeeds/SmartFeedsController.swift b/Shared/SmartFeeds/SmartFeedsController.swift index 8ff75f510..fb578f117 100644 --- a/Shared/SmartFeeds/SmartFeedsController.swift +++ b/Shared/SmartFeeds/SmartFeedsController.swift @@ -11,7 +11,7 @@ import RSCore import Account final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable { - + var containerID: ContainerIdentifier? { return ContainerIdentifier.smartFeedController } @@ -27,7 +27,7 @@ final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable { private init() { self.smartFeeds = [todayFeed, unreadFeed, starredFeed] } - + func find(by identifier: SidebarItemIdentifier) -> PseudoFeed? { switch identifier { case .smartFeed(let stringIdentifer): @@ -45,5 +45,5 @@ final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable { return nil } } - + } diff --git a/Shared/SmartFeeds/TodayFeedDelegate.swift b/Shared/SmartFeeds/TodayFeedDelegate.swift index 06f215ef5..ce1bfb9b6 100644 --- a/Shared/SmartFeeds/TodayFeedDelegate.swift +++ b/Shared/SmartFeeds/TodayFeedDelegate.swift @@ -17,13 +17,13 @@ struct TodayFeedDelegate: SmartFeedDelegate { var sidebarItemID: SidebarItemIdentifier? { return SidebarItemIdentifier.smartFeed(String(describing: TodayFeedDelegate.self)) } - + let nameForDisplay = NSLocalizedString("Today", comment: "Today pseudo-feed title") let fetchType = FetchType.today(nil) var smallIcon: IconImage? { return AppAssets.todayFeedImage } - + func fetchUnreadCount(for account: Account, completion: @escaping SingleUnreadCountCompletionBlock) { account.fetchUnreadCountForToday(completion) } diff --git a/Shared/SmartFeeds/UnreadFeed.swift b/Shared/SmartFeeds/UnreadFeed.swift index 540eb9620..04d313d37 100644 --- a/Shared/SmartFeeds/UnreadFeed.swift +++ b/Shared/SmartFeeds/UnreadFeed.swift @@ -19,7 +19,7 @@ import ArticlesDatabase // This just shows the global unread count, which appDelegate already has. Easy. final class UnreadFeed: PseudoFeed { - + var account: Account? = nil public var defaultReadFilterType: ReadFilterType { @@ -32,7 +32,7 @@ final class UnreadFeed: PseudoFeed { let nameForDisplay = NSLocalizedString("All Unread", comment: "All Unread pseudo-feed title") let fetchType = FetchType.unread(nil) - + var unreadCount = 0 { didSet { if unreadCount != oldValue { @@ -44,13 +44,13 @@ final class UnreadFeed: PseudoFeed { var smallIcon: IconImage? { return AppAssets.unreadFeedImage } - + #if os(macOS) var pasteboardWriter: NSPasteboardWriting { return SmartFeedPasteboardWriter(smartFeed: self) } #endif - + init() { self.unreadCount = appDelegate.unreadCount @@ -65,7 +65,7 @@ final class UnreadFeed: PseudoFeed { } extension UnreadFeed: ArticleFetcher { - + func fetchArticles() throws -> Set
{ return try fetchUnreadArticles() } diff --git a/Shared/Timeline/ArticleArray.swift b/Shared/Timeline/ArticleArray.swift index 2f8d69e06..802db632f 100644 --- a/Shared/Timeline/ArticleArray.swift +++ b/Shared/Timeline/ArticleArray.swift @@ -49,11 +49,11 @@ extension Array where Element == Article { return articleAtRow(oneIndex) } } - + func sortedByDate(_ sortDirection: ComparisonResult, groupByFeed: Bool = false) -> ArticleArray { return ArticleSorter.sortedByDate(articles: self, sortDirection: sortDirection, groupByFeed: groupByFeed) } - + func canMarkAllAsRead() -> Bool { return anyArticleIsUnread() } @@ -107,7 +107,7 @@ extension Array where Element == Article { guard let position = firstIndex(of: article) else { return [] } return articlesAbove(position: position) } - + func articlesAbove(position: Int) -> [Article] { guard position < count else { return [] } let articlesAbove = self[.. [Article] { guard position < count else { return [] } var articlesBelow = Array(self[position...]) @@ -128,6 +128,6 @@ extension Array where Element == Article { articlesBelow.removeFirst() return articlesBelow } - + } diff --git a/Shared/Timeline/ArticleSorter.swift b/Shared/Timeline/ArticleSorter.swift index c7ba1a748..2561ddc4c 100644 --- a/Shared/Timeline/ArticleSorter.swift +++ b/Shared/Timeline/ArticleSorter.swift @@ -17,7 +17,7 @@ protocol SortableArticle { } struct ArticleSorter { - + static func sortedByDate(articles: [T], sortDirection: ComparisonResult, groupByFeed: Bool) -> [T] { @@ -27,9 +27,9 @@ struct ArticleSorter { return sortedByDate(articles: articles, sortDirection: sortDirection) } } - + // MARK: - - + private static func sortedByFeedName(articles: [T], sortByDateDirection: ComparisonResult) -> [T] { // Group articles by "feed-feedID" - feed ID is used to differentiate between @@ -39,11 +39,11 @@ struct ArticleSorter { .sorted { $0.key < $1.key } .flatMap { (tuple) -> [T] in let (_, articles) = tuple - + return sortedByDate(articles: articles, sortDirection: sortByDateDirection) } } - + private static func sortedByDate(articles: [T], sortDirection: ComparisonResult) -> [T] { return articles.sorted { (article1, article2) -> Bool in @@ -53,9 +53,9 @@ struct ArticleSorter { if sortDirection == .orderedDescending { return article1.sortableDate > article2.sortableDate } - + return article1.sortableDate < article2.sortableDate } } - + } diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index bfaab1439..95dae355d 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -61,14 +61,14 @@ final class FetchRequestOperation { let numberOfFetchers = fetchers.count var fetchersReturned = 0 var fetchedArticles = Set
() - + func process(_ articles: Set
) { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() return } - + assert(!self.isFinished) fetchedArticles.formUnion(articles) @@ -79,7 +79,7 @@ final class FetchRequestOperation { callCompletionIfNeeded() } } - + for fetcher in fetchers { if (fetcher as? SidebarItem)?.readFiltered(readFilterEnabledTable: readFilterEnabledTable) ?? true { fetcher.fetchUnreadArticlesAsync { articleSetResult in @@ -92,7 +92,7 @@ final class FetchRequestOperation { process(articles) } } - + } } } diff --git a/Shared/Timeline/FetchRequestQueue.swift b/Shared/Timeline/FetchRequestQueue.swift index 4fd9ff093..fcdf70c72 100644 --- a/Shared/Timeline/FetchRequestQueue.swift +++ b/Shared/Timeline/FetchRequestQueue.swift @@ -14,7 +14,7 @@ final class FetchRequestQueue { private var pendingRequests = [FetchRequestOperation]() private var currentRequest: FetchRequestOperation? = nil - + var isAnyCurrentRequest: Bool { if let currentRequest = currentRequest { return !currentRequest.isCanceled diff --git a/Shared/Timer/RefreshInterval.swift b/Shared/Timer/RefreshInterval.swift index 603ed2cac..d313bfab6 100644 --- a/Shared/Timer/RefreshInterval.swift +++ b/Shared/Timer/RefreshInterval.swift @@ -16,7 +16,7 @@ enum RefreshInterval: Int, CaseIterable, Identifiable { case every2Hours = 5 case every4Hours = 6 case every8Hours = 7 - + func inSeconds() -> TimeInterval { switch self { case .manually: @@ -35,9 +35,9 @@ enum RefreshInterval: Int, CaseIterable, Identifiable { return 8 * 60 * 60 } } - + var id: String { description() } - + func description() -> String { switch self { case .manually: @@ -56,5 +56,5 @@ enum RefreshInterval: Int, CaseIterable, Identifiable { return NSLocalizedString("Every 8 Hours", comment: "Every 8 Hours") } } - + } diff --git a/Shared/Tree/FolderTreeControllerDelegate.swift b/Shared/Tree/FolderTreeControllerDelegate.swift index 2c1e60cf2..d3c5b97b4 100644 --- a/Shared/Tree/FolderTreeControllerDelegate.swift +++ b/Shared/Tree/FolderTreeControllerDelegate.swift @@ -13,7 +13,7 @@ import Articles import Account final class FolderTreeControllerDelegate: TreeControllerDelegate { - + func treeController(treeController: TreeController, childNodesFor node: Node) -> [Node]? { return node.isRoot ? childNodesForRootNode(node) : childNodes(node) @@ -21,27 +21,27 @@ final class FolderTreeControllerDelegate: TreeControllerDelegate { } private extension FolderTreeControllerDelegate { - + func childNodesForRootNode(_ node: Node) -> [Node]? { - + let accountNodes: [Node] = AccountManager.shared.sortedActiveAccounts.map { account in let accountNode = Node(representedObject: account, parent: node) accountNode.canHaveChildNodes = true return accountNode } return accountNodes - + } - + func childNodes(_ node: Node) -> [Node]? { - + guard let account = node.representedObject as? Account, let folders = account.folders else { return nil } - + let folderNodes: [Node] = folders.map { createNode($0, parent: node) } return folderNodes.sortedAlphabetically() - + } func createNode(_ folder: Folder, parent: Node) -> Node { @@ -49,5 +49,5 @@ private extension FolderTreeControllerDelegate { node.canHaveChildNodes = false return node } - + } diff --git a/Shared/Tree/SidebarTreeControllerDelegate.swift b/Shared/Tree/SidebarTreeControllerDelegate.swift index e6369c32e..381afd2b6 100644 --- a/Shared/Tree/SidebarTreeControllerDelegate.swift +++ b/Shared/Tree/SidebarTreeControllerDelegate.swift @@ -15,15 +15,15 @@ final class SidebarTreeControllerDelegate: TreeControllerDelegate { private var filterExceptions = Set() var isReadFiltered = false - + func addFilterException(_ feedID: SidebarItemIdentifier) { filterExceptions.insert(feedID) } - + func resetFilterExceptions() { filterExceptions = Set() } - + func treeController(treeController: TreeController, childNodesFor node: Node) -> [Node]? { if node.isRoot { return childNodesForRootNode(node) @@ -40,7 +40,7 @@ final class SidebarTreeControllerDelegate: TreeControllerDelegate { } private extension SidebarTreeControllerDelegate { - + func childNodesForRootNode(_ rootNode: Node) -> [Node]? { var topLevelNodes = [Node]() @@ -50,7 +50,7 @@ private extension SidebarTreeControllerDelegate { topLevelNodes.append(smartFeedsNode) topLevelNodes.append(contentsOf: sortedAccountNodes(rootNode)) - + return topLevelNodes } @@ -65,13 +65,13 @@ private extension SidebarTreeControllerDelegate { let container = containerNode.representedObject as! Container var children = [AnyObject]() - + for feed in container.topLevelFeeds { if let sidebarItemID = feed.sidebarItemID, !(!filterExceptions.contains(sidebarItemID) && isReadFiltered && feed.unreadCount == 0) { children.append(feed) } } - + if let folders = container.folders { for folder in folders { if let sidebarItemID = folder.sidebarItemID, !(!filterExceptions.contains(sidebarItemID) && isReadFiltered && folder.unreadCount == 0) { @@ -107,18 +107,18 @@ private extension SidebarTreeControllerDelegate { if let folder = representedObject as? Folder { return createNode(folder: folder, parent: parent) } - + if let account = representedObject as? Account { return createNode(account: account, parent: parent) } return nil } - + func createNode(feed: Feed, parent: Node) -> Node { return parent.createChildNode(feed) } - + func createNode(folder: Folder, parent: Node) -> Node { let node = parent.createChildNode(folder) node.canHaveChildNodes = true diff --git a/Shared/UserInfoKey.swift b/Shared/UserInfoKey.swift index ae44ca44e..2adcd7445 100644 --- a/Shared/UserInfoKey.swift +++ b/Shared/UserInfoKey.swift @@ -14,7 +14,7 @@ struct UserInfoKey { static let url = "url" static let articlePath = "articlePath" static let feedIdentifier = "feedIdentifier" - + static let windowState = "windowState" static let windowFullScreenState = "windowFullScreenState" static let containerExpandedWindowState = "containerExpandedWindowState" diff --git a/Shared/UserNotifications/UserNotificationManager.swift b/Shared/UserNotifications/UserNotificationManager.swift index 386a14f3a..436c27471 100644 --- a/Shared/UserNotifications/UserNotificationManager.swift +++ b/Shared/UserNotifications/UserNotificationManager.swift @@ -41,7 +41,7 @@ final class UserNotificationManager { guard let articles = note.userInfo?[Account.UserInfoKey.newArticles] as? Set
else { return } - + for article in articles { if !article.status.read, let feed = article.feed, feed.isNotifyAboutNewArticles ?? false { sendNotification(feed: feed, article: article) @@ -55,7 +55,7 @@ final class UserNotificationManager { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers) return } - + if let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, let statusKey = note.userInfo?[Account.UserInfoKey.statusKey] as? ArticleStatus.Key, let flag = note.userInfo?[Account.UserInfoKey.statusFlag] as? Bool, @@ -71,7 +71,7 @@ private extension UserNotificationManager { func sendNotification(feed: Feed, article: Article) { let content = UNMutableNotificationContent() - + content.title = feed.nameForDisplay if !ArticleStringFormatter.truncatedTitle(article).isEmpty { content.subtitle = ArticleStringFormatter.truncatedTitle(article) @@ -84,11 +84,11 @@ private extension UserNotificationManager { if let attachment = thumbnailAttachment(for: article, feed: feed) { content.attachments.append(attachment) } - + let request = UNNotificationRequest.init(identifier: "articleID:\(article.articleID)", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } - + /// Determine if there is an available icon for the article. This will then move it to the caches directory and make it avialble for the notification. /// - Parameters: /// - article: `Article` @@ -102,7 +102,7 @@ private extension UserNotificationManager { } return nil } - + func registerCategoriesAndActions() { let readAction = UNNotificationAction(identifier: ActionIdentifier.markAsRead, title: NSLocalizedString("Mark as Read", comment: "Mark as Read"), options: []) let starredAction = UNNotificationAction(identifier: ActionIdentifier.markAsStarred, title: NSLocalizedString("Mark as Starred", comment: "Mark as Starred"), options: []) diff --git a/Shared/Widget/WidgetDataDecoder.swift b/Shared/Widget/WidgetDataDecoder.swift index e2d03f53b..a7f57064e 100644 --- a/Shared/Widget/WidgetDataDecoder.swift +++ b/Shared/Widget/WidgetDataDecoder.swift @@ -9,7 +9,7 @@ import Foundation struct WidgetDataDecoder { - + static func decodeWidgetData() throws -> WidgetData { let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) @@ -21,7 +21,7 @@ struct WidgetDataDecoder { return WidgetData(currentUnreadCount: 0, currentTodayCount: 0, currentStarredCount: 0, unreadArticles: [], starredArticles: [], todayArticles: [], lastUpdateTime: Date()) } } - + static func sampleData() -> WidgetData { let pathToSample = Bundle.main.url(forResource: "widget-sample", withExtension: "json") do { @@ -32,5 +32,5 @@ struct WidgetDataDecoder { return WidgetData(currentUnreadCount: 0, currentTodayCount: 0, currentStarredCount: 0, unreadArticles: [], starredArticles: [], todayArticles: [], lastUpdateTime: Date()) } } - + } diff --git a/Shared/Widget/WidgetDeepLinks.swift b/Shared/Widget/WidgetDeepLinks.swift index 782efb1a6..df51e2012 100644 --- a/Shared/Widget/WidgetDeepLinks.swift +++ b/Shared/Widget/WidgetDeepLinks.swift @@ -9,7 +9,7 @@ import Foundation enum WidgetDeepLink { - + case unread case unreadArticle(id: String) case today @@ -17,7 +17,7 @@ enum WidgetDeepLink { case starred case starredArticle(id: String) case icon - + var url: URL { switch self { case .unread: @@ -42,5 +42,5 @@ enum WidgetDeepLink { return URL(string: "nnw://icon")! } } - + } diff --git a/Tests/NetNewsWire-iOSTests/NetNewsWire_iOSTests.swift b/Tests/NetNewsWire-iOSTests/NetNewsWire_iOSTests.swift index 1b3a9586a..5dd8f59bd 100644 --- a/Tests/NetNewsWire-iOSTests/NetNewsWire_iOSTests.swift +++ b/Tests/NetNewsWire-iOSTests/NetNewsWire_iOSTests.swift @@ -9,27 +9,27 @@ import XCTest final class NetNewsWire_iOSTests: XCTestCase { - + override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - + func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } - + } diff --git a/Tests/NetNewsWireTests/ArticleSorterTests.swift b/Tests/NetNewsWireTests/ArticleSorterTests.swift index 8e6989092..9bcd12b76 100644 --- a/Tests/NetNewsWireTests/ArticleSorterTests.swift +++ b/Tests/NetNewsWireTests/ArticleSorterTests.swift @@ -13,44 +13,44 @@ import XCTest @testable import NetNewsWire final class ArticleSorterTests: XCTestCase { - + // MARK: sortByDate ascending tests - + func testSortByDateAscending() { let now = Date() - + let article1 = TestArticle(sortableName: "Susie's Feed", sortableDate: now.addingTimeInterval(-60.0), sortableArticleID: "1", sortableFeedID: "4") let article2 = TestArticle(sortableName: "Phil's Feed", sortableDate: now.addingTimeInterval(60.0), sortableArticleID: "2", sortableFeedID: "6") let article3 = TestArticle(sortableName: "Phil's Feed", sortableDate: now.addingTimeInterval(120.0), sortableArticleID: "3", sortableFeedID: "6") let article4 = TestArticle(sortableName: "Susie's Feed", sortableDate: now.addingTimeInterval(-120.0), sortableArticleID: "4", sortableFeedID: "5") - + let articles = [article1, article2, article3, article4] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedAscending, groupByFeed: false) - + XCTAssertEqual(sortedArticles.count, articles.count) XCTAssertEqual(sortedArticles.articleAtRow(0), article4) XCTAssertEqual(sortedArticles.articleAtRow(1), article1) XCTAssertEqual(sortedArticles.articleAtRow(2), article2) XCTAssertEqual(sortedArticles.articleAtRow(3), article3) } - + func testSortByDateAscendingWithSameDate() { let now = Date() - + // Articles with the same date should end up being sorted by their article ID let article1 = TestArticle(sortableName: "Phil's Feed", sortableDate: now, sortableArticleID: "1", sortableFeedID: "1") let article2 = TestArticle(sortableName: "Matt's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "2") let article3 = TestArticle(sortableName: "Sally's Feed", sortableDate: now, sortableArticleID: "3", sortableFeedID: "3") let article4 = TestArticle(sortableName: "Susie's Feed", sortableDate: Date(timeInterval: -60.0, since: now), sortableArticleID: "4", sortableFeedID: "4") let article5 = TestArticle(sortableName: "Paul's Feed", sortableDate: Date(timeInterval: -120.0, since: now), sortableArticleID: "5", sortableFeedID: "5") - + let articles = [article1, article2, article3, article4, article5] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedAscending, groupByFeed: false) - + XCTAssertEqual(sortedArticles.count, articles.count) XCTAssertEqual(sortedArticles.articleAtRow(0), article5) XCTAssertEqual(sortedArticles.articleAtRow(1), article4) @@ -58,7 +58,7 @@ final class ArticleSorterTests: XCTestCase { XCTAssertEqual(sortedArticles.articleAtRow(3), article2) XCTAssertEqual(sortedArticles.articleAtRow(4), article3) } - + func testSortByDateAscendingWithGroupByFeed() { let now = Date() @@ -71,12 +71,12 @@ final class ArticleSorterTests: XCTestCase { let article7 = TestArticle(sortableName: "Phil's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "1") let article8 = TestArticle(sortableName: "Zippy's Feed", sortableDate: now, sortableArticleID: "1", sortableFeedID: "0") let article9 = TestArticle(sortableName: "Zippy's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "0") - + let articles = [article1, article2, article3, article4, article5, article6, article7, article8, article9] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedAscending, groupByFeed: true) - + XCTAssertEqual(sortedArticles.count, 9) - + // Gordy's feed articles XCTAssertEqual(sortedArticles.articleAtRow(0), article4) XCTAssertEqual(sortedArticles.articleAtRow(1), article5) @@ -93,42 +93,42 @@ final class ArticleSorterTests: XCTestCase { } // MARK: sortByDate descending tests - + func testSortByDateDescending() { let now = Date() - + let article1 = TestArticle(sortableName: "Susie's Feed", sortableDate: now.addingTimeInterval(-60.0), sortableArticleID: "1", sortableFeedID: "4") let article2 = TestArticle(sortableName: "Phil's Feed", sortableDate: now.addingTimeInterval(60.0), sortableArticleID: "2", sortableFeedID: "6") let article3 = TestArticle(sortableName: "Phil's Feed", sortableDate: now.addingTimeInterval(120.0), sortableArticleID: "3", sortableFeedID: "6") let article4 = TestArticle(sortableName: "Susie's Feed", sortableDate: now.addingTimeInterval(-120.0), sortableArticleID: "4", sortableFeedID: "5") - + let articles = [article1, article2, article3, article4] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedDescending, groupByFeed: false) - + XCTAssertEqual(sortedArticles.count, articles.count) XCTAssertEqual(sortedArticles.articleAtRow(0), article3) XCTAssertEqual(sortedArticles.articleAtRow(1), article2) XCTAssertEqual(sortedArticles.articleAtRow(2), article1) XCTAssertEqual(sortedArticles.articleAtRow(3), article4) } - + func testSortByDateDescendingWithSameDate() { let now = Date() - + // Articles with the same date should end up being sorted by their article ID let article1 = TestArticle(sortableName: "Phil's Feed", sortableDate: now, sortableArticleID: "1", sortableFeedID: "1") let article2 = TestArticle(sortableName: "Matt's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "2") let article3 = TestArticle(sortableName: "Sally's Feed", sortableDate: now, sortableArticleID: "3", sortableFeedID: "3") let article4 = TestArticle(sortableName: "Susie's Feed", sortableDate: Date(timeInterval: -60.0, since: now), sortableArticleID: "4", sortableFeedID: "4") let article5 = TestArticle(sortableName: "Paul's Feed", sortableDate: Date(timeInterval: -120.0, since: now), sortableArticleID: "5", sortableFeedID: "5") - + let articles = [article1, article2, article3, article4, article5] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedDescending, groupByFeed: false) - + XCTAssertEqual(sortedArticles.count, articles.count) XCTAssertEqual(sortedArticles.articleAtRow(0), article1) XCTAssertEqual(sortedArticles.articleAtRow(1), article2) @@ -136,7 +136,7 @@ final class ArticleSorterTests: XCTestCase { XCTAssertEqual(sortedArticles.articleAtRow(3), article4) XCTAssertEqual(sortedArticles.articleAtRow(4), article5) } - + func testSortByDateDescendingWithGroupByFeed() { let now = Date() @@ -149,12 +149,12 @@ final class ArticleSorterTests: XCTestCase { let article7 = TestArticle(sortableName: "Phil's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "1") let article8 = TestArticle(sortableName: "Zippy's Feed", sortableDate: now, sortableArticleID: "1", sortableFeedID: "0") let article9 = TestArticle(sortableName: "Zippy's Feed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "0") - + let articles = [article1, article2, article3, article4, article5, article6, article7, article8, article9] let sortedArticles = ArticleSorter.sortedByDate(articles: articles, sortDirection: .orderedDescending, groupByFeed: true) - + XCTAssertEqual(sortedArticles.count, 9) - + // Gordy's feed articles XCTAssertEqual(sortedArticles.articleAtRow(0), article5) XCTAssertEqual(sortedArticles.articleAtRow(1), article4) @@ -169,12 +169,12 @@ final class ArticleSorterTests: XCTestCase { XCTAssertEqual(sortedArticles.articleAtRow(7), article8) XCTAssertEqual(sortedArticles.articleAtRow(8), article9) } - + // MARK: Additional group by feed tests func testGroupByFeedWithCaseInsensitiveFeedNames() { let now = Date() - + let article1 = TestArticle(sortableName: "phil's feed", sortableDate: now, sortableArticleID: "1", sortableFeedID: "1") let article2 = TestArticle(sortableName: "PhIl's FEed", sortableDate: now, sortableArticleID: "2", sortableFeedID: "1") let article3 = TestArticle(sortableName: "APPLE's feed", sortableDate: now, sortableArticleID: "3", sortableFeedID: "2") @@ -187,7 +187,7 @@ final class ArticleSorterTests: XCTestCase { groupByFeed: true) XCTAssertEqual(sortedArticles.count, articles.count) - + // Apple's feed articles XCTAssertEqual(sortedArticles.articleAtRow(0), article3) XCTAssertEqual(sortedArticles.articleAtRow(1), article5) @@ -196,7 +196,7 @@ final class ArticleSorterTests: XCTestCase { XCTAssertEqual(sortedArticles.articleAtRow(3), article2) XCTAssertEqual(sortedArticles.articleAtRow(4), article4) } - + func testGroupByFeedWithSameFeedNames() { let now = Date() @@ -219,7 +219,7 @@ final class ArticleSorterTests: XCTestCase { XCTAssertEqual(sortedArticles.articleAtRow(3), article2) XCTAssertEqual(sortedArticles.articleAtRow(4), article4) } - + } private struct TestArticle: SortableArticle, Equatable { @@ -236,5 +236,5 @@ private extension Array where Element == TestArticle { } return self[row] } - + } diff --git a/Tests/NetNewsWireTests/ScriptingTests/AppleScriptXCTestCase.swift b/Tests/NetNewsWireTests/ScriptingTests/AppleScriptXCTestCase.swift index ee60cc6d7..318fa06a0 100644 --- a/Tests/NetNewsWireTests/ScriptingTests/AppleScriptXCTestCase.swift +++ b/Tests/NetNewsWireTests/ScriptingTests/AppleScriptXCTestCase.swift @@ -9,11 +9,11 @@ import XCTest class AppleScriptXCTestCase: XCTestCase { - + override func setUp() { super.setUp() } - + override func tearDown() { super.tearDown() } @@ -36,31 +36,31 @@ class AppleScriptXCTestCase: XCTestCase { XCTFail("Failed Getting script URL") return nil } - + guard let testScript = NSAppleScript(contentsOf: testScriptUrl, error: &errorDict) else { print ("error is \(String(describing: errorDict))") XCTFail("Failed initializing NSAppleScript") return nil } - + let scriptResult = testScript.executeAndReturnError(&errorDict) if (errorDict != nil) { print ("error is \(String(describing: errorDict))") XCTFail("Failed executing script") return nil } - + let usrfDictionary = scriptResult.usrfDictionary() guard let testResult = usrfDictionary["test_result"] else { XCTFail("test script didn't return test result in usrf") return nil } - + if (testResult.booleanValue != true) { print("test_result was \(testResult)") print("script_result was \(String(describing: usrfDictionary["script_result"]))") } - + XCTAssert(testResult.booleanValue == true, "test_result should be true") return usrfDictionary["script_result"] } diff --git a/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift b/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift index 2c3db6030..dcec9ef5d 100644 --- a/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift +++ b/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift @@ -13,7 +13,7 @@ final class ScriptingTests: AppleScriptXCTestCase { override func setUp() { super.setUp() } - + override func tearDown() { super.tearDown() } @@ -30,27 +30,27 @@ final class ScriptingTests: AppleScriptXCTestCase { let scriptResult = doIndividualScript(filename: "testGenericScript") XCTAssert( scriptResult?.stringValue == "Geoducks!") } - + func testGetUrlScript() { _ = doIndividualScript(filename: "testGetURL") } - + func testNameAndUrlOfEveryFeedScript() { _ = doIndividualScript(filename: "testNameAndUrlOfEveryFeed") } - + func testNameOfEveryFolderScript() { _ = doIndividualScript(filename: "testNameOfEveryFolder") } - + func testNameOfAuthorsScript() { _ = doIndividualScript(filename: "testNameOfAuthors") } - + func testFeedExists() { _ = doIndividualScript(filename: "testFeedExists") } - + func doIndividualScriptWithExpectation(filename:String) { let scriptExpectation = self.expectation(description: filename+"expectation") DispatchQueue.main.async { diff --git a/Widget/Shared Views/SizeCategories.swift b/Widget/Shared Views/SizeCategories.swift index ecc1d632f..8f148a720 100644 --- a/Widget/Shared Views/SizeCategories.swift +++ b/Widget/Shared Views/SizeCategories.swift @@ -9,7 +9,7 @@ import SwiftUI struct SizeCategories { - + let largeSizeCategories: [ContentSizeCategory] = [.extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, @@ -17,10 +17,10 @@ struct SizeCategories { .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge] - - + + func isSizeCategoryLarge(category: ContentSizeCategory) -> Bool { largeSizeCategories.filter{ $0 == category }.count == 1 } - + } diff --git a/Widget/TimelineProvider.swift b/Widget/TimelineProvider.swift index 8ca18dc5d..390765bf1 100644 --- a/Widget/TimelineProvider.swift +++ b/Widget/TimelineProvider.swift @@ -10,7 +10,7 @@ import WidgetKit import SwiftUI struct Provider: TimelineProvider { - + func placeholder(in context: Context) -> WidgetTimelineEntry { do { let data = try WidgetDataDecoder.decodeWidgetData() @@ -19,7 +19,7 @@ struct Provider: TimelineProvider { return WidgetTimelineEntry(date: Date(), widgetData: WidgetDataDecoder.sampleData()) } } - + func getSnapshot(in context: Context, completion: @escaping (WidgetTimelineEntry) -> Void) { if context.isPreview { do { @@ -41,31 +41,31 @@ struct Provider: TimelineProvider { } } } - + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { // Create current timeline entry for now. let date = Date() var entry: WidgetTimelineEntry - + do { let widgetData = try WidgetDataDecoder.decodeWidgetData() entry = WidgetTimelineEntry(date: date, widgetData: widgetData) } catch { entry = WidgetTimelineEntry(date: date, widgetData: WidgetData(currentUnreadCount: 0, currentTodayCount: 0, currentStarredCount: 0, unreadArticles: [], starredArticles: [], todayArticles: [], lastUpdateTime: Date())) } - + // Configure next update in 1 hour. let nextUpdateDate = Calendar.current.date(byAdding: .hour, value: 1, to: date)! - + let timeline = Timeline( entries:[entry], policy: .after(nextUpdateDate)) - + completion(timeline) } - + public typealias Entry = WidgetTimelineEntry - + } struct WidgetTimelineEntry: TimelineEntry { diff --git a/Widget/WidgetBundle.swift b/Widget/WidgetBundle.swift index 4e17b9cd7..9dc304484 100644 --- a/Widget/WidgetBundle.swift +++ b/Widget/WidgetBundle.swift @@ -31,9 +31,9 @@ struct UnreadWidget: Widget { struct TodayWidget: Widget { let kind: String = "com.ranchero.NetNewsWire.TodayWidget" - + var body: some WidgetConfiguration { - + return StaticConfiguration(kind: kind, provider: Provider(), content: { entry in TodayWidgetView(entry: entry) .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -49,9 +49,9 @@ struct TodayWidget: Widget { struct StarredWidget: Widget { let kind: String = "com.ranchero.NetNewsWire.StarredWidget" - + var body: some WidgetConfiguration { - + return StaticConfiguration(kind: kind, provider: Provider(), content: { entry in StarredWidgetView(entry: entry) .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/buildscripts/VerifyNoBS.swift b/buildscripts/VerifyNoBS.swift index c2c72ba22..6672ecc54 100755 --- a/buildscripts/VerifyNoBS.swift +++ b/buildscripts/VerifyNoBS.swift @@ -23,13 +23,13 @@ struct LocatedMessage { /// Utility to process the pbxproj file struct BuildSettingsVerifier { - + public enum ProcessXcodeprojResult { case foundBuildSettings([LocatedMessage]) case error(String) case success(String) } - + /// Mode to run the utility in. Mode defines the output format public enum Mode { /// Write errors to stderr @@ -37,18 +37,18 @@ struct BuildSettingsVerifier { /// Write errors to stdout in a format that is picked up by Xcode case xcode } - + /// The mode to run in let mode: Mode - + /// The absolute file URL to the pbxproj file let projUrl: URL - + init(mode: Mode, projUrl: URL) { self.mode = mode self.projUrl = projUrl } - + /// Reports an error either to stderr or to stdout, depending on the mode func reportError(message: String, fileUrl: URL? = nil, line: Int? = nil) { switch mode { @@ -61,17 +61,17 @@ struct BuildSettingsVerifier { } case .xcode: var messageParts = [String]() - + if let fileUrl = fileUrl { messageParts.append("\(fileUrl.path):") } - + if let line = line { messageParts.append("\(line): ") } - + messageParts.append("error: \(message)") - + print(messageParts.joined()) } } @@ -115,10 +115,10 @@ struct BuildSettingsVerifier { } return .success(":-)") } - + public func verify() -> Int32 { print("Verifying there are no build settings...") - + let result = processXcodeprojAt(url: projUrl) switch result { diff --git a/buildscripts/clean_swift_whitespace.sh b/buildscripts/clean_swift_whitespace.sh index e067e1899..2b0b470a8 100755 --- a/buildscripts/clean_swift_whitespace.sh +++ b/buildscripts/clean_swift_whitespace.sh @@ -19,6 +19,6 @@ file_count=0 while IFS= read -r -d '' file; do "$CLEAN_SCRIPT" "$file" ((file_count++)) -done < <(find "$PROJECT_ROOT" -name "*.swift" -type f -print0) +done < <(find "$PROJECT_ROOT" \( -name ".*" -prune \) -o \( -type f -name "*.swift" -print0 \)) echo "✅ Cleaned $file_count Swift file(s)." diff --git a/iOS/Account/CloudKitAccountViewController.swift b/iOS/Account/CloudKitAccountViewController.swift index 094ebfb6d..be7e5694d 100644 --- a/iOS/Account/CloudKitAccountViewController.swift +++ b/iOS/Account/CloudKitAccountViewController.swift @@ -18,10 +18,10 @@ final class CloudKitAccountViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() setupFooter() - + tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } - + private func setupFooter() { footerLabel.text = NSLocalizedString("NetNewsWire will use your iCloud account to sync your subscriptions across your Mac and iOS devices.", comment: "iCloud") } @@ -30,22 +30,22 @@ final class CloudKitAccountViewController: UITableViewController { dismiss(animated: true, completion: nil) delegate?.dismiss() } - + @IBAction func add(_ sender: Any) { guard AddCloudKitAccountUtilities.isiCloudDriveEnabled else { presentError(AddCloudKitAccountError.iCloudDriveMissing) return } - + let _ = AccountManager.shared.createAccount(type: .cloudKit) dismiss(animated: true, completion: nil) delegate?.dismiss() } - + override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } - + override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView diff --git a/iOS/Account/LocalAccountViewController.swift b/iOS/Account/LocalAccountViewController.swift index e6c0a2b25..698d2701a 100644 --- a/iOS/Account/LocalAccountViewController.swift +++ b/iOS/Account/LocalAccountViewController.swift @@ -13,7 +13,7 @@ final class LocalAccountViewController: UITableViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var footerLabel: UILabel! - + weak var delegate: AddAccountDismissDelegate? override func viewDidLoad() { @@ -23,7 +23,7 @@ final class LocalAccountViewController: UITableViewController { nameTextField.delegate = self tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } - + private func setupFooter() { footerLabel.text = NSLocalizedString("Local accounts do not sync your feeds across devices.", comment: "Local") } @@ -31,18 +31,18 @@ final class LocalAccountViewController: UITableViewController { @IBAction func cancel(_ sender: Any) { dismiss(animated: true, completion: nil) } - + @IBAction func add(_ sender: Any) { let account = AccountManager.shared.createAccount(type: .onMyMac) account.name = nameTextField.text dismiss(animated: true, completion: nil) delegate?.dismiss() } - + override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } - + override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView @@ -52,14 +52,14 @@ final class LocalAccountViewController: UITableViewController { return super.tableView(tableView, viewForHeaderInSection: section) } } - + } extension LocalAccountViewController: UITextFieldDelegate { - + func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } - + } diff --git a/iOS/Account/ReaderAPIAccountViewController.swift b/iOS/Account/ReaderAPIAccountViewController.swift index ceadceb5d..1f9ac05e5 100644 --- a/iOS/Account/ReaderAPIAccountViewController.swift +++ b/iOS/Account/ReaderAPIAccountViewController.swift @@ -27,7 +27,7 @@ final class ReaderAPIAccountViewController: UITableViewController { weak var account: Account? var accountType: AccountType? weak var delegate: AddAccountDismissDelegate? - + override func viewDidLoad() { super.viewDidLoad() setupFooter() @@ -35,7 +35,7 @@ final class ReaderAPIAccountViewController: UITableViewController { activityIndicator.isHidden = true usernameTextField.delegate = self passwordTextField.delegate = self - + if let unwrappedAccount = account, let credentials = try? retrieveCredentialsForAccount(for: unwrappedAccount) { actionButton.setTitle(NSLocalizedString("Update Credentials", comment: "Update Credentials"), for: .normal) @@ -45,7 +45,7 @@ final class ReaderAPIAccountViewController: UITableViewController { } else { actionButton.setTitle(NSLocalizedString("Add Account", comment: "Add Account"), for: .normal) } - + if let unwrappedAccountType = accountType { switch unwrappedAccountType { case .freshRSS: @@ -61,14 +61,14 @@ final class ReaderAPIAccountViewController: UITableViewController { title = "" } } - + NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: usernameTextField) NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: passwordTextField) tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") - + } - + private func setupFooter() { switch accountType { case .bazQux: @@ -87,11 +87,11 @@ final class ReaderAPIAccountViewController: UITableViewController { return } } - + override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } - + override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView @@ -101,7 +101,7 @@ final class ReaderAPIAccountViewController: UITableViewController { return super.tableView(tableView, viewForHeaderInSection: section) } } - + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: @@ -115,8 +115,8 @@ final class ReaderAPIAccountViewController: UITableViewController { return 1 } } - - + + @IBAction func cancel(_ sender: Any) { dismiss(animated: true, completion: nil) } @@ -130,19 +130,19 @@ final class ReaderAPIAccountViewController: UITableViewController { showHideButton.setTitle("Show", for: .normal) } } - + @IBAction func action(_ sender: Any) { guard validateDataEntry(), let type = accountType else { return } - + let username = usernameTextField.text! let password = passwordTextField.text! let url = apiURL()! - + // When you fill in the email address via auto-complete it adds extra whitespace let trimmedUsername = username.trimmingCharacters(in: .whitespaces) - + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: type, username: trimmedUsername) else { showError(NSLocalizedString("There is already an account of that type with that username created.", comment: "Duplicate Error")) return @@ -196,7 +196,7 @@ final class ReaderAPIAccountViewController: UITableViewController { } } } - + private func retrieveCredentialsForAccount(for account: Account) throws -> Credentials? { switch accountType { case .bazQux, .inoreader, .theOldReader, .freshRSS: @@ -205,7 +205,7 @@ final class ReaderAPIAccountViewController: UITableViewController { return nil } } - + private func headerViewImage() -> UIImage? { if let accountType = accountType { switch accountType { @@ -223,7 +223,7 @@ final class ReaderAPIAccountViewController: UITableViewController { } return nil } - + private func validateDataEntry() -> Bool { switch accountType { case .freshRSS: @@ -243,7 +243,7 @@ final class ReaderAPIAccountViewController: UITableViewController { } return true } - + @IBAction func signUpWithProvider(_ sender: Any) { var url: URL! switch accountType { @@ -262,7 +262,7 @@ final class ReaderAPIAccountViewController: UITableViewController { safari.modalPresentationStyle = .currentContext self.present(safari, animated: true, completion: nil) } - + private func apiURL() -> URL? { switch accountType { case .freshRSS: @@ -277,9 +277,9 @@ final class ReaderAPIAccountViewController: UITableViewController { return nil } } - - - + + + @objc func textDidChange(_ note: Notification) { actionButton.isEnabled = !(usernameTextField.text?.isEmpty ?? false) } diff --git a/iOS/Add/AddComboTableViewCell.swift b/iOS/Add/AddComboTableViewCell.swift index 110ce6580..0551babfd 100644 --- a/iOS/Add/AddComboTableViewCell.swift +++ b/iOS/Add/AddComboTableViewCell.swift @@ -12,10 +12,10 @@ final class AddComboTableViewCell: VibrantTableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var label: UILabel! - + override func updateVibrancy(animated: Bool) { super.updateVibrancy(animated: animated) - + let iconTintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : AppAssets.secondaryAccentColor if animated { UIView.animate(withDuration: Self.duration) { @@ -26,5 +26,5 @@ final class AddComboTableViewCell: VibrantTableViewCell { } updateLabelVibrancy(label, color: labelColor, animated: animated) } - + } diff --git a/iOS/Add/AddFeedFolderViewController.swift b/iOS/Add/AddFeedFolderViewController.swift index 393d2a3aa..b66a360fe 100644 --- a/iOS/Add/AddFeedFolderViewController.swift +++ b/iOS/Add/AddFeedFolderViewController.swift @@ -15,15 +15,15 @@ protocol AddFeedFolderViewControllerDelegate { } final class AddFeedFolderViewController: UITableViewController { - + var delegate: AddFeedFolderViewControllerDelegate? var initialContainer: Container? - + var containers = [Container]() override func viewDidLoad() { super.viewDidLoad() - + let sortedActiveAccounts = AccountManager.shared.sortedActiveAccounts for account in sortedActiveAccounts { @@ -53,15 +53,15 @@ final class AddFeedFolderViewController: UITableViewController { return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! AddComboTableViewCell } }() - + if let smallIconProvider = container as? SmallIconProvider { cell.icon?.image = smallIconProvider.smallIcon?.image } - + if let displayNameProvider = container as? DisplayNameProvider { cell.label?.text = displayNameProvider.nameForDisplay } - + if let compContainer = initialContainer, container === compContainer { cell.accessoryType = .checkmark } else { @@ -73,7 +73,7 @@ final class AddFeedFolderViewController: UITableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let container = containers[indexPath.row] - + if let account = container as? Account, account.behaviors.contains(.disallowFeedInRootFolder) { tableView.selectRow(at: nil, animated: false, scrollPosition: .none) } else { @@ -83,19 +83,19 @@ final class AddFeedFolderViewController: UITableViewController { dismiss() } } - + // MARK: Actions - + @IBAction func cancel(_ sender: Any) { dismiss() } - + } private extension AddFeedFolderViewController { - + func dismiss() { dismiss(animated: true) } - + } diff --git a/iOS/Add/AddFeedSelectFolderTableViewCell.swift b/iOS/Add/AddFeedSelectFolderTableViewCell.swift index ea82058c4..00dc050c6 100644 --- a/iOS/Add/AddFeedSelectFolderTableViewCell.swift +++ b/iOS/Add/AddFeedSelectFolderTableViewCell.swift @@ -9,14 +9,14 @@ import UIKit final class AddFeedSelectFolderTableViewCell: VibrantTableViewCell { - + @IBOutlet weak var folderLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! - + override func updateVibrancy(animated: Bool) { super.updateVibrancy(animated: animated) updateLabelVibrancy(folderLabel, color: labelColor, animated: animated) updateLabelVibrancy(detailLabel, color: labelColor, animated: animated) } - + } diff --git a/iOS/Add/AddFeedViewController.swift b/iOS/Add/AddFeedViewController.swift index bc4b65e42..ce5cbf57b 100644 --- a/iOS/Add/AddFeedViewController.swift +++ b/iOS/Add/AddFeedViewController.swift @@ -13,24 +13,24 @@ import RSTree import RSParser final class AddFeedViewController: UITableViewController { - + @IBOutlet weak var addButton: UIBarButtonItem! @IBOutlet weak var urlTextField: UITextField! @IBOutlet weak var urlTextFieldToSuperViewConstraint: NSLayoutConstraint! @IBOutlet weak var nameTextField: UITextField! - + static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0) - + private var folderLabel = "" private var userCancelled = false - + private let activityIndicator = UIActivityIndicatorView(style: .medium) var initialFeed: String? var initialFeedName: String? var container: Container? - + override func viewDidLoad() { super.viewDidLoad() @@ -39,77 +39,77 @@ final class AddFeedViewController: UITableViewController { initialFeed = urlString.normalizedURL } } - + urlTextField.autocorrectionType = .no urlTextField.autocapitalizationType = .none urlTextField.text = initialFeed urlTextField.delegate = self - + if initialFeed != nil { addButton.isEnabled = true } - + nameTextField.text = initialFeedName nameTextField.delegate = self - + if let defaultContainer = AddFeedDefaultContainer.defaultContainer { container = defaultContainer } else { addButton.isEnabled = false } - + updateFolderLabel() - + tableView.register(UINib(nibName: "AddFeedSelectFolderTableViewCell", bundle: nil), forCellReuseIdentifier: "AddFeedSelectFolderTableViewCell") NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: urlTextField) - + if initialFeed == nil { urlTextField.becomeFirstResponder() } } - + @IBAction func cancel(_ sender: Any) { userCancelled = true dismiss(animated: true) } - + @IBAction func add(_ sender: Any) { let urlString = urlTextField.text ?? "" let normalizedURLString = urlString.normalizedURL - + guard !normalizedURLString.isEmpty, let url = URL(string: normalizedURLString) else { return } - + guard let container = container else { return } - + var account: Account? if let containerAccount = container as? Account { account = containerAccount } else if let containerFolder = container as? Folder, let containerAccount = containerFolder.account { account = containerAccount } - + if account!.hasFeed(withURL: url.absoluteString) { presentError(AccountError.createErrorAlreadySubscribed) return } - + addButton.isEnabled = false addButton.customView = activityIndicator addButton.customView?.isHidden = false activityIndicator.startAnimating() - + let feedName = (nameTextField.text?.isEmpty ?? true) ? nil : nameTextField.text - + BatchUpdate.shared.start() - + account!.createFeed(url: url.absoluteString, name: feedName, container: container, validateFeed: true) { result in BatchUpdate.shared.end() - + switch result { case .success(let feed): self.dismiss(animated: true) @@ -124,11 +124,11 @@ final class AddFeedViewController: UITableViewController { } } - + @objc func textDidChange(_ note: Notification) { updateUI() } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "AddFeedSelectFolderTableViewCell", for: indexPath) as? AddFeedSelectFolderTableViewCell @@ -138,7 +138,7 @@ final class AddFeedViewController: UITableViewController { return super.tableView(tableView, cellForRowAt: indexPath) } } - + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 2 { let navController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFeedFolderNavViewController") as! UINavigationController @@ -149,7 +149,7 @@ final class AddFeedViewController: UITableViewController { present(navController, animated: true) } } - + } // MARK: AddFeedFolderViewControllerDelegate @@ -165,22 +165,22 @@ extension AddFeedViewController: AddFeedFolderViewControllerDelegate { // MARK: UITextFieldDelegate extension AddFeedViewController: UITextFieldDelegate { - + func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } - + } // MARK: Private private extension AddFeedViewController { - + func updateUI() { addButton.isEnabled = (urlTextField.text?.mayBeURL ?? false) } - + func updateFolderLabel() { if let containerName = (container as? DisplayNameProvider)?.nameForDisplay { if container is Folder { diff --git a/iOS/Add/AddFolderViewController.swift b/iOS/Add/AddFolderViewController.swift index 478953dea..7fbef5dba 100644 --- a/iOS/Add/AddFolderViewController.swift +++ b/iOS/Add/AddFolderViewController.swift @@ -16,13 +16,13 @@ final class AddFolderViewController: UITableViewController { @IBOutlet private weak var nameTextField: UITextField! @IBOutlet private weak var accountLabel: UILabel! @IBOutlet private weak var accountPickerView: UIPickerView! - + static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0) - + private var shouldDisplayPicker: Bool { return accounts.count > 1 } - + private var accounts: [Account]! { didSet { if let predefinedAccount = accounts.first(where: { $0.accountID == AppDefaults.shared.addFolderAccountID }) { @@ -39,33 +39,33 @@ final class AddFolderViewController: UITableViewController { accountLabel.text = selectedAccount.flatMap { ($0 as DisplayNameProvider).nameForDisplay } } } - + override func viewDidLoad() { super.viewDidLoad() - + accounts = AccountManager.shared .sortedActiveAccounts .filter { !$0.behaviors.contains(.disallowFolderManagement) } - + nameTextField.delegate = self - + if shouldDisplayPicker { accountPickerView.dataSource = self accountPickerView.delegate = self - + if let index = accounts.firstIndex(of: selectedAccount) { accountPickerView.selectRow(index, inComponent: 0, animated: false) } - + } else { accountPickerView.isHidden = true } - + NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: nameTextField) - + nameTextField.becomeFirstResponder() } - + private func didSelect(_ account: Account) { AppDefaults.shared.addFolderAccountID = account.accountID selectedAccount = account @@ -74,7 +74,7 @@ final class AddFolderViewController: UITableViewController { @IBAction func cancel(_ sender: Any) { dismiss(animated: true) } - + @IBAction func add(_ sender: Any) { guard let folderName = nameTextField.text else { return @@ -93,42 +93,42 @@ final class AddFolderViewController: UITableViewController { @objc func textDidChange(_ note: Notification) { addButton.isEnabled = !(nameTextField.text?.isEmpty ?? false) } - + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let defaultNumberOfRows = super.tableView(tableView, numberOfRowsInSection: section) if section == 1 && !shouldDisplayPicker { return defaultNumberOfRows - 1 } - + return defaultNumberOfRows } } extension AddFolderViewController: UIPickerViewDataSource, UIPickerViewDelegate { - + func numberOfComponents(in pickerView: UIPickerView) ->Int { return 1 } - + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return accounts.count } - + func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return (accounts[row] as DisplayNameProvider).nameForDisplay } - + func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { didSelect(accounts[row]) } - + } extension AddFolderViewController: UITextFieldDelegate { - + func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } - + } diff --git a/iOS/Add/SelectComboTableViewCell.swift b/iOS/Add/SelectComboTableViewCell.swift index 6687cbc48..5402c5dc6 100644 --- a/iOS/Add/SelectComboTableViewCell.swift +++ b/iOS/Add/SelectComboTableViewCell.swift @@ -12,10 +12,10 @@ final class SelectComboTableViewCell: VibrantTableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var label: UILabel! - + override func updateVibrancy(animated: Bool) { super.updateVibrancy(animated: animated) - + let iconTintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label if animated { UIView.animate(withDuration: Self.duration) { @@ -24,8 +24,8 @@ final class SelectComboTableViewCell: VibrantTableViewCell { } else { self.icon.tintColor = iconTintColor } - + updateLabelVibrancy(label, color: labelColor, animated: animated) } - + } diff --git a/iOS/AppAssets.swift b/iOS/AppAssets.swift index 601f72727..6b1b8612a 100644 --- a/iOS/AppAssets.swift +++ b/iOS/AppAssets.swift @@ -10,7 +10,7 @@ import RSCore import Account struct AppAssets { - + static var accountBazQuxImage: UIImage = { return UIImage(named: "accountBazQux")! }() @@ -90,39 +90,39 @@ struct AppAssets { static var circleClosedImage: UIImage = { return UIImage(systemName: "largecircle.fill.circle")! }() - + static var circleOpenImage: UIImage = { return UIImage(systemName: "circle")! }() - + static var disclosureImage: UIImage = { return UIImage(named: "disclosure")! }() - + static var copyImage: UIImage = { return UIImage(systemName: "doc.on.doc")! }() - + static var deactivateImage: UIImage = { UIImage(systemName: "minus.circle")! }() - + static var editImage: UIImage = { UIImage(systemName: "square.and.pencil")! }() - + static var faviconTemplateImage: RSImage = { return RSImage(named: "faviconTemplateImage")! }() - + static var filterImage: UIImage = { UIImage(systemName: "line.3.horizontal.decrease")! }() - + static var folderOutlinePlus: UIImage = { UIImage(systemName: "folder.badge.plus")! }() - + static var fullScreenBackgroundColor: UIColor = { return UIColor(named: "fullScreenBackgroundColor")! }() @@ -130,91 +130,91 @@ struct AppAssets { static var infoImage: UIImage = { UIImage(systemName: "info.circle")! }() - + static var markAllAsReadImage: UIImage = { return UIImage(named: "markAllAsRead")! }() - + static var markBelowAsReadImage: UIImage = { return UIImage(systemName: "arrowtriangle.down.circle")! }() - + static var markAboveAsReadImage: UIImage = { return UIImage(systemName: "arrowtriangle.up.circle")! }() - + static var mainFolderImage: IconImage = { return IconImage(UIImage(systemName: "folder")!, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) }() - + static var mainFolderImageNonIcon: UIImage = { return UIImage(systemName: "folder")!.withRenderingMode(.alwaysOriginal).withTintColor(.secondaryLabel) }() - + static var moreImage: UIImage = { return UIImage(systemName: "ellipsis.circle")! }() - + static var nextArticleImage: UIImage = { return UIImage(systemName: "chevron.down")! }() - + static var nextUnreadArticleImage: UIImage = { return UIImage(systemName: "chevron.down.circle")! }() - + static var plus: UIImage = { UIImage(systemName: "plus")! }() - + static var prevArticleImage: UIImage = { return UIImage(systemName: "chevron.up")! }() - + static var openInSidebarImage: UIImage = { return UIImage(systemName: "arrow.turn.down.left")! }() - + static var primaryAccentColor: UIColor { return UIColor(named: "primaryAccentColor")! } - + static var safariImage: UIImage = { return UIImage(systemName: "safari")! }() - + static var searchFeedImage: IconImage = { return IconImage(UIImage(systemName: "magnifyingglass")!, isSymbol: true) }() - + static var secondaryAccentColor: UIColor { return UIColor(named: "secondaryAccentColor")! } - + static var sectionHeaderColor: UIColor = { return UIColor(named: "sectionHeaderColor")! }() - + static var shareImage: UIImage = { return UIImage(systemName: "square.and.arrow.up")! }() - + static var smartFeedImage: UIImage = { return UIImage(systemName: "gear")! }() - + static var starColor: UIColor = { return UIColor(named: "starColor")! }() - + static var starClosedImage: UIImage = { return UIImage(systemName: "star.fill")! }() - + static var starOpenImage: UIImage = { return UIImage(systemName: "star")! }() - + static var starredFeedImage: IconImage { let image = UIImage(systemName: "star.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.starColor.cgColor) @@ -223,12 +223,12 @@ struct AppAssets { static var tickMarkColor: UIColor = { return UIColor(named: "tickMarkColor")! }() - + static var timelineStarImage: UIImage = { let image = UIImage(systemName: "star.fill")! return image.withTintColor(AppAssets.starColor, renderingMode: .alwaysOriginal) }() - + static var todayFeedImage: IconImage { let image = UIImage(systemName: "sun.max.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: UIColor.systemOrange.cgColor) @@ -237,17 +237,17 @@ struct AppAssets { static var trashImage: UIImage = { return UIImage(systemName: "trash")! }() - + static var unreadCellIndicatorImage: IconImage { let image = UIImage(systemName: "circle.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) } - + static var unreadFeedImage: IconImage { let image = UIImage(systemName: "largecircle.fill.circle")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) } - + static var vibrantTextColor: UIColor = { return UIColor(named: "vibrantTextColor")! }() @@ -283,5 +283,5 @@ struct AppAssets { return AppAssets.accountTheOldReaderImage } } - + } diff --git a/iOS/AppDefaults.swift b/iOS/AppDefaults.swift index 7afbeebc0..1ecc7de11 100644 --- a/iOS/AppDefaults.swift +++ b/iOS/AppDefaults.swift @@ -23,7 +23,7 @@ enum UserInterfaceColorPalette: Int, CustomStringConvertible, CaseIterable { return NSLocalizedString("Dark", comment: "Dark") } } - + } extension Notification.Name { @@ -33,16 +33,16 @@ extension Notification.Name { final class AppDefaults { static let defaultThemeName = "Default" - + static let shared = AppDefaults() private init() {} - + static var store: UserDefaults = { let appIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as! String let suiteName = "\(appIdentifierPrefix)group.\(Bundle.main.bundleIdentifier!)" return UserDefaults.init(suiteName: suiteName)! }() - + struct Key { static let userInterfaceColorPalette = "userInterfaceColorPalette" static let lastImageCacheFlushDate = "lastImageCacheFlushDate" @@ -78,7 +78,7 @@ final class AppDefaults { firstRunDate = Date() return true }() - + static var userInterfaceColorPalette: UserInterfaceColorPalette { get { if let result = UserInterfaceColorPalette(rawValue: int(for: Key.userInterfaceColorPalette)) { @@ -100,7 +100,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.addFeedAccountID, newValue) } } - + var addFeedFolderName: String? { get { return AppDefaults.string(for: Key.addFeedFolderName) @@ -109,7 +109,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.addFeedFolderName, newValue) } } - + var addFolderAccountID: String? { get { return AppDefaults.string(for: Key.addFolderAccountID) @@ -118,7 +118,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.addFolderAccountID, newValue) } } - + var useSystemBrowser: Bool { get { return UserDefaults.standard.bool(forKey: Key.useSystemBrowser) @@ -127,7 +127,7 @@ final class AppDefaults { UserDefaults.standard.setValue(newValue, forKey: Key.useSystemBrowser) } } - + var lastImageCacheFlushDate: Date? { get { return AppDefaults.date(for: Key.lastImageCacheFlushDate) @@ -194,7 +194,7 @@ final class AppDefaults { AppDefaults.setBool(for: Key.confirmMarkAllAsRead, newValue) } } - + var isArticleContentJavascriptEnabled: Bool { get { return AppDefaults.bool(for: Key.articleContentJavascriptEnabled) @@ -203,7 +203,7 @@ final class AppDefaults { AppDefaults.setBool(for: Key.articleContentJavascriptEnabled, newValue) } } - + var lastRefresh: Date? { get { return AppDefaults.date(for: Key.lastRefresh) @@ -212,7 +212,7 @@ final class AppDefaults { AppDefaults.setDate(for: Key.lastRefresh, newValue) } } - + var timelineNumberOfLines: Int { get { return AppDefaults.int(for: Key.timelineNumberOfLines) @@ -221,7 +221,7 @@ final class AppDefaults { AppDefaults.setInt(for: Key.timelineNumberOfLines, newValue) } } - + var timelineIconSize: IconSize { get { let rawValue = AppDefaults.store.integer(forKey: Key.timelineIconDimension) @@ -231,7 +231,7 @@ final class AppDefaults { AppDefaults.store.set(newValue.rawValue, forKey: Key.timelineIconDimension) } } - + var currentThemeName: String? { get { return AppDefaults.string(for: Key.currentThemeName) @@ -240,7 +240,7 @@ final class AppDefaults { AppDefaults.setString(for: Key.currentThemeName, newValue) } } - + static func registerDefaults() { let defaults: [String : Any] = [Key.userInterfaceColorPalette: UserInterfaceColorPalette.automatic.rawValue, Key.timelineGroupByFeed: false, @@ -272,7 +272,7 @@ private extension AppDefaults { static func string(for key: String) -> String? { return UserDefaults.standard.string(forKey: key) } - + static func setString(for key: String, _ value: String?) { UserDefaults.standard.set(value, forKey: key) } @@ -288,11 +288,11 @@ private extension AppDefaults { static func int(for key: String) -> Int { return AppDefaults.store.integer(forKey: key) } - + static func setInt(for key: String, _ x: Int) { AppDefaults.store.set(x, forKey: key) } - + static func date(for key: String) -> Date? { return AppDefaults.store.object(forKey: key) as? Date } @@ -317,5 +317,5 @@ private extension AppDefaults { setInt(for: key, ComparisonResult.orderedDescending.rawValue) } } - + } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index a7626bba2..898aa4867 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -20,12 +20,12 @@ var appDelegate: AppDelegate! @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UnreadCountProvider { - + private let backgroundTaskDispatchQueue = DispatchQueue.init(label: "BGTaskScheduler") private var waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid private var syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid - + var shuttingDown = false { didSet { if shuttingDown { @@ -33,7 +33,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } } } - + private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application") var widgetDataEncoder: WidgetDataEncoder! @@ -46,10 +46,10 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } } } - + var isSyncArticleStatusRunning = false var isWaitingForSyncTasks = false - + override init() { super.init() appDelegate = self @@ -59,15 +59,15 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC let documentAccountsFolder = documentFolder.appendingPathComponent("Accounts").absoluteString let documentAccountsFolderPath = String(documentAccountsFolder.suffix(from: documentAccountsFolder.index(documentAccountsFolder.startIndex, offsetBy: 7))) AccountManager.shared = AccountManager(accountsFolder: documentAccountsFolderPath) - + let documentThemesFolder = documentFolder.appendingPathComponent("Themes").absoluteString let documentThemesFolderPath = String(documentThemesFolder.suffix(from: documentAccountsFolder.index(documentThemesFolder.startIndex, offsetBy: 7))) ArticleThemesManager.shared = ArticleThemesManager(folderPath: documentThemesFolderPath) - + NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountRefreshDidFinish(_:)), name: .AccountRefreshDidFinish, object: nil) } - + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AppDefaults.registerDefaults() @@ -75,23 +75,23 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC if isFirstRun { Self.logger.info("Is first run.") } - + if isFirstRun && !AccountManager.shared.anyAccountHasAtLeastOneFeed() { let localAccount = AccountManager.shared.defaultAccount DefaultFeedsImporter.importDefaultFeeds(account: localAccount) } - + registerBackgroundTasks() CacheCleaner.purgeIfNecessary() initializeDownloaders() initializeHomeScreenQuickActions() - + DispatchQueue.main.async { self.unreadCount = AccountManager.shared.unreadCount // Force the badge to update on launch. self.updateBadge() } - + UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .sound, .alert]) { (granted, error) in if granted { DispatchQueue.main.async { @@ -102,21 +102,21 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC UNUserNotificationCenter.current().delegate = self UserNotificationManager.shared.start() - + NetworkMonitor.shared.start() ExtensionContainersFile.shared.start() ExtensionFeedAddRequestFile.shared.start() - + widgetDataEncoder = WidgetDataEncoder() #if DEBUG ArticleStatusSyncTimer.shared.update() #endif - + return true - + } - + func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { DispatchQueue.main.async { self.resumeDatabaseProcessingIfNecessary() @@ -126,7 +126,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } } } - + func applicationWillTerminate(_ application: UIApplication) { shuttingDown = true } @@ -142,33 +142,33 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } // MARK: Notifications - + @objc func unreadCountDidChange(_ note: Notification) { if note.object is AccountManager { unreadCount = AccountManager.shared.unreadCount } } - + @objc func accountRefreshDidFinish(_ note: Notification) { AppDefaults.shared.lastRefresh = Date() } - + // MARK: - API - + func manualRefresh(errorHandler: @escaping (Error) -> ()) { UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate } ).forEach { $0.cleanUp(conditional: true) } AccountManager.shared.refreshAll(errorHandler: errorHandler) } - + func resumeDatabaseProcessingIfNecessary() { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() Self.logger.info("Application processing resumed.") } } - + func prepareAccountsForBackground() { updateBadge() ExtensionFeedAddRequestFile.shared.suspend() @@ -195,16 +195,16 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) } } - + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.list, .banner, .badge, .sound]) } - + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { defer { completionHandler() } - + let userInfo = response.notification.request.content.userInfo - + switch response.actionIdentifier { case UserNotificationManager.ActionIdentifier.markAsRead: handleMarkAsRead(userInfo: userInfo) @@ -218,15 +218,15 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC }) } } - + } - + } // MARK: App Initialization private extension AppDelegate { - + private func initializeDownloaders() { let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! let imagesFolderURL = tempDir.appendingPathComponent("Images") @@ -237,7 +237,7 @@ private extension AppDelegate { let unreadTitle = NSLocalizedString("First Unread", comment: "First Unread") let unreadIcon = UIApplicationShortcutIcon(systemImageName: "chevron.down.circle") let unreadItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.FirstUnread", localizedTitle: unreadTitle, localizedSubtitle: nil, icon: unreadIcon, userInfo: nil) - + let searchTitle = NSLocalizedString("Search", comment: "Search") let searchIcon = UIApplicationShortcutIcon(systemImageName: "magnifyingglass") let searchItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowSearch", localizedTitle: searchTitle, localizedSubtitle: nil, icon: searchIcon, userInfo: nil) @@ -248,38 +248,38 @@ private extension AppDelegate { UIApplication.shared.shortcutItems = [addItem, searchItem, unreadItem] } - + } // MARK: Go To Background private extension AppDelegate { - + func waitForSyncTasksToFinish() { guard !isWaitingForSyncTasks && UIApplication.shared.applicationState == .background else { return } - + isWaitingForSyncTasks = true - + self.waitBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask { [weak self] in guard let self = self else { return } self.completeProcessing(true) Self.logger.info("Accounts wait for progress terminated for running too long.") } - + DispatchQueue.main.async { [weak self] in self?.waitToComplete() { [weak self] suspend in self?.completeProcessing(suspend) } } } - + func waitToComplete(completion: @escaping (Bool) -> Void) { guard UIApplication.shared.applicationState == .background else { Self.logger.info("App came back to foreground, no longer waiting.") completion(false) return } - + if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning || widgetDataEncoder.isRunning { Self.logger.info("Waiting for sync to finish…") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in @@ -290,7 +290,7 @@ private extension AppDelegate { completion(true) } } - + func completeProcessing(_ suspend: Bool) { if suspend { suspendApplication() @@ -299,33 +299,33 @@ private extension AppDelegate { self.waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid isWaitingForSyncTasks = false } - + func syncArticleStatus() { guard !isSyncArticleStatusRunning else { return } - + isSyncArticleStatusRunning = true - + let completeProcessing = { [unowned self] in self.isSyncArticleStatusRunning = false UIApplication.shared.endBackgroundTask(self.syncBackgroundUpdateTask) self.syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid } - + self.syncBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask { completeProcessing() Self.logger.info("Accounts sync processing terminated for running too long.") } - + DispatchQueue.main.async { AccountManager.shared.syncArticleStatusAll() { completeProcessing() } } } - + func suspendApplication() { guard UIApplication.shared.applicationState == .background else { return } - + AccountManager.shared.suspendNetworkAll() AccountManager.shared.suspendDatabaseAll() ArticleThemeDownloader.shared.cleanUp() @@ -336,10 +336,10 @@ private extension AppDelegate { sceneDelegate.suspend() } } - + Self.logger.info("Application processing suspended.") } - + } // MARK: Background Tasks @@ -353,7 +353,7 @@ private extension AppDelegate { self.performBackgroundFeedRefresh(with: task as! BGAppRefreshTask) } } - + /// Schedules a background app refresh based on `AppDefaults.refreshInterval`. func scheduleBackgroundFeedRefresh() { let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh") @@ -369,7 +369,7 @@ private extension AppDelegate { } } } - + /// Performs background feed refresh. /// - Parameter task: `BGAppRefreshTask` /// - Warning: As of Xcode 11 beta 2, when triggered from the debugger this doesn't work. @@ -406,11 +406,11 @@ private extension AppDelegate { // Handle Notification Actions private extension AppDelegate { - + func handleMarkAsRead(userInfo: [AnyHashable: Any]) { handleStatusNotification(userInfo: userInfo, statusKey: .read) } - + func handleMarkAsStarred(userInfo: [AnyHashable: Any]) { handleStatusNotification(userInfo: userInfo, statusKey: .starred) } diff --git a/iOS/Article/ArticleExtractorButton.swift b/iOS/Article/ArticleExtractorButton.swift index 9becdd73b..830eda31c 100644 --- a/iOS/Article/ArticleExtractorButton.swift +++ b/iOS/Article/ArticleExtractorButton.swift @@ -16,9 +16,9 @@ enum ArticleExtractorButtonState { } final class ArticleExtractorButton: UIButton { - + private var animatedLayer: CALayer? - + var buttonState: ArticleExtractorButtonState = .off { didSet { if buttonState != oldValue { @@ -39,7 +39,7 @@ final class ArticleExtractorButton: UIButton { } } } - + override var accessibilityLabel: String? { get { switch buttonState { @@ -57,7 +57,7 @@ final class ArticleExtractorButton: UIButton { super.accessibilityLabel = newValue } } - + override func layoutSubviews() { super.layoutSubviews() guard case .animated = buttonState else { @@ -66,31 +66,31 @@ final class ArticleExtractorButton: UIButton { stripAnimatedSublayer() addAnimatedSublayer(to: layer) } - + private func stripAnimatedSublayer() { animatedLayer?.removeFromSuperlayer() } - + private func addAnimatedSublayer(to hostedLayer: CALayer) { let image1 = AppAssets.articleExtractorOffTinted.cgImage! let image2 = AppAssets.articleExtractorOnTinted.cgImage! let images = [image1, image2, image1] - + animatedLayer = CALayer() let imageSize = AppAssets.articleExtractorOff.size animatedLayer!.bounds = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height) animatedLayer!.position = CGPoint(x: bounds.midX, y: bounds.midY) - + hostedLayer.addSublayer(animatedLayer!) - + let animation = CAKeyframeAnimation(keyPath: "contents") animation.calculationMode = CAAnimationCalculationMode.linear animation.keyTimes = [0, 0.5, 1] animation.duration = 2 animation.values = images as [Any] animation.repeatCount = HUGE - + animatedLayer!.add(animation, forKey: "contents") } - + } diff --git a/iOS/Article/ArticleIconSchemeHandler.swift b/iOS/Article/ArticleIconSchemeHandler.swift index dbef022c4..092c6e689 100644 --- a/iOS/Article/ArticleIconSchemeHandler.swift +++ b/iOS/Article/ArticleIconSchemeHandler.swift @@ -11,13 +11,13 @@ import WebKit import Articles final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler { - + weak var coordinator: SceneCoordinator? - + init(coordinator: SceneCoordinator) { self.coordinator = coordinator } - + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { guard let url = urlSchemeTask.request.url, let coordinator = coordinator else { @@ -37,12 +37,12 @@ final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler { let iconView = IconView(frame: CGRect(x: 0, y: 0, width: 48, height: 48)) iconView.iconImage = iconImage let renderedImage = iconView.asImage() - + guard let data = renderedImage.dataRepresentation() else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)) return } - + let headerFields = ["Cache-Control": "no-cache"] if let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headerFields) { urlSchemeTask.didReceive(response) @@ -51,10 +51,10 @@ final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler { } } - + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { urlSchemeTask.didFailWithError(URLError(.unknown)) } - + } diff --git a/iOS/Article/ArticleSearchBar.swift b/iOS/Article/ArticleSearchBar.swift index 9f391cdc8..de3181a6f 100644 --- a/iOS/Article/ArticleSearchBar.swift +++ b/iOS/Article/ArticleSearchBar.swift @@ -22,9 +22,9 @@ import UIKit var prevButton: UIButton! var background: UIView! var shouldBeginEditing: Bool = true - + weak private var resultsLabel: UILabel! - + var resultsCount: UInt = 0 { didSet { updateUI() @@ -35,30 +35,30 @@ import UIKit updateUI() } } - + weak var delegate: SearchBarDelegate? - + override var keyCommands: [UIKeyCommand]? { return [UIKeyCommand(title: "Exit Find", action: #selector(donePressed(_:)), input: UIKeyCommand.inputEscape)] } - + override init(frame: CGRect) { super.init(frame: frame) commonInit() } - + required init(coder: NSCoder) { super.init(coder: coder) commonInit() } - + override func didMoveToSuperview() { super.didMoveToSuperview() layer.backgroundColor = UIColor(named: "barBackgroundColor")?.cgColor ?? UIColor.white.cgColor isOpaque = true NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: searchField) } - + private func updateUI() { if resultsCount > 0 { let format = NSLocalizedString("%d of %d", comment: "Results selection and count") @@ -66,23 +66,23 @@ import UIKit } else { resultsLabel.text = NSLocalizedString("No results", comment: "No results") } - + nextButton.isEnabled = selectedResult < resultsCount prevButton.isEnabled = resultsCount > 0 && selectedResult > 1 } - + @discardableResult override func becomeFirstResponder() -> Bool { searchField.becomeFirstResponder() } - + @discardableResult override func resignFirstResponder() -> Bool { searchField.resignFirstResponder() } - + override var isFirstResponder: Bool { searchField.isFirstResponder } - + deinit { NotificationCenter.default.removeObserver(self) } @@ -95,12 +95,12 @@ private extension ArticleSearchBar { spacing = 8 layoutMargins.left = 8 layoutMargins.right = 8 - + background = UIView(frame: bounds) background.backgroundColor = .systemGray5 background.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(background) - + let doneButton = UIButton() doneButton.setTitle(NSLocalizedString("Done", comment: "Done"), for: .normal) doneButton.setTitleColor(UIColor.label, for: .normal) @@ -109,14 +109,14 @@ private extension ArticleSearchBar { doneButton.addTarget(self, action: #selector(donePressed), for: .touchUpInside) doneButton.isEnabled = true addArrangedSubview(doneButton) - + let resultsLabel = UILabel() searchField = UISearchTextField() searchField.autocapitalizationType = .none searchField.autocorrectionType = .no searchField.returnKeyType = .search searchField.delegate = self - + resultsLabel.font = .systemFont(ofSize: UIFont.smallSystemFontSize) resultsLabel.textColor = .secondaryLabel resultsLabel.text = "" @@ -124,17 +124,17 @@ private extension ArticleSearchBar { resultsLabel.adjustsFontSizeToFitWidth = true searchField.rightView = resultsLabel searchField.rightViewMode = .always - + self.resultsLabel = resultsLabel addArrangedSubview(searchField) - + prevButton = UIButton(type: .system) prevButton.setImage(UIImage(systemName: "chevron.up"), for: .normal) prevButton.accessibilityLabel = "Previous Result" prevButton.isAccessibilityElement = true prevButton.addTarget(self, action: #selector(previousPressed), for: .touchUpInside) addArrangedSubview(prevButton) - + nextButton = UIButton(type: .system) nextButton.setImage(UIImage(systemName: "chevron.down"), for: .normal) nextButton.accessibilityLabel = "Next Result" @@ -145,25 +145,25 @@ private extension ArticleSearchBar { } private extension ArticleSearchBar { - + @objc func textDidChange(_ notification: Notification) { delegate?.searchBar?(self, textDidChange: searchField.text ?? "") - + if searchField.text?.isEmpty ?? true { searchField.rightViewMode = .never } else { searchField.rightViewMode = .always } } - + @objc func nextPressed() { delegate?.nextWasPressed?(self) } - + @objc func previousPressed() { delegate?.previousWasPressed?(self) } - + @objc func donePressed(_ _: Any? = nil) { delegate?.doneWasPressed?(self) } @@ -174,7 +174,7 @@ extension ArticleSearchBar: UITextFieldDelegate { delegate?.nextWasPressed?(self) return false } - + func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return shouldBeginEditing } diff --git a/iOS/Article/ArticleViewController.swift b/iOS/Article/ArticleViewController.swift index 33a35f8d8..a5720fae0 100644 --- a/iOS/Article/ArticleViewController.swift +++ b/iOS/Article/ArticleViewController.swift @@ -13,7 +13,7 @@ import Articles import SafariServices final class ArticleViewController: UIViewController { - + typealias State = (extractedArticle: ExtractedArticle?, isShowingExtractedArticle: Bool, articleExtractorButtonState: ArticleExtractorButtonState, @@ -25,26 +25,26 @@ final class ArticleViewController: UIViewController { @IBOutlet private weak var readBarButtonItem: UIBarButtonItem! @IBOutlet private weak var starBarButtonItem: UIBarButtonItem! @IBOutlet private weak var actionBarButtonItem: UIBarButtonItem! - + @IBOutlet private var searchBar: ArticleSearchBar! @IBOutlet private var searchBarBottomConstraint: NSLayoutConstraint! private var defaultControls: [UIBarButtonItem]? - + private var pageViewController: UIPageViewController! - + private var currentWebViewController: WebViewController? { return pageViewController?.viewControllers?.first as? WebViewController } - + private var articleExtractorButton: ArticleExtractorButton = { let button = ArticleExtractorButton(type: .system) button.frame = CGRect(x: 0, y: 0, width: 44.0, height: 44.0) button.setImage(AppAssets.articleExtractorOff, for: .normal) return button }() - + weak var coordinator: SceneCoordinator! - + private let poppableDelegate = PoppableGestureRecognizerDelegate() var article: Article? { @@ -60,7 +60,7 @@ final class ArticleViewController: UIViewController { updateUI() } } - + var restoreScrollPosition: (isShowingExtractedArticle: Bool, articleWindowScrollY: Int)? { didSet { if let rsp = restoreScrollPosition { @@ -68,7 +68,7 @@ final class ArticleViewController: UIViewController { } } } - + var currentState: State? { guard let controller = currentWebViewController else { return nil} return State(extractedArticle: controller.extractedArticle, @@ -76,14 +76,14 @@ final class ArticleViewController: UIViewController { articleExtractorButtonState: controller.articleExtractorButtonState, windowScrollY: controller.windowScrollY) } - + var restoreState: State? - + private let keyboardManager = KeyboardManager(type: .detail) override var keyCommands: [UIKeyCommand]? { return keyboardManager.keyCommands } - + override func viewDidLoad() { super.viewDidLoad() @@ -99,15 +99,15 @@ final class ArticleViewController: UIViewController { ]) fullScreenTapZone.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapNavigationBar))) navigationItem.titleView = fullScreenTapZone - + articleExtractorButton.addTarget(self, action: #selector(toggleArticleExtractor(_:)), for: .touchUpInside) toolbarItems?.insert(UIBarButtonItem(customView: articleExtractorButton), at: 6) - + if let parentNavController = navigationController?.parent as? UINavigationController { poppableDelegate.navigationController = parentNavController parentNavController.interactivePopGestureRecognizer?.delegate = poppableDelegate } - + pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [:]) pageViewController.delegate = self pageViewController.dataSource = self @@ -128,7 +128,7 @@ final class ArticleViewController: UIViewController { view.topAnchor.constraint(equalTo: pageViewController.view.topAnchor), view.bottomAnchor.constraint(equalTo: pageViewController.view.bottomAnchor) ]) - + let controller: WebViewController if let state = restoreState { controller = createWebViewController(article, updateView: false) @@ -139,18 +139,18 @@ final class ArticleViewController: UIViewController { } else { controller = createWebViewController(article, updateView: true) } - + if let rsp = restoreScrollPosition { controller.setScrollPosition(isShowingExtractedArticle: rsp.isShowingExtractedArticle, articleWindowScrollY: rsp.articleWindowScrollY) } articleExtractorButton.buttonState = controller.articleExtractorButtonState - + self.pageViewController.setViewControllers([controller], direction: .forward, animated: false, completion: nil) if AppDefaults.shared.logicalArticleFullscreenEnabled { controller.hideBars() } - + // Search bar searchBar.translatesAutoresizingMaskIntoConstraints = false NotificationCenter.default.addObserver(self, selector: #selector(beginFind(_:)), name: .FindInArticle, object: nil) @@ -158,10 +158,10 @@ final class ArticleViewController: UIViewController { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIWindow.keyboardWillChangeFrameNotification, object: nil) searchBar.delegate = self view.bringSubviewToFront(searchBar) - + updateUI() } - + override func viewWillAppear(_ animated: Bool) { let hideToolbars = AppDefaults.shared.logicalArticleFullscreenEnabled if hideToolbars { @@ -178,7 +178,7 @@ final class ArticleViewController: UIViewController { coordinator.isArticleViewControllerPending = false searchBar.shouldBeginEditing = true } - + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if searchBar != nil && !searchBar.isHidden { @@ -186,12 +186,12 @@ final class ArticleViewController: UIViewController { searchBar.shouldBeginEditing = false } } - + override func viewSafeAreaInsetsDidChange() { // This will animate if the show/hide bars animation is happening. view.layoutIfNeeded() } - + override func willTransition(to newCollection: UITraitCollection, with coordinator: any UIViewControllerTransitionCoordinator) { // We only want to show bars when rotating to horizontalSizeClass == .regular // (i.e., big) iPhones to resolve crash #4483. @@ -199,9 +199,9 @@ final class ArticleViewController: UIViewController { currentWebViewController?.showBars() } } - + func updateUI() { - + guard let article = article else { articleExtractorButton.isEnabled = false nextUnreadBarButtonItem.isEnabled = false @@ -218,11 +218,11 @@ final class ArticleViewController: UIViewController { nextArticleBarButtonItem.isEnabled = coordinator.isNextArticleAvailable readBarButtonItem.isEnabled = true starBarButtonItem.isEnabled = true - + let permalinkPresent = article.preferredLink != nil articleExtractorButton.isEnabled = permalinkPresent && !AppDefaults.shared.isDeveloperBuild actionBarButtonItem.isEnabled = permalinkPresent - + if article.status.read { readBarButtonItem.image = AppAssets.circleOpenImage readBarButtonItem.isEnabled = article.isAvailableToMarkUnread @@ -232,7 +232,7 @@ final class ArticleViewController: UIViewController { readBarButtonItem.isEnabled = true readBarButtonItem.accLabelText = NSLocalizedString("Selected - Mark Article Unread", comment: "Selected - Mark Article Unread") } - + if article.status.starred { starBarButtonItem.image = AppAssets.starClosedImage starBarButtonItem.accLabelText = NSLocalizedString("Selected - Star Article", comment: "Selected - Star Article") @@ -241,13 +241,13 @@ final class ArticleViewController: UIViewController { starBarButtonItem.accLabelText = NSLocalizedString("Star Article", comment: "Star Article") } } - + // MARK: Notifications - + @objc dynamic func unreadCountDidChange(_ notification: Notification) { updateUI() } - + @objc func statusesDidChange(_ note: Notification) { guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set else { return @@ -263,14 +263,14 @@ final class ArticleViewController: UIViewController { @objc func contentSizeCategoryDidChange(_ note: Notification) { currentWebViewController?.fullReload() } - + @objc func willEnterForeground(_ note: Notification) { // The toolbar will come back on you if you don't hide it again if AppDefaults.shared.logicalArticleFullscreenEnabled { currentWebViewController?.hideBars() } } - + // MARK: Actions @objc func didTapNavigationBar() { @@ -284,27 +284,27 @@ final class ArticleViewController: UIViewController { @IBAction func toggleArticleExtractor(_ sender: Any) { currentWebViewController?.toggleArticleExtractor() } - + @IBAction func nextUnread(_ sender: Any) { coordinator.selectNextUnread() } - + @IBAction func prevArticle(_ sender: Any) { coordinator.selectPrevArticle() } - + @IBAction func nextArticle(_ sender: Any) { coordinator.selectNextArticle() } - + @IBAction func toggleRead(_ sender: Any) { coordinator.toggleReadForCurrentArticle() } - + @IBAction func toggleStar(_ sender: Any) { coordinator.toggleStarredForCurrentArticle() } - + @IBAction func showActivityDialog(_ sender: Any) { currentWebViewController?.showActivityDialog(popOverBarButtonItem: actionBarButtonItem) } @@ -312,13 +312,13 @@ final class ArticleViewController: UIViewController { @objc func toggleReaderView(_ sender: Any?) { currentWebViewController?.toggleArticleExtractor() } - + // MARK: Keyboard Shortcuts @objc func navigateToTimeline(_ sender: Any?) { coordinator.navigateToTimeline() } - + // MARK: API func focus() { @@ -340,7 +340,7 @@ final class ArticleViewController: UIViewController { func scrollPageUp() { currentWebViewController?.scrollPageUp() } - + func stopArticleExtractorIfProcessing() { currentWebViewController?.stopArticleExtractorIfProcessing() } @@ -348,7 +348,7 @@ final class ArticleViewController: UIViewController { func openInAppBrowser() { currentWebViewController?.openInAppBrowser() } - + func setScrollPosition(isShowingExtractedArticle: Bool, articleWindowScrollY: Int) { currentWebViewController?.setScrollPosition(isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY) } @@ -361,29 +361,29 @@ public extension Notification.Name { } extension ArticleViewController: SearchBarDelegate { - + func searchBar(_ searchBar: ArticleSearchBar, textDidChange searchText: String) { currentWebViewController?.searchText(searchText) { found in searchBar.resultsCount = found.count - + if let index = found.index { searchBar.selectedResult = index + 1 } } } - + func doneWasPressed(_ searchBar: ArticleSearchBar) { NotificationCenter.default.post(name: .EndFindInArticle, object: nil) } - + func nextWasPressed(_ searchBar: ArticleSearchBar) { if searchBar.selectedResult < searchBar.resultsCount { currentWebViewController?.selectNextSearchResult() searchBar.selectedResult += 1 } } - + func previousWasPressed(_ searchBar: ArticleSearchBar) { if searchBar.selectedResult > 1 { currentWebViewController?.selectPreviousSearchResult() @@ -393,14 +393,14 @@ extension ArticleViewController: SearchBarDelegate { } extension ArticleViewController { - + @objc func beginFind(_ _: Any? = nil) { searchBar.isHidden = false navigationController?.setToolbarHidden(true, animated: true) currentWebViewController?.additionalSafeAreaInsets.bottom = searchBar.frame.height searchBar.becomeFirstResponder() } - + @objc func endFind(_ _: Any? = nil) { searchBar.resignFirstResponder() searchBar.isHidden = true @@ -408,13 +408,13 @@ extension ArticleViewController { currentWebViewController?.additionalSafeAreaInsets.bottom = 0 currentWebViewController?.endSearch() } - + @objc func keyboardWillChangeFrame(_ notification: Notification) { if !searchBar.isHidden, let duration = notification.userInfo?[UIWindow.keyboardAnimationDurationUserInfoKey] as? Double, let curveRaw = notification.userInfo?[UIWindow.keyboardAnimationCurveUserInfoKey] as? UInt, let frame = notification.userInfo?[UIWindow.keyboardFrameEndUserInfoKey] as? CGRect { - + let curve = UIView.AnimationOptions(rawValue: curveRaw) let newHeight = view.safeAreaLayoutGuide.layoutFrame.maxY - frame.minY currentWebViewController?.additionalSafeAreaInsets.bottom = newHeight + searchBar.frame.height + 10 @@ -424,26 +424,26 @@ extension ArticleViewController { }) } } - + } // MARK: WebViewControllerDelegate extension ArticleViewController: WebViewControllerDelegate { - + func webViewController(_ webViewController: WebViewController, articleExtractorButtonStateDidUpdate buttonState: ArticleExtractorButtonState) { if webViewController === currentWebViewController { articleExtractorButton.buttonState = buttonState } } - + } // MARK: UIPageViewControllerDataSource extension ArticleViewController: UIPageViewControllerDataSource { - + func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let webViewController = viewController as? WebViewController, let currentArticle = webViewController.article, @@ -452,7 +452,7 @@ extension ArticleViewController: UIPageViewControllerDataSource { } return createWebViewController(article) } - + func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let webViewController = viewController as? WebViewController, let currentArticle = webViewController.article, @@ -461,7 +461,7 @@ extension ArticleViewController: UIPageViewControllerDataSource { } return createWebViewController(article) } - + } // MARK: UIPageViewControllerDelegate @@ -471,19 +471,19 @@ extension ArticleViewController: UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard finished, completed else { return } guard let article = currentWebViewController?.article else { return } - + coordinator.selectArticle(article, animations: [.select, .scroll, .navigation]) articleExtractorButton.buttonState = currentWebViewController?.articleExtractorButtonState ?? .off - + previousViewControllers.compactMap({ $0 as? WebViewController }).forEach({ $0.stopWebViewActivity() }) } - + } // MARK: UIGestureRecognizerDelegate extension ArticleViewController: UIGestureRecognizerDelegate { - + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } @@ -495,13 +495,13 @@ extension ArticleViewController: UIGestureRecognizerDelegate { } return false } - + } // MARK: Private private extension ArticleViewController { - + func createWebViewController(_ article: Article?, updateView: Bool = true) -> WebViewController { let controller = WebViewController() controller.coordinator = coordinator @@ -509,5 +509,5 @@ private extension ArticleViewController { controller.setArticle(article, updateView: updateView) return controller } - + } diff --git a/iOS/Article/ContextMenuPreviewViewController.swift b/iOS/Article/ContextMenuPreviewViewController.swift index 6752220f2..92565101e 100644 --- a/iOS/Article/ContextMenuPreviewViewController.swift +++ b/iOS/Article/ContextMenuPreviewViewController.swift @@ -15,37 +15,37 @@ final class ContextMenuPreviewViewController: UIViewController { @IBOutlet weak var blogAuthorLabel: UILabel! @IBOutlet weak var articleTitleLabel: UILabel! @IBOutlet weak var dateTimeLabel: UILabel! - + var article: Article! - + override func viewDidLoad() { super.viewDidLoad() - + blogNameLabel.text = article.feed?.nameForDisplay ?? "" blogAuthorLabel.text = article.byline() articleTitleLabel.text = article.title ?? "" - + let icon = IconView() icon.iconImage = article.iconImage() icon.translatesAutoresizingMaskIntoConstraints = false view.addSubview(icon) - + NSLayoutConstraint.activate([ icon.widthAnchor.constraint(equalToConstant: 48), icon.heightAnchor.constraint(equalToConstant: 48), icon.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8), icon.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20) ]) - + let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .medium dateTimeLabel.text = dateFormatter.string(from: article.logicalDatePublished) - + // When in landscape the context menu preview will force this controller into a tiny // view space. If it is documented anywhere what that is, I haven't found it. This // set of magic numbers is what I worked out by testing a variety of phones. - + let width: CGFloat let heightPadding: CGFloat if view.bounds.width > view.bounds.height { @@ -56,7 +56,7 @@ final class ContextMenuPreviewViewController: UIViewController { width = view.bounds.width heightPadding = 8 } - + view.setNeedsLayout() view.layoutIfNeeded() preferredContentSize = CGSize(width: width, height: dateTimeLabel.frame.maxY + heightPadding) diff --git a/iOS/Article/FindInArticleActivity.swift b/iOS/Article/FindInArticleActivity.swift index 1561b153d..c915432d4 100644 --- a/iOS/Article/FindInArticleActivity.swift +++ b/iOS/Article/FindInArticleActivity.swift @@ -12,27 +12,27 @@ final class FindInArticleActivity: UIActivity { override var activityTitle: String? { NSLocalizedString("Find in Article", comment: "Find in Article") } - + override var activityType: UIActivity.ActivityType? { UIActivity.ActivityType(rawValue: "com.ranchero.NetNewsWire.find") } - + override var activityImage: UIImage? { UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular)) } - + override class var activityCategory: UIActivity.Category { .action } - + override func canPerform(withActivityItems activityItems: [Any]) -> Bool { true } - + override func prepare(withActivityItems activityItems: [Any]) { - + } - + override func perform() { NotificationCenter.default.post(Notification(name: .FindInArticle)) activityDidFinish(true) diff --git a/iOS/Article/ImageScrollView.swift b/iOS/Article/ImageScrollView.swift index 6cd584c0d..50561e736 100644 --- a/iOS/Article/ImageScrollView.swift +++ b/iOS/Article/ImageScrollView.swift @@ -14,63 +14,63 @@ import UIKit } open class ImageScrollView: UIScrollView { - + @objc public enum ScaleMode: Int { case aspectFill case aspectFit case widthFill case heightFill } - + @objc public enum Offset: Int { case beginning case center } - + static let kZoomInFactorFromMinWhenDoubleTap: CGFloat = 2 - + @objc open var imageContentMode: ScaleMode = .widthFill @objc open var initialOffset: Offset = .beginning - + @objc public private(set) var zoomView: UIImageView? = nil - + @objc open weak var imageScrollViewDelegate: ImageScrollViewDelegate? - + var imageSize: CGSize = CGSize.zero private var pointToCenterAfterResize: CGPoint = CGPoint.zero private var scaleToRestoreAfterResize: CGFloat = 1.0 var maxScaleFromMinScale: CGFloat = 3.0 - + var zoomedFrame: CGRect { return zoomView?.frame ?? CGRect.zero } - + override open var frame: CGRect { willSet { if frame.equalTo(newValue) == false && newValue.equalTo(CGRect.zero) == false && imageSize.equalTo(CGSize.zero) == false { prepareToResize() } } - + didSet { if frame.equalTo(oldValue) == false && frame.equalTo(CGRect.zero) == false && imageSize.equalTo(CGSize.zero) == false { recoverFromResizing() } } } - + override public init(frame: CGRect) { super.init(frame: frame) - + initialize() } - + required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - + initialize() } - + private func initialize() { showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false @@ -78,135 +78,135 @@ open class ImageScrollView: UIScrollView { decelerationRate = UIScrollView.DecelerationRate.fast delegate = self } - + @objc public func adjustFrameToCenter() { - + guard let unwrappedZoomView = zoomView else { return } - + var frameToCenter = unwrappedZoomView.frame - + // center horizontally if frameToCenter.size.width < bounds.width { frameToCenter.origin.x = (bounds.width - frameToCenter.size.width) / 2 } else { frameToCenter.origin.x = 0 } - + // center vertically if frameToCenter.size.height < bounds.height { frameToCenter.origin.y = (bounds.height - frameToCenter.size.height) / 2 } else { frameToCenter.origin.y = 0 } - + unwrappedZoomView.frame = frameToCenter } - + private func prepareToResize() { let boundsCenter = CGPoint(x: bounds.midX, y: bounds.midY) pointToCenterAfterResize = convert(boundsCenter, to: zoomView) - + scaleToRestoreAfterResize = zoomScale - + // If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum // allowable scale when the scale is restored. if scaleToRestoreAfterResize <= minimumZoomScale + CGFloat(Float.ulpOfOne) { scaleToRestoreAfterResize = 0 } } - + private func recoverFromResizing() { setMaxMinZoomScalesForCurrentBounds() - + // restore zoom scale, first making sure it is within the allowable range. let maxZoomScale = max(minimumZoomScale, scaleToRestoreAfterResize) zoomScale = min(maximumZoomScale, maxZoomScale) - + // restore center point, first making sure it is within the allowable range. - + // convert our desired center point back to our own coordinate space let boundsCenter = convert(pointToCenterAfterResize, to: zoomView) - + // calculate the content offset that would yield that center point var offset = CGPoint(x: boundsCenter.x - bounds.size.width/2.0, y: boundsCenter.y - bounds.size.height/2.0) - + // restore offset, adjusted to be within the allowable range let maxOffset = maximumContentOffset() let minOffset = minimumContentOffset() - + var realMaxOffset = min(maxOffset.x, offset.x) offset.x = max(minOffset.x, realMaxOffset) - + realMaxOffset = min(maxOffset.y, offset.y) offset.y = max(minOffset.y, realMaxOffset) - + contentOffset = offset } - + private func maximumContentOffset() -> CGPoint { return CGPoint(x: contentSize.width - bounds.width,y:contentSize.height - bounds.height) } - + private func minimumContentOffset() -> CGPoint { return CGPoint.zero } - + // MARK: - Set up - + open func setup() { var topSupperView = superview - + while topSupperView?.superview != nil { topSupperView = topSupperView?.superview } - + // Make sure views have already layout with precise frame topSupperView?.layoutIfNeeded() } - + // MARK: - Display image - + @objc open func display(image: UIImage) { - + if let zoomView = zoomView { zoomView.removeFromSuperview() } - + zoomView = UIImageView(image: image) zoomView!.isUserInteractionEnabled = true addSubview(zoomView!) - + let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognizer(_:))) tapGesture.numberOfTapsRequired = 2 zoomView!.addGestureRecognizer(tapGesture) - + let downSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeUpGestureRecognizer(_:))) downSwipeGesture.direction = .down zoomView!.addGestureRecognizer(downSwipeGesture) - + let upSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeDownGestureRecognizer(_:))) upSwipeGesture.direction = .up zoomView!.addGestureRecognizer(upSwipeGesture) - + configureImageForSize(image.size) adjustFrameToCenter() } - + private func configureImageForSize(_ size: CGSize) { imageSize = size contentSize = imageSize setMaxMinZoomScalesForCurrentBounds() zoomScale = minimumZoomScale - + switch initialOffset { case .beginning: contentOffset = CGPoint.zero case .center: let xOffset = contentSize.width < bounds.width ? 0 : (contentSize.width - bounds.width)/2 let yOffset = contentSize.height < bounds.height ? 0 : (contentSize.height - bounds.height)/2 - + switch imageContentMode { case .aspectFit: contentOffset = CGPoint.zero @@ -219,14 +219,14 @@ open class ImageScrollView: UIScrollView { } } } - + private func setMaxMinZoomScalesForCurrentBounds() { // calculate min/max zoomscale let xScale = bounds.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = bounds.height / imageSize.height // the scale needed to perfectly fit the image height-wise - + var minScale: CGFloat = 1 - + switch imageContentMode { case .aspectFill: minScale = max(xScale, yScale) @@ -237,21 +237,21 @@ open class ImageScrollView: UIScrollView { case .heightFill: minScale = yScale } - - + + let maxScale = maxScaleFromMinScale*minScale - + // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if minScale > maxScale { minScale = maxScale } - + maximumZoomScale = maxScale minimumZoomScale = minScale // * 0.999 // the multiply factor to prevent user cannot scroll page while they use this control in UIPageViewController } - + // MARK: - Gesture - + @objc func doubleTapGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { // zoom out if it bigger than middle scale point. Else, zoom in if zoomScale >= maximumZoomScale / 2.0 { @@ -262,100 +262,100 @@ open class ImageScrollView: UIScrollView { zoom(to: zoomRect, animated: true) } } - + @objc func swipeUpGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.state == .ended { imageScrollViewDelegate?.imageScrollViewDidGestureSwipeUp(imageScrollView: self) } } - + @objc func swipeDownGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.state == .ended { imageScrollViewDelegate?.imageScrollViewDidGestureSwipeDown(imageScrollView: self) } } - + private func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect { var zoomRect = CGRect.zero - + // the zoom rect is in the content view's coordinates. // at a zoom scale of 1.0, it would be the size of the imageScrollView's bounds. // as the zoom scale decreases, so more content is visible, the size of the rect grows. zoomRect.size.height = frame.size.height / scale zoomRect.size.width = frame.size.width / scale - + // choose an origin so as to get the right center. zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0) zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0) - + return zoomRect } - + open func refresh() { if let image = zoomView?.image { display(image: image) } } - + open func resize() { self.configureImageForSize(self.imageSize) } } extension ImageScrollView: UIScrollViewDelegate { - + public func scrollViewDidScroll(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewDidScroll?(scrollView) } - + public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewWillBeginDragging?(scrollView) } - + public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) { imageScrollViewDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } - + public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { imageScrollViewDelegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) } - + public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewWillBeginDecelerating?(scrollView) } - + public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewDidEndDecelerating?(scrollView) } - + public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewDidEndScrollingAnimation?(scrollView) } - + public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { imageScrollViewDelegate?.scrollViewWillBeginZooming?(scrollView, with: view) } - + public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { imageScrollViewDelegate?.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale) } - + public func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return false } - + @available(iOS 11.0, *) public func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) { imageScrollViewDelegate?.scrollViewDidChangeAdjustedContentInset?(scrollView) } - + public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return zoomView } - + public func scrollViewDidZoom(_ scrollView: UIScrollView) { adjustFrameToCenter() imageScrollViewDelegate?.scrollViewDidZoom?(scrollView) } - + } diff --git a/iOS/Article/ImageTransition.swift b/iOS/Article/ImageTransition.swift index d923b131f..3135ebf08 100644 --- a/iOS/Article/ImageTransition.swift +++ b/iOS/Article/ImageTransition.swift @@ -16,15 +16,15 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning { var originFrame: CGRect! var maskFrame: CGRect! var originImage: UIImage! - + init(controller: WebViewController) { self.webViewController = controller } - + func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } - + func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if presenting { animateTransitionPresenting(using: transitionContext) @@ -32,18 +32,18 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning { animateTransitionReturning(using: transitionContext) } } - + private func animateTransitionPresenting(using transitionContext: UIViewControllerContextTransitioning) { let imageView = UIImageView(image: originImage) imageView.frame = originFrame - + let fromView = transitionContext.view(forKey: .from)! fromView.removeFromSuperview() transitionContext.containerView.backgroundColor = AppAssets.fullScreenBackgroundColor transitionContext.containerView.addSubview(imageView) - + webViewController?.hideClickedImage() UIView.animate( @@ -61,27 +61,27 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning { transitionContext.completeTransition(true) }) } - + private func animateTransitionReturning(using transitionContext: UIViewControllerContextTransitioning) { let imageController = transitionContext.viewController(forKey: .from) as! ImageViewController let imageView = UIImageView(image: originImage) imageView.frame = imageController.zoomedFrame - + let fromView = transitionContext.view(forKey: .from)! let windowFrame = fromView.window!.frame fromView.removeFromSuperview() - + let toView = transitionContext.view(forKey: .to)! transitionContext.containerView.addSubview(toView) - + let maskingView = UIView() - + let fullMaskFrame = CGRect(x: windowFrame.minX, y: maskFrame.minY, width: windowFrame.width, height: maskFrame.height) let path = UIBezierPath(rect: fullMaskFrame) let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath maskingView.layer.mask = maskLayer - + maskingView.addSubview(imageView) transitionContext.containerView.addSubview(maskingView) @@ -106,5 +106,5 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning { } }) } - + } diff --git a/iOS/Article/ImageViewController.swift b/iOS/Article/ImageViewController.swift index 93fd1e394..73f31652e 100644 --- a/iOS/Article/ImageViewController.swift +++ b/iOS/Article/ImageViewController.swift @@ -10,7 +10,7 @@ import UIKit final class ImageViewController: UIViewController { - + @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var shareButton: UIButton! @IBOutlet weak var imageScrollView: ImageScrollView! @@ -18,13 +18,13 @@ final class ImageViewController: UIViewController { @IBOutlet weak var titleBackground: UIVisualEffectView! @IBOutlet weak var titleLeading: NSLayoutConstraint! @IBOutlet weak var titleTrailing: NSLayoutConstraint! - + var image: UIImage! var imageTitle: String? var zoomedFrame: CGRect { return imageScrollView.zoomedFrame } - + override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand( @@ -34,23 +34,23 @@ final class ImageViewController: UIViewController { ) ] } - + override func viewDidLoad() { super.viewDidLoad() - + closeButton.imageView?.contentMode = .scaleAspectFit closeButton.accessibilityLabel = NSLocalizedString("Close", comment: "Close") shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Share") - + imageScrollView.setup() imageScrollView.imageScrollViewDelegate = self imageScrollView.imageContentMode = .aspectFit imageScrollView.initialOffset = .center imageScrollView.display(image: image) - + titleLabel.text = imageTitle ?? "" layoutTitleLabel() - + guard imageTitle != "" else { titleBackground.removeFromSuperview() return @@ -64,7 +64,7 @@ final class ImageViewController: UIViewController { self?.imageScrollView.resize() }) } - + @IBAction func share(_ sender: Any) { guard let image = image else { return } let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil) @@ -72,11 +72,11 @@ final class ImageViewController: UIViewController { activityViewController.popoverPresentationController?.sourceRect = shareButton.bounds present(activityViewController, animated: true) } - + @IBAction func done(_ sender: Any) { dismiss(animated: true) } - + private func layoutTitleLabel(){ let width = view.frame.width let multiplier = traitCollection.userInterfaceIdiom == .pad ? CGFloat(0.1) : CGFloat(0.04) @@ -93,10 +93,10 @@ extension ImageViewController: ImageScrollViewDelegate { func imageScrollViewDidGestureSwipeUp(imageScrollView: ImageScrollView) { dismiss(animated: true) } - + func imageScrollViewDidGestureSwipeDown(imageScrollView: ImageScrollView) { dismiss(animated: true) } - - + + } diff --git a/iOS/Article/OpenInSafariActivity.swift b/iOS/Article/OpenInSafariActivity.swift index feb72d2c2..837850e1f 100644 --- a/iOS/Article/OpenInSafariActivity.swift +++ b/iOS/Article/OpenInSafariActivity.swift @@ -9,17 +9,17 @@ import UIKit final class OpenInBrowserActivity: UIActivity { - + private var activityItems: [Any]? override var activityTitle: String? { return NSLocalizedString("Open in Browser", comment: "Open in Browser") } - + override var activityImage: UIImage? { return UIImage(systemName: "globe", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular)) } - + override var activityType: UIActivity.ActivityType? { return UIActivity.ActivityType(rawValue: "com.rancharo.NetNewsWire-Evergreen.safari") } @@ -27,23 +27,23 @@ final class OpenInBrowserActivity: UIActivity { override class var activityCategory: UIActivity.Category { return .action } - + override func canPerform(withActivityItems activityItems: [Any]) -> Bool { return true } - + override func prepare(withActivityItems activityItems: [Any]) { self.activityItems = activityItems } - + override func perform() { guard let url = activityItems?.first(where: { $0 is URL }) as? URL else { activityDidFinish(false) return } - + UIApplication.shared.open(url, options: [:], completionHandler: nil) activityDidFinish(true) } - + } diff --git a/iOS/Article/PreloadedWebView.swift b/iOS/Article/PreloadedWebView.swift index 32f4760a3..48c9f1435 100644 --- a/iOS/Article/PreloadedWebView.swift +++ b/iOS/Article/PreloadedWebView.swift @@ -10,7 +10,7 @@ import Foundation import WebKit final class PreloadedWebView: WKWebView { - + private var isReady: Bool = false private var readyCompletion: (() -> Void)? @@ -19,17 +19,17 @@ final class PreloadedWebView: WKWebView { super.init(frame: .zero, configuration: configuration) NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) } - + required init?(coder: NSCoder) { super.init(coder: coder) - + } - + func preload() { navigationDelegate = self loadFileURL(ArticleRenderer.blank.url, allowingReadAccessTo: ArticleRenderer.blank.baseURL) } - + func ready(completion: @escaping () -> Void) { if isReady { completeRequest(completion: completion) @@ -37,7 +37,7 @@ final class PreloadedWebView: WKWebView { readyCompletion = completion } } - + @objc func userDefaultsDidChange(_ sender: Any) { Task { @MainActor in if configuration.defaultWebpagePreferences.allowsContentJavaScript != AppDefaults.shared.isArticleContentJavascriptEnabled { @@ -64,7 +64,7 @@ extension PreloadedWebView: WKNavigationDelegate { // MARK: Private private extension PreloadedWebView { - + func completeRequest(completion: @escaping () -> Void) { isReady = false navigationDelegate = nil diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index 58fd92948..e96e32910 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -658,9 +658,9 @@ private extension WebViewController { self.showFullScreenImage(image: image, clickMessage: clickMessage, webView: webView) } } - + private func showFullScreenImage(image: UIImage, clickMessage: ImageClickMessage, webView: WKWebView) { - + let y = CGFloat(clickMessage.y) + webView.safeAreaInsets.top let rect = CGRect(x: CGFloat(clickMessage.x), y: y, width: CGFloat(clickMessage.width), height: CGFloat(clickMessage.height)) transition.originFrame = webView.convert(rect, to: nil) diff --git a/iOS/Article/WebViewProvider.swift b/iOS/Article/WebViewProvider.swift index 5aa6d0981..2e555d8f0 100644 --- a/iOS/Article/WebViewProvider.swift +++ b/iOS/Article/WebViewProvider.swift @@ -17,7 +17,7 @@ final class WebViewProvider: NSObject { private let articleIconSchemeHandler: ArticleIconSchemeHandler private let operationQueue = MainThreadOperationQueue() private var queue = NSMutableArray() - + init(coordinator: SceneCoordinator) { articleIconSchemeHandler = ArticleIconSchemeHandler(coordinator: coordinator) super.init() @@ -27,12 +27,12 @@ final class WebViewProvider: NSObject { func replenishQueueIfNeeded() { operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) } - + func dequeueWebView(completion: @escaping (PreloadedWebView) -> ()) { operationQueue.add(WebViewProviderDequeueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler, completion: completion)) operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) } - + } final class WebViewProviderReplenishQueueOperation: MainThreadOperation { @@ -48,12 +48,12 @@ final class WebViewProviderReplenishQueueOperation: MainThreadOperation { private var queue: NSMutableArray private var articleIconSchemeHandler: ArticleIconSchemeHandler - + init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler) { self.queue = queue self.articleIconSchemeHandler = articleIconSchemeHandler } - + func run() { while queue.count < minimumQueueDepth { let webView = PreloadedWebView(articleIconSchemeHandler: articleIconSchemeHandler) @@ -62,11 +62,11 @@ final class WebViewProviderReplenishQueueOperation: MainThreadOperation { } self.operationDelegate?.operationDidComplete(self) } - + } final class WebViewProviderDequeueOperation: MainThreadOperation { - + // MainThreadOperation public var isCanceled = false public var id: Int? @@ -77,13 +77,13 @@ final class WebViewProviderDequeueOperation: MainThreadOperation { private var queue: NSMutableArray private var articleIconSchemeHandler: ArticleIconSchemeHandler private var completion: (PreloadedWebView) -> () - + init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler, completion: @escaping (PreloadedWebView) -> ()) { self.queue = queue self.articleIconSchemeHandler = articleIconSchemeHandler self.completion = completion } - + func run() { if let webView = queue.lastObject as? PreloadedWebView { self.completion(webView) @@ -93,11 +93,11 @@ final class WebViewProviderDequeueOperation: MainThreadOperation { } assertionFailure("Creating PreloadedWebView in \(#function); queue has run dry.") - + let webView = PreloadedWebView(articleIconSchemeHandler: articleIconSchemeHandler) webView.preload() self.completion(webView) self.operationDelegate?.operationDidComplete(self) } - + } diff --git a/iOS/Article/WrapperScriptMessageHandler.swift b/iOS/Article/WrapperScriptMessageHandler.swift index 463916da4..7cd0afc62 100644 --- a/iOS/Article/WrapperScriptMessageHandler.swift +++ b/iOS/Article/WrapperScriptMessageHandler.swift @@ -10,16 +10,16 @@ import Foundation import WebKit final class WrapperScriptMessageHandler: NSObject, WKScriptMessageHandler { - + // We need to wrap a message handler to prevent a circlular reference private weak var handler: WKScriptMessageHandler? - + init(_ handler: WKScriptMessageHandler) { self.handler = handler } - + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { handler?.userContentController(userContentController, didReceive: message) } - + } diff --git a/iOS/ArticleActivityItemSource.swift b/iOS/ArticleActivityItemSource.swift index 6463f2d74..2b3e10f01 100644 --- a/iOS/ArticleActivityItemSource.swift +++ b/iOS/ArticleActivityItemSource.swift @@ -9,25 +9,25 @@ import UIKit final class ArticleActivityItemSource: NSObject, UIActivityItemSource { - + private let url: URL private let subject: String? - + init(url: URL, subject: String?) { self.url = url self.subject = subject } - + func activityViewControllerPlaceholderItem(_ : UIActivityViewController) -> Any { return url } - + func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { return url } - + func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String { return subject ?? "" } - + } diff --git a/iOS/IconView.swift b/iOS/IconView.swift index 1d8eba0ae..f7bffaa05 100644 --- a/iOS/IconView.swift +++ b/iOS/IconView.swift @@ -47,11 +47,11 @@ final class IconView: UIView { private var isSymbolImage: Bool { return iconImage?.isSymbol ?? false } - + private var isBackgroundSuppressed: Bool { return iconImage?.isBackgroundSuppressed ?? false } - + override init(frame: CGRect) { super.init(frame: frame) commonInit() @@ -61,7 +61,7 @@ final class IconView: UIView { super.init(coder: coder) commonInit() } - + convenience init() { self.init(frame: .zero) } diff --git a/iOS/Inspector/AccountInspectorViewController.swift b/iOS/Inspector/AccountInspectorViewController.swift index 9763411c9..f2aa865ce 100644 --- a/iOS/Inspector/AccountInspectorViewController.swift +++ b/iOS/Inspector/AccountInspectorViewController.swift @@ -21,23 +21,23 @@ final class AccountInspectorViewController: UITableViewController { var isModal = false weak var account: Account? - + override func viewDidLoad() { super.viewDidLoad() - + guard let account = account else { return } - + nameTextField.placeholder = account.defaultName nameTextField.text = account.name nameTextField.delegate = self activeSwitch.isOn = account.isActive - + navigationItem.title = account.nameForDisplay - + if account.type != .onMyMac { deleteAccountButton.setTitle(NSLocalizedString("Remove Account", comment: "Remove Account"), for: .normal) } - + if account.type != .cloudKit { limitationsAndSolutionsButton.isHidden = true } @@ -46,11 +46,11 @@ final class AccountInspectorViewController: UITableViewController { let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) navigationItem.leftBarButtonItem = doneBarButtonItem } - + tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } - + override func viewWillDisappear(_ animated: Bool) { account?.name = nameTextField.text account?.isActive = activeSwitch.isOn @@ -59,7 +59,7 @@ final class AccountInspectorViewController: UITableViewController { @objc func done() { dismiss(animated: true) } - + @IBAction func credentials(_ sender: Any) { guard let account = account else { return } switch account.type { @@ -86,12 +86,12 @@ final class AccountInspectorViewController: UITableViewController { break } } - + @IBAction func deleteAccount(_ sender: Any) { guard let account = account else { return } - + let title = NSLocalizedString("Remove Account", comment: "Remove Account") let message: String = { switch account.type { @@ -105,7 +105,7 @@ final class AccountInspectorViewController: UITableViewController { let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) alertController.addAction(cancelAction) - + let markTitle = NSLocalizedString("Remove", comment: "Remove") let markAction = UIAlertAction(title: markTitle, style: .destructive) { [weak self] (action) in guard let self = self, let account = self.account else { return } @@ -118,7 +118,7 @@ final class AccountInspectorViewController: UITableViewController { } alertController.addAction(markAction) alertController.preferredAction = markAction - + present(alertController, animated: true) } @@ -132,7 +132,7 @@ final class AccountInspectorViewController: UITableViewController { // MARK: Table View extension AccountInspectorViewController { - + var hidesCredentialsSection: Bool { guard let account = account else { return true @@ -147,7 +147,7 @@ extension AccountInspectorViewController { override func numberOfSections(in tableView: UITableView) -> Int { guard let account = account else { return 0 } - + if account == AccountManager.shared.defaultAccount { return 1 } else if hidesCredentialsSection { @@ -156,11 +156,11 @@ extension AccountInspectorViewController { return super.numberOfSections(in: tableView) } } - + override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } - + override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let account = account else { return nil } @@ -172,16 +172,16 @@ extension AccountInspectorViewController { return super.tableView(tableView, viewForHeaderInSection: section) } } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell - + if indexPath.section == 1, hidesCredentialsSection { cell = super.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 2)) } else { cell = super.tableView(tableView, cellForRowAt: indexPath) } - + return cell } @@ -191,17 +191,17 @@ extension AccountInspectorViewController { } return false } - + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.selectRow(at: nil, animated: true, scrollPosition: .none) } - + } // MARK: UITextFieldDelegate extension AccountInspectorViewController: UITextFieldDelegate { - + func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true diff --git a/iOS/Inspector/FeedInspectorViewController.swift b/iOS/Inspector/FeedInspectorViewController.swift index b51c2dc92..c734d8bea 100644 --- a/iOS/Inspector/FeedInspectorViewController.swift +++ b/iOS/Inspector/FeedInspectorViewController.swift @@ -12,52 +12,52 @@ import SafariServices import UserNotifications final class FeedInspectorViewController: UITableViewController { - + static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 500.0) - + var feed: Feed! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var notifyAboutNewArticlesSwitch: UISwitch! @IBOutlet weak var alwaysShowReaderViewSwitch: UISwitch! @IBOutlet weak var homePageLabel: InteractiveLabel! @IBOutlet weak var feedURLLabel: InteractiveLabel! - + private var headerView: InspectorIconHeaderView? private var iconImage: IconImage? { return IconImageCache.shared.imageForFeed(feed) } - + private let homePageIndexPath = IndexPath(row: 0, section: 1) - + private var shouldHideHomePageSection: Bool { return feed.homePageURL == nil } - + private var userNotificationSettings: UNNotificationSettings? - + override func viewDidLoad() { tableView.register(InspectorIconHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") - + navigationItem.title = feed.nameForDisplay nameTextField.text = feed.nameForDisplay - + notifyAboutNewArticlesSwitch.setOn(feed.isNotifyAboutNewArticles ?? false, animated: false) - + alwaysShowReaderViewSwitch.setOn(feed.isArticleExtractorAlwaysOn ?? false, animated: false) homePageLabel.text = feed.homePageURL feedURLLabel.text = feed.url - + NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) - + NotificationCenter.default.addObserver(self, selector: #selector(updateNotificationSettings), name: UIApplication.willEnterForegroundNotification, object: nil) - + } - + override func viewDidAppear(_ animated: Bool) { updateNotificationSettings() } - + override func viewDidDisappear(_ animated: Bool) { if nameTextField.text != feed.nameForDisplay { let nameText = nameTextField.text ?? "" @@ -65,12 +65,12 @@ final class FeedInspectorViewController: UITableViewController { feed.rename(to: newName) { _ in } } } - + // MARK: Notifications @objc func feedIconDidBecomeAvailable(_ notification: Notification) { headerView?.iconView.iconImage = iconImage } - + @IBAction func notifyAboutNewArticlesChanged(_ sender: Any) { guard let settings = userNotificationSettings else { notifyAboutNewArticlesSwitch.isOn = !notifyAboutNewArticlesSwitch.isOn @@ -97,22 +97,22 @@ final class FeedInspectorViewController: UITableViewController { } } } - + @IBAction func alwaysShowReaderViewChanged(_ sender: Any) { feed.isArticleExtractorAlwaysOn = alwaysShowReaderViewSwitch.isOn } - + @IBAction func done(_ sender: Any) { dismiss(animated: true) } - + /// Returns a new indexPath, taking into consideration any /// conditions that may require the tableView to be /// displayed differently than what is setup in the storyboard. private func shift(_ indexPath: IndexPath) -> IndexPath { return IndexPath(row: indexPath.row, section: shift(indexPath.section)) } - + /// Returns a new section, taking into consideration any /// conditions that may require the tableView to be /// displayed differently than what is setup in the storyboard. @@ -123,7 +123,7 @@ final class FeedInspectorViewController: UITableViewController { return section } - + } // MARK: Table View @@ -134,15 +134,15 @@ extension FeedInspectorViewController { let numberOfSections = super.numberOfSections(in: tableView) return shouldHideHomePageSection ? numberOfSections - 1 : numberOfSections } - + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return super.tableView(tableView, numberOfRowsInSection: shift(section)) } - + override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: shift(section)) } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: shift(indexPath)) if indexPath.section == 0 && indexPath.row == 1 { @@ -154,11 +154,11 @@ extension FeedInspectorViewController { } return cell } - + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { super.tableView(tableView, titleForHeaderInSection: shift(section)) } - + override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if shift(section) == 0 { headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as? InspectorIconHeaderView @@ -168,12 +168,12 @@ extension FeedInspectorViewController { return super.tableView(tableView, viewForHeaderInSection: shift(section)) } } - + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if shift(indexPath) == homePageIndexPath, let homePageUrlString = feed.homePageURL, let homePageUrl = URL(string: homePageUrlString) { - + let safari = SFSafariViewController(url: homePageUrl) safari.modalPresentationStyle = .pageSheet present(safari, animated: true) { @@ -181,24 +181,24 @@ extension FeedInspectorViewController { } } } - + } // MARK: UITextFieldDelegate extension FeedInspectorViewController: UITextFieldDelegate { - + func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } - + } // MARK: UNUserNotificationCenter extension FeedInspectorViewController { - + @objc func updateNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in @@ -210,7 +210,7 @@ extension FeedInspectorViewController { } } } - + func notificationUpdateErrorAlert() -> UIAlertController { let alert = UIAlertController(title: NSLocalizedString("Enable Notifications", comment: "Notifications"), message: NSLocalizedString("Notifications need to be enabled in the Settings app.", comment: "Notifications need to be enabled in the Settings app."), preferredStyle: .alert) @@ -223,5 +223,5 @@ extension FeedInspectorViewController { alert.preferredAction = openSettings return alert } - + } diff --git a/iOS/Inspector/InspectorIconHeaderView.swift b/iOS/Inspector/InspectorIconHeaderView.swift index db5768cc7..fcb7d6d14 100644 --- a/iOS/Inspector/InspectorIconHeaderView.swift +++ b/iOS/Inspector/InspectorIconHeaderView.swift @@ -11,17 +11,17 @@ import UIKit final class InspectorIconHeaderView: UITableViewHeaderFooterView { var iconView = IconView() - + override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } - + func commonInit() { addSubview(iconView) } diff --git a/iOS/IntentsExtension/IntentHandler.swift b/iOS/IntentsExtension/IntentHandler.swift index 4352b21f8..5e5e20ebc 100644 --- a/iOS/IntentsExtension/IntentHandler.swift +++ b/iOS/IntentsExtension/IntentHandler.swift @@ -9,7 +9,7 @@ import Intents final class IntentHandler: INExtension { - + override func handler(for intent: INIntent) -> Any { switch intent { case is AddWebFeedIntent: @@ -18,5 +18,5 @@ final class IntentHandler: INExtension { fatalError("Unhandled intent type: \(intent)") } } - + } diff --git a/iOS/KeyboardManager.swift b/iOS/KeyboardManager.swift index fab554f4b..c32b7ba32 100644 --- a/iOS/KeyboardManager.swift +++ b/iOS/KeyboardManager.swift @@ -16,16 +16,16 @@ enum KeyboardType: String { } final class KeyboardManager { - + private(set) var _keyCommands: [UIKeyCommand] var keyCommands: [UIKeyCommand] { guard !UIResponder.isFirstResponderTextField else { return [UIKeyCommand]() } return _keyCommands } - + init(type: KeyboardType) { _keyCommands = KeyboardManager.globalAuxilaryKeyCommands() - + switch type { case .sidebar: _keyCommands.append(contentsOf: KeyboardManager.hardcodeFeedKeyCommands()) @@ -34,7 +34,7 @@ final class KeyboardManager { default: break } - + let globalFile = Bundle.main.path(forResource: KeyboardType.global.rawValue, ofType: "plist")! let globalEntries = NSArray(contentsOfFile: globalFile)! as! [[String: Any]] let globalCommands = globalEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) } @@ -44,7 +44,7 @@ final class KeyboardManager { let specificEntries = NSArray(contentsOfFile: specificFile)! as! [[String: Any]] _keyCommands.append(contentsOf: specificEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) } ) } - + static func createKeyCommand(title: String, action: String, input: String, modifiers: UIKeyModifierFlags) -> UIKeyCommand { let selector = NSSelectorFromString(action) let keyCommand = UIKeyCommand(title: title, image: nil, action: selector, input: input, modifierFlags: modifiers, propertyList: nil, alternates: [], discoverabilityTitle: nil, attributes: [], state: .on) @@ -56,7 +56,7 @@ final class KeyboardManager { } private extension KeyboardManager { - + static func createKeyCommand(keyEntry: [String: Any]) -> UIKeyCommand? { guard let input = createKeyCommandInput(keyEntry: keyEntry) else { return nil } let modifiers = createKeyModifierFlags(keyEntry: keyEntry) @@ -75,7 +75,7 @@ private extension KeyboardManager { static func createKeyCommandInput(keyEntry: [String: Any]) -> String? { guard let key = keyEntry["key"] as? String else { return nil } - + switch(key) { case "[space]": return "\u{0020}" @@ -100,34 +100,34 @@ private extension KeyboardManager { default: return key } - + } - + static func createKeyModifierFlags(keyEntry: [String: Any]) -> UIKeyModifierFlags { var flags = UIKeyModifierFlags() - + if keyEntry["shiftModifier"] as? Bool ?? false { flags.insert(.shift) } - + if keyEntry["optionModifier"] as? Bool ?? false { flags.insert(.alternate) } - + if keyEntry["commandModifier"] as? Bool ?? false { flags.insert(.command) } - + if keyEntry["controlModifier"] as? Bool ?? false { flags.insert(.control) } return flags } - + static func globalAuxilaryKeyCommands() -> [UIKeyCommand] { var keys = [UIKeyCommand]() - + let addNewFeedTitle = NSLocalizedString("New Feed", comment: "New Feed") keys.append(KeyboardManager.createKeyCommand(title: addNewFeedTitle, action: "addNewFeed:", input: "n", modifiers: [.command])) @@ -151,7 +151,7 @@ private extension KeyboardManager { let gotoSettings = NSLocalizedString("Go To Settings", comment: "Go To Settings") keys.append(KeyboardManager.createKeyCommand(title: gotoSettings, action: "goToSettings:", input: ",", modifiers: [.command])) - + let articleSearchTitle = NSLocalizedString("Article Search", comment: "Article Search") keys.append(KeyboardManager.createKeyCommand(title: articleSearchTitle, action: "articleSearch:", input: "f", modifiers: [.command, .alternate])) @@ -169,7 +169,7 @@ private extension KeyboardManager { return keys } - + static func hardcodeFeedKeyCommands() -> [UIKeyCommand] { var keys = [UIKeyCommand]() @@ -178,16 +178,16 @@ private extension KeyboardManager { let nextDownTitle = NSLocalizedString("Select Next Down", comment: "Select Next Down") keys.append(KeyboardManager.createKeyCommand(title: nextDownTitle, action: "selectNextDown:", input: UIKeyCommand.inputDownArrow, modifiers: [])) - + let getFeedInfo = NSLocalizedString("Get Feed Info", comment: "Get Feed Info") keys.append(KeyboardManager.createKeyCommand(title: getFeedInfo, action: "showFeedInspector:", input: "i", modifiers: .command)) return keys } - + static func hardcodeArticleKeyCommands() -> [UIKeyCommand] { var keys = [UIKeyCommand]() - + let openInBrowserTitle = NSLocalizedString("Open In Browser", comment: "Open In Browser") keys.append(KeyboardManager.createKeyCommand(title: openInBrowserTitle, action: "openInBrowser:", input: UIKeyCommand.inputRightArrow, modifiers: [.command])) @@ -202,7 +202,7 @@ private extension KeyboardManager { let toggleStarredTitle = NSLocalizedString("Toggle Starred Status", comment: "Toggle Starred Status") keys.append(KeyboardManager.createKeyCommand(title: toggleStarredTitle, action: "toggleStarred:", input: "l", modifiers: [.command, .shift])) - + let findInArticleTitle = NSLocalizedString("Find in Article", comment: "Find in Article") keys.append(KeyboardManager.createKeyCommand(title: findInArticleTitle, action: "beginFind:", input: "f", modifiers: [.command])) @@ -217,5 +217,5 @@ private extension KeyboardManager { return keys } - + } diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift index e88b6e911..531cf4777 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift @@ -13,15 +13,15 @@ protocol MainFeedCollectionHeaderReusableViewDelegate: AnyObject { } class MainFeedCollectionHeaderReusableView: UICollectionReusableView { - + var delegate: MainFeedCollectionHeaderReusableViewDelegate? - + @IBOutlet weak var headerTitle: UILabel! @IBOutlet weak var disclosureIndicator: UIImageView! @IBOutlet weak var unreadCountLabel: UILabel! private var unreadLabelWidthConstraint: NSLayoutConstraint? - - + + override var accessibilityLabel: String? { set {} get { @@ -43,10 +43,10 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { return NSLocalizedString("Collapsed", comment: "Disclosure button collapsed state for accessibility") } } - - + + private var _unreadCount: Int = 0 - + var unreadCount: Int { get { return _unreadCount @@ -57,14 +57,14 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { unreadCountLabel.text = newValue.formatted() } } - + var disclosureExpanded = true { didSet { updateExpandedState(animate: true) updateUnreadCount() } } - + override func awakeFromNib() { super.awakeFromNib() unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80) @@ -72,35 +72,35 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { configureUI() addTapGesture() } - + func configureUI() { headerTitle.textColor = traitCollection.userInterfaceIdiom == .pad ? .tertiaryLabel : .label } - + private func addTapGesture() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(containerHeaderTapped)) self.addGestureRecognizer(tapGesture) self.isUserInteractionEnabled = true } - + @objc private func containerHeaderTapped() { delegate?.mainFeedCollectionHeaderReusableViewDidTapDisclosureIndicator(self) } - + func configureContainer(withTitle title: String) { headerTitle.text = title disclosureIndicator.transform = .identity } - + func updateExpandedState(animate: Bool) { - + if disclosureExpanded == false { unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80) } else { unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 0) unreadLabelWidthConstraint?.isActive = false } - + let angle: CGFloat = disclosureExpanded ? 0 : -.pi / 2 let transform = CGAffineTransform(rotationAngle: angle) let animations = { @@ -112,7 +112,7 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { animations() } } - + func updateUnreadCount() { if !disclosureExpanded && unreadCount > 0 { UIView.animate(withDuration: 0.3) { @@ -124,5 +124,5 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { } } } - + } diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift index 5b1cf7027..f4df3725f 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift @@ -13,12 +13,12 @@ import RSTree class MainFeedCollectionViewCell: UICollectionViewCell { - + @IBOutlet weak var feedTitle: UILabel! @IBOutlet weak var faviconView: IconView! @IBOutlet weak var unreadCountLabel: UILabel! private var faviconLeadingConstraint: NSLayoutConstraint? - + var iconImage: IconImage? { didSet { faviconView.iconImage = iconImage @@ -29,9 +29,9 @@ class MainFeedCollectionViewCell: UICollectionViewCell { } } } - + private var _unreadCount: Int = 0 - + var unreadCount: Int { get { return _unreadCount @@ -46,7 +46,7 @@ class MainFeedCollectionViewCell: UICollectionViewCell { unreadCountLabel.text = newValue.formatted() } } - + /// If the feed is contained in a folder, the indentation level is 1 /// and the cell's favicon leading constrain is increased. Otherwise, /// it has the standard leading constraint. @@ -61,7 +61,7 @@ class MainFeedCollectionViewCell: UICollectionViewCell { } } } - + override var accessibilityLabel: String? { set {} get { @@ -73,16 +73,16 @@ class MainFeedCollectionViewCell: UICollectionViewCell { } } } - + override func awakeFromNib() { super.awakeFromNib() faviconLeadingConstraint = faviconView.leadingAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leadingAnchor) faviconLeadingConstraint?.isActive = true } - + override func updateConfiguration(using state: UICellConfigurationState) { var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) - + switch (state.isHighlighted || state.isSelected || state.isFocused, traitCollection.userInterfaceIdiom) { case (true, .pad): backgroundConfig.backgroundColor = .tertiarySystemFill @@ -114,6 +114,6 @@ class MainFeedCollectionViewCell: UICollectionViewCell { } self.backgroundConfiguration = backgroundConfig } - + } diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift index 1444e7710..9f984311f 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift @@ -13,14 +13,14 @@ protocol MainFeedCollectionViewFolderCellDelegate: AnyObject { } class MainFeedCollectionViewFolderCell: UICollectionViewCell { - + @IBOutlet weak var folderTitle: UILabel! @IBOutlet weak var faviconView: IconView! @IBOutlet weak var unreadCountLabel: UILabel! @IBOutlet weak var disclosureButton: UIButton! - + var delegate: MainFeedCollectionViewFolderCellDelegate? - + private var _unreadCount: Int = 0 var unreadCount: Int { get { @@ -37,7 +37,7 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { unreadCountLabel.text = newValue.formatted() } } - + var iconImage: IconImage? { didSet { faviconView.iconImage = iconImage @@ -48,19 +48,19 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { } } } - + var disclosureExpanded = true { didSet { updateExpandedState(animate: true) updateUnreadCount() } } - + override func awakeFromNib() { super.awakeFromNib() disclosureButton.addInteraction(UIPointerInteraction()) } - + func updateExpandedState(animate: Bool) { let angle: CGFloat = disclosureExpanded ? 0 : -.pi / 2 let transform = CGAffineTransform(rotationAngle: angle) @@ -73,7 +73,7 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { animations() } } - + func updateUnreadCount() { if !disclosureExpanded && unreadCount > 0 && unreadCountLabel.alpha != 1 { UIView.animate(withDuration: 0.3) { @@ -85,18 +85,18 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { } } } - + @IBAction func toggleDisclosure() { setDisclosure(isExpanded: !disclosureExpanded, animated: true) delegate?.mainFeedCollectionFolderViewCellDisclosureDidToggle(self, expanding: disclosureExpanded) } - + func setDisclosure(isExpanded: Bool, animated: Bool) { disclosureExpanded = isExpanded } - - + + override var accessibilityLabel: String? { set {} get { @@ -108,10 +108,10 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { } } } - + override func updateConfiguration(using state: UICellConfigurationState) { var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) - + switch (state.isHighlighted || state.isSelected || state.isFocused, traitCollection.userInterfaceIdiom) { case (true, .pad): backgroundConfig.backgroundColor = .tertiarySystemFill @@ -129,12 +129,12 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { folderTitle.font = UIFont.preferredFont(forTextStyle: .body) unreadCountLabel.font = UIFont.preferredFont(forTextStyle: .body) } - + if state.cellDropState == .targeted { backgroundConfig.backgroundColor = .tertiarySystemFill } - + self.backgroundConfiguration = backgroundConfig } - + } diff --git a/iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift b/iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift index 135c99a7b..53a1643b3 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift @@ -11,13 +11,13 @@ import Foundation final class MainFeedRowIdentifier: NSObject, NSCopying { var indexPath: IndexPath - + init(indexPath: IndexPath) { self.indexPath = indexPath } - + func copy(with zone: NSZone? = nil) -> Any { return self } - + } diff --git a/iOS/MainFeed/MainFeedCollectionViewController+Drag.swift b/iOS/MainFeed/MainFeedCollectionViewController+Drag.swift index 83547347e..97b437dcd 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController+Drag.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController+Drag.swift @@ -21,20 +21,20 @@ extension MainFeedCollectionViewController: UICollectionViewDragDelegate { guard let node = coordinator.nodeFor(indexPath), let feed = node.representedObject as? Feed else { return [UIDragItem]() } - + let data = feed.url.data(using: .utf8) let itemProvider = NSItemProvider() - + itemProvider.registerDataRepresentation(forTypeIdentifier: UTType.url.identifier, visibility: .ownProcess) { completion in completion(data, nil) return nil } - + let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = node return [dragItem] } - - + + } diff --git a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift index ded25a1af..97a24bd89 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift @@ -18,7 +18,7 @@ import UniformTypeIdentifiers extension MainFeedCollectionViewController: UICollectionViewDropDelegate { - + func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: any UICollectionViewDropCoordinator) { guard let dragItem = coordinator.items.first?.dragItem, let dragNode = dragItem.localObject as? Node, @@ -26,17 +26,17 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { let destIndexPath = coordinator.destinationIndexPath else { return } - + let isFolderDrop: Bool = { if self.coordinator.nodeFor(destIndexPath)?.representedObject is Folder, let propCell = collectionView.cellForItem(at: destIndexPath) { return coordinator.session.location(in: propCell).y >= 0 } return false }() - + // Based on the drop we have to determine a node to start looking for a parent container. let destNode: Node? = { - + if isFolderDrop { return self.coordinator.nodeFor(destIndexPath) } else { @@ -48,7 +48,7 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { return nil } } - + }() // Now we start looking for the parent container @@ -60,22 +60,22 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { return self.coordinator.rootNode.childAtIndex(destIndexPath.section)?.representedObject as? Account } }() - + guard let destination = destinationContainer, let feed = dragNode.representedObject as? Feed else { return } - + if source.account == destination.account { moveFeedInAccount(feed: feed, sourceContainer: source, destinationContainer: destination) } else { moveFeedBetweenAccounts(feed: feed, sourceContainer: source, destinationContainer: destination) } } - + func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: any UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal { - + guard let destIndexPath = destinationIndexPath, destIndexPath.section > 0, collectionView.hasActiveDrag else { return UICollectionViewDropProposal(operation: .forbidden) } - + guard let destFeed = coordinator.nodeFor(destIndexPath)?.representedObject as? SidebarItem, let destAccount = destFeed.account, let destCell = collectionView.cellForItem(at: destIndexPath) else { @@ -101,17 +101,17 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } } - + func collectionView(_ collectionView: UICollectionView, canHandle session: any UIDropSession) -> Bool { return session.localDragSession != nil } - + func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) { } - + func moveFeedInAccount(feed: Feed, sourceContainer: Container, destinationContainer: Container) { guard sourceContainer !== destinationContainer else { return } - + BatchUpdate.shared.start() sourceContainer.account?.moveFeed(feed, from: sourceContainer, to: destinationContainer) { result in BatchUpdate.shared.end() @@ -123,11 +123,11 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { } } } - + func moveFeedBetweenAccounts(feed: Feed, sourceContainer: Container, destinationContainer: Container) { - + if let existingFeed = destinationContainer.account?.existingFeed(withURL: feed.url) { - + BatchUpdate.shared.start() destinationContainer.account?.addFeed(existingFeed, to: destinationContainer) { result in switch result { @@ -146,9 +146,9 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { self.presentError(error) } } - + } else { - + BatchUpdate.shared.start() destinationContainer.account?.createFeed(url: feed.url, name: feed.editedName, container: destinationContainer, validateFeed: false) { result in switch result { @@ -167,8 +167,8 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { self.presentError(error) } } - + } } - + } diff --git a/iOS/MainFeed/MainFeedCollectionViewController.swift b/iOS/MainFeed/MainFeedCollectionViewController.swift index a21490555..2ddebb20d 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController.swift @@ -23,7 +23,7 @@ private let folderIdentifier = "Folder" private let containerReuseIdentifier = "Container" class MainFeedCollectionViewController: UICollectionViewController, UndoableCommandRunner { - + @IBOutlet weak var filterButton: UIBarButtonItem! @IBOutlet weak var addNewItemButton: UIBarButtonItem! { didSet { @@ -34,32 +34,32 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + private let keyboardManager = KeyboardManager(type: .sidebar) override var keyCommands: [UIKeyCommand]? { - + // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard // commands that the system is looking for by going up the responder chain. They will interfere with // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } - + return keyboardManager.keyCommands } - + override var canBecomeFirstResponder: Bool { return true } - + var undoableCommands = [UndoableCommand]() weak var coordinator: SceneCoordinator! - + /// On iPhone, this property is used to prevent the user from selecting a new feed while the current feed is being deselected. /// While `isAnimating` is `true`, `shouldSelectItemAt()` will not allow new selection. /// The value is set to `true` in `viewWillAppear(_:)` if a feed is selected, and reset to `false` in /// `viewDidAppear(_:)` after a delay to allow the deselection animation to complete. private var isAnimating: Bool = false - - + + override func viewDidLoad() { super.viewDidLoad() registerForNotifications() @@ -68,18 +68,18 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm collectionView.dropDelegate = self becomeFirstResponder() } - + override func viewWillAppear(_ animated: Bool) { navigationController?.isToolbarHidden = false updateUI() super.viewWillAppear(animated) - + collectionView.refreshControl = UIRefreshControl() collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - + if traitCollection.userInterfaceIdiom == .phone { self.navigationController?.navigationBar.prefersLargeTitles = false - + /// On iPhone, we want to deselect the feed when the user navigates /// back to the feeds view. To prevent the user from selecting a new feed while /// the current feed is being deselected, set `isAnimating` to true. @@ -91,10 +91,10 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) - + /// On iPhone, once the deselection animation has completed, set `isAnimating` /// to false and this will allow selection. if traitCollection.userInterfaceIdiom == .phone { @@ -106,7 +106,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil) @@ -120,17 +120,17 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm registerForTraitChanges([UITraitPreferredContentSizeCategory.self], target: self, action: #selector(preferredContentSizeCategoryDidChange)) } - + // MARK: - Collection View Configuration func configureCollectionView() { var config = UICollectionLayoutListConfiguration(appearance: traitCollection.userInterfaceIdiom == .pad ? .sidebar : .insetGrouped) config.separatorConfiguration.color = .tertiarySystemFill config.headerMode = .supplementary - + config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in if indexPath.section == 0 { return UISwipeActionsConfiguration(actions: []) } var actions = [UIContextualAction]() - + // Set up the delete action let deleteTitle = NSLocalizedString("Delete", comment: "Delete") let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] (action, view, completion) in @@ -141,7 +141,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm deleteAction.accessibilityLabel = deleteTitle deleteAction.backgroundColor = UIColor.systemRed actions.append(deleteAction) - + // Set up the rename action let renameTitle = NSLocalizedString("Rename", comment: "Rename") let renameAction = UIContextualAction(style: .normal, title: nil) { [weak self] (action, view, completion) in @@ -152,27 +152,27 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm renameAction.image = UIImage(systemName: "pencil") renameAction.accessibilityLabel = renameTitle actions.append(renameAction) - + if let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed { let moreTitle = NSLocalizedString("More", comment: "More") let moreAction = UIContextualAction(style: .normal, title: nil) { [weak self] (action, view, completion) in - + if let self = self { - + let alert = UIAlertController(title: feed.nameForDisplay, message: nil, preferredStyle: .actionSheet) if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view popoverController.sourceRect = CGRect(x: view.frame.size.width/2, y: view.frame.size.height/2, width: 1, height: 1) } - + if let action = self.getInfoAlertAction(indexPath: indexPath, completion: completion) { alert.addAction(action) } - + if let action = self.homePageAlertAction(indexPath: indexPath, completion: completion) { alert.addAction(action) } - + if let action = self.copyFeedPageAlertAction(indexPath: indexPath, completion: completion) { alert.addAction(action) } @@ -180,22 +180,22 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm if let action = self.copyHomePageAlertAction(indexPath: indexPath, completion: completion) { alert.addAction(action) } - + if let action = self.markAllAsReadAlertAction(indexPath: indexPath, completion: completion) { alert.addAction(action) } - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in completion(true) }) self.present(alert, animated: true) - + } - + } - + moreAction.backgroundColor = UIColor.systemGray moreAction.image = UIImage(systemName: "ellipsis") moreAction.accessibilityLabel = moreTitle @@ -204,21 +204,21 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm let config = UISwipeActionsConfiguration(actions: actions) config.performsFirstActionWithFullSwipe = false - + return config } - + let layout = UICollectionViewCompositionalLayout.list(using: config) collectionView.setCollectionViewLayout(layout, animated: false) collectionView.refreshControl = UIRefreshControl() collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - + if config.appearance == .sidebar { // This defrosts the glass. collectionView.backgroundColor = .clear } } - + @IBAction func settings(_ sender: UIBarButtonItem) { coordinator.showSettings() } @@ -242,53 +242,53 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm configure(cell!, indexPath: indexPath) return cell! } - + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: folderIdentifier, for: indexPath) as! MainFeedCollectionViewFolderCell configure(cell, indexPath: indexPath) cell.delegate = self return cell - + } - + override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader else { return UICollectionReusableView() } - + let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: containerReuseIdentifier, for: indexPath ) as! MainFeedCollectionHeaderReusableView - + guard let nameProvider = coordinator.rootNode.childAtIndex(indexPath.section)?.representedObject as? DisplayNameProvider else { return UICollectionReusableView() } - + headerView.delegate = self headerView.headerTitle.text = nameProvider.nameForDisplay - + guard let sectionNode = coordinator.rootNode.childAtIndex(indexPath.section) else { return headerView } - + if let account = sectionNode.representedObject as? Account { headerView.unreadCount = account.unreadCount } else { headerView.unreadCount = 0 } - + headerView.tag = indexPath.section headerView.disclosureExpanded = coordinator.isExpanded(sectionNode) - + if indexPath.section != 0 { headerView.addInteraction(UIContextMenuInteraction(delegate: self)) } - + return headerView } - + override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { becomeFirstResponder() coordinator.selectFeed(indexPath: indexPath, animations: [.navigation, .select, .scroll]) @@ -303,15 +303,15 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } */ - + // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if traitCollection.userInterfaceIdiom == .pad { return true } return !isAnimating } - - + + override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return true } @@ -321,9 +321,9 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { - + } - + override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let sidebarItem = coordinator.nodeFor(indexPath)?.representedObject as? SidebarItem else { return nil @@ -338,11 +338,11 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm return nil } } - + // MARK: - Key Commands - + // MARK: Keyboard shortcuts - + @objc func collapseAllExceptForGroupItems(_ sender: Any?) { coordinator.collapseAllFolders() } @@ -355,7 +355,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + @objc override func delete(_ sender: Any?) { if let indexPath = coordinator.currentFeedIndexPath { delete(indexPath: indexPath) @@ -365,7 +365,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm @objc func expandAll(_ sender: Any?) { coordinator.expandAllSectionsAndFolders() } - + @objc func expandSelectedRows(_ sender: Any?) { if let indexPath = coordinator.currentFeedIndexPath, let node = coordinator.nodeFor(indexPath) { coordinator.expand(node) @@ -374,7 +374,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + @objc func markAllAsRead(_ sender: Any) { guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return @@ -385,7 +385,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm self?.coordinator.markAllAsReadInTimeline() } } - + @objc func navigateToTimeline(_ sender: Any?) { coordinator.navigateToTimeline() } @@ -393,7 +393,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm @objc func openInBrowser(_ sender: Any?) { coordinator.showBrowserForCurrentFeed() } - + @objc func selectNextDown(_ sender: Any?) { coordinator.selectNextFeed() } @@ -401,19 +401,19 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm @objc func selectNextUp(_ sender: Any?) { coordinator.selectPrevFeed() } - + @objc func showFeedInspector(_ sender: Any?) { coordinator.showFeedInspector() } - - + + // MARK: - API - + func focus() { becomeFirstResponder() } - + func updateUI() { if coordinator.isReadFeedsFiltered { setFilterButtonToActive() @@ -422,11 +422,11 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } addNewItemButton?.isEnabled = !AccountManager.shared.activeAccounts.isEmpty - + configureContextMenu() } - - + + func updateFeedSelection(animations: Animations) { if let indexPath = coordinator.currentFeedIndexPath { collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations) @@ -440,7 +440,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + func openInAppBrowser() { if let indexPath = coordinator.currentFeedIndexPath, let url = coordinator.homePageURLForFeed(indexPath) { @@ -449,7 +449,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm present(vc, animated: true) } } - + func reloadFeeds(initialLoad: Bool, changes: ShadowTableChanges, completion: (() -> Void)? = nil) { updateUI() @@ -458,16 +458,16 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm completion?() return } - + collectionView.performBatchUpdates { if let deletes = changes.deletes, !deletes.isEmpty { collectionView.deleteSections(IndexSet(deletes)) } - + if let inserts = changes.inserts, !inserts.isEmpty { collectionView.insertSections(IndexSet(inserts)) } - + if let moves = changes.moves, !moves.isEmpty { for move in moves { collectionView.moveSection(move.from, toSection: move.to) @@ -479,11 +479,11 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm if let deletes = rowChange.deleteIndexPaths, !deletes.isEmpty { collectionView.deleteItems(at: deletes) } - + if let inserts = rowChange.insertIndexPaths, !inserts.isEmpty { collectionView.insertItems(at: inserts) } - + if let moves = rowChange.moveIndexPaths, !moves.isEmpty { for move in moves { collectionView.moveItem(at: move.0, to: move.1) @@ -492,7 +492,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + if let rowChanges = changes.rowChanges { for rowChange in rowChanges { if let reloads = rowChange.reloadIndexPaths, !reloads.isEmpty { @@ -503,7 +503,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm completion?() } - + func applyToAvailableCells(_ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) { collectionView.visibleCells.forEach { cell in guard let indexPath = collectionView.indexPath(for: cell) else { return } @@ -512,14 +512,14 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + func configureIcon(_ cell: MainFeedCollectionViewCell, _ indexPath: IndexPath) { guard let node = coordinator.nodeFor(indexPath), let sidebarItem = node.representedObject as? SidebarItem, let sidebarItemID = sidebarItem.sidebarItemID else { return } cell.iconImage = IconImageCache.shared.imageFor(sidebarItemID) } - + func configureIcon(_ cell: MainFeedCollectionViewFolderCell, _ indexPath: IndexPath) { guard let node = coordinator.nodeFor(indexPath), let sidebarItem = node.representedObject as? SidebarItem, let sidebarItemID = sidebarItem.sidebarItemID else { return @@ -530,7 +530,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm func configureCellsForRepresentedObject(_ representedObject: AnyObject) { //applyToCellsForRepresentedObject(representedObject, configure) } - + func applyToCellsForRepresentedObject(_ representedObject: AnyObject, _ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) { applyToAvailableCells { (cell, indexPath) in if let node = coordinator.nodeFor(indexPath), @@ -541,7 +541,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - + func restoreSelectionIfNecessary(adjustScroll: Bool) { if let indexPath = coordinator.mainFeedIndexPathForCurrentTimeline() { if adjustScroll { @@ -551,11 +551,11 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } } } - - + + // MARK: - Private - - + + /// Configure standard feed cells func configure(_ cell: MainFeedCollectionViewCell, indexPath: IndexPath) { guard let node = coordinator.nodeFor(indexPath) else { return } @@ -563,7 +563,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm if let _ = node.parent?.representedObject as? Folder { indentationLevel = 1 } - + if let sidebarItem = node.representedObject as? SidebarItem { cell.feedTitle.text = sidebarItem.nameForDisplay cell.unreadCount = sidebarItem.unreadCount @@ -571,22 +571,22 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm configureIcon(cell, indexPath) } } - + /// Configure folders func configure(_ cell: MainFeedCollectionViewFolderCell, indexPath: IndexPath) { guard let node = coordinator.nodeFor(indexPath) else { return } - + if let folder = node.representedObject as? Folder { cell.folderTitle.text = folder.nameForDisplay cell.unreadCount = folder.unreadCount configureIcon(cell, indexPath) } - + if let containerID = (node.representedObject as? Container)?.containerID { cell.setDisclosure(isExpanded: coordinator.isExpanded(containerID), animated: false) } } - + private func headerViewForAccount(_ account: Account) -> MainFeedCollectionHeaderReusableView? { guard let node = coordinator.rootNode.childNodeRepresentingObject(account), @@ -597,40 +597,40 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm return collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: sectionIndex)) as? MainFeedCollectionHeaderReusableView } - + private func reloadAllVisibleCells(completion: (() -> Void)? = nil) { guard let indexPaths = collectionView.indexPathsForSelectedItems else { return } collectionView.reloadItems(at: indexPaths) restoreSelectionIfNecessary(adjustScroll: false) } - + func setFilterButtonToActive() { filterButton.tintColor = AppAssets.primaryAccentColor filterButton?.accLabelText = NSLocalizedString("Selected - Filter Read Feeds", comment: "Selected - Filter Read Feeds") } - + func setFilterButtonToInactive() { filterButton.tintColor = nil filterButton?.accLabelText = NSLocalizedString("Filter Read Feeds", comment: "Filter Read Feeds") } - - - + + + // MARK: - Notifications - - + + @objc func preferredContentSizeCategoryDidChange() { IconImageCache.shared.emptyCache() reloadAllVisibleCells() } - + @objc func unreadCountDidChange(_ note: Notification) { updateUI() guard let unreadCountProvider = note.object as? UnreadCountProvider else { return } - + if let account = unreadCountProvider as? Account { if let headerView = headerViewForAccount(account) { headerView.unreadCount = account.unreadCount @@ -646,16 +646,16 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } guard let unreadCountNode = node, let indexPath = coordinator.indexPathFor(unreadCountNode) else { return } - + if let cell = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewCell { cell.unreadCount = unreadCountProvider.unreadCount } - + if let cell = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewFolderCell { cell.unreadCount = unreadCountProvider.unreadCount } } - + @objc func feedSettingDidChange(_ note: Notification) { guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? String else { return @@ -664,7 +664,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm configureCellsForRepresentedObject(feed) } } - + @objc func faviconDidBecomeAvailable(_ note: Notification) { applyToAvailableCells(configureIcon) } @@ -675,7 +675,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm } applyToCellsForRepresentedObject(feed, configureIcon(_:_:)) } - + // MARK: - Actions @objc func configureContextMenu(_: Any? = nil) { @@ -684,75 +684,75 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm 1. Add Feed 2. Add Folder */ - + var menuItems: [UIAction] = [] - + let addFeedActionTitle = NSLocalizedString("Add Feed", comment: "Add Feed") let addFeedAction = UIAction(title: addFeedActionTitle, image: AppAssets.plus) { _ in self.coordinator.showAddFeed() } menuItems.append(addFeedAction) - + let addFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder") let addFolderAction = UIAction(title: addFolderActionTitle, image: AppAssets.folderOutlinePlus) { _ in self.coordinator.showAddFolder() } - + menuItems.append(addFolderAction) - + let contextMenu = UIMenu(title: NSLocalizedString("Add Item", comment: "Add Item"), image: nil, identifier: nil, options: [], children: menuItems.reversed()) - + self.addNewItemButton.menu = contextMenu } - + @objc func refreshAccounts(_ sender: Any) { collectionView.refreshControl?.endRefreshing() - + // This is a hack to make sure that an error dialog doesn't interfere with dismissing the refreshControl. // If the error dialog appears too closely to the call to endRefreshing, then the refreshControl never disappears. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self)) } } - + @IBAction func add(_ sender: UIBarButtonItem) { let title = NSLocalizedString("Add Item", comment: "Add Item") let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) - + let addFeedActionTitle = NSLocalizedString("Add Web Feed", comment: "Add Web Feed") let addFeedAction = UIAlertAction(title: addFeedActionTitle, style: .default) { _ in self.coordinator.showAddFeed() } - + let addFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder") let addFolderAction = UIAlertAction(title: addFolderActionTitle, style: .default) { _ in self.coordinator.showAddFolder() } - + alertController.addAction(addFeedAction) - + alertController.addAction(addFolderAction) alertController.addAction(cancelAction) - + alertController.popoverPresentationController?.barButtonItem = sender present(alertController, animated: true) } - - + + @IBAction func toggleFilter(_ sender: Any) { coordinator.toggleReadFeedsFilter() } - - + + func toggle(_ headerView: MainFeedCollectionHeaderReusableView) { guard let sectionNode = coordinator.rootNode.childAtIndex(headerView.tag) else { return } - + if coordinator.isExpanded(sectionNode) { headerView.disclosureExpanded = false coordinator.collapse(sectionNode) @@ -761,7 +761,7 @@ class MainFeedCollectionViewController: UICollectionViewController, UndoableComm coordinator.expand(sectionNode) } } - + } extension MainFeedCollectionViewController: MainFeedCollectionHeaderReusableViewDelegate { @@ -780,8 +780,8 @@ extension MainFeedCollectionViewController: MainFeedCollectionViewFolderCellDele collapse(sender) } } - - + + func expand(_ cell: MainFeedCollectionViewFolderCell) { guard let indexPath = collectionView.indexPath(for: cell), let node = coordinator.nodeFor(indexPath) else { return @@ -795,9 +795,9 @@ extension MainFeedCollectionViewController: MainFeedCollectionViewFolderCellDele } coordinator.collapse(node) } - - - + + + } @@ -810,7 +810,7 @@ extension MainFeedCollectionViewController: UIContextMenuInteractionDelegate { else { return nil } - + return UIContextMenuConfiguration(identifier: sectionIndex as NSCopying, previewProvider: nil) { suggestedActions in var menuElements = [UIMenuElement]() @@ -821,41 +821,41 @@ extension MainFeedCollectionViewController: UIContextMenuInteractionDelegate { } menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.deactivateAccountAction(account: account)])) - + return UIMenu(title: "", children: menuElements) } } - + func contextMenuInteraction(_ interaction: UIContextMenuInteraction, previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - + guard let sectionIndex = configuration.identifier as? Int, let cell = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: sectionIndex)) as? MainFeedCollectionHeaderReusableView else { return nil } - - + + return UITargetedPreview(view: cell, parameters: CroppingPreviewParameters(view: cell)) } - - + + } extension MainFeedCollectionViewController { func makeFeedContextMenu(indexPath: IndexPath, includeDeleteRename: Bool) -> UIContextMenuConfiguration { return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [ weak self] suggestedActions in - + guard let self = self else { return nil } - + var menuElements = [UIMenuElement]() - + if let inspectorAction = self.getInfoAction(indexPath: indexPath) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [inspectorAction])) } - + if let homePageAction = self.homePageAction(indexPath: indexPath) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [homePageAction])) } - + var pageActions = [UIAction]() if let copyFeedPageAction = self.copyFeedPageAction(indexPath: indexPath) { pageActions.append(copyFeedPageAction) @@ -870,7 +870,7 @@ extension MainFeedCollectionViewController { if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction])) } - + if includeDeleteRename { menuElements.append(UIMenu(title: "", options: .displayInline, @@ -879,24 +879,24 @@ extension MainFeedCollectionViewController { self.deleteAction(indexPath: indexPath) ])) } - + return UIMenu(title: "", children: menuElements) - + }) - + } - + func makeFolderContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration { return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [weak self] suggestedActions in guard let self = self else { return nil } - + var menuElements = [UIMenuElement]() if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction])) } - + menuElements.append(UIMenu(title: "", options: .displayInline, children: [ @@ -923,14 +923,14 @@ extension MainFeedCollectionViewController { guard coordinator.homePageURLForFeed(indexPath) != nil else { return nil } - + let title = NSLocalizedString("Open Home Page", comment: "Open Home Page") let action = UIAction(title: title, image: AppAssets.safariImage) { [weak self] action in self?.coordinator.showBrowserForFeed(indexPath) } return action } - + func homePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard coordinator.homePageURLForFeed(indexPath) != nil else { return nil @@ -943,20 +943,20 @@ extension MainFeedCollectionViewController { } return action } - + func copyFeedPageAction(indexPath: IndexPath) -> UIAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, let url = URL(string: feed.url) else { return nil } - + let title = NSLocalizedString("Copy Feed URL", comment: "Copy Feed URL") let action = UIAction(title: title, image: AppAssets.copyImage) { action in UIPasteboard.general.url = url } return action } - + func copyFeedPageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, let url = URL(string: feed.url) else { @@ -970,21 +970,21 @@ extension MainFeedCollectionViewController { } return action } - + func copyHomePageAction(indexPath: IndexPath) -> UIAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, let homePageURL = feed.homePageURL, let url = URL(string: homePageURL) else { return nil } - + let title = NSLocalizedString("Copy Home Page URL", comment: "Copy Home Page URL") let action = UIAction(title: title, image: AppAssets.copyImage) { action in UIPasteboard.general.url = url } return action } - + func copyHomePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, let homePageURL = feed.homePageURL, @@ -999,20 +999,20 @@ extension MainFeedCollectionViewController { } return action } - + func markAllAsReadAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, feed.unreadCount > 0, let articles = try? feed.fetchArticles(), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } - + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String let cancel = { completion(true) } - + let action = UIAlertAction(title: title, style: .default) { [weak self] action in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in @@ -1022,16 +1022,16 @@ extension MainFeedCollectionViewController { } return action } - + func deleteAction(indexPath: IndexPath) -> UIAction { let title = NSLocalizedString("Delete", comment: "Delete") - + let action = UIAction(title: title, image: AppAssets.trashImage, attributes: .destructive) { [weak self] action in self?.delete(indexPath: indexPath) } return action } - + func renameAction(indexPath: IndexPath) -> UIAction { let title = NSLocalizedString("Rename", comment: "Rename") let action = UIAction(title: title, image: AppAssets.editImage) { [weak self] action in @@ -1039,12 +1039,12 @@ extension MainFeedCollectionViewController { } return action } - + func getInfoAction(indexPath: IndexPath) -> UIAction? { guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed else { return nil } - + let title = NSLocalizedString("Get Info", comment: "Get Info") let action = UIAction(title: title, image: AppAssets.infoImage) { [weak self] action in self?.coordinator.showFeedInspector(for: feed) @@ -1087,7 +1087,7 @@ extension MainFeedCollectionViewController { sidebarItem.unreadCount > 0 else { return nil } - + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, sidebarItem.nameForDisplay) as String let action = UIAction(title: title, image: AppAssets.markAllAsReadImage) { [weak self] action in @@ -1128,19 +1128,19 @@ extension MainFeedCollectionViewController { let formatString = NSLocalizedString("Rename “%@”", comment: "Rename feed") let title = NSString.localizedStringWithFormat(formatString as NSString, sidebarItem.nameForDisplay) as String - + let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert) - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) - + let renameTitle = NSLocalizedString("Rename", comment: "Rename") let renameAction = UIAlertAction(title: renameTitle, style: .default) { [weak self] action in - + guard let name = alertController.textFields?[0].text, !name.isEmpty else { return } - + if let feed = sidebarItem as? Feed { feed.rename(to: name) { result in switch result { @@ -1160,23 +1160,23 @@ extension MainFeedCollectionViewController { } } } - + } - + alertController.addAction(renameAction) alertController.preferredAction = renameAction - + alertController.addTextField() { textField in textField.text = sidebarItem.nameForDisplay textField.placeholder = NSLocalizedString("Name", comment: "Name") } - + self.present(alertController, animated: true) { - + } - + } - + func delete(indexPath: IndexPath) { guard let sidebarItem = coordinator.nodeFor(indexPath)?.representedObject as? SidebarItem else { return } @@ -1191,22 +1191,22 @@ extension MainFeedCollectionViewController { let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” feed?", comment: "Feed delete text") message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, sidebarItem.nameForDisplay) as String } - + let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) - + let deleteTitle = NSLocalizedString("Delete", comment: "Delete") let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [weak self] action in self?.performDelete(indexPath: indexPath) } alertController.addAction(deleteAction) alertController.preferredAction = deleteAction - + self.present(alertController, animated: true) } - + func performDelete(indexPath: IndexPath) { guard let undoManager = undoManager, let deleteNode = coordinator.nodeFor(indexPath), @@ -1219,11 +1219,11 @@ extension MainFeedCollectionViewController { } else if let feed = deleteNode.representedObject as? Feed { ActivityManager.cleanUp(feed) } - + if indexPath == coordinator.currentFeedIndexPath { coordinator.selectFeed(indexPath: nil) } - + pushUndoableCommand(deleteCommand) deleteCommand.perform() } diff --git a/iOS/MainFeed/RefreshProgressView.swift b/iOS/MainFeed/RefreshProgressView.swift index 2ca6423ce..9bb79b50e 100644 --- a/iOS/MainFeed/RefreshProgressView.swift +++ b/iOS/MainFeed/RefreshProgressView.swift @@ -10,10 +10,10 @@ import UIKit import Account final class RefreshProgressView: UIView { - + @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var label: UILabel! - + override func awakeFromNib() { NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) @@ -24,7 +24,7 @@ final class RefreshProgressView: UIView { isAccessibilityElement = true accessibilityTraits = [.updatesFrequently, .notEnabled] } - + func update() { if !AccountManager.shared.combinedRefreshProgress.isComplete { progressChanged(animated: false) @@ -50,7 +50,7 @@ final class RefreshProgressView: UIView { deinit { NotificationCenter.default.removeObserver(self) } - + } // MARK: Private @@ -68,7 +68,7 @@ private extension RefreshProgressView { if isInViewHierarchy { progressView.setProgress(1, animated: animated) } - + func completeLabel() { // Check that there are no pending downloads. if AccountManager.shared.combinedRefreshProgress.isComplete { @@ -101,7 +101,7 @@ private extension RefreshProgressView { } } } - + func updateRefreshLabel() { if let accountLastArticleFetchEndTime = AccountManager.shared.lastArticleFetchEndTime { @@ -131,5 +131,5 @@ private extension RefreshProgressView { self?.scheduleUpdateRefreshLabel() } } - + } diff --git a/iOS/MainTimeline/Cells/MainTimelineCellData.swift b/iOS/MainTimeline/Cells/MainTimelineCellData.swift index 397f60409..2a151eefa 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCellData.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCellData.swift @@ -12,7 +12,7 @@ import Articles struct MainTimelineCellData { private static let noText = NSLocalizedString("(No Text)", comment: "No Text") - + let title: String let attributedTitle: NSAttributedString let summary: String @@ -38,7 +38,7 @@ struct MainTimelineCellData { } else { self.summary = truncatedSummary } - + self.dateString = ArticleStringFormatter.dateString(article.logicalDatePublished) if let feedName = feedName { @@ -47,7 +47,7 @@ struct MainTimelineCellData { else { self.feedName = "" } - + if let byline = byline { self.byline = byline } else { @@ -63,7 +63,7 @@ struct MainTimelineCellData { self.starred = article.status.starred self.numberOfLines = numberOfLines self.iconSize = iconSize - + } init() { //Empty @@ -81,5 +81,5 @@ struct MainTimelineCellData { self.numberOfLines = 0 self.iconSize = .medium } - + } diff --git a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift index 9cd6374af..fbe62a0d6 100644 --- a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift @@ -21,15 +21,15 @@ class MainTimelineFeedCell: UITableViewCell { configure(cellData) } } - + var isPreview: Bool = false - + override func awakeFromNib() { super.awakeFromNib() indicatorView.alpha = 0.0 configureStackView() } - + private func configureStackView() { switch traitCollection.preferredContentSizeCategory { case .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge: @@ -42,11 +42,11 @@ class MainTimelineFeedCell: UITableViewCell { metaDataStackView.distribution = .fill } } - + private func configure(_ cellData: MainTimelineCellData) { updateIndicatorView(cellData) articleTitle.numberOfLines = cellData.numberOfLines - + applyTitleTextWithAttributes(configurationState) if cellData.showFeedName == .feed { @@ -56,10 +56,10 @@ class MainTimelineFeedCell: UITableViewCell { } else if cellData.showFeedName == .none { authorByLine.text = "" } - + articleDate.text = cellData.dateString } - + private func updateIndicatorView(_ cellData: MainTimelineCellData) { if cellData.read == false { if indicatorView.alpha == 0.0 { @@ -86,7 +86,7 @@ class MainTimelineFeedCell: UITableViewCell { } } } - + private func applyTitleTextWithAttributes(_ state: UICellConfigurationState) { let attributedCellText = NSMutableAttributedString() let isSelected = state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped @@ -119,17 +119,17 @@ class MainTimelineFeedCell: UITableViewCell { } articleTitle.attributedText = attributedCellText } - + override func updateConfiguration(using state: UICellConfigurationState) { super.updateConfiguration(using: state) - + var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) backgroundConfig.cornerRadius = 20 if traitCollection.userInterfaceIdiom == .pad { backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing] backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12) } - + if state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped { backgroundConfig.backgroundColor = AppAssets.primaryAccentColor applyTitleTextWithAttributes(state) @@ -140,9 +140,9 @@ class MainTimelineFeedCell: UITableViewCell { articleDate.textColor = .secondaryLabel authorByLine.textColor = .secondaryLabel } - + self.backgroundConfiguration = backgroundConfig } - - + + } diff --git a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift index 58177de03..fd9a195d0 100644 --- a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift @@ -9,29 +9,29 @@ import UIKit class MainTimelineIconFeedCell: UITableViewCell { - + @IBOutlet weak var articleTitle: UILabel! @IBOutlet weak var authorByLine: UILabel! @IBOutlet weak var iconView: IconView! @IBOutlet weak var indicatorView: IconView! @IBOutlet weak var articleDate: UILabel! @IBOutlet weak var metaDataStackView: UIStackView! - + var cellData: MainTimelineCellData! { didSet { configure(cellData) } } - + var isPreview: Bool = false - + override func awakeFromNib() { super.awakeFromNib() indicatorView.alpha = 0.0 iconView.translatesAutoresizingMaskIntoConstraints = false configureStackView() } - + private func configureStackView() { switch traitCollection.preferredContentSizeCategory { case .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge: @@ -44,13 +44,13 @@ class MainTimelineIconFeedCell: UITableViewCell { metaDataStackView.distribution = .fill } } - - + + private func configure(_ cellData: MainTimelineCellData) { updateIndicatorView(cellData) articleTitle.numberOfLines = cellData.numberOfLines applyTitleTextWithAttributes(configurationState) - + if cellData.showFeedName == .feed { authorByLine.text = cellData.feedName } else if cellData.showFeedName == .byline { @@ -58,34 +58,34 @@ class MainTimelineIconFeedCell: UITableViewCell { } else if cellData.showFeedName == .none { authorByLine.text = "" } - + setIconImage(cellData.iconImage, with: cellData.iconSize) - + articleDate.text = cellData.dateString } - + private func setIconImage(_ iconImage: IconImage?, with size: IconSize) { iconView.iconImage = iconImage updateIconViewSizeConstraints(to: size.size) } - + func setIconImage(_ iconImage: IconImage?) { iconView.iconImage = iconImage } - + private func updateIconViewSizeConstraints(to size: CGSize) { for constraint in iconView.constraints { constraint.isActive = false } - + NSLayoutConstraint.activate([ iconView.widthAnchor.constraint(equalToConstant: size.width), iconView.heightAnchor.constraint(equalToConstant: size.height) ]) - + setNeedsLayout() } - + private func updateIndicatorView(_ cellData: MainTimelineCellData) { if cellData.read == false { if indicatorView.alpha == 0.0 { @@ -112,12 +112,12 @@ class MainTimelineIconFeedCell: UITableViewCell { } } } - + private func applyTitleTextWithAttributes(_ state: UICellConfigurationState) { let attributedCellText = NSMutableAttributedString() - - - + + + let isSelected = state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped if cellData.title != "" { let paragraphStyle = NSMutableParagraphStyle() @@ -148,17 +148,17 @@ class MainTimelineIconFeedCell: UITableViewCell { } articleTitle.attributedText = attributedCellText } - + override func updateConfiguration(using state: UICellConfigurationState) { super.updateConfiguration(using: state) - + var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) backgroundConfig.cornerRadius = 20 if traitCollection.userInterfaceIdiom == .pad { backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing] backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12) } - + if state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped { backgroundConfig.backgroundColor = AppAssets.primaryAccentColor applyTitleTextWithAttributes(state) @@ -169,9 +169,9 @@ class MainTimelineIconFeedCell: UITableViewCell { articleDate.textColor = .secondaryLabel authorByLine.textColor = .secondaryLabel } - + self.backgroundConfiguration = backgroundConfig - + } - + } diff --git a/iOS/MainTimeline/MainTimelineDataSource.swift b/iOS/MainTimeline/MainTimelineDataSource.swift index f89ef54f8..6b6ed7692 100644 --- a/iOS/MainTimeline/MainTimelineDataSource.swift +++ b/iOS/MainTimeline/MainTimelineDataSource.swift @@ -13,6 +13,6 @@ final class MainTimelineDataSource: U override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } - + } diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index d21da0714..bc4367023 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -18,7 +18,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu private var numberOfTextLines = 0 private var iconSize = IconSize.medium private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(showFeedInspector(_:))) - + private var refreshProgressView: RefreshProgressView? @IBOutlet var markAllAsReadButton: UIBarButtonItem? @@ -28,7 +28,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu private lazy var dataSource = makeDataSource() private let searchController = UISearchController(searchResultsController: nil) - + weak var coordinator: SceneCoordinator? var undoableCommands = [UndoableCommand]() let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) @@ -97,7 +97,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu private let keyboardManager = KeyboardManager(type: .timeline) override var keyCommands: [UIKeyCommand]? { - + // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard // commands that the system is looking for by going up the responder chain. They will interfere with // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. @@ -105,7 +105,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu return keyboardManager.keyCommands } - + private var navigationBarTitleLabel: UILabel { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold() @@ -118,7 +118,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu label.addInteraction(pointerInteraction) return label } - + private var navigationBarSubtitleTitleLabel: UILabel { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .footnote) @@ -129,7 +129,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu label.addGestureRecognizer(tap) return label } - + override var canBecomeFirstResponder: Bool { return true } @@ -137,7 +137,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu override func viewDidLoad() { assert(coordinator != nil) - + super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) @@ -156,7 +156,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange), name: .DisplayNameDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) - + // Setup the Search Controller searchController.delegate = self searchController.searchResultsUpdater = self @@ -168,43 +168,43 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu NSLocalizedString("All Articles", comment: "All Articles") ] navigationItem.searchController = searchController - + if traitCollection.userInterfaceIdiom == .pad { searchController.searchBar.selectedScopeButtonIndex = 1 navigationItem.searchBarPlacementAllowsExternalIntegration = true } definesPresentationContext = true - + // Configure the table tableView.dataSource = dataSource tableView.isPrefetchingEnabled = false - + numberOfTextLines = AppDefaults.shared.timelineNumberOfLines iconSize = AppDefaults.shared.timelineIconSize - + refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - + configureToolbar() resetUI(resetScroll: true) - + // Load the table and then scroll to the saved position if available applyChanges(animated: false) { if let restoreIndexPath = self.timelineMiddleIndexPath { self.tableView.scrollToRow(at: restoreIndexPath, at: .middle, animated: false) } } - + // Disable swipe back on iPad Mice guard let gesture = self.navigationController?.interactivePopGestureRecognizer as? UIPanGestureRecognizer else { return } gesture.allowedScrollTypesMask = [] - + navigationItem.titleView = navigationBarTitleLabel navigationItem.subtitleView = navigationBarSubtitleTitleLabel } - + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isToolbarHidden = false @@ -217,7 +217,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") updateNavigationBarSubtitle("") } - + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) isTimelineViewControllerPending = false @@ -235,9 +235,9 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } } } - + // MARK: Actions - + @objc func openInBrowser(_ sender: Any?) { assert(coordinator != nil) coordinator?.showBrowserForCurrentArticle() @@ -247,7 +247,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu assert(coordinator != nil) coordinator?.showInAppBrowser() } - + @IBAction func toggleFilter(_ sender: Any) { assert(coordinator != nil) coordinator?.toggleReadArticlesFilter() @@ -260,29 +260,29 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu @IBAction func markAllAsRead(_ sender: Any) { let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") - + if let source = sender as? UIBarButtonItem { MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in self?.markAllAsReadInTimeline() } } - + if let _ = sender as? UIKeyCommand { guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { return } - + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markAllAsReadInTimeline() } } } - + @IBAction func firstUnread(_ sender: Any) { assert(coordinator != nil) coordinator?.selectFirstUnread() } - + @objc func refreshAccounts(_ sender: Any) { refreshControl?.endRefreshing() @@ -292,9 +292,9 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self)) } } - + // MARK: Keyboard shortcuts - + @objc func selectNextUp(_ sender: Any?) { assert(coordinator != nil) coordinator?.selectPrevArticle() @@ -309,12 +309,12 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu assert(coordinator != nil) coordinator?.navigateToFeeds() } - + @objc func navigateToDetail(_ sender: Any?) { assert(coordinator != nil) coordinator?.navigateToDetail() } - + @objc func showFeedInspector(_ sender: Any?) { assert(coordinator != nil) coordinator?.showFeedInspector() @@ -331,7 +331,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } } } - + func updateNavigationBarTitle(_ text: String) { if let label = navigationItem.titleView as? UILabel { label.text = text @@ -339,7 +339,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu label.sizeToFit() } } - + func updateNavigationBarSubtitle(_ text: String) { if let label = navigationItem.subtitleView as? UILabel { label.text = text @@ -351,11 +351,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu func reinitializeArticles(resetScroll: Bool) { resetUI(resetScroll: resetScroll) } - + func reloadArticles(animated: Bool) { applyChanges(animated: animated) } - + func updateArticleSelection(animations: Animations) { if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { if tableView.indexPathForSelectedRow != indexPath { @@ -364,7 +364,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } else { tableView.selectRow(at: nil, animated: animations.contains(.select), scrollPosition: .none) } - + updateUI() } @@ -372,7 +372,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu refreshProgressView?.update() updateToolbar() } - + func hideSearch() { navigationItem.searchController?.isActive = false } @@ -382,11 +382,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 navigationItem.searchController?.searchBar.becomeFirstResponder() } - + func focus() { becomeFirstResponder() } - + // MARK: - Table view override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { @@ -397,41 +397,41 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu let readTitle = article.status.read ? NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : NSLocalizedString("Mark as Read", comment: "Mark as Read") - + let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] (action, view, completion) in self?.toggleRead(article) completion(true) } - + readAction.image = article.status.read ? AppAssets.circleClosedImage : AppAssets.circleOpenImage readAction.backgroundColor = AppAssets.primaryAccentColor - + return UISwipeActionsConfiguration(actions: [readAction]) } - + override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - + // Set up the star action let starTitle = article.status.starred ? NSLocalizedString("Unstar", comment: "Unstar") : NSLocalizedString("Star", comment: "Star") - + let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] (action, view, completion) in self?.toggleStar(article) completion(true) } - + starAction.image = article.status.starred ? AppAssets.starOpenImage : AppAssets.starClosedImage starAction.backgroundColor = AppAssets.starColor - + // Set up the read action let moreTitle = NSLocalizedString("More", comment: "More") let moreAction = UIContextualAction(style: .normal, title: moreTitle) { [weak self] (action, view, completion) in - + if let self = self { - + let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view @@ -445,11 +445,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu if let action = self.markBelowAsReadAlertAction(article, indexPath: indexPath, completion: completion) { alert.addAction(action) } - + if let action = self.discloseFeedAlertAction(article, completion: completion) { alert.addAction(action) } - + if let action = self.markAllInFeedAsReadAlertAction(article, indexPath: indexPath, completion: completion) { alert.addAction(action) } @@ -468,28 +468,28 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu }) self.present(alert, animated: true) - + } - + } - + moreAction.image = AppAssets.moreImage moreAction.backgroundColor = UIColor.systemGray return UISwipeActionsConfiguration(actions: [starAction, moreAction]) - + } override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - + return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] suggestedActions in guard let self = self else { return nil } - + var menuElements = [UIMenuElement]() - + var markActions = [UIAction]() if let action = self.toggleArticleReadStatusAction(article) { markActions.append(action) @@ -502,7 +502,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu markActions.append(action) } menuElements.append(UIMenu(title: "", options: .displayInline, children: markActions)) - + var secondaryActions = [UIAction]() if let action = self.discloseFeedAction(article) { secondaryActions.append(action) @@ -513,7 +513,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu if !secondaryActions.isEmpty { menuElements.append(UIMenu(title: "", options: .displayInline, children: secondaryActions)) } - + var copyActions = [UIAction]() if let action = self.copyArticleURLAction(article) { copyActions.append(action) @@ -524,19 +524,19 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu if !copyActions.isEmpty { menuElements.append(UIMenu(title: "", options: .displayInline, children: copyActions)) } - + if let action = self.openInBrowserAction(article) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) } - + if let action = self.shareAction(article, indexPath: indexPath) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) } - + return UIMenu(title: "", children: menuElements) }) - + } override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { @@ -544,7 +544,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else { return nil } - + let previewView = cell.contentView let inset: CGFloat = 12 let visibleBounds = previewView.bounds.insetBy(dx: inset, dy: 2) @@ -554,13 +554,13 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu cornerRadius: 20) return UITargetedPreview(view: previewView, parameters: parameters) } - + override func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { guard let row = configuration.identifier as? Int, let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else { return nil } - + let previewView = cell.contentView let inset: CGFloat = 0 let visibleBounds = previewView.bounds.insetBy(dx: inset, dy: 2) @@ -568,7 +568,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu parameters.backgroundColor = .clear parameters.visiblePath = UIBezierPath(roundedRect: visibleBounds, cornerRadius: 20) - + return UITargetedPreview(view: previewView, parameters: parameters) } @@ -577,17 +577,17 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu let article = dataSource.itemIdentifier(for: indexPath) coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) } - + override func scrollViewDidScroll(_ scrollView: UIScrollView) { scrollPositionQueue.add(self, #selector(scrollPositionDidChange)) } - + // MARK: Notifications @objc dynamic func unreadCountDidChange(_ notification: Notification) { updateUI() } - + @objc func statusesDidChange(_ note: Notification) { guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, !articleIDs.isEmpty else { return @@ -663,21 +663,21 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu @objc func contentSizeCategoryDidChange(_ note: Notification) { reloadAllVisibleCells() } - + @objc func displayNameDidChange(_ note: Notification) { updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") } - + @objc func willEnterForeground(_ note: Notification) { updateUI() } - + @objc func scrollPositionDidChange() { timelineMiddleIndexPath = tableView.middleVisibleRow() } - + // MARK: Reloading - + func queueReloadAvailableCells() { CoalescingQueue.standard.add(self, #selector(reloadAllVisibleCells)) } @@ -752,7 +752,7 @@ private extension MainTimelineViewController { case .alwaysRead: navigationItem.rightBarButtonItem = nil } - + if isReadArticlesFiltered { filterButton.style = .prominent filterButton.tintColor = AppAssets.primaryAccentColor @@ -771,10 +771,10 @@ private extension MainTimelineViewController { tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) } } - + updateToolbar() } - + func updateToolbar() { markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable firstUnreadButton.isEnabled = isTimelineUnreadAvailable @@ -792,14 +792,14 @@ private extension MainTimelineViewController { } } } - + func applyChanges(animated: Bool, completion: (() -> Void)? = nil) { if (articles?.count ?? 0) == 0 { tableView.rowHeight = tableView.estimatedRowHeight } else { tableView.rowHeight = UITableView.automaticDimension } - + var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) @@ -809,7 +809,7 @@ private extension MainTimelineViewController { completion?() } } - + func makeDataSource() -> UITableViewDiffableDataSource { let dataSource: UITableViewDiffableDataSource = MainTimelineDataSource(tableView: tableView, cellProvider: { [weak self] tableView, indexPath, article in @@ -823,12 +823,12 @@ private extension MainTimelineViewController { cell.cellData = cellData return cell } - + }) dataSource.defaultRowAnimation = .middle return dataSource } - + @discardableResult func configure(article: Article) -> MainTimelineCellData { let iconImage = iconImageFor(article) @@ -837,7 +837,7 @@ private extension MainTimelineViewController { let cellData = MainTimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcon, numberOfLines: numberOfTextLines, iconSize: iconSize) return cellData } - + func iconImageFor(_ article: Article) -> IconImage? { if !showIcons { return nil @@ -852,7 +852,7 @@ private extension MainTimelineViewController { func toggleArticleReadStatusAction(_ article: Article) -> UIAction? { guard !article.status.read || article.isAvailableToMarkUnread else { return nil } - + let title = article.status.read ? NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : NSLocalizedString("Mark as Read", comment: "Mark as Read") @@ -861,10 +861,10 @@ private extension MainTimelineViewController { let action = UIAction(title: title, image: image) { [weak self] action in self?.toggleRead(article) } - + return action } - + func toggleStar(_ article: Article) { assert(coordinator != nil) coordinator?.toggleStar(article) @@ -880,7 +880,7 @@ private extension MainTimelineViewController { let action = UIAction(title: title, image: image) { [weak self] action in self?.toggleStar(article) } - + return action } @@ -933,7 +933,7 @@ private extension MainTimelineViewController { } return action } - + func markAboveAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { return nil @@ -962,7 +962,7 @@ private extension MainTimelineViewController { let cancel = { completion(true) } - + let action = UIAlertAction(title: title, style: .default) { [weak self] action in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.markBelowAsRead(article) @@ -992,7 +992,7 @@ private extension MainTimelineViewController { } return action } - + func discloseFeedAlertAction(_ article: Article, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = article.feed, !timelineFeedIsEqualTo(feed) else { return nil } @@ -1020,11 +1020,11 @@ private extension MainTimelineViewController { guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { return nil } - - + + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String - + let action = UIAction(title: title, image: AppAssets.markAllAsReadImage) { [weak self] action in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markAllAsRead(articles) @@ -1038,18 +1038,18 @@ private extension MainTimelineViewController { guard let fetchedArticles = try? feed.fetchArticles() else { return nil } - + let articles = Array(fetchedArticles) guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { return nil } - + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String let cancel = { completion(true) } - + let action = UIAlertAction(title: title, style: .default) { [weak self] action in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.markAllAsRead(articles) @@ -1058,7 +1058,7 @@ private extension MainTimelineViewController { } return action } - + func copyArticleURLAction(_ article: Article) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Copy Article URL", comment: "Copy Article URL") @@ -1067,7 +1067,7 @@ private extension MainTimelineViewController { } return action } - + func copyExternalURLAction(_ article: Article) -> UIAction? { guard let externalLink = article.externalLink, externalLink != article.preferredLink, let url = URL(string: externalLink) else { return nil } let title = NSLocalizedString("Copy External URL", comment: "Copy External URL") @@ -1101,18 +1101,18 @@ private extension MainTimelineViewController { } return action } - + func shareDialogForTableCell(indexPath: IndexPath, url: URL, title: String?) { let activityViewController = UIActivityViewController(url: url, title: title, applicationActivities: nil) - + guard let cell = tableView.cellForRow(at: indexPath) else { return } let popoverController = activityViewController.popoverPresentationController popoverController?.sourceView = cell popoverController?.sourceRect = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height) - + present(activityViewController, animated: true) } - + func shareAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share") @@ -1121,7 +1121,7 @@ private extension MainTimelineViewController { } return action } - + func shareAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share") @@ -1131,5 +1131,5 @@ private extension MainTimelineViewController { } return action } - + } diff --git a/iOS/MainTimeline/MarkAsReadAlertController.swift b/iOS/MainTimeline/MarkAsReadAlertController.swift index 5bbce1406..670add4c6 100644 --- a/iOS/MainTimeline/MarkAsReadAlertController.swift +++ b/iOS/MainTimeline/MarkAsReadAlertController.swift @@ -16,19 +16,19 @@ extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {} struct MarkAsReadAlertController { - + static func confirm(_ controller: UIViewController?, coordinator: SceneCoordinator?, confirmTitle: String, sourceType: T, cancelCompletion: (() -> Void)? = nil, completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType { - + guard let controller = controller, let coordinator = coordinator else { completion() return } - + if AppDefaults.shared.confirmMarkAllAsRead { let alertController = MarkAsReadAlertController.alert(coordinator: coordinator, confirmTitle: confirmTitle, cancelCompletion: cancelCompletion, sourceType: sourceType) { _ in completion() @@ -38,20 +38,20 @@ struct MarkAsReadAlertController { completion() } } - + private static func alert(coordinator: SceneCoordinator, confirmTitle: String, cancelCompletion: (() -> Void)?, sourceType: T, completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType { - - + + let title = NSLocalizedString("Mark As Read", comment: "Mark As Read") let message = NSLocalizedString("You can turn this confirmation off in Settings.", comment: "You can turn this confirmation off in Settings.") let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") let settingsTitle = NSLocalizedString("Open Settings", comment: "Open Settings") - + let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in cancelCompletion?() @@ -60,24 +60,24 @@ struct MarkAsReadAlertController { coordinator.showSettings(scrollToArticlesSection: true) } let markAction = UIAlertAction(title: confirmTitle, style: .default, handler: completion) - + alertController.addAction(markAction) alertController.addAction(settingsAction) alertController.addAction(cancelAction) - + if let barButtonItem = sourceType as? UIBarButtonItem { alertController.popoverPresentationController?.barButtonItem = barButtonItem } - + if let rect = sourceType as? CGRect { alertController.popoverPresentationController?.sourceRect = rect } - + if let view = sourceType as? UIView { alertController.popoverPresentationController?.sourceView = view } return alertController } - + } diff --git a/iOS/RootSplitViewController.swift b/iOS/RootSplitViewController.swift index 861b335e2..ea45abc9e 100644 --- a/iOS/RootSplitViewController.swift +++ b/iOS/RootSplitViewController.swift @@ -10,28 +10,28 @@ import UIKit import Account final class RootSplitViewController: UISplitViewController { - + var coordinator: SceneCoordinator! - + override var prefersStatusBarHidden: Bool { return coordinator.prefersStatusBarHidden } - + override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } - + override func viewDidAppear(_ animated: Bool) { coordinator.resetFocus() } - + override func show(_ column: UISplitViewController.Column) { guard !coordinator.isNavigationDisabled else { return } super.show(column) } - + // MARK: Keyboard Shortcuts - + @objc func scrollOrGoToNextUnread(_ sender: Any?) { coordinator.scrollOrGoToNextUnread() } @@ -39,24 +39,24 @@ final class RootSplitViewController: UISplitViewController { @objc func scrollUp(_ sender: Any?) { coordinator.scrollUp() } - + @objc func goToPreviousUnread(_ sender: Any?) { coordinator.selectPrevUnread() } - + @objc func nextUnread(_ sender: Any?) { coordinator.selectNextUnread() } - + @objc func markRead(_ sender: Any?) { coordinator.markAsReadForCurrentArticle() } - + @objc func markUnreadAndGoToNextUnread(_ sender: Any?) { coordinator.markAsUnreadForCurrentArticle() coordinator.selectNextUnread() } - + @objc func markAllAsReadAndGoToNextUnread(_ sender: Any?) { coordinator.markAllAsReadInTimeline() { self.coordinator.selectNextUnread() @@ -66,23 +66,23 @@ final class RootSplitViewController: UISplitViewController { @objc func markAboveAsRead(_ sender: Any?) { coordinator.markAboveAsRead() } - + @objc func markBelowAsRead(_ sender: Any?) { coordinator.markBelowAsRead() } - + @objc func markUnread(_ sender: Any?) { coordinator.markAsUnreadForCurrentArticle() } - + @objc func goToPreviousSubscription(_ sender: Any?) { coordinator.selectPrevFeed() } - + @objc func goToNextSubscription(_ sender: Any?) { coordinator.selectNextFeed() } - + @objc func openInBrowser(_ sender: Any?) { coordinator.showBrowserForCurrentArticle() } @@ -90,11 +90,11 @@ final class RootSplitViewController: UISplitViewController { @objc func openInAppBrowser(_ sender: Any?) { coordinator.showInAppBrowser() } - + @objc func articleSearch(_ sender: Any?) { coordinator.showSearch() } - + @objc func addNewFeed(_ sender: Any?) { coordinator.showAddFeed() } @@ -106,27 +106,27 @@ final class RootSplitViewController: UISplitViewController { @objc func cleanUp(_ sender: Any?) { coordinator.cleanUp(conditional: false) } - + @objc func toggleReadFeedsFilter(_ sender: Any?) { coordinator.toggleReadFeedsFilter() } - + @objc func toggleReadArticlesFilter(_ sender: Any?) { coordinator.toggleReadArticlesFilter() } - + @objc func refresh(_ sender: Any?) { appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self)) } - + @objc func goToToday(_ sender: Any?) { coordinator.selectTodayFeed() } - + @objc func goToAllUnread(_ sender: Any?) { coordinator.selectAllUnreadFeed() } - + @objc func goToStarred(_ sender: Any?) { coordinator.selectStarredFeed() } @@ -138,7 +138,7 @@ final class RootSplitViewController: UISplitViewController { @objc func toggleRead(_ sender: Any?) { coordinator.toggleReadForCurrentArticle() } - + @objc func toggleStarred(_ sender: Any?) { coordinator.toggleStarredForCurrentArticle() } diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 731341d70..905ac6286 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -33,7 +33,7 @@ struct FeedNode: Hashable { self.node = node self.sidebarItemID = (node.representedObject as! SidebarItem).sidebarItemID! } - + func hash(into hasher: inout Hasher) { hasher.combine(sidebarItemID) } @@ -78,13 +78,13 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { private var isSearching: Bool = false private var savedSearchArticles: ArticleArray? = nil private var savedSearchArticleIds: Set? = nil - + var isTimelineViewControllerPending = false var isArticleViewControllerPending = false - + /// `Bool` to track whether a refresh is scheduled. private var isNavigationBarSubtitleRefreshScheduled: Bool = false - + private(set) var sortDirection = AppDefaults.shared.timelineSortDirection { didSet { if sortDirection != oldValue { @@ -92,7 +92,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } } } - + private(set) var groupByFeed = AppDefaults.shared.timelineGroupByFeed { didSet { if groupByFeed != oldValue { @@ -100,18 +100,18 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } } } - + var prefersStatusBarHidden = false - + private let treeControllerDelegate = SidebarTreeControllerDelegate() private let treeController: TreeController - + var stateRestorationActivity: NSUserActivity { let activity = activityManager.stateRestorationActivity var userInfo = activity.userInfo ?? [AnyHashable: Any]() - + userInfo[UserInfoKey.windowState] = windowState() - + let articleState = articleViewController?.currentState userInfo[UserInfoKey.isShowingExtractedArticle] = articleState?.isShowingExtractedArticle ?? false userInfo[UserInfoKey.articleWindowScrollY] = articleState?.windowScrollY ?? 0 @@ -119,17 +119,17 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { activity.userInfo = userInfo return activity } - + var isNavigationDisabled = false - + var isRootSplitCollapsed: Bool { return rootSplitViewController.isCollapsed } - + var isReadFeedsFiltered: Bool { return treeControllerDelegate.isReadFiltered } - + var isReadArticlesFiltered: Bool { if let sidebarItemID = timelineFeed?.sidebarItemID, let readFilterEnabled = readFilterEnabledTable[sidebarItemID] { return readFilterEnabled @@ -137,15 +137,15 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { return timelineDefaultReadFilterType != .none } } - + var timelineDefaultReadFilterType: ReadFilterType { return timelineFeed?.defaultReadFilterType ?? .none } - + var rootNode: Node { return treeController.rootNode } - + // At some point we should refactor the current Feed IndexPath out and only use the timeline feed private(set) var currentFeedIndexPath: IndexPath? @@ -155,7 +155,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } return IconImageCache.shared.imageForFeed(timelineFeed) } - + private var exceptionArticleFetcher: ArticleFetcher? private(set) var timelineFeed: SidebarItem? { didSet { @@ -163,9 +163,9 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { updateNavigationBarSubtitles(nil) } } - + var timelineMiddleIndexPath: IndexPath? - + private(set) var showFeedNames = ShowFeedName.none private(set) var showIcons = false @@ -173,7 +173,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { guard let indexPath = currentFeedIndexPath else { return nil } - + let prevIndexPath: IndexPath? = { if indexPath.row - 1 < 0 { for i in (0..= shadowTable[indexPath.section].feedNodes.count { for i in indexPath.section + 1.. 0 } - + var isNextArticleAvailable: Bool { guard let articleRow = currentArticleRow else { return false } return articleRow + 1 < articles.count } - + var prevArticle: Article? { guard isPrevArticleAvailable, let articleRow = currentArticleRow else { return nil } return articles[articleRow - 1] } - + var nextArticle: Article? { guard isNextArticleAvailable, let articleRow = currentArticleRow else { return nil } return articles[articleRow + 1] } - + var firstUnreadArticleIndexPath: IndexPath? { for (row, article) in articles.enumerated() { if !article.status.read { @@ -247,7 +247,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } return nil } - + var currentArticle: Article? private(set) var articles = ArticleArray() { @@ -274,17 +274,17 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { var isTimelineUnreadAvailable: Bool { return timelineUnreadCount > 0 } - + var isAnyUnreadAvailable: Bool { return appDelegate.unreadCount > 0 } - + var timelineUnreadCount: Int = 0 { didSet { updateNavigationBarSubtitles(nil) } } - + init(rootSplitViewController: RootSplitViewController) { self.rootSplitViewController = rootSplitViewController self.rootSplitViewController.minimumPrimaryColumnWidth = 300 @@ -293,7 +293,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.rootSplitViewController.maximumSupplementaryColumnWidth = 500 self.rootSplitViewController.preferredSupplementaryColumnWidthFraction = 0.4 self.rootSplitViewController.preferredSplitBehavior = .tile - + self.treeController = TreeController(delegate: treeControllerDelegate) super.init() @@ -315,7 +315,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { markExpanded(sectionNode) shadowTable.append((sectionID: "", feedNodes: [FeedNode]())) } - + NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidInitialize(_:)), name: .UnreadCountDidInitialize, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil) @@ -332,17 +332,17 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(themeDownloadDidFail(_:)), name: .didFailToImportThemeWithError, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateNavigationBarSubtitles(_:)), name: .combinedRefreshProgressDidChange, object: nil) - + } - + func restoreWindowState(_ activity: NSUserActivity?) { if let activity = activity, let windowState = activity.userInfo?[UserInfoKey.windowState] as? [AnyHashable: Any] { - + if let containerExpandedWindowState = windowState[UserInfoKey.containerExpandedWindowState] as? [[AnyHashable: AnyHashable]] { let containerIdentifiers = containerExpandedWindowState.compactMap( { ContainerIdentifier(userInfo: $0) }) expandedTable = Set(containerIdentifiers) } - + if let readArticlesFilterState = windowState[UserInfoKey.readArticlesFilterState] as? [[AnyHashable: AnyHashable]: Bool] { for key in readArticlesFilterState.keys { if let feedIdentifier = SidebarItemIdentifier(userInfo: key) { @@ -358,14 +358,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { if let readFeedsFilterState = windowState[UserInfoKey.readFeedsFilterState] as? Bool { treeControllerDelegate.isReadFiltered = readFeedsFilterState } - + } else { - + rebuildBackingStores(initialLoad: true) - + } } - + func handle(_ activity: NSUserActivity) { selectFeed(indexPath: nil) { guard let activityType = ActivityType(rawValue: activity.activityType) else { return } @@ -383,12 +383,12 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } } } - + func handle(_ response: UNNotificationResponse) { let userInfo = response.notification.request.content.userInfo handleReadArticle(userInfo) } - + func resetFocus() { if currentArticle != nil { mainTimelineViewController?.focus() @@ -396,7 +396,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { mainFeedCollectionViewController?.focus() } } - + func selectFirstUnreadInAllUnread() { markExpanded(SmartFeedsController.shared) self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.unreadFeed) { @@ -414,14 +414,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } } } - + // MARK: Notifications - + @objc func unreadCountDidInitialize(_ notification: Notification) { guard notification.object is AccountManager else { return } - + if isReadFeedsFiltered { rebuildBackingStores() } @@ -432,14 +432,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { guard AccountManager.shared.isUnreadCountsInitialized else { return } - + queueRebuildBackingStores() } @objc func statusesDidChange(_ note: Notification) { updateUnreadCount() } - + @objc func containerChildrenDidChange(_ note: Notification) { if timelineFetcherContainsAnyPseudoFeed() || timelineFetcherContainsAnyFolder() { fetchAndMergeArticlesAsync(animated: true) { @@ -450,11 +450,11 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { rebuildBackingStores() } } - + @objc func batchUpdateDidPerform(_ notification: Notification) { rebuildBackingStores() } - + @objc func displayNameDidChange(_ note: Notification) { rebuildBackingStores() } @@ -469,7 +469,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.rebuildBackingStores() } } - + @objc func userDidAddAccount(_ note: Notification) { let expandNewAccount = { if let account = note.userInfo?[Account.UserInfoKey.account] as? Account, @@ -477,7 +477,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.markExpanded(node) } } - + if timelineFetcherContainsAnyPseudoFeed() { fetchAndMergeArticlesAsync(animated: true) { self.mainTimelineViewController?.reinitializeArticles(resetScroll: false) @@ -495,7 +495,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.unmarkExpanded(node) } } - + if timelineFetcherContainsAnyPseudoFeed() { fetchAndMergeArticlesAsync(animated: true) { self.mainTimelineViewController?.reinitializeArticles(resetScroll: false) @@ -512,25 +512,25 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } discloseFeed(feed, animations: [.scroll, .navigation]) } - + @objc func userDefaultsDidChange(_ note: Notification) { Task { @MainActor in self.sortDirection = AppDefaults.shared.timelineSortDirection self.groupByFeed = AppDefaults.shared.timelineGroupByFeed } } - + @objc func accountDidDownloadArticles(_ note: Notification) { guard let feeds = note.userInfo?[Account.UserInfoKey.feeds] as? Set else { return } - + let shouldFetchAndMergeArticles = timelineFetcherContainsAnyFeed(feeds) || timelineFetcherContainsAnyPseudoFeed() if shouldFetchAndMergeArticles { queueFetchAndMergeArticles() } } - + @objc func willEnterForeground(_ note: Notification) { // Don't interfere with any fetch requests that we may have initiated before the app was returned to the foreground. // For example if you select Next Unread from the Home Screen Quick actions, you can start a request before we are @@ -539,18 +539,18 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { queueFetchAndMergeArticles() } } - + @objc func importDownloadedTheme(_ note: Notification) { guard let userInfo = note.userInfo, let url = userInfo["url"] as? URL else { return } - + DispatchQueue.main.async { self.importTheme(filename: url.path) } } - + @objc func themeDownloadDidFail(_ note: Notification) { guard let userInfo = note.userInfo, let error = userInfo["error"] as? Error else { @@ -560,8 +560,8 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.rootSplitViewController.presentError(error, dismiss: nil) } } - - + + /// Updates navigation bar subtitles in response to feed selection, unread count changes, /// `combinedRefreshProgressDidChange` notifications, and a timed refresh every /// 60s. @@ -590,10 +590,10 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { let refreshed = relativeDateTimeFormatter.localizedString(for: accountLastArticleFetchEndTime, relativeTo: Date()) let localizedRefreshText = NSLocalizedString("Updated %@", comment: "Updated") let refreshText = NSString.localizedStringWithFormat(localizedRefreshText as NSString, refreshed) as String - + // Update Feeds with Updated text self.mainFeedCollectionViewController?.navigationItem.subtitle = refreshText - + // If unread count > 0, add unread string to timeline if let _ = timelineFeed, timelineUnreadCount > 0 { let localizedUnreadCount = NSLocalizedString("%i Unread", comment: "14 Unread") @@ -610,7 +610,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } else { // Use 'Updated Just Now' while <60s have passed since refresh. self.mainFeedCollectionViewController?.navigationItem.subtitle = NSLocalizedString("Updated Just Now", comment: "Updated Just Now") - + // If unread count > 0, add unread string to timeline if let _ = timelineFeed, timelineUnreadCount > 0 { let localizedUnreadCount = NSLocalizedString("%i Unread", comment: "14 Unread") @@ -633,11 +633,11 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { // Updating in progress, apply to both iPhone and iPad Feeds. self.mainFeedCollectionViewController?.navigationItem.subtitle = NSLocalizedString("Updating...", comment: "Updating...") } - + scheduleNavigationBarSubtitleUpdate() - + } - + func scheduleNavigationBarSubtitleUpdate() { if isNavigationBarSubtitleRefreshScheduled { return @@ -650,13 +650,13 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } // MARK: API - + func suspend() { fetchAndMergeArticlesQueue.performCallsImmediately() rebuildBackingStoresQueue.performCallsImmediately() fetchRequestQueue.cancelAllRequests() } - + func cleanUp(conditional: Bool) { if isReadFeedsFiltered { rebuildBackingStores() @@ -665,7 +665,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { refreshTimeline(resetScroll: false) } } - + func toggleReadFeedsFilter() { if isReadFeedsFiltered { treeControllerDelegate.isReadFiltered = false @@ -675,7 +675,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { rebuildBackingStores() mainFeedCollectionViewController?.updateUI() } - + func toggleReadArticlesFilter() { guard let sidebarItemID = timelineFeed?.sidebarItemID else { return @@ -686,7 +686,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } else { readFilterEnabledTable[sidebarItemID] = true } - + refreshTimeline(resetScroll: false) } @@ -699,15 +699,15 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } }) } - + func numberOfSections() -> Int { return shadowTable.count } - + func numberOfRows(in section: Int) -> Int { return shadowTable[section].feedNodes.count } - + func nodeFor(_ indexPath: IndexPath) -> Node? { guard indexPath.section > -1 && indexPath.row > -1 && @@ -726,18 +726,18 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } return nil } - + func articleFor(_ articleID: String) -> Article? { return idToArticleDictionary[articleID] } - + func cappedIndexPath(_ indexPath: IndexPath) -> IndexPath { guard indexPath.section < shadowTable.count && indexPath.row < shadowTable[indexPath.section].feedNodes.count else { return IndexPath(row: shadowTable[shadowTable.count - 1].feedNodes.count - 1, section: shadowTable.count - 1) } return indexPath } - + func unreadCountFor(_ node: Node) -> Int { // The coordinator supplies the unread count for the currently selected feed if node.representedObject === timelineFeed as AnyObject { @@ -749,7 +749,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { assertionFailure("This method should only be called for nodes that have an UnreadCountProvider as the represented object.") return 0 } - + func refreshTimeline(resetScroll: Bool) { if let article = self.currentArticle, let account = article.account { exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID) @@ -758,25 +758,25 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.mainTimelineViewController?.reinitializeArticles(resetScroll: resetScroll) } } - + func isExpanded(_ containerID: ContainerIdentifier) -> Bool { return expandedTable.contains(containerID) } - + func isExpanded(_ containerIdentifiable: ContainerIdentifiable) -> Bool { if let containerID = containerIdentifiable.containerID { return isExpanded(containerID) } return false } - + func isExpanded(_ node: Node) -> Bool { if let containerIdentifiable = node.representedObject as? ContainerIdentifiable { return isExpanded(containerIdentifiable) } return false } - + func expand(_ containerID: ContainerIdentifier) { markExpanded(containerID) rebuildBackingStores() @@ -801,13 +801,13 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } rebuildBackingStores() } - + func collapse(_ containerID: ContainerIdentifier) { unmarkExpanded(containerID) rebuildBackingStores() clearTimelineIfNoLongerAvailable() } - + /// This is a special function that expects the caller to change the disclosure arrow state outside this function. /// Failure to do so will get the Sidebar into an invalid state. func collapse(_ node: Node) { @@ -827,14 +827,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { rebuildBackingStores() clearTimelineIfNoLongerAvailable() } - + func mainFeedIndexPathForCurrentTimeline() -> IndexPath? { guard let node = treeController.rootNode.descendantNodeRepresentingObject(timelineFeed as AnyObject) else { return nil } return indexPathFor(node) } - + func selectFeed(_ sidebarItem: SidebarItem?, animations: Animations = [], deselectArticle: Bool = true, completion: (() -> Void)? = nil) { let indexPath: IndexPath? = { if let sidebarItem, let indexPath = indexPathFor(sidebarItem as AnyObject) { @@ -846,16 +846,16 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { selectFeed(indexPath: indexPath, animations: animations, deselectArticle: deselectArticle, completion: completion) updateNavigationBarSubtitles(nil) } - + func selectFeed(indexPath: IndexPath?, animations: Animations = [], deselectArticle: Bool = true, completion: (() -> Void)? = nil) { guard indexPath != currentFeedIndexPath else { completion?() return } - + currentFeedIndexPath = indexPath mainFeedCollectionViewController.updateFeedSelection(animations: animations) - + if deselectArticle { selectArticle(nil) @@ -871,9 +871,9 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } completion?() } - + } else { - + setTimelineFeed(nil, animated: false) { if self.isReadFeedsFiltered { self.rebuildBackingStores() @@ -882,24 +882,24 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.rootSplitViewController.show(.primary) completion?() } - + } updateNavigationBarSubtitles(nil) - + } - + func selectPrevFeed() { if let indexPath = prevFeedIndexPath { selectFeed(indexPath: indexPath, animations: [.navigation, .scroll]) } } - + func selectNextFeed() { if let indexPath = nextFeedIndexPath { selectFeed(indexPath: indexPath, animations: [.navigation, .scroll]) } } - + func selectTodayFeed(completion: (() -> Void)? = nil) { markExpanded(SmartFeedsController.shared) self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.todayFeed) { @@ -923,18 +923,18 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { func selectArticle(_ article: Article?, animations: Animations = [], isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) { guard article != currentArticle else { return } - + currentArticle = article activityManager.reading(feed: timelineFeed, article: article) - + if article == nil { rootSplitViewController.show(.supplementary) mainTimelineViewController?.updateArticleSelection(animations: animations) return } - + rootSplitViewController.show(.secondary) - + // Mark article as read before navigating to it, so the read status does not flash unread/read on display markArticles(Set([article!]), statusKey: .read, flag: true) @@ -944,7 +944,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { articleViewController?.restoreScrollPosition = (isShowingExtractedArticle, articleWindowScrollY) } } - + func beginSearching() { isSearching = true preSearchTimelineFeed = timelineFeed @@ -963,7 +963,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } else { setTimelineFeed(nil, animated: true) } - + lastSearchString = "" lastSearchScope = nil preSearchTimelineFeed = nil @@ -973,97 +973,97 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { selectArticle(nil) mainTimelineViewController?.focus() } - + func searchArticles(_ searchString: String, _ searchScope: SearchScope) { - + guard isSearching else { return } - + if searchString.count < 3 { setTimelineFeed(nil, animated: true) return } - + if searchString != lastSearchString || searchScope != lastSearchScope { - + switch searchScope { case .global: setTimelineFeed(SmartFeed(delegate: SearchFeedDelegate(searchString: searchString)), animated: true) case .timeline: setTimelineFeed(SmartFeed(delegate: SearchTimelineFeedDelegate(searchString: searchString, articleIDs: savedSearchArticleIds!)), animated: true) } - + lastSearchString = searchString lastSearchScope = searchScope } - + } - + func findPrevArticle(_ article: Article) -> Article? { guard let index = articles.firstIndex(of: article), index > 0 else { return nil } return articles[index - 1] } - + func findNextArticle(_ article: Article) -> Article? { guard let index = articles.firstIndex(of: article), index + 1 != articles.count else { return nil } return articles[index + 1] } - + func selectPrevArticle() { if let article = prevArticle { selectArticle(article, animations: [.navigation, .scroll]) } } - + func selectNextArticle() { if let article = nextArticle { selectArticle(article, animations: [.navigation, .scroll]) } } - + func selectFirstUnread() { if selectFirstUnreadArticleInTimeline() { activityManager.selectingNextUnread() } } - + func selectPrevUnread() { - + // This should never happen, but I don't want to risk throwing us // into an infinite loop searching for an unread that isn't there. if appDelegate.unreadCount < 1 { return } - + isNavigationDisabled = true defer { isNavigationDisabled = false } - + if selectPrevUnreadArticleInTimeline() { return } - + selectPrevUnreadFeedFetcher() selectPrevUnreadArticleInTimeline() } func selectNextUnread() { - + // This should never happen, but I don't want to risk throwing us // into an infinite loop searching for an unread that isn't there. if appDelegate.unreadCount < 1 { return } - + isNavigationDisabled = true defer { isNavigationDisabled = false } - + if selectNextUnreadArticleInTimeline() { return } @@ -1076,7 +1076,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.selectNextUnreadArticleInTimeline() } } - + func scrollOrGoToNextUnread() { if articleViewController?.canScrollDown() ?? false { articleViewController?.scrollPageDown() @@ -1090,11 +1090,11 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { articleViewController?.scrollPageUp() } } - + func markAllAsRead(_ articles: [Article], completion: (() -> Void)? = nil) { markArticlesWithUndo(articles, statusKey: .read, flag: true, completion: completion) } - + func markAllAsReadInTimeline(completion: (() -> Void)? = nil) { markAllAsRead(articles) { self.rootSplitViewController.show(.primary) @@ -1137,25 +1137,25 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { let articleBelowArray = articles.articlesBelow(article: article) markAllAsRead(articleBelowArray) } - + func markAsReadForCurrentArticle() { if let article = currentArticle { markArticlesWithUndo([article], statusKey: .read, flag: true) } } - + func markAsUnreadForCurrentArticle() { if let article = currentArticle { markArticlesWithUndo([article], statusKey: .read, flag: false) } } - + func toggleReadForCurrentArticle() { if let article = currentArticle { toggleRead(article) } } - + func toggleRead(_ article: Article) { guard !article.status.read || article.isAvailableToMarkUnread else { return } markArticlesWithUndo([article], statusKey: .read, flag: !article.status.read) @@ -1166,7 +1166,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { toggleStar(article) } } - + func toggleStar(_ article: Article) { markArticlesWithUndo([article], statusKey: .starred, flag: !article.status.starred) } @@ -1223,14 +1223,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { self.rootSplitViewController.setNeedsStatusBarAppearanceUpdate() } } - + func hideStatusBar() { prefersStatusBarHidden = true UIView.animate(withDuration: 0.15) { self.rootSplitViewController.setNeedsStatusBarAppearanceUpdate() } } - + func showSettings(scrollToArticlesSection: Bool = false) { let settingsNavController = UIStoryboard.settings.instantiateInitialViewController() as! UINavigationController let settingsViewController = settingsNavController.topViewController as! SettingsViewController @@ -1239,7 +1239,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { settingsViewController.presentingParentController = rootSplitViewController rootSplitViewController.present(settingsNavController, animated: true) } - + func showAccountInspector(for account: Account) { let accountInspectorNavController = UIStoryboard.inspector.instantiateViewController(identifier: "AccountInspectorNavigationViewController") as! UINavigationController @@ -1250,14 +1250,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { accountInspectorController.account = account rootSplitViewController.present(accountInspectorNavController, animated: true) } - + func showFeedInspector() { guard let feed = timelineFeed as? Feed ?? currentArticle?.feed else { return } showFeedInspector(for: feed) } - + func showFeedInspector(for feed: Feed) { let feedInspectorNavController = UIStoryboard.inspector.instantiateViewController(identifier: "FeedInspectorNavigationViewController") as! UINavigationController @@ -1267,30 +1267,30 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { feedInspectorController.feed = feed rootSplitViewController.present(feedInspectorNavController, animated: true) } - + func showAddFeed(initialFeed: String? = nil, initialFeedName: String? = nil) { - + // Since Add Feed can be opened from anywhere with a keyboard shortcut, we have to deselect any currently selected feeds selectFeed(nil) let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFeedViewControllerNav") as! UINavigationController - + let addViewController = addNavViewController.topViewController as! AddFeedViewController addViewController.initialFeed = initialFeed addViewController.initialFeedName = initialFeedName - + addNavViewController.modalPresentationStyle = .formSheet addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay mainFeedCollectionViewController.present(addNavViewController, animated: true) } - + func showAddFolder() { let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFolderViewControllerNav") as! UINavigationController addNavViewController.modalPresentationStyle = .formSheet addNavViewController.preferredContentSize = AddFolderViewController.preferredContentSizeForFormSheetDisplay mainFeedCollectionViewController.present(addNavViewController, animated: true) } - + func showFullScreenImage(image: UIImage, imageTitle: String?, transitioningDelegate: UIViewControllerTransitioningDelegate) { let imageVC = UIStoryboard.main.instantiateController(ofType: ImageViewController.self) imageVC.image = image @@ -1299,7 +1299,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { imageVC.transitioningDelegate = transitioningDelegate rootSplitViewController.present(imageVC, animated: true) } - + func homePageURLForFeed(_ indexPath: IndexPath) -> URL? { guard let node = nodeFor(indexPath), let feed = node.representedObject as? Feed, @@ -1309,19 +1309,19 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { } return url } - + func showBrowserForFeed(_ indexPath: IndexPath) { if let url = homePageURLForFeed(indexPath) { UIApplication.shared.open(url, options: [:]) } } - + func showBrowserForCurrentFeed() { if let ip = currentFeedIndexPath, let url = homePageURLForFeed(ip) { UIApplication.shared.open(url, options: [:]) } } - + func showBrowserForArticle(_ article: Article) { guard let url = article.preferredURL else { return } UIApplication.shared.open(url, options: [:]) @@ -1331,7 +1331,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { guard let url = currentArticle?.preferredURL else { return } UIApplication.shared.open(url, options: [:]) } - + func showInAppBrowser() { if currentArticle != nil { articleViewController?.openInAppBrowser() @@ -1345,14 +1345,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { mainFeedCollectionViewController?.focus() selectArticle(nil) } - + func navigateToTimeline() { if currentArticle == nil && articles.count > 0 { selectArticle(articles[0]) } mainTimelineViewController?.focus() } - + func navigateToDetail() { articleViewController?.focus() } @@ -1360,22 +1360,22 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { func toggleSidebar() { rootSplitViewController.preferredDisplayMode = rootSplitViewController.displayMode == .oneBesideSecondary ? .secondaryOnly : .oneBesideSecondary } - + func selectArticleInCurrentFeed(_ articleID: String, isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) { if let article = self.articles.first(where: { $0.articleID == articleID }) { self.selectArticle(article, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY) } } - + func importTheme(filename: String) { do { try ArticleThemeImporter.importTheme(controller: rootSplitViewController, url: URL(fileURLWithPath: filename)) } catch { NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error" : error]) } - + } - + /// This will dismiss the foremost view controller if the user /// has launched from an external action (i.e., a widget tap, or /// selecting an article via a notification). @@ -1385,14 +1385,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner { /// otherwise, this function does nothing. func dismissIfLaunchingFromExternalAction() { guard let presentedController = mainFeedCollectionViewController.presentedViewController else { return } - + if presentedController.isKind(of: SFSafariViewController.self) { presentedController.dismiss(animated: true, completion: nil) } guard let settings = presentedController.children.first as? SettingsViewController else { return } settings.dismiss(animated: true, completion: nil) } - + } // MARK: UISplitViewControllerDelegate @@ -1421,18 +1421,18 @@ extension SceneCoordinator: UISplitViewControllerDelegate { return .primary } } - + } // MARK: UINavigationControllerDelegate extension SceneCoordinator: UINavigationControllerDelegate { - + func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { guard UIApplication.shared.applicationState != .background else { return } - + guard rootSplitViewController.isCollapsed else { return } @@ -1475,7 +1475,7 @@ private extension SceneCoordinator { } runCommand(markReadCommand) } - + func updateUnreadCount() { var count = 0 for article in articles { @@ -1485,7 +1485,7 @@ private extension SceneCoordinator { } timelineUnreadCount = count } - + func rebuildArticleDictionaries() { var idDictionary = [String: Article]() @@ -1496,11 +1496,11 @@ private extension SceneCoordinator { _idToArticleDictionary = idDictionary articleDictionaryNeedsUpdate = false } - + func ensureFeedIsAvailableToSelect(_ sidebarItem: SidebarItem, completion: @escaping () -> Void) { addToFilterExceptionsIfNecessary(sidebarItem) addShadowTableToFilterExceptions() - + rebuildBackingStores(completion: { self.treeControllerDelegate.resetFilterExceptions() completion() @@ -1523,17 +1523,17 @@ private extension SceneCoordinator { } } } - + func addParentFolderToFilterExceptions(_ sidebarItem: SidebarItem) { guard let node = treeController.rootNode.descendantNodeRepresentingObject(sidebarItem as AnyObject), let folder = node.parent?.representedObject as? Folder, let folderSidebarItemID = folder.sidebarItemID else { return } - + treeControllerDelegate.addFilterException(folderSidebarItemID) } - + func addShadowTableToFilterExceptions() { for section in shadowTable { for feedNode in section.feedNodes { @@ -1543,7 +1543,7 @@ private extension SceneCoordinator { } } } - + func queueRebuildBackingStores() { rebuildBackingStoresQueue.add(self, #selector(rebuildBackingStoresWithDefaults)) } @@ -1551,19 +1551,19 @@ private extension SceneCoordinator { @objc func rebuildBackingStoresWithDefaults() { rebuildBackingStores() } - + func rebuildBackingStores(initialLoad: Bool = false, updateExpandedNodes: (() -> Void)? = nil, completion: (() -> Void)? = nil) { if !BatchUpdate.shared.isPerforming { addToFilterExceptionsIfNecessary(timelineFeed) treeController.rebuild() treeControllerDelegate.resetFilterExceptions() - + updateExpandedNodes?() let changes = rebuildShadowTable() mainFeedCollectionViewController.reloadFeeds(initialLoad: initialLoad, changes: changes, completion: completion) } } - + func rebuildShadowTable() -> ShadowTableChanges { var newShadowTable = [(sectionID: String, feedNodes: [FeedNode])]() @@ -1677,7 +1677,7 @@ private extension SceneCoordinator { } return false } - + func clearTimelineIfNoLongerAvailable() { if let feed = timelineFeed, !shadowTableContains(feed) { selectFeed(nil, deselectArticle: true) @@ -1690,18 +1690,18 @@ private extension SceneCoordinator { } return indexPathFor(node) } - + func setTimelineFeed(_ sidebarItem: SidebarItem?, animated: Bool, completion: (() -> Void)? = nil) { timelineFeed = sidebarItem - + fetchAndReplaceArticlesAsync(animated: animated) { self.mainTimelineViewController?.reinitializeArticles(resetScroll: true) completion?() } } - + func updateShowNamesAndIcons() { - + if timelineFeed is Feed { showFeedNames = { for article in articles { @@ -1719,12 +1719,12 @@ private extension SceneCoordinator { self.showIcons = true return } - + if showFeedNames == .none { self.showIcons = false return } - + for article in articles { if let authors = article.authors { for author in authors { @@ -1735,10 +1735,10 @@ private extension SceneCoordinator { } } } - + self.showIcons = false } - + func markExpanded(_ containerID: ContainerIdentifier) { expandedTable.insert(containerID) } @@ -1748,13 +1748,13 @@ private extension SceneCoordinator { markExpanded(containerID) } } - + func markExpanded(_ node: Node) { if let containerIdentifiable = node.representedObject as? ContainerIdentifiable { markExpanded(containerIdentifiable) } } - + func unmarkExpanded(_ containerID: ContainerIdentifier) { expandedTable.remove(containerID) } @@ -1782,16 +1782,16 @@ private extension SceneCoordinator { return articles.count - 1 } }() - + return selectPrevArticleInTimeline(startingRow: startingRow) } - + func selectPrevArticleInTimeline(startingRow: Int) -> Bool { - + guard startingRow >= 0 else { return false } - + for i in (0...startingRow).reversed() { let article = articles[i] if !article.status.read { @@ -1799,13 +1799,13 @@ private extension SceneCoordinator { return true } } - + return false - + } - + func selectPrevUnreadFeedFetcher() { - + let indexPath: IndexPath = { if currentFeedIndexPath == nil { return IndexPath(row: 0, section: 0) @@ -1826,20 +1826,20 @@ private extension SceneCoordinator { return IndexPath(row: indexPath.row - 1, section: indexPath.section) } }() - + if selectPrevUnreadFeedFetcher(startingWith: nextIndexPath) { return } let maxIndexPath = IndexPath(row: shadowTable[shadowTable.count - 1].feedNodes.count - 1, section: shadowTable.count - 1) selectPrevUnreadFeedFetcher(startingWith: maxIndexPath) - + } - + @discardableResult func selectPrevUnreadFeedFetcher(startingWith indexPath: IndexPath) -> Bool { - + for i in (0...indexPath.section).reversed() { - + let startingRow: Int = { if indexPath.section == i { return indexPath.row @@ -1847,39 +1847,39 @@ private extension SceneCoordinator { return shadowTable[i].feedNodes.count - 1 } }() - + for j in (0...startingRow).reversed() { - + let prevIndexPath = IndexPath(row: j, section: i) guard let node = nodeFor(prevIndexPath), let unreadCountProvider = node.representedObject as? UnreadCountProvider else { assertionFailure() return true } - + if isExpanded(node) { continue } - + if unreadCountProvider.unreadCount > 0 { selectFeed(indexPath: prevIndexPath, animations: [.scroll, .navigation]) return true } - + } - + } - + return false - + } - + // MARK: Select Next Unread - + @discardableResult func selectFirstUnreadArticleInTimeline() -> Bool { return selectNextArticleInTimeline(startingRow: 0, animated: true) } - + @discardableResult func selectNextUnreadArticleInTimeline() -> Bool { let startingRow: Int = { @@ -1889,16 +1889,16 @@ private extension SceneCoordinator { return 0 } }() - + return selectNextArticleInTimeline(startingRow: startingRow, animated: false) } - + func selectNextArticleInTimeline(startingRow: Int, animated: Bool) -> Bool { - + guard startingRow < articles.count else { return false } - + for i in startingRow.. Void) { - + let indexPath: IndexPath = { if currentFeedIndexPath == nil { return IndexPath(row: -1, section: 0) @@ -1920,7 +1920,7 @@ private extension SceneCoordinator { return currentFeedIndexPath! } }() - + // Increment or wrap around the IndexPath let nextIndexPath: IndexPath = { if indexPath.row + 1 >= shadowTable[indexPath.section].feedNodes.count { @@ -1933,7 +1933,7 @@ private extension SceneCoordinator { return IndexPath(row: indexPath.row + 1, section: indexPath.section) } }() - + selectNextUnreadFeed(startingWith: nextIndexPath) { found in if !found { self.selectNextUnreadFeed(startingWith: IndexPath(row: 0, section: 0)) { _ in @@ -1943,13 +1943,13 @@ private extension SceneCoordinator { completion() } } - + } - + func selectNextUnreadFeed(startingWith indexPath: IndexPath, completion: @escaping (Bool) -> Void) { - + for i in indexPath.section.. 0 { selectFeed(indexPath: nextIndexPath, animations: [.scroll, .navigation], deselectArticle: false) { self.currentArticle = nil @@ -1978,32 +1978,32 @@ private extension SceneCoordinator { } return } - + } - + } - + completion(false) - + } - + // MARK: Fetching Articles - + func emptyTheTimeline() { if !articles.isEmpty { replaceArticles(with: Set
(), animated: false) } } - + func sortParametersDidChange() { replaceArticles(with: Set(articles), animated: true) } - + func replaceArticles(with unsortedArticles: Set
, animated: Bool) { let sortedArticles = Array(unsortedArticles).sortedByDate(sortDirection, groupByFeed: groupByFeed) replaceArticles(with: sortedArticles, animated: animated) } - + func replaceArticles(with sortedArticles: ArticleArray, animated: Bool) { if articles != sortedArticles { articles = sortedArticles @@ -2012,7 +2012,7 @@ private extension SceneCoordinator { mainTimelineViewController?.reloadArticles(animated: animated) } } - + func queueFetchAndMergeArticles() { fetchAndMergeArticlesQueue.add(self, #selector(fetchAndMergeArticlesAsync)) } @@ -2023,13 +2023,13 @@ private extension SceneCoordinator { self.mainTimelineViewController?.restoreSelectionIfNecessary(adjustScroll: false) } } - + func fetchAndMergeArticlesAsync(animated: Bool = true, completion: (() -> Void)? = nil) { - + guard let timelineFeed = timelineFeed else { return } - + fetchUnsortedArticlesAsync(for: [timelineFeed]) { [weak self] (unsortedArticles) in // Merge articles by articleID. For any unique articleID in current articles, add to unsortedArticles. guard let strongSelf = self else { @@ -2049,9 +2049,9 @@ private extension SceneCoordinator { strongSelf.replaceArticles(with: updatedArticles, animated: animated) completion?() } - + } - + func cancelPendingAsyncFetches() { fetchSerialNumber += 1 fetchRequestQueue.cancelAllRequests() @@ -2066,19 +2066,19 @@ private extension SceneCoordinator { completion() return } - + var fetchers = [ArticleFetcher]() fetchers.append(timelineFeed) if exceptionArticleFetcher != nil { fetchers.append(exceptionArticleFetcher!) exceptionArticleFetcher = nil } - + fetchUnsortedArticlesAsync(for: fetchers) { [weak self] (articles) in self?.replaceArticles(with: articles, animated: animated) completion() } - + } func fetchUnsortedArticlesAsync(for representedObjects: [Any], completion: @escaping ArticleSetBlock) { @@ -2086,7 +2086,7 @@ private extension SceneCoordinator { // if it’s been superseded by a newer fetch, or the timeline was emptied, etc., it won’t get called. precondition(Thread.isMainThread) cancelPendingAsyncFetches() - + let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher } let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers) { [weak self] (articles, operation) in precondition(Thread.isMainThread) @@ -2095,7 +2095,7 @@ private extension SceneCoordinator { } completion(articles) } - + fetchRequestQueue.add(fetchOperation) } @@ -2105,18 +2105,18 @@ private extension SceneCoordinator { } return false } - + func timelineFetcherContainsAnyFolder() -> Bool { if timelineFeed is Folder { return true } return false } - + func timelineFetcherContainsAnyFeed(_ feeds: Set) -> Bool { - + // Return true if there’s a match or if a folder contains (recursively) one of feeds - + if let feed = timelineFeed as? Feed { for oneFeed in feeds { if feed.feedID == oneFeed.feedID || feed.url == oneFeed.url { @@ -2130,13 +2130,13 @@ private extension SceneCoordinator { } } } - + return false - + } - + // MARK: NSUserActivity - + func windowState() -> [AnyHashable: Any] { let containerExpandedWindowState = expandedTable.map( { $0.userInfo }) var readArticlesFilterState = [[AnyHashable: AnyHashable]: Bool]() @@ -2149,7 +2149,7 @@ private extension SceneCoordinator { UserInfoKey.readArticlesFilterState: readArticlesFilterState ] } - + func handleSelectFeed(_ userInfo: [AnyHashable : Any]?) { guard let userInfo = userInfo, let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable], @@ -2158,9 +2158,9 @@ private extension SceneCoordinator { } treeControllerDelegate.addFilterException(feedIdentifier) - + switch feedIdentifier { - + case .smartFeed: guard let smartFeed = SmartFeedsController.shared.find(by: feedIdentifier) else { return } @@ -2173,10 +2173,10 @@ private extension SceneCoordinator { } } }) - + case .script: break - + case .folder(let accountID, let folderName): guard let accountNode = self.findAccountNode(accountID: accountID), let account = accountNode.representedObject as? Account else { @@ -2184,33 +2184,33 @@ private extension SceneCoordinator { } markExpanded(account) - + rebuildBackingStores(initialLoad: true, completion: { self.treeControllerDelegate.resetFilterExceptions() - + if let folderNode = self.findFolderNode(folderName: folderName, beginningAt: accountNode), let indexPath = self.indexPathFor(folderNode) { self.selectFeed(indexPath: indexPath) { self.mainFeedCollectionViewController.focus() } } }) - + case .feed(let accountID, let feedID): guard let accountNode = findAccountNode(accountID: accountID), let account = accountNode.representedObject as? Account, let feed = account.existingFeed(withFeedID: feedID) else { return } - + self.discloseFeed(feed, initialLoad: true) { self.mainFeedCollectionViewController.focus() } } } - + func handleReadArticle(_ userInfo: [AnyHashable : Any]?) { guard let userInfo = userInfo else { return } - + guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any], let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String, let accountName = articlePathUserInfo[ArticlePathKey.accountName] as? String, @@ -2220,22 +2220,22 @@ private extension SceneCoordinator { let account = accountNode.representedObject as? Account else { return } - + exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID) if restoreFeedSelection(userInfo, accountID: accountID, feedID: feedID, articleID: articleID) { return } - + guard let feed = account.existingFeed(withFeedID: feedID) else { return } - + discloseFeed(feed) { self.selectArticleInCurrentFeed(articleID) } } - + func restoreFeedSelection(_ userInfo: [AnyHashable : Any], accountID: String, feedID: String, articleID: String) -> Bool { guard let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable], let sidebarItemID = SidebarItemIdentifier(userInfo: feedIdentifierUserInfo), @@ -2255,7 +2255,7 @@ private extension SceneCoordinator { treeControllerDelegate.addFilterException(sidebarItemID) } return found - + case .feed: let found = selectFeedAndArticle(sidebarItemID: sidebarItemID, articleID: articleID, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY) if found { @@ -2265,11 +2265,11 @@ private extension SceneCoordinator { } } return found - + } - + } - + func findAccountNode(accountID: String, accountName: String? = nil) -> Node? { if let node = treeController.rootNode.descendantNode(where: { ($0.representedObject as? Account)?.accountID == accountID }) { return node @@ -2281,7 +2281,7 @@ private extension SceneCoordinator { return nil } - + func findFolderNode(folderName: String, beginningAt startingNode: Node) -> Node? { if let node = startingNode.descendantNode(where: { ($0.representedObject as? Folder)?.nameForDisplay == folderName }) { return node @@ -2295,16 +2295,16 @@ private extension SceneCoordinator { } return nil } - + func selectFeedAndArticle(sidebarItemID: SidebarItemIdentifier, articleID: String, isShowingExtractedArticle: Bool, articleWindowScrollY: Int) -> Bool { guard let feedNode = nodeFor(sidebarItemID: sidebarItemID), let feedIndexPath = indexPathFor(feedNode) else { return false } selectFeed(indexPath: feedIndexPath) { self.selectArticleInCurrentFeed(articleID, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY) } - + return true } - + } diff --git a/iOS/SceneDelegate.swift b/iOS/SceneDelegate.swift index a7160b8f6..57ea9ac8b 100644 --- a/iOS/SceneDelegate.swift +++ b/iOS/SceneDelegate.swift @@ -11,16 +11,16 @@ import UserNotifications import Account final class SceneDelegate: UIResponder, UIWindowSceneDelegate { - + var window: UIWindow? var coordinator: SceneCoordinator! - + // UIWindowScene delegate - + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - + window!.tintColor = AppAssets.primaryAccentColor - + let rootViewController = window!.rootViewController as! RootSplitViewController rootViewController.presentsWithGesture = true rootViewController.showsSecondaryOnlyButton = true @@ -36,7 +36,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { coordinator = SceneCoordinator(rootSplitViewController: rootViewController) rootViewController.coordinator = coordinator rootViewController.delegate = coordinator - + coordinator.restoreWindowState(session.stateRestorationActivity) updateUserInterfaceStyle() @@ -47,34 +47,34 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.scene(scene, openURLContexts: connectionOptions.urlContexts) return } - + if let shortcutItem = connectionOptions.shortcutItem { handleShortcutItem(shortcutItem) return } - + if let notificationResponse = connectionOptions.notificationResponse { coordinator.handle(notificationResponse) return } - + if let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity { coordinator.handle(userActivity) } } - + func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { appDelegate.resumeDatabaseProcessingIfNecessary() handleShortcutItem(shortcutItem) completionHandler(true) } - + func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { appDelegate.resumeDatabaseProcessingIfNecessary() coordinator.handle(userActivity) } - + func sceneDidEnterBackground(_ scene: UIScene) { ArticleStringFormatter.emptyCaches() appDelegate.prepareAccountsForBackground() @@ -85,39 +85,39 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { appDelegate.prepareAccountsForForeground() coordinator.resetFocus() } - + func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { return coordinator.stateRestorationActivity } - + // API - + func handle(_ response: UNNotificationResponse) { appDelegate.resumeDatabaseProcessingIfNecessary() coordinator.handle(response) } - + func suspend() { coordinator.suspend() } - + func cleanUp(conditional: Bool) { coordinator.cleanUp(conditional: conditional) } - + // Handle Opening of URLs - + func scene(_ scene: UIScene, openURLContexts urlContexts: Set) { guard let context = urlContexts.first else { return } - + DispatchQueue.main.async { - + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.coordinator.dismissIfLaunchingFromExternalAction() } - + let urlString = context.url.absoluteString - + // Handle the feed: and feeds: schemes if urlString.starts(with: "feed:") || urlString.starts(with: "feeds:") { let normalizedURLString = urlString.normalizedURL @@ -125,7 +125,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.coordinator.showAddFeed(initialFeed: normalizedURLString, initialFeedName: nil) } } - + // Show Unread View or Article if urlString.contains(WidgetDeepLink.unread.url.absoluteString) { guard let comps = URLComponents(string: urlString ) else { return } @@ -141,7 +141,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.coordinator.selectAllUnreadFeed() } } - + // Show Today View or Article if urlString.contains(WidgetDeepLink.today.url.absoluteString) { guard let comps = URLComponents(string: urlString ) else { return } @@ -157,7 +157,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.coordinator.selectTodayFeed() } } - + // Show Starred View or Article if urlString.contains(WidgetDeepLink.starred.url.absoluteString) { guard let comps = URLComponents(string: urlString ) else { return } @@ -173,31 +173,31 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.coordinator.selectStarredFeed() } } - + let filename = context.url.standardizedFileURL.path if filename.hasSuffix(ArticleTheme.nnwThemeSuffix) { self.coordinator.importTheme(filename: filename) return } - + // Handle theme URLs: netnewswire://theme/add?url={url} guard let comps = URLComponents(url: context.url, resolvingAgainstBaseURL: false), "theme" == comps.host, let queryItems = comps.queryItems else { 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, response, error in guard let location = location else { return } - + do { try ArticleThemeDownloader.shared.handleFile(at: location) } catch { @@ -212,14 +212,14 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { } else { return } - - + + } } } private extension SceneDelegate { - + func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) { switch shortcutItem.type { case "com.ranchero.NetNewsWire.FirstUnread": diff --git a/iOS/Settings/AboutViewController.swift b/iOS/Settings/AboutViewController.swift index f8ee4334f..44486580e 100644 --- a/iOS/Settings/AboutViewController.swift +++ b/iOS/Settings/AboutViewController.swift @@ -15,11 +15,11 @@ final class AboutViewController: UITableViewController { @IBOutlet weak var acknowledgmentsTextView: UITextView! @IBOutlet weak var thanksTextView: UITextView! @IBOutlet weak var dedicationTextView: UITextView! - + override func viewDidLoad() { - + super.viewDidLoad() - + configureCell(file: "About", textView: aboutTextView) configureCell(file: "Credits", textView: creditsTextView) configureCell(file: "Thanks", textView: thanksTextView) @@ -32,7 +32,7 @@ final class AboutViewController: UITableViewController { buildLabel.numberOfLines = 0 buildLabel.sizeToFit() buildLabel.translatesAutoresizingMaskIntoConstraints = false - + let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0)) wrapperView.translatesAutoresizingMaskIntoConstraints = false wrapperView.addSubview(buildLabel) @@ -42,11 +42,11 @@ final class AboutViewController: UITableViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } - + } private extension AboutViewController { - + func configureCell(file: String, textView: UITextView) { let url = Bundle.main.url(forResource: file, withExtension: "rtf")! let string = try! NSAttributedString(url: url, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) @@ -55,5 +55,5 @@ private extension AboutViewController { textView.adjustsFontForContentSizeCategory = true textView.font = .preferredFont(forTextStyle: .body) } - + } diff --git a/iOS/Settings/AddAccountViewController.swift b/iOS/Settings/AddAccountViewController.swift index 1f73fac29..3cd80df61 100644 --- a/iOS/Settings/AddAccountViewController.swift +++ b/iOS/Settings/AddAccountViewController.swift @@ -21,7 +21,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe case icloud case web case selfhosted - + var sectionHeader: String { switch self { case .local: @@ -34,7 +34,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe return NSLocalizedString("Self-hosted", comment: "Self hosted Account") } } - + var sectionFooter: String { switch self { case .local: @@ -47,7 +47,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe return NSLocalizedString("Self-hosted accounts sync your feeds across all your devices", comment: "Self hosted Account") } } - + var sectionContent: [AccountType] { switch self { case .local: @@ -65,7 +65,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe } } } - + override func viewDidLoad() { super.viewDidLoad() } @@ -73,27 +73,27 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe override func numberOfSections(in tableView: UITableView) -> Int { return AddAccountSections.allCases.count } - + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == AddAccountSections.local.rawValue { return AddAccountSections.local.sectionContent.count } - + if section == AddAccountSections.icloud.rawValue { return AddAccountSections.icloud.sectionContent.count } - + if section == AddAccountSections.web.rawValue { return AddAccountSections.web.sectionContent.count } - + if section == AddAccountSections.selfhosted.rawValue { return AddAccountSections.selfhosted.sectionContent.count } return 0 } - + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case AddAccountSections.local.rawValue: @@ -108,7 +108,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe return nil } } - + override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch section { case AddAccountSections.local.rawValue: @@ -123,10 +123,10 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe return nil } } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsAccountTableViewCell", for: indexPath) as! SettingsComboTableViewCell - + switch indexPath.section { case AddAccountSections.local.rawValue: cell.comboNameLabel?.text = AddAccountSections.local.sectionContent[indexPath.row].localizedAccountName() @@ -149,15 +149,15 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe case AddAccountSections.selfhosted.rawValue: cell.comboNameLabel?.text = AddAccountSections.selfhosted.sectionContent[indexPath.row].localizedAccountName() cell.comboImage?.image = AppAssets.image(for: AddAccountSections.selfhosted.sectionContent[indexPath.row]) - + default: return cell } return cell } - + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - + switch indexPath.section { case AddAccountSections.local.rawValue: let type = AddAccountSections.local.sectionContent[indexPath.row] @@ -175,7 +175,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe return } } - + private func presentController(for accountType: AccountType) { switch accountType { case .onMyMac: @@ -216,15 +216,15 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe present(navController, animated: true) } } - + func dismiss() { navigationController?.popViewController(animated: false) } - + } extension AddAccountViewController: OAuthAccountAuthorizationOperationDelegate { - + func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) { let rootViewController = view.window?.rootViewController @@ -241,7 +241,7 @@ extension AddAccountViewController: OAuthAccountAuthorizationOperationDelegate { dismiss() } - + func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) { presentError(error) } diff --git a/iOS/Settings/ArticleThemeImporter.swift b/iOS/Settings/ArticleThemeImporter.swift index b1f554ae3..bf38e59f1 100644 --- a/iOS/Settings/ArticleThemeImporter.swift +++ b/iOS/Settings/ArticleThemeImporter.swift @@ -9,7 +9,7 @@ import UIKit struct ArticleThemeImporter { - + static func importTheme(controller: UIViewController, url: URL) throws { let theme = try ArticleTheme(url: url, isAppTheme: false) @@ -20,10 +20,10 @@ struct ArticleThemeImporter { let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, theme.creatorHomePage) as String let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) - + if let websiteURL = URL(string: theme.creatorHomePage) { let visitSiteTitle = NSLocalizedString("Show Website", comment: "Show Website") let visitSiteAction = UIAlertAction(title: visitSiteTitle, style: .default) { action in @@ -71,32 +71,32 @@ struct ArticleThemeImporter { } else { importTheme() } - + } - + alertController.addAction(installThemeAction) alertController.preferredAction = installThemeAction controller.present(alertController, animated: true) } - + } private extension ArticleThemeImporter { - + static func confirmImportSuccess(controller: UIViewController, themeName: String) { let title = NSLocalizedString("Theme installed", comment: "Theme installed") - + let localizedMessageText = NSLocalizedString("The theme “%@” has been installed.", comment: "Theme installed") let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, themeName) as String let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - + let doneTitle = NSLocalizedString("Done", comment: "Done") alertController.addAction(UIAlertAction(title: doneTitle, style: .default)) - + controller.present(alertController, animated: true) } - + } diff --git a/iOS/Settings/ArticleThemesTableViewController.swift b/iOS/Settings/ArticleThemesTableViewController.swift index 24a17ac01..241ac229e 100644 --- a/iOS/Settings/ArticleThemesTableViewController.swift +++ b/iOS/Settings/ArticleThemesTableViewController.swift @@ -20,12 +20,12 @@ final class ArticleThemesTableViewController: UITableViewController { let importBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(importTheme(_:))); importBarButtonItem.title = NSLocalizedString("Import Theme", comment: "Import Theme"); navigationItem.rightBarButtonItem = importBarButtonItem - + NotificationCenter.default.addObserver(self, selector: #selector(articleThemeNamesDidChangeNotification(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil) } - + // MARK: Notifications - + @objc func articleThemeNamesDidChangeNotification(_ note: Notification) { tableView.reloadData() } @@ -49,21 +49,21 @@ final class ArticleThemesTableViewController: UITableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) - + let themeName: String if indexPath.row == 0 { themeName = ArticleTheme.defaultTheme.name } else { themeName = ArticleThemesManager.shared.themeNames[indexPath.row - 1] } - + cell.textLabel?.text = themeName if themeName == ArticleThemesManager.shared.currentTheme.name { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } - + return cell } @@ -82,12 +82,12 @@ final class ArticleThemesTableViewController: UITableViewController { let deleteTitle = NSLocalizedString("Delete", comment: "Delete") let deleteAction = UIContextualAction(style: .normal, title: deleteTitle) { [weak self] (action, view, completion) in let title = NSLocalizedString("Delete Theme?", comment: "Delete Theme") - + let localizedMessageText = NSLocalizedString("Are you sure you want to delete the theme “%@”?.", comment: "Delete Theme Message") let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, themeName) as String let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - + let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { action in completion(true) @@ -100,13 +100,13 @@ final class ArticleThemesTableViewController: UITableViewController { completion(true) } alertController.addAction(deleteAction) - + self?.present(alertController, animated: true) } - + deleteAction.image = AppAssets.trashImage deleteAction.backgroundColor = UIColor.systemRed - + return UISwipeActionsConfiguration(actions: [deleteAction]) } } @@ -114,12 +114,12 @@ final class ArticleThemesTableViewController: UITableViewController { // MARK: UIDocumentPickerDelegate extension ArticleThemesTableViewController: UIDocumentPickerDelegate { - + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let url = urls.first else { return } if url.startAccessingSecurityScopedResource() { - + defer { url.stopAccessingSecurityScopedResource() } diff --git a/iOS/Settings/ModernTimelineCustomizerTableViewController.swift b/iOS/Settings/ModernTimelineCustomizerTableViewController.swift index a76320a9e..82bc23db2 100644 --- a/iOS/Settings/ModernTimelineCustomizerTableViewController.swift +++ b/iOS/Settings/ModernTimelineCustomizerTableViewController.swift @@ -11,7 +11,7 @@ import Articles class ModernTimelineCustomizerTableViewController: UITableViewController { - + private var previewArticle: Article { var components = DateComponents() components.year = 1925 @@ -20,7 +20,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { let calendar = Calendar.current let date = calendar.date(from: components)! - + return Article(accountID: "_testID", articleID: "_testArticleID", feedID: "_testFeedID", @@ -38,16 +38,16 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { authors: Set([Author(authorID: "_testAuthorID", name: "F. Scott Fitzgerald", url: nil, avatarURL: nil, emailAddress: nil)!]), status: ArticleStatus(articleID: "_testArticleID", read: false, starred: false, dateArrived: .now)) } - - + + override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Timeline Customizer", comment: "Timeline Customizer") NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) - + } - + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { tableView.reloadSections(IndexSet(integer: 2), with: .fade) } @@ -61,7 +61,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } - + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("Icon Size", comment: "Icon Size")} if section == 1 { return NSLocalizedString("Number of Lines", comment: "Number of Lines")} @@ -70,21 +70,21 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { return nil } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "IconSizeCell") as! ModernTimelineSliderCell cell.sliderConfiguration = .iconSize return cell } - + if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "NumberOfLinesCell") as! ModernTimelineSliderCell cell.sliderConfiguration = .numberOfLines return cell } - - + + if indexPath.section == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "MainTimelineIconFeedCell") as? MainTimelineIconFeedCell ?? MainTimelineIconFeedCell() cell.cellData = MainTimelineCellData(article: previewArticle, @@ -98,7 +98,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { cell.isPreview = true return cell } - + if indexPath.section == 3 { let cell = tableView.dequeueReusableCell(withIdentifier: "MainTimelineFeedCell") as? MainTimelineFeedCell ?? MainTimelineFeedCell() cell.cellData = MainTimelineCellData(article: previewArticle, @@ -112,11 +112,11 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { cell.isPreview = true return cell } - + return UITableViewCell() - + } - + override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return nil } @@ -124,7 +124,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } - + // MARK: - Notifications @objc func userDefaultsDidChange(_ note: Notification) { tableView.reloadSections(IndexSet(integersIn: 2...3), with: .none) diff --git a/iOS/Settings/ModernTimelineSliderCell.swift b/iOS/Settings/ModernTimelineSliderCell.swift index 33ce5c6e7..c39d21e34 100644 --- a/iOS/Settings/ModernTimelineSliderCell.swift +++ b/iOS/Settings/ModernTimelineSliderCell.swift @@ -14,35 +14,35 @@ enum SliderConfiguration { } class ModernTimelineSliderCell: UITableViewCell { - - + + @IBOutlet weak var slider: UISlider! - + private let container = UIView() - - + + override func awakeFromNib() { super.awakeFromNib() setup() } - + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } - + required init?(coder: NSCoder) { super.init(coder: coder) setup() } - + private func setup() { container.layer.cornerRadius = contentView.frame.height/2 container.backgroundColor = .systemBackground container.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(container) contentView.sendSubviewToBack(container) - + NSLayoutConstraint.activate([ container.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), container.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0), @@ -51,7 +51,7 @@ class ModernTimelineSliderCell: UITableViewCell { ]) contentView.backgroundColor = .systemGroupedBackground } - + var sliderConfiguration: SliderConfiguration! { didSet { switch sliderConfiguration { @@ -70,14 +70,14 @@ class ModernTimelineSliderCell: UITableViewCell { } } } - - + + override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) - + // Configure the view for the selected state } - + @IBAction func sliderValueChanges(_ sender: Any) { switch sliderConfiguration { case .numberOfLines: @@ -89,5 +89,5 @@ class ModernTimelineSliderCell: UITableViewCell { return } } - + } diff --git a/iOS/Settings/SettingsComboTableViewCell.swift b/iOS/Settings/SettingsComboTableViewCell.swift index 3cd329651..df99d19ef 100644 --- a/iOS/Settings/SettingsComboTableViewCell.swift +++ b/iOS/Settings/SettingsComboTableViewCell.swift @@ -16,7 +16,7 @@ final class SettingsComboTableViewCell: VibrantTableViewCell { override func updateVibrancy(animated: Bool) { super.updateVibrancy(animated: animated) updateLabelVibrancy(comboNameLabel, color: labelColor, animated: animated) - + let tintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label if animated { UIView.animate(withDuration: Self.duration) { @@ -26,5 +26,5 @@ final class SettingsComboTableViewCell: VibrantTableViewCell { self.comboImage?.tintColor = tintColor } } - + } diff --git a/iOS/Settings/SettingsViewController.swift b/iOS/Settings/SettingsViewController.swift index 53dc5a59c..89f8211e8 100644 --- a/iOS/Settings/SettingsViewController.swift +++ b/iOS/Settings/SettingsViewController.swift @@ -16,7 +16,7 @@ import UniformTypeIdentifiers final class SettingsViewController: UITableViewController { private weak var opmlAccount: Account? - + @IBOutlet weak var timelineSortOrderSwitch: UISwitch! @IBOutlet weak var groupByFeedSwitch: UISwitch! @IBOutlet weak var refreshClearsReadArticlesSwitch: UISwitch! @@ -26,10 +26,10 @@ final class SettingsViewController: UITableViewController { @IBOutlet weak var colorPaletteDetailLabel: UILabel! @IBOutlet weak var openLinksInNetNewsWire: UISwitch! @IBOutlet weak var enableJavaScriptSwitch: UISwitch! - + var scrollToArticlesSection = false weak var presentingParentController: UIViewController? - + override func viewDidLoad() { // This hack mostly works around a bug in static tables with dynamic type. See: https://spin.atomicobject.com/2018/10/15/dynamic-type-static-uitableview/ NotificationCenter.default.removeObserver(tableView!, name: UIContentSizeCategory.didChangeNotification, object: nil) @@ -41,14 +41,14 @@ final class SettingsViewController: UITableViewController { tableView.register(UINib(nibName: "SettingsComboTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsComboTableViewCell") tableView.register(UINib(nibName: "SettingsTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsTableViewCell") - + tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 } - + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) - + if AppDefaults.shared.timelineSortDirection == .orderedAscending { timelineSortOrderSwitch.isOn = true } else { @@ -67,7 +67,7 @@ final class SettingsViewController: UITableViewController { refreshClearsReadArticlesSwitch.isOn = false } - + articleThemeDetailLabel.text = ArticleThemesManager.shared.currentTheme.name if AppDefaults.shared.confirmMarkAllAsRead { @@ -81,17 +81,17 @@ final class SettingsViewController: UITableViewController { } else { showFullscreenArticlesSwitch.isOn = false } - + if AppDefaults.shared.isArticleContentJavascriptEnabled { enableJavaScriptSwitch.isOn = true } else { enableJavaScriptSwitch.isOn = false } - + colorPaletteDetailLabel.text = String(describing: AppDefaults.userInterfaceColorPalette) - + openLinksInNetNewsWire.isOn = !AppDefaults.shared.useSystemBrowser - + let buildLabel = NonIntrinsicLabel(frame: CGRect(x: 32.0, y: 0.0, width: 0.0, height: 0.0)) buildLabel.font = UIFont.systemFont(ofSize: 11.0) @@ -99,27 +99,27 @@ final class SettingsViewController: UITableViewController { buildLabel.text = "\(Bundle.main.appName) \(Bundle.main.versionNumber) (Build \(Bundle.main.buildNumber))" buildLabel.sizeToFit() buildLabel.translatesAutoresizingMaskIntoConstraints = false - + let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0)) wrapperView.translatesAutoresizingMaskIntoConstraints = false wrapperView.addSubview(buildLabel) tableView.tableFooterView = wrapperView } - + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.tableView.selectRow(at: nil, animated: true, scrollPosition: .none) - + if scrollToArticlesSection { tableView.scrollToRow(at: IndexPath(row: 0, section: 4), at: .top, animated: true) scrollToArticlesSection = false } } - + // MARK: UITableView - + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { @@ -244,7 +244,7 @@ final class SettingsViewController: UITableViewController { override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return false } - + override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } @@ -252,21 +252,21 @@ final class SettingsViewController: UITableViewController { override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } - + override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } - + override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { return super.tableView(tableView, indentationLevelForRowAt: IndexPath(row: 0, section: 1)) } - + // MARK: Actions - + @IBAction func done(_ sender: Any) { dismiss(animated: true) } - + @IBAction func switchTimelineOrder(_ sender: Any) { if timelineSortOrderSwitch.isOn { AppDefaults.shared.timelineSortDirection = .orderedAscending @@ -274,7 +274,7 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.timelineSortDirection = .orderedDescending } } - + @IBAction func switchGroupByFeed(_ sender: Any) { if groupByFeedSwitch.isOn { AppDefaults.shared.timelineGroupByFeed = true @@ -282,7 +282,7 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.timelineGroupByFeed = false } } - + @IBAction func switchClearsReadArticles(_ sender: Any) { if refreshClearsReadArticlesSwitch.isOn { AppDefaults.shared.refreshClearsReadArticles = true @@ -290,7 +290,7 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.refreshClearsReadArticles = false } } - + @IBAction func switchConfirmMarkAllAsRead(_ sender: Any) { if confirmMarkAllAsReadSwitch.isOn { AppDefaults.shared.confirmMarkAllAsRead = true @@ -298,7 +298,7 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.confirmMarkAllAsRead = false } } - + @IBAction func switchFullscreenArticles(_ sender: Any) { if showFullscreenArticlesSwitch.isOn { AppDefaults.shared.articleFullscreenAvailable = true @@ -306,7 +306,7 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.articleFullscreenAvailable = false } } - + @IBAction func switchBrowserPreference(_ sender: Any) { if openLinksInNetNewsWire.isOn { AppDefaults.shared.useSystemBrowser = false @@ -314,18 +314,18 @@ final class SettingsViewController: UITableViewController { AppDefaults.shared.useSystemBrowser = true } } - + @IBAction func switchJavaScriptPreference(_ sender: Any) { AppDefaults.shared.isArticleContentJavascriptEnabled = enableJavaScriptSwitch.isOn } - - + + // MARK: Notifications - + @objc func contentSizeCategoryDidChange() { tableView.reloadData() } - + @objc func accountsDidChange() { tableView.reloadData() } @@ -333,17 +333,17 @@ final class SettingsViewController: UITableViewController { @objc func displayNameDidChange() { tableView.reloadData() } - + @objc func browserPreferenceDidChange() { tableView.reloadData() } - + } // MARK: OPML Document Picker extension SettingsViewController: UIDocumentPickerDelegate { - + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { for url in urls { opmlAccount?.importOPML(url) { result in @@ -358,13 +358,13 @@ extension SettingsViewController: UIDocumentPickerDelegate { } } } - + } // MARK: Private private extension SettingsViewController { - + func addFeed() { self.dismiss(animated: true) @@ -374,10 +374,10 @@ private extension SettingsViewController { addViewController.initialFeedName = NSLocalizedString("NetNewsWire News", comment: "NetNewsWire News") addNavViewController.modalPresentationStyle = .formSheet addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay - + presentingParentController?.present(addNavViewController, animated: true) } - + func importOPML(sourceView: UIView, sourceRect: CGRect) { switch AccountManager.shared.activeAccounts.count { case 0: @@ -389,11 +389,11 @@ private extension SettingsViewController { importOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect) } } - + func importOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) { let title = NSLocalizedString("Choose an account to receive the imported feeds and folders", comment: "Import Account") let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) - + if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view popoverController.sourceRect = sourceRect @@ -412,15 +412,15 @@ private extension SettingsViewController { self.present(alert, animated: true) } - + func importOPMLDocumentPicker() { - + let docPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.opml, UTType.xml], asCopy: true) docPicker.delegate = self docPicker.modalPresentationStyle = .formSheet self.present(docPicker, animated: true) } - + func exportOPML(sourceView: UIView, sourceRect: CGRect) { if AccountManager.shared.accounts.count == 1 { opmlAccount = AccountManager.shared.accounts.first! @@ -429,11 +429,11 @@ private extension SettingsViewController { exportOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect) } } - + func exportOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) { let title = NSLocalizedString("Choose an account with the subscriptions to export", comment: "Export Account") let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) - + if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view popoverController.sourceRect = sourceRect @@ -452,10 +452,10 @@ private extension SettingsViewController { self.present(alert, animated: true) } - + func exportOPMLDocumentPicker() { guard let account = opmlAccount else { return } - + let accountName = account.nameForDisplay.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespaces) let filename = "Subscriptions-\(accountName).opml" let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent(filename) @@ -465,12 +465,12 @@ private extension SettingsViewController { } catch { self.presentError(title: "OPML Export Error", message: error.localizedDescription) } - + let docPicker = UIDocumentPickerViewController(forExporting: [tempFile]) docPicker.modalPresentationStyle = .formSheet self.present(docPicker, animated: true) } - + func openURL(_ urlString: String) { let vc = SFSafariViewController(url: URL(string: urlString)!) vc.modalPresentationStyle = .pageSheet diff --git a/iOS/ShareExtension/ShareFolderPickerCell.swift b/iOS/ShareExtension/ShareFolderPickerCell.swift index f007809e7..dea7d8484 100644 --- a/iOS/ShareExtension/ShareFolderPickerCell.swift +++ b/iOS/ShareExtension/ShareFolderPickerCell.swift @@ -9,7 +9,7 @@ import UIKit final class ShareFolderPickerCell: UITableViewCell { - + @IBOutlet weak var icon: UIImageView! @IBOutlet weak var label: UILabel! } diff --git a/iOS/ShareExtension/ShareFolderPickerController.swift b/iOS/ShareExtension/ShareFolderPickerController.swift index dd0672ca0..83a4751f1 100644 --- a/iOS/ShareExtension/ShareFolderPickerController.swift +++ b/iOS/ShareExtension/ShareFolderPickerController.swift @@ -20,13 +20,13 @@ final class ShareFolderPickerController: UITableViewController { var selectedContainerID: ContainerIdentifier? weak var delegate: ShareFolderPickerControllerDelegate? - + override func viewDidLoad() { tableView.register(UINib(nibName: "ShareFolderPickerAccountCell", bundle: Bundle.main), forCellReuseIdentifier: "AccountCell") tableView.register(UINib(nibName: "ShareFolderPickerFolderCell", bundle: Bundle.main), forCellReuseIdentifier: "FolderCell") - + } - + override func numberOfSections(in tableView: UITableView) -> Int { return 1 } @@ -34,7 +34,7 @@ final class ShareFolderPickerController: UITableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return containers?.count ?? 0 } - + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let container = containers?[indexPath.row] let cell: ShareFolderPickerCell = { @@ -44,7 +44,7 @@ final class ShareFolderPickerController: UITableViewController { return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! ShareFolderPickerCell } }() - + if let account = container as? ExtensionAccount { cell.icon.image = AppAssets.image(for: account.type) } else { @@ -58,13 +58,13 @@ final class ShareFolderPickerController: UITableViewController { } else { cell.accessoryType = .none } - + return cell } - + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let container = containers?[indexPath.row] else { return } - + if let account = container as? ExtensionAccount, account.disallowFeedInRootFolder { tableView.selectRow(at: nil, animated: false, scrollPosition: .none) } else { @@ -73,5 +73,5 @@ final class ShareFolderPickerController: UITableViewController { delegate?.shareFolderPickerDidSelect(container) } } - + } diff --git a/iOS/ShareExtension/ShareViewController.swift b/iOS/ShareExtension/ShareViewController.swift index 4bcd04788..250d987b4 100644 --- a/iOS/ShareExtension/ShareViewController.swift +++ b/iOS/ShareExtension/ShareViewController.swift @@ -15,15 +15,15 @@ import RSTree import UniformTypeIdentifiers final class ShareViewController: SLComposeServiceViewController, ShareFolderPickerControllerDelegate { - + private var url: URL? private var extensionContainers: ExtensionContainers? private var flattenedContainers: [ExtensionContainer]! private var selectedContainer: ExtensionContainer? private var folderItem: SLComposeSheetConfigurationItem! - + override func viewDidLoad() { - + extensionContainers = ExtensionContainersFile.read() flattenedContainers = extensionContainers?.flattened ?? [ExtensionContainer]() if let extensionContainers = extensionContainers { @@ -92,15 +92,15 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick return }) } - + // Reddit in particular doesn't pass the URL correctly and instead puts it in the contentText url = URL(string: contentText) } - + override func isContentValid() -> Bool { return url != nil && selectedContainer != nil } - + override func didSelectPost() { guard let url = url, let selectedContainer = selectedContainer, let containerID = selectedContainer.containerID else { self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) @@ -111,13 +111,13 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick if !contentText.mayBeURL { name = contentText.isEmpty ? nil : contentText } - + let request = ExtensionFeedAddRequest(name: name, feedURL: url, destinationContainerID: containerID) ExtensionFeedAddRequestFile.save(request) - + self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } - + func shareFolderPickerDidSelect(_ container: ExtensionContainer) { ShareDefaultContainer.saveDefaultContainer(container) self.selectedContainer = container @@ -126,37 +126,37 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick } 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 ?? "" - + folderItem = SLComposeSheetConfigurationItem() folderItem.title = "Folder" updateFolderItemValue() - + folderItem.tapHandler = { - + let folderPickerController = ShareFolderPickerController() - + folderPickerController.navigationController?.title = NSLocalizedString("Folder", comment: "Folder") folderPickerController.delegate = self folderPickerController.containers = self.flattenedContainers folderPickerController.selectedContainerID = self.selectedContainer?.containerID - + self.pushConfigurationViewController(folderPickerController) - + } - + return [folderItem!, urlItem] - + } - + } private extension ShareViewController { - + func updateFolderItemValue() { if let account = selectedContainer as? ExtensionAccount { self.folderItem.value = account.name @@ -164,5 +164,5 @@ private extension ShareViewController { self.folderItem.value = "\(folder.accountName) / \(folder.name)" } } - + } diff --git a/iOS/TitleActivityItemSource.swift b/iOS/TitleActivityItemSource.swift index e34627e8e..25aab7ce2 100644 --- a/iOS/TitleActivityItemSource.swift +++ b/iOS/TitleActivityItemSource.swift @@ -35,5 +35,5 @@ final class TitleActivityItemSource: NSObject, UIActivityItemSource { return NSNull() } } - + } diff --git a/iOS/UIKit Extensions/Animations.swift b/iOS/UIKit Extensions/Animations.swift index 258b173c3..18b256f7a 100644 --- a/iOS/UIKit Extensions/Animations.swift +++ b/iOS/UIKit Extensions/Animations.swift @@ -10,16 +10,16 @@ import Foundation /// Used to select which animations should be performed public struct Animations: OptionSet { - + /// Selections and deselections will be animated. public static let select = Animations(rawValue: 1) - + /// Scrolling will be animated public static let scroll = Animations(rawValue: 2) - + /// Pushing and popping navigation view controllers will be animated public static let navigation = Animations(rawValue: 4) - + public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue diff --git a/iOS/UIKit Extensions/Array-Extensions.swift b/iOS/UIKit Extensions/Array-Extensions.swift index 9a4710680..7a9b0f3d0 100644 --- a/iOS/UIKit Extensions/Array-Extensions.swift +++ b/iOS/UIKit Extensions/Array-Extensions.swift @@ -9,12 +9,12 @@ import UIKit extension Array where Element == CGRect { - + func maxY() -> CGFloat { - + var y: CGFloat = 0.0 self.forEach { y = Swift.max(y, $0.maxY) } return y } - + } diff --git a/iOS/UIKit Extensions/Bundle-Extensions.swift b/iOS/UIKit Extensions/Bundle-Extensions.swift index 54b955620..533965428 100644 --- a/iOS/UIKit Extensions/Bundle-Extensions.swift +++ b/iOS/UIKit Extensions/Bundle-Extensions.swift @@ -9,17 +9,17 @@ import Foundation extension Bundle { - + var appName: String { return infoDictionary?["CFBundleName"] as! String } - + var versionNumber: String { return infoDictionary?["CFBundleShortVersionString"] as! String } - + var buildNumber: String { return infoDictionary?["CFBundleVersion"] as! String } - + } diff --git a/iOS/UIKit Extensions/CroppingPreviewParameters.swift b/iOS/UIKit Extensions/CroppingPreviewParameters.swift index 81153b138..6e42b2c18 100644 --- a/iOS/UIKit Extensions/CroppingPreviewParameters.swift +++ b/iOS/UIKit Extensions/CroppingPreviewParameters.swift @@ -9,11 +9,11 @@ import UIKit final class CroppingPreviewParameters: UIPreviewParameters { - + override init() { super.init() } - + init(view: UIView) { super.init() let newBounds = CGRect(x: 1, y: 1, width: view.bounds.width - 2, height: view.bounds.height - 2) diff --git a/iOS/UIKit Extensions/ImageHeaderView.swift b/iOS/UIKit Extensions/ImageHeaderView.swift index 82157e045..3efca8420 100644 --- a/iOS/UIKit Extensions/ImageHeaderView.swift +++ b/iOS/UIKit Extensions/ImageHeaderView.swift @@ -11,19 +11,19 @@ import UIKit final class ImageHeaderView: UITableViewHeaderFooterView { static let rowHeight = CGFloat(integerLiteral: 88) - + var imageView = UIImageView() - + override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } - + func commonInit() { imageView.tintColor = UIColor.label imageView.contentMode = .scaleAspectFit diff --git a/iOS/UIKit Extensions/ModalNavigationController.swift b/iOS/UIKit Extensions/ModalNavigationController.swift index 52dcb9570..edaf85b42 100644 --- a/iOS/UIKit Extensions/ModalNavigationController.swift +++ b/iOS/UIKit Extensions/ModalNavigationController.swift @@ -12,10 +12,10 @@ final class ModalNavigationController: UINavigationController { override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() - + // This hack is to resolve https://github.com/brentsimmons/NetNewsWire/issues/1301 let frame = navigationBar.frame navigationBar.frame = CGRect(x: frame.minX, y: frame.minY, width: frame.size.width, height: 64.0) } - + } diff --git a/iOS/UIKit Extensions/NonIntrinsicLabel.swift b/iOS/UIKit Extensions/NonIntrinsicLabel.swift index 8d1f43b54..532ffe101 100644 --- a/iOS/UIKit Extensions/NonIntrinsicLabel.swift +++ b/iOS/UIKit Extensions/NonIntrinsicLabel.swift @@ -14,5 +14,5 @@ final class NonIntrinsicLabel: UILabel { override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) } - + } diff --git a/iOS/UIKit Extensions/PoppableGestureRecognizerDelegate.swift b/iOS/UIKit Extensions/PoppableGestureRecognizerDelegate.swift index 2906290bd..5356944de 100644 --- a/iOS/UIKit Extensions/PoppableGestureRecognizerDelegate.swift +++ b/iOS/UIKit Extensions/PoppableGestureRecognizerDelegate.swift @@ -10,7 +10,7 @@ import UIKit final class PoppableGestureRecognizerDelegate: NSObject, UIGestureRecognizerDelegate { - + weak var navigationController: UINavigationController? func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { @@ -20,12 +20,12 @@ final class PoppableGestureRecognizerDelegate: NSObject, UIGestureRecognizerDele func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } - + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer is UIPanGestureRecognizer { return true } return false } - + } diff --git a/iOS/UIKit Extensions/String-Extensions.swift b/iOS/UIKit Extensions/String-Extensions.swift index 538cd92eb..a1a4bf6c9 100644 --- a/iOS/UIKit Extensions/String-Extensions.swift +++ b/iOS/UIKit Extensions/String-Extensions.swift @@ -9,17 +9,17 @@ import UIKit extension String { - + func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil) return ceil(boundingBox.height) } - + func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil) return ceil(boundingBox.width) } - + } diff --git a/iOS/UIKit Extensions/TickMarkSlider.swift b/iOS/UIKit Extensions/TickMarkSlider.swift index 59a5585c5..91f023061 100644 --- a/iOS/UIKit Extensions/TickMarkSlider.swift +++ b/iOS/UIKit Extensions/TickMarkSlider.swift @@ -13,7 +13,7 @@ final class TickMarkSlider: UISlider { private var enableFeedback = false private let feedbackGenerator = UISelectionFeedbackGenerator() - + private var roundedValue: Float? override var value: Float { didSet { @@ -24,17 +24,17 @@ final class TickMarkSlider: UISlider { } } } - + func addTickMarks() { enableFeedback = true - + let numberOfGaps = Int(maximumValue) - Int(minimumValue) - + var gapLayoutGuides = [UILayoutGuide]() - + for i in 0...numberOfGaps { - + let tick = UIView() tick.translatesAutoresizingMaskIntoConstraints = false tick.backgroundColor = AppAssets.tickMarkColor @@ -47,11 +47,11 @@ final class TickMarkSlider: UISlider { if i == 0 { tick.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true } - + if let lastGapLayoutGuild = gapLayoutGuides.last { lastGapLayoutGuild.trailingAnchor.constraint(equalTo: tick.leadingAnchor).isActive = true } - + if i != numberOfGaps { let gapLayoutGuild = UILayoutGuide() gapLayoutGuides.append(gapLayoutGuild) @@ -60,17 +60,17 @@ final class TickMarkSlider: UISlider { } else { tick.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true } - + } - + if let firstGapLayoutGuild = gapLayoutGuides.first { for i in 1.. Bool { let result = super.continueTracking(touch, with: event) value = value.rounded() @@ -80,5 +80,5 @@ final class TickMarkSlider: UISlider { override func endTracking(_ touch: UITouch?, with event: UIEvent?) { value = value.rounded() } - + } diff --git a/iOS/UIKit Extensions/UIActivityViewController-Extensions.swift b/iOS/UIKit Extensions/UIActivityViewController-Extensions.swift index 453fb64be..12d11b24d 100644 --- a/iOS/UIKit Extensions/UIActivityViewController-Extensions.swift +++ b/iOS/UIKit Extensions/UIActivityViewController-Extensions.swift @@ -12,7 +12,7 @@ extension UIActivityViewController { convenience init(url: URL, title: String?, applicationActivities: [UIActivity]?) { let itemSource = ArticleActivityItemSource(url: url, subject: title) let titleSource = TitleActivityItemSource(title: title) - + self.init(activityItems: [titleSource, itemSource], applicationActivities: applicationActivities) } } diff --git a/iOS/UIKit Extensions/UIBarButtonItem-Extensions.swift b/iOS/UIKit Extensions/UIBarButtonItem-Extensions.swift index b05e77fdd..abdd086a9 100644 --- a/iOS/UIKit Extensions/UIBarButtonItem-Extensions.swift +++ b/iOS/UIKit Extensions/UIBarButtonItem-Extensions.swift @@ -9,7 +9,7 @@ import UIKit public extension UIBarButtonItem { - + @IBInspectable var accEnabled: Bool { get { return isAccessibilityElement @@ -18,7 +18,7 @@ public extension UIBarButtonItem { isAccessibilityElement = newValue } } - + @IBInspectable var accLabelText: String? { get { return accessibilityLabel @@ -27,5 +27,5 @@ public extension UIBarButtonItem { accessibilityLabel = newValue } } - + } diff --git a/iOS/UIKit Extensions/UICollectionView-Extensions.swift b/iOS/UIKit Extensions/UICollectionView-Extensions.swift index 72929f115..8eb5bd71b 100644 --- a/iOS/UIKit Extensions/UICollectionView-Extensions.swift +++ b/iOS/UIKit Extensions/UICollectionView-Extensions.swift @@ -20,7 +20,7 @@ extension UICollectionView { indexPath.row < dataSource.collectionView(self, numberOfItemsInSection: indexPath.section) else { return } - + selectItem(at: indexPath, animated: animations.contains(.select), scrollPosition: []) if !indexPathsForVisibleItems.contains(indexPath) { diff --git a/iOS/UIKit Extensions/UIFont-Extensions.swift b/iOS/UIKit Extensions/UIFont-Extensions.swift index d250066b8..14b68ca93 100644 --- a/iOS/UIKit Extensions/UIFont-Extensions.swift +++ b/iOS/UIKit Extensions/UIFont-Extensions.swift @@ -9,7 +9,7 @@ import UIKit extension UIFont { - + func withTraits(traits:UIFontDescriptor.SymbolicTraits) -> UIFont { if let descriptor = fontDescriptor.withSymbolicTraits(traits) { return UIFont(descriptor: descriptor, size: 0) //size 0 means keep the size as it is @@ -17,13 +17,13 @@ extension UIFont { return self } } - + func bold() -> UIFont { return withTraits(traits: .traitBold) } - + func italic() -> UIFont { return withTraits(traits: .traitItalic) } - + } diff --git a/iOS/UIKit Extensions/UIPageViewController-Extensions.swift b/iOS/UIKit Extensions/UIPageViewController-Extensions.swift index 8db0ce553..adfa5135d 100644 --- a/iOS/UIKit Extensions/UIPageViewController-Extensions.swift +++ b/iOS/UIKit Extensions/UIPageViewController-Extensions.swift @@ -9,7 +9,7 @@ import UIKit extension UIPageViewController { - + var scrollViewInsidePageControl: UIScrollView? { for view in view.subviews { if let scrollView = view as? UIScrollView { @@ -18,5 +18,5 @@ extension UIPageViewController { } return nil } - + } diff --git a/iOS/UIKit Extensions/UIStoryboard-Extensions.swift b/iOS/UIKit Extensions/UIStoryboard-Extensions.swift index ef48e061d..0c46b47e9 100644 --- a/iOS/UIKit Extensions/UIStoryboard-Extensions.swift +++ b/iOS/UIKit Extensions/UIStoryboard-Extensions.swift @@ -9,39 +9,39 @@ import UIKit extension UIStoryboard { - + static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0) - + static var main: UIStoryboard { return UIStoryboard(name: "Main", bundle: nil) } - + static var add: UIStoryboard { return UIStoryboard(name: "Add", bundle: nil) } - + static var settings: UIStoryboard { return UIStoryboard(name: "Settings", bundle: nil) } - + static var inspector: UIStoryboard { return UIStoryboard(name: "Inspector", bundle: nil) } - + static var account: UIStoryboard { return UIStoryboard(name: "Account", bundle: nil) } - + func instantiateController(ofType type: T.Type = T.self) -> T where T: UIViewController { - + let storyboardId = String(describing: type) guard let viewController = instantiateViewController(withIdentifier: storyboardId) as? T else { print("Unable to load view with Scene Identifier: \(storyboardId)") fatalError() } - + return viewController - + } - + } diff --git a/iOS/UIKit Extensions/UITableView-Extensions.swift b/iOS/UIKit Extensions/UITableView-Extensions.swift index fd0c4c0ee..532a339c0 100644 --- a/iOS/UIKit Extensions/UITableView-Extensions.swift +++ b/iOS/UIKit Extensions/UITableView-Extensions.swift @@ -9,7 +9,7 @@ import UIKit extension UITableView { - + /** Selects a row and scrolls it to the middle if it is not visible */ @@ -20,7 +20,7 @@ extension UITableView { indexPath.row < dataSource.tableView(self, numberOfRowsInSection: indexPath.section) else { return } - + selectRow(at: indexPath, animated: animations.contains(.select), scrollPosition: .none) if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame) { @@ -29,12 +29,12 @@ extension UITableView { } } } - + func cellCompletelyVisible(_ indexPath: IndexPath) -> Bool { let rect = rectForRow(at: indexPath) return safeAreaLayoutGuide.layoutFrame.contains(rect) } - + public func middleVisibleRow() -> IndexPath? { if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame), visibleIndexPaths.count > 2 { return visibleIndexPaths[visibleIndexPaths.count / 2] diff --git a/iOS/UIKit Extensions/UIViewController-Extensions.swift b/iOS/UIKit Extensions/UIViewController-Extensions.swift index 7b6f7731c..9402e665d 100644 --- a/iOS/UIKit Extensions/UIViewController-Extensions.swift +++ b/iOS/UIKit Extensions/UIViewController-Extensions.swift @@ -11,7 +11,7 @@ import RSCore import Account extension UIViewController { - + func presentError(_ error: Error, dismiss: (() -> Void)? = nil) { if let accountError = error as? AccountError, accountError.isCredentialsError { presentAccountError(accountError, dismiss: dismiss) @@ -41,7 +41,7 @@ extension UIViewController { 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) @@ -61,44 +61,44 @@ extension UIViewController { } private extension UIViewController { - + func presentAccountError(_ error: AccountError, dismiss: (() -> Void)? = nil) { let title = NSLocalizedString("Account Error", comment: "Account Error") let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert) - + if error.account?.type == .feedbin { let credentialsTitle = NSLocalizedString("Update Credentials", comment: "Update Credentials") let credentialsAction = UIAlertAction(title: credentialsTitle, style: .default) { [weak self] _ in dismiss?() - + let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController navController.modalPresentationStyle = .formSheet let addViewController = navController.topViewController as! FeedbinAccountViewController addViewController.account = error.account self?.present(navController, animated: true) } - + alertController.addAction(credentialsAction) alertController.preferredAction = credentialsAction } - + let dismissTitle = NSLocalizedString("OK", comment: "OK") let dismissAction = UIAlertAction(title: dismissTitle, style: .default) { _ in dismiss?() } alertController.addAction(dismissAction) - + self.present(alertController, animated: true, completion: nil) } - + func presentErrorWithRecovery(error: RecoverableError & LocalizedError, dismiss: (() -> Void)? = nil) { let title = error.errorDescription ?? NSLocalizedString("Error", comment: "Error") let message = [error.failureReason, error.recoverySuggestion].compactMap { $0 }.joined(separator: " ") - + let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - + // Add recovery options as buttons for (index, option) in error.recoveryOptions.enumerated() { let action = UIAlertAction(title: option, style: index == 0 ? .default : .cancel) { _ in @@ -106,13 +106,13 @@ private extension UIViewController { _ = error.attemptRecovery(optionIndex: index) } alertController.addAction(action) - + // Make the first option the preferred action if index == 0 { alertController.preferredAction = action } } - + self.present(alertController, animated: true, completion: nil) } diff --git a/iOS/UIKit Extensions/VibrantButton.swift b/iOS/UIKit Extensions/VibrantButton.swift index c44f94831..91f105e94 100644 --- a/iOS/UIKit Extensions/VibrantButton.swift +++ b/iOS/UIKit Extensions/VibrantButton.swift @@ -9,7 +9,7 @@ import UIKit final class VibrantButton: UIButton { - + @IBInspectable var backgroundHighlightColor: UIColor = AppAssets.secondaryAccentColor override init(frame: CGRect) { @@ -20,7 +20,7 @@ final class VibrantButton: UIButton { super.init(coder: coder) commonInit() } - + private func commonInit() { setTitleColor(AppAssets.vibrantTextColor, for: .highlighted) let disabledColor = AppAssets.secondaryAccentColor.withAlphaComponent(0.5) @@ -47,5 +47,5 @@ final class VibrantButton: UIButton { isHighlighted = false super.touchesCancelled(touches, with: event) } - + } diff --git a/iOS/UIKit Extensions/VibrantLabel.swift b/iOS/UIKit Extensions/VibrantLabel.swift index 174266e7e..49363ed1b 100644 --- a/iOS/UIKit Extensions/VibrantLabel.swift +++ b/iOS/UIKit Extensions/VibrantLabel.swift @@ -9,17 +9,17 @@ import UIKit final class VibrantLabel: UILabel { - + override init(frame: CGRect) { super.init(frame: frame) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } - + private func commonInit() { highlightedTextColor = AppAssets.vibrantTextColor } diff --git a/iOS/UIKit Extensions/VibrantTableViewCell.swift b/iOS/UIKit Extensions/VibrantTableViewCell.swift index 22d74deb0..cde421a36 100644 --- a/iOS/UIKit Extensions/VibrantTableViewCell.swift +++ b/iOS/UIKit Extensions/VibrantTableViewCell.swift @@ -9,27 +9,27 @@ import UIKit class VibrantTableViewCell: UITableViewCell { - + static let duration: TimeInterval = 0.6 - + var labelColor: UIColor { return isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label } - + var secondaryLabelColor: UIColor { return isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.secondaryLabel } - + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } - + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } - + private func commonInit() { applyThemeProperties() } @@ -43,7 +43,7 @@ class VibrantTableViewCell: UITableViewCell { super.setSelected(selected, animated: animated) updateVibrancy(animated: animated) } - + /// Subclass overrides should call super func applyThemeProperties() { let selectedBackgroundView = UIView(frame: .zero) @@ -56,7 +56,7 @@ class VibrantTableViewCell: UITableViewCell { updateLabelVibrancy(textLabel, color: labelColor, animated: animated) updateLabelVibrancy(detailTextLabel, color: labelColor, animated: animated) } - + func updateLabelVibrancy(_ label: UILabel?, color: UIColor, animated: Bool) { guard let label = label else { return } if animated { @@ -67,33 +67,33 @@ class VibrantTableViewCell: UITableViewCell { label.textColor = color } } - + } class VibrantBasicTableViewCell: VibrantTableViewCell { - + @IBOutlet private var label: UILabel! @IBOutlet private var detail: UILabel! @IBOutlet private var icon: UIImageView! - + @IBInspectable var imageNormal: UIImage? @IBInspectable var imageSelected: UIImage? - + var iconTint: UIColor { return isHighlighted || isSelected ? labelColor : AppAssets.primaryAccentColor } - + var iconImage: UIImage? { return isHighlighted || isSelected ? imageSelected : imageNormal } - + override func updateVibrancy(animated: Bool) { super.updateVibrancy(animated: animated) updateIconVibrancy(icon, color: iconTint, image: iconImage, animated: animated) updateLabelVibrancy(label, color: labelColor, animated: animated) updateLabelVibrancy(detail, color: secondaryLabelColor, animated: animated) } - + private func updateIconVibrancy(_ icon: UIImageView?, color: UIColor, image: UIImage?, animated: Bool) { guard let icon = icon else { return } if animated { @@ -106,5 +106,5 @@ class VibrantBasicTableViewCell: VibrantTableViewCell { icon.image = image } } - + }