GIve AccountDelegate an account property and drop redundant account parameters.

This commit is contained in:
Brent Simmons committed 2026-06-14 14:54:56 -07:00
1 parent 9db1a7b143
commit 3ff3462b05
9 files changed
+506 -215

No files matched your search

+23 -22
View File
@@ -344,7 +344,8 @@ public enum FetchType {
self._fetchAllUnreadCounts()
}
delegate.accountDidInitialize(self)
delegate.account = self
delegate.accountDidInitialize()
}
// MARK: - Credentials
@@ -458,7 +459,7 @@ public enum FetchType {
}
public func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
await delegate.receiveRemoteNotification(for: self, userInfo: userInfo)
await delegate.receiveRemoteNotification(userInfo: userInfo)
}
// MARK: - Refreshing
@@ -471,7 +472,7 @@ public enum FetchType {
}
public func refreshAll() async throws {
try await delegate.refreshAll(for: self)
try await delegate.refreshAll()
}
// MARK: - Activity Log
@@ -525,12 +526,12 @@ public enum FetchType {
// MARK: - Syncing Article Status
public func sendArticleStatus() async throws {
try await delegate.sendArticleStatus(for: self)
try await delegate.sendArticleStatus()
}
@discardableResult
public func syncArticleStatus() async throws -> Bool {
try await delegate.syncArticleStatus(for: self)
try await delegate.syncArticleStatus()
}
// MARK: - OPML
@@ -543,10 +544,10 @@ public enum FetchType {
Task { @MainActor in
do {
try await delegate.importOPML(for: self, opmlFile: opmlFile)
try await delegate.importOPML(opmlFile: opmlFile)
// Reset the last fetch date to get the article history for the added feeds.
lastArticleFetchStartTime = nil
try? await delegate.refreshAll(for: self)
try? await delegate.refreshAll()
completion(.success(()))
} catch {
completion(.failure(error))
@@ -562,7 +563,7 @@ public enum FetchType {
/// Resume network activity for the delegate after a previous `suspendNetwork()`.
public func resumeDelegate() {
delegate.resume(account: self)
delegate.resume()
}
/// Reload OPML, etc.
@@ -579,7 +580,7 @@ public enum FetchType {
}
public func prepareForDeletion() {
delegate.accountWillBeDeleted(self)
delegate.accountWillBeDeleted()
}
func deleteSettings() {
@@ -612,7 +613,7 @@ public enum FetchType {
public func markArticles(_ articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.markArticles(for: self, articles: articles, statusKey: statusKey, flag: flag)
try await delegate.markArticles(articles: articles, statusKey: statusKey, flag: flag)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -693,13 +694,13 @@ public enum FetchType {
}
func addFeed(_ feed: Feed, container: Container) async throws {
try await delegate.addFeed(account: self, feed: feed, container: container)
try await delegate.addFeed(feed: feed, container: container)
}
public func addFeed(_ feed: Feed, to container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.addFeed(account: self, feed: feed, container: container)
try await delegate.addFeed(feed: feed, container: container)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -710,7 +711,7 @@ public enum FetchType {
public func createFeed(url: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result<Feed, Error>) -> Void) {
Task { @MainActor in
do {
let feed = try await delegate.createFeed(for: self, url: url, name: name, container: container, validateFeed: validateFeed)
let feed = try await delegate.createFeed(url: url, name: name, container: container, validateFeed: validateFeed)
completion(.success(feed))
} catch {
completion(.failure(error))
@@ -736,7 +737,7 @@ public enum FetchType {
public func removeFeed(_ feed: Feed, from container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.removeFeed(account: self, feed: feed, container: container)
try await delegate.removeFeed(feed: feed, container: container)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -747,7 +748,7 @@ public enum FetchType {
public func moveFeed(_ feed: Feed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.moveFeed(account: self, feed: feed, sourceContainer: from, destinationContainer: to)
try await delegate.moveFeed(feed: feed, sourceContainer: from, destinationContainer: to)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -756,13 +757,13 @@ public enum FetchType {
}
public func renameFeed(_ feed: Feed, name: String) async throws {
try await delegate.renameFeed(for: self, with: feed, to: name)
try await delegate.renameFeed(with: feed, to: name)
}
public func restoreFeed(_ feed: Feed, container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.restoreFeed(for: self, feed: feed, container: container)
try await delegate.restoreFeed(feed: feed, container: container)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -772,13 +773,13 @@ public enum FetchType {
@discardableResult
public func addFolder(_ name: String) async throws -> Folder {
try await delegate.createFolder(for: self, name: name)
try await delegate.createFolder(name: name)
}
public func removeFolder(_ folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.removeFolder(for: self, with: folder)
try await delegate.removeFolder(with: folder)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -787,13 +788,13 @@ public enum FetchType {
}
public func renameFolder(_ folder: Folder, to name: String) async throws {
try await delegate.renameFolder(for: self, with: folder, to: name)
try await delegate.renameFolder(with: folder, to: name)
}
public func restoreFolder(_ folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
Task { @MainActor in
do {
try await delegate.restoreFolder(for: self, folder: folder)
try await delegate.restoreFolder(folder: folder)
completion(.success(()))
} catch {
completion(.failure(error))
@@ -1114,7 +1115,7 @@ public enum FetchType {
await logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(feedSettingsDatabase.databasePath)) {
await feedSettingsDatabase.vacuum()
}
await delegate.vacuumDatabases(for: self)
await delegate.vacuumDatabases()
}
public func fetchCloudKitStats(progress: @escaping CloudKitStatsProgressHandler) async throws -> CloudKitStats {
@@ -14,6 +14,11 @@ import Secrets
@MainActor protocol AccountDelegate: ProgressInfoReporter {
/// The account this delegate belongs to. Set by the account during its init,
/// before `accountDidInitialize()` is called. Held weakly to avoid a retain
/// cycle (the account owns its delegate strongly).
var account: Account? { get set }
var behaviors: AccountBehaviors { get }
var isOPMLImportInProgress: Bool { get }
@@ -22,44 +27,44 @@ import Secrets
var credentials: Credentials? { get set }
var accountSettings: AccountSettings? { get set }
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async
func refreshAll(for account: Account) async throws
func refreshAll() async throws
/// Returns `true` if any meaningful work was done (statuses sent or local
/// statuses changed); `false` if the round was a no-op.
func syncArticleStatus(for account: Account) async throws -> Bool
func sendArticleStatus(for account: Account) async throws
func refreshArticleStatus(for account: Account) async throws
func syncArticleStatus() async throws -> Bool
func sendArticleStatus() async throws
func refreshArticleStatus() async throws
func importOPML(for account: Account, opmlFile: URL) async throws
func importOPML(opmlFile: URL) async throws
func createFolder(for account: Account, name: String) async throws -> Folder
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws
func removeFolder(for account: Account, with folder: Folder) async throws
func createFolder(name: String) async throws -> Folder
func renameFolder(with folder: Folder, to name: String) async throws
func removeFolder(with folder: Folder) async throws
func createFeed(for account: Account, url: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed
func renameFeed(for account: Account, with feed: Feed, to name: String) async throws
func addFeed(account: Account, feed: Feed, container: Container) async throws
func removeFeed(account: Account, feed: Feed, container: Container) async throws
func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws
func createFeed(url: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed
func renameFeed(with feed: Feed, to name: String) async throws
func addFeed(feed: Feed, container: Container) async throws
func removeFeed(feed: Feed, container: Container) async throws
func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws
func restoreFeed(for account: Account, feed: Feed, container: Container) async throws
func restoreFolder(for account: Account, folder: Folder) async throws
func restoreFeed(feed: Feed, container: Container) async throws
func restoreFolder(folder: Folder) async throws
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws
func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws
// Called at the end of account’s init method.
func accountDidInitialize(_ account: Account)
func accountDidInitialize()
func accountWillBeDeleted(_ account: Account)
func accountWillBeDeleted()
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials?
func vacuumDatabases(for account: Account) async
func vacuumDatabases() async
/// Suspend all network activity
func suspendNetwork()
/// Resume network activity after a previous `suspendNetwork()`.
func resume(account: Account)
func resume()
}
@@ -105,7 +105,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete")
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
guard let account else {
return
}
lastNoChangeSyncDate = nil
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
await withCheckedContinuation { continuation in
@@ -118,7 +121,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func refreshAll(for account: Account) async throws {
func refreshAll() async throws {
guard let account else {
return
}
guard refreshProgressInfo.isComplete else {
return
}
@@ -134,7 +140,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete")
}
func syncArticleStatus(for account: Account) async throws -> Bool {
func syncArticleStatus() async throws -> Bool {
guard let account else {
return false
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
if let lastNoChangeSyncDate, Date().timeIntervalSince(lastNoChangeSyncDate) < Self.noChangeBackoffInterval {
@@ -143,7 +152,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
let sentCount = try await sendArticleStatus(account: account, showProgress: false)
try await refreshArticleStatus(for: account)
try await refreshArticleStatus()
let didReceiveChanges = !(articlesZoneHasNoChanges && accountZoneHasNoChanges)
let didWork = sentCount > 0 || didReceiveChanges
@@ -172,13 +181,19 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
return delegate.lastChangedCount == 0 && delegate.lastDeletedCount == 0
}
func sendArticleStatus(for account: Account) async throws {
func sendArticleStatus() async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
_ = try await sendArticleStatus(account: account, showProgress: false)
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete")
}
func refreshArticleStatus(for account: Account) async throws {
func refreshArticleStatus() async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
let op = CloudKitReceiveStatusOperation(articlesZone: articlesZone, accountID: account.accountID, accountDisplayName: account.nameForDisplay)
@@ -194,7 +209,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func importOPML(for account: Account, opmlFile: URL) async throws {
func importOPML(opmlFile: URL) async throws {
guard let account else {
return
}
guard refreshProgressInfo.isComplete else {
return
}
@@ -228,7 +246,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
@discardableResult
func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) url: \(urlString)")
defer {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete url: \(urlString)")
@@ -243,7 +264,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
func renameFeed(with feed: Feed, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)")
let editedName = name.isEmpty ? nil : name
syncProgress.addTask()
@@ -263,7 +287,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func removeFeed(account: Account, feed: Feed, container: Container) async throws {
func removeFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)")
defer {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)")
@@ -284,7 +311,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)")
syncProgress.addTask()
defer {
@@ -304,7 +334,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func addFeed(account: Account, feed: Feed, container: Container) async throws {
func addFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)")
syncProgress.addTask()
defer {
@@ -323,7 +356,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws {
func restoreFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)")
defer {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)")
@@ -353,7 +389,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func createFolder(for account: Account, name: String) async throws -> Folder {
func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) name: \(name)")
syncProgress.addTask()
defer {
@@ -376,7 +415,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
func renameFolder(with folder: Folder, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) new name: \(name)")
defer {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete new name: \(name)")
@@ -396,7 +438,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func removeFolder(for account: Account, with folder: Folder) async throws {
func removeFolder(with folder: Folder) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) name: \(folder.name ?? "")")
defer {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete name: \(folder.name ?? "")")
@@ -473,7 +518,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func restoreFolder(for account: Account, folder: Folder) async throws {
func restoreFolder(folder: Folder) async throws {
guard let account else {
throw AccountError.invalidParameter
}
guard let name = folder.name else {
throw AccountError.invalidParameter
}
@@ -499,7 +547,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
group.addTask {
do {
try await self.restoreFeed(for: account, feed: feed, container: folder)
try await self.restoreFeed(feed: feed, container: folder)
await self.syncProgress.completeTask()
return nil
} catch {
@@ -526,7 +574,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
}
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
let updatedArticles = await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
@@ -540,15 +591,17 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account)
}
if let count = await syncDatabase.selectPendingCount(), count > 100 {
try await sendArticleStatus(for: account)
try await sendArticleStatus()
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete")
}
func accountDidInitialize(_ account: Account) {
func accountDidInitialize() {
guard let account else {
return
}
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
self.account = account
syncErrorHandler = { [weak self] error, operation, fileName, functionName, lineNumber in
Task { @MainActor [weak self] in
@@ -608,7 +661,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
accountZone.resetChangeToken()
articlesZone.resetChangeToken()
@@ -619,7 +672,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
nil
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
guard let account else {
return
}
await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) {
await syncDatabase.vacuum()
}
@@ -664,7 +720,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
refresher.suspend()
}
func resume(account: Account) {
func resume() {
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
refresher.resume()
}
@@ -779,7 +835,7 @@ private extension CloudKitAccountDelegate {
let feeds = account.flattenedFeeds()
do {
try await refreshArticleStatus(for: account)
try await refreshArticleStatus()
syncProgress.completeTask()
} catch {
postSyncError(error, account: account, operation: "Refreshing article status")
@@ -25,6 +25,7 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
@MainActor final class FeedbinAccountDelegate: AccountDelegate {
weak var account: Account?
let behaviors: AccountBehaviors = [.disallowFeedCopyInRootFolder]
let server: String? = "api.feedbin.com"
var isOPMLImportInProgress = false
@@ -81,10 +82,13 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
}
func refreshAll(for account: Account) async throws {
func refreshAll() async throws {
guard let account else {
return
}
if credentials == nil {
credentials = try? account.retrieveCredentials(type: .basic)
}
@@ -103,13 +107,19 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func syncArticleStatus(for account: Account) async throws -> Bool {
func syncArticleStatus() async throws -> Bool {
guard let account else {
return false
}
let sentCount = try await sendArticleStatusReturningCount(for: account)
let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account)
return sentCount > 0 || refreshChangedCount > 0
}
func sendArticleStatus(for account: Account) async throws {
func sendArticleStatus() async throws {
guard let account else {
return
}
_ = try await sendArticleStatusReturningCount(for: account)
}
@@ -148,7 +158,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func refreshArticleStatus(for account: Account) async throws {
func refreshArticleStatus() async throws {
guard let account else {
return
}
_ = try await refreshArticleStatusReturningCount(for: account)
}
@@ -186,7 +199,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func importOPML(for account: Account, opmlFile: URL) async throws {
func importOPML(opmlFile: URL) async throws {
guard let account else {
return
}
let opmlData = try Data(contentsOf: opmlFile)
guard !opmlData.isEmpty else {
return
@@ -216,14 +232,20 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func createFolder(for account: Account, name: String) async throws -> Folder {
func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
guard let folder = account.ensureFolder(with: name) else {
throw AccountError.invalidParameter
}
return folder
}
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
func renameFolder(with folder: Folder, to name: String) async throws {
guard let account else {
return
}
guard folder.hasAtLeastOneFeed() else {
folder.name = name
return
@@ -245,7 +267,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func removeFolder(for account: Account, with folder: Folder) async throws {
func removeFolder(with folder: Folder) async throws {
guard let account else {
return
}
// Feedbin uses tags and if at least one feed isn't tagged, then the folder doesn't exist on their system
guard folder.hasAtLeastOneFeed() else {
account.removeFolderFromTree(folder)
@@ -286,7 +311,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
@discardableResult
func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
@@ -309,7 +337,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
func renameFeed(with feed: Feed, to name: String) async throws {
guard let account else {
return
}
// This error should never happen
guard let subscriptionID = feed.externalID else {
throw AccountError.invalidParameter
@@ -330,7 +361,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func removeFeed(account: Account, feed: Feed, container: Container) async throws {
func removeFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .removeFeed, detail: feed.url) {
if feed.folderRelationship?.count ?? 0 > 1 {
try await deleteTagging(for: account, with: feed, from: container)
@@ -340,18 +374,24 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .moveFeed, detail: feed.url) {
if sourceContainer is Account {
try await addFeed(account: account, feed: feed, container: destinationContainer)
try await addFeed(feed: feed, container: destinationContainer)
} else {
try await deleteTagging(for: account, with: feed, from: sourceContainer)
try await addFeed(account: account, feed: feed, container: destinationContainer)
try await addFeed(feed: feed, container: destinationContainer)
}
}
}
func addFeed(account: Account, feed: Feed, container: Container) async throws {
func addFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .addFeed, detail: feed.url) {
if let folder = container as? Folder, let feedID = Int(feed.feedID) {
@@ -373,22 +413,28 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws {
func restoreFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
if let existingFeed = account.existingFeed(withURL: feed.url) {
try await account.addFeed(existingFeed, container: container)
} else {
try await createFeed(for: account, url: feed.url, name: feed.editedName, container: container, validateFeed: true)
try await createFeed(url: feed.url, name: feed.editedName, container: container, validateFeed: true)
}
}
func restoreFolder(for account: Account, folder: Folder) async throws {
func restoreFolder(folder: Folder) async throws {
guard let account else {
return
}
await account.logActivity(kind: .restoreFolder, detail: folder.name ?? "") {
for feed in folder.topLevelFeeds {
folder.topLevelFeeds.remove(feed)
do {
try await restoreFeed(for: account, feed: feed, container: folder)
try await restoreFeed(feed: feed, container: folder)
} catch {
Self.logger.error("Feedbin: Restore folder feed error: \(error.localizedDescription)")
postSyncError(error, account: account, operation: "Restoring feed")
@@ -399,7 +445,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
}
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
guard let account else {
return
}
let updatedArticles = await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
let syncStatuses = Set(updatedArticles.map { article in
SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag)
@@ -410,15 +459,15 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account)
}
if let count = await syncDatabase.selectPendingCount(), count > 100 {
try await sendArticleStatus(for: account)
try await sendArticleStatus()
}
}
func accountDidInitialize(_ account: Account) {
credentials = try? account.retrieveCredentials(type: .basic)
func accountDidInitialize() {
credentials = try? account?.retrieveCredentials(type: .basic)
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
}
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
@@ -427,7 +476,10 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
return try await caller.validateCredentials()
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
guard let account else {
return
}
await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) {
await syncDatabase.vacuum()
}
@@ -441,8 +493,8 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
}
/// Resume network activity after a previous `suspendNetwork()`.
func resume(account: Account) {
if credentials == nil {
func resume() {
if let account, credentials == nil {
credentials = try? account.retrieveCredentials(type: .basic)
}
caller.resume()
@@ -519,8 +571,8 @@ private extension FeedbinAccountDelegate {
}
func refreshArticlesAndStatuses(_ account: Account) async throws {
try await sendArticleStatus(for: account)
try await refreshArticleStatus(for: account)
try await sendArticleStatus()
try await refreshArticleStatus()
try await refreshArticles(account)
try await refreshMissingArticles(account)
refreshProgress.reset()
@@ -781,7 +833,7 @@ private extension FeedbinAccountDelegate {
}
if let bestSpecifier = FeedSpecifier.bestFeed(in: Set(feedSpecifiers)) {
let feed = try await createFeed(for: account, url: bestSpecifier.urlString, name: name, container: container, validateFeed: true)
let feed = try await createFeed(url: bestSpecifier.urlString, name: name, container: container, validateFeed: true)
return feed
} else {
throw AccountError.invalidParameter
@@ -811,7 +863,7 @@ private extension FeedbinAccountDelegate {
// Download the initial articles
let (entries, page) = try await caller.retrieveEntries(feedID: feed.feedID)
await processEntries(account: account, entries: entries)
try await refreshArticleStatus(for: account)
try await refreshArticleStatus()
try await refreshArticles(account, page: page, updateFetchDate: nil)
try await refreshMissingArticles(account)
@@ -66,7 +66,7 @@ import Secrets
let caller: FeedlyAPICaller
private let syncDatabase: SyncDatabase
private weak var initializedAccount: Account?
weak var account: Account?
private static let logger = Feedly.logger
private static let articleDownloadChunkSize = 1000
@@ -109,10 +109,13 @@ import Secrets
// MARK: - Account API
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
}
func refreshAll(for account: Account) async throws {
func refreshAll() async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: refreshAll")
if credentials == nil {
@@ -169,7 +172,10 @@ import Secrets
progressInfo = ProgressInfo()
}
func syncArticleStatus(for account: Account) async throws -> Bool {
func syncArticleStatus() async throws -> Bool {
guard let account else {
return false
}
if let lastNoChangeSyncDate, Date().timeIntervalSince(lastNoChangeSyncDate) < Self.noChangeBackoffInterval {
Self.logger.debug("Feedly: Skipping sync — no changes on last check, backing off")
return false
@@ -197,7 +203,10 @@ import Secrets
return sentCount > 0 || refreshCounts.totalChanged > 0
}
func sendArticleStatus(for account: Account) async throws {
func sendArticleStatus() async throws {
guard let account else {
return
}
_ = try await sendArticleStatusReturningCount(for: account)
}
@@ -261,7 +270,10 @@ import Secrets
}
}
func refreshArticleStatus(for account: Account) async throws {
func refreshArticleStatus() async throws {
guard let account else {
return
}
_ = try await refreshArticleStatusReturningCounts(for: account)
}
@@ -314,7 +326,10 @@ import Secrets
}
}
func importOPML(for account: Account, opmlFile: URL) async throws {
func importOPML(opmlFile: URL) async throws {
guard let account else {
return
}
let opmlData = try Data(contentsOf: opmlFile)
guard !opmlData.isEmpty else {
return
@@ -339,7 +354,10 @@ import Secrets
}
}
func createFolder(for account: Account, name: String) async throws -> Folder {
func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
Self.logger.debug("FeedlyAccountDelegate: createFolder")
refreshProgress.addTask()
defer {
@@ -357,7 +375,10 @@ import Secrets
}
}
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
func renameFolder(with folder: Folder, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: renameFolder")
guard let id = folder.externalID else {
@@ -379,7 +400,10 @@ import Secrets
}
}
func removeFolder(for account: Account, with folder: Folder) async throws {
func removeFolder(with folder: Folder) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: removeFolder")
guard let id = folder.externalID else {
@@ -398,7 +422,10 @@ import Secrets
}
@discardableResult
func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
Self.logger.debug("FeedlyAccountDelegate: createFeed")
guard let credentials else {
@@ -441,7 +468,10 @@ import Secrets
}
}
func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
func renameFeed(with feed: Feed, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: renameFeed")
let folderCollectionIDs = account.folders?.filter { $0.has(feed) }.compactMap { $0.externalID }
@@ -466,7 +496,10 @@ import Secrets
}
}
func addFeed(account: Account, feed: Feed, container: Container) async throws {
func addFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: addFeed")
guard credentials != nil else {
@@ -490,7 +523,10 @@ import Secrets
}
}
func removeFeed(account: Account, feed: Feed, container: Container) async throws {
func removeFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: removeFeed")
guard let folder = container as? Folder, let collectionID = folder.externalID else {
@@ -510,7 +546,10 @@ import Secrets
}
}
func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: moveFeed")
guard let from = sourceContainer as? Folder, let to = destinationContainer as? Folder,
@@ -542,17 +581,23 @@ import Secrets
}
}
func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws {
func restoreFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: restoreFeed")
if let existingFeed = account.existingFeed(withURL: feed.url) {
try await account.addFeed(existingFeed, container: container)
} else {
_ = try await createFeed(for: account, url: feed.url, name: feed.editedName, container: container, validateFeed: true)
_ = try await createFeed(url: feed.url, name: feed.editedName, container: container, validateFeed: true)
}
}
func restoreFolder(for account: Account, folder: Folder) async throws {
func restoreFolder(folder: Folder) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: restoreFolder")
await account.logActivity(kind: .restoreFolder, detail: folder.name ?? "") {
@@ -561,7 +606,7 @@ import Secrets
folder.topLevelFeeds.remove(feed)
do {
try await restoreFeed(for: account, feed: feed, container: folder)
try await restoreFeed(feed: feed, container: folder)
} catch {
Self.logger.error("Feedly: Restore folder feed error: \(error.localizedDescription)")
postSyncError(error, account: account, operation: "Restoring feed")
@@ -571,7 +616,10 @@ import Secrets
}
}
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: markArticles")
let updatedArticles = await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
@@ -585,17 +633,22 @@ import Secrets
NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account)
}
if let count = await syncDatabase.selectPendingCount(), count > Self.pendingStatusSendThreshold {
try await sendArticleStatus(for: account)
try await sendArticleStatus()
}
}
func accountDidInitialize(_ account: Account) {
func accountDidInitialize() {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: accountDidInitialize")
initializedAccount = account
credentials = try? account.retrieveCredentials(type: .oauthAccessToken)
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
guard let account else {
return
}
Self.logger.debug("FeedlyAccountDelegate: accountWillBeDeleted")
// Capture `caller` so the logout outlives the delegate.
@@ -619,7 +672,10 @@ import Secrets
return credentials
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
guard let account else {
return
}
await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) {
await syncDatabase.vacuum()
}
@@ -634,9 +690,9 @@ import Secrets
}
/// Resume network activity after a previous `suspendNetwork()`.
func resume(account: Account) {
func resume() {
Self.logger.debug("FeedlyAccountDelegate: resume")
if credentials == nil {
if let account, credentials == nil {
credentials = try? account.retrieveCredentials(type: .oauthAccessToken)
}
caller.resume()
@@ -868,7 +924,7 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate {
func reauthorizeFeedlyAPICaller() async -> Bool {
Self.logger.debug("FeedlyAccountDelegate: reauthorizeFeedlyAPICaller")
guard let account = initializedAccount else {
guard let account else {
return false
}
@@ -40,10 +40,13 @@ import Secrets
return refresher
}()
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
}
@MainActor func refreshAll(for account: Account) async throws {
@MainActor func refreshAll() async throws {
guard let account else {
return
}
guard progressInfo.isComplete, !Platform.isRunningUnitTests else {
return
}
@@ -54,17 +57,20 @@ import Secrets
account.lastRefreshCompletedDate = Date()
}
@MainActor func syncArticleStatus(for account: Account) async throws -> Bool {
@MainActor func syncArticleStatus() async throws -> Bool {
false
}
@MainActor func sendArticleStatus(for account: Account) async throws {
@MainActor func sendArticleStatus() async throws {
}
@MainActor func refreshArticleStatus(for account: Account) async throws {
@MainActor func refreshArticleStatus() async throws {
}
@MainActor func importOPML(for account: Account, opmlFile: URL) async throws {
@MainActor func importOPML(opmlFile: URL) async throws {
guard let account else {
return
}
try account.logActivity(kind: .importOPML, detail: opmlFile.lastPathComponent) {
let opmlData = try Data(contentsOf: opmlFile)
let parserData = ParserData(url: opmlFile.absoluteString, data: opmlData)
@@ -81,7 +87,10 @@ import Secrets
}
}
@MainActor func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
@MainActor func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
guard let url = URL(string: urlString) else {
throw AccountError.invalidParameter
}
@@ -91,62 +100,64 @@ import Secrets
}
}
@MainActor func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
@MainActor func renameFeed(with feed: Feed, to name: String) async throws {
feed.editedName = name
}
@MainActor func removeFeed(account: Account, feed: Feed, container: Container) async throws {
@MainActor func removeFeed(feed: Feed, container: Container) async throws {
container.removeFeedFromTreeAtTopLevel(feed)
}
@MainActor func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
@MainActor func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
sourceContainer.removeFeedFromTreeAtTopLevel(feed)
destinationContainer.addFeedToTreeAtTopLevel(feed)
}
@MainActor func addFeed(account: Account, feed: Feed, container: Container) async throws {
@MainActor func addFeed(feed: Feed, container: Container) async throws {
container.addFeedToTreeAtTopLevel(feed)
}
@MainActor func restoreFeed(for account: Account, feed: Feed, container: Container) async throws {
@MainActor func restoreFeed(feed: Feed, container: Container) async throws {
container.addFeedToTreeAtTopLevel(feed)
}
@MainActor func createFolder(for account: Account, name: String) async throws -> Folder {
@MainActor func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
guard let folder = account.ensureFolder(with: name) else {
throw AccountError.invalidParameter
}
return folder
}
@MainActor func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
@MainActor func renameFolder(with folder: Folder, to name: String) async throws {
folder.name = name
}
@MainActor func removeFolder(for account: Account, with folder: Folder) async throws {
account.removeFolderFromTree(folder)
@MainActor func removeFolder(with folder: Folder) async throws {
account?.removeFolderFromTree(folder)
}
@MainActor func restoreFolder(for account: Account, folder: Folder) async throws {
account.addFolderToTree(folder)
@MainActor func restoreFolder(folder: Folder) async throws {
account?.addFolderToTree(folder)
}
@MainActor func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
@MainActor func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
await account?.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
}
func accountDidInitialize(_ account: Account) {
self.account = account
func accountDidInitialize() {
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
}
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
nil
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
}
// MARK: Suspend and Resume (for iOS)
@@ -155,7 +166,7 @@ import Secrets
refresher.suspend()
}
@MainActor func resume(account: Account) {
@MainActor func resume() {
refresher.resume()
}
@@ -396,7 +396,7 @@ import os
try await account.logActivity(kind: .refreshArticles, detail: feed.nameForDisplay) {
try await downloadFeed(account: account, feed: feed, page: 1)
}
try await refreshArticleStatus(for: account)
try await refreshArticleStatus()
try await refreshMissingStories(for: account)
}
@@ -19,6 +19,7 @@ import os
import Secrets
@MainActor final class NewsBlurAccountDelegate: AccountDelegate {
weak var account: Account?
var behaviors: AccountBehaviors = []
var isOPMLImportInProgress: Bool = false
@@ -70,10 +71,13 @@ import Secrets
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
}
func refreshAll(for account: Account) async throws {
func refreshAll() async throws {
guard let account else {
return
}
if credentials == nil {
credentials = try? account.retrieveCredentials(type: .newsBlurSessionID)
}
@@ -86,10 +90,10 @@ import Secrets
try await refreshFeeds(for: account)
refreshProgress.completeTask()
try await sendArticleStatus(for: account)
try await sendArticleStatus()
refreshProgress.completeTask()
try await refreshArticleStatus(for: account)
try await refreshArticleStatus()
refreshProgress.completeTask()
try await refreshMissingStories(for: account)
@@ -103,13 +107,19 @@ import Secrets
}
}
@MainActor func syncArticleStatus(for account: Account) async throws -> Bool {
@MainActor func syncArticleStatus() async throws -> Bool {
guard let account else {
return false
}
let sentCount = try await sendArticleStatusReturningCount(for: account)
let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account)
return sentCount > 0 || refreshChangedCount > 0
}
@MainActor func sendArticleStatus(for account: Account) async throws {
@MainActor func sendArticleStatus() async throws {
guard let account else {
return
}
_ = try await sendArticleStatusReturningCount(for: account)
}
@@ -173,7 +183,10 @@ import Secrets
}
}
@MainActor func refreshArticleStatus(for account: Account) async throws {
@MainActor func refreshArticleStatus() async throws {
guard let account else {
return
}
_ = try await refreshArticleStatusReturningCount(for: account)
}
@@ -279,10 +292,13 @@ import Secrets
return !feedIDsAndItems.isEmpty
}
@MainActor func importOPML(for account: Account, opmlFile: URL) async throws {
@MainActor func importOPML(opmlFile: URL) async throws {
}
@MainActor func createFolder(for account: Account, name: String) async throws -> Folder {
@MainActor func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
@@ -298,7 +314,10 @@ import Secrets
}
}
@MainActor func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
@MainActor func renameFolder(with folder: Folder, to name: String) async throws {
guard let account else {
return
}
guard let folderToRename = folder.name else {
throw AccountError.invalidParameter
}
@@ -321,7 +340,10 @@ import Secrets
}
}
@MainActor func removeFolder(for account: Account, with folder: Folder) async throws {
@MainActor func removeFolder(with folder: Folder) async throws {
guard let account else {
return
}
guard let folderToRemove = folder.name else {
throw AccountError.invalidParameter
}
@@ -347,7 +369,10 @@ import Secrets
}
@discardableResult
@MainActor func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
@MainActor func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
@@ -368,7 +393,10 @@ import Secrets
}
}
@MainActor func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
@MainActor func renameFeed(with feed: Feed, to name: String) async throws {
guard let account else {
return
}
guard let feedID = feed.externalID else {
throw AccountError.invalidParameter
}
@@ -388,7 +416,10 @@ import Secrets
}
}
@MainActor func addFeed(account: Account, feed: Feed, container: Container) async throws {
@MainActor func addFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
account.logActivity(kind: .addFeed, detail: feed.url) {
if let containerAccount = container as? Account {
containerAccount.addFeedToTreeAtTopLevel(feed)
@@ -405,13 +436,19 @@ import Secrets
}
}
@MainActor func removeFeed(account: Account, feed: Feed, container: Container) async throws {
@MainActor func removeFeed(feed: Feed, container: Container) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .removeFeed, detail: feed.url) {
try await deleteFeed(for: account, with: feed, from: container)
}
}
@MainActor func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
@MainActor func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
guard let account else {
return
}
guard let feedID = feed.externalID else {
throw AccountError.invalidParameter
}
@@ -431,15 +468,21 @@ import Secrets
}
}
@MainActor func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws {
@MainActor func restoreFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
if let existingFeed = account.existingFeed(withURL: feed.url) {
try await account.addFeed(existingFeed, container: container)
} else {
try await createFeed(for: account, url: feed.url, name: feed.editedName, container: container, validateFeed: true)
try await createFeed(url: feed.url, name: feed.editedName, container: container, validateFeed: true)
}
}
@MainActor func restoreFolder(for account: Account, folder: Folder) async throws {
@MainActor func restoreFolder(folder: Folder) async throws {
guard let account else {
return
}
guard let folderName = folder.name else {
throw AccountError.invalidParameter
}
@@ -452,9 +495,9 @@ import Secrets
do {
try await account.logActivity(kind: .restoreFolder, detail: folderName) {
let folder = try await createFolder(for: account, name: folderName)
let folder = try await createFolder(name: folderName)
for feed in feedsToRestore {
try await restoreFeed(for: account, feed: feed, container: folder)
try await restoreFeed(feed: feed, container: folder)
}
}
} catch {
@@ -464,7 +507,10 @@ import Secrets
}
}
@MainActor func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
@MainActor func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
guard let account else {
return
}
await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
let syncStatuses = Set(articles.map { article in
SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag)
@@ -475,15 +521,18 @@ import Secrets
NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account)
}
if let count = await syncDatabase.selectPendingCount(), count > 100 {
try await sendArticleStatus(for: account)
try await sendArticleStatus()
}
}
func accountDidInitialize(_ account: Account) {
credentials = try? account.retrieveCredentials(type: .newsBlurSessionID)
func accountDidInitialize() {
credentials = try? account?.retrieveCredentials(type: .newsBlurSessionID)
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
guard let account else {
return
}
Task { @MainActor in
try? await account.logActivity(kind: .validateCredentials, detail: "Logging out of NewsBlur") {
try await caller.logout()
@@ -497,7 +546,10 @@ import Secrets
return try await caller.validateCredentials()
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
guard let account else {
return
}
await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) {
await syncDatabase.vacuum()
}
@@ -511,8 +563,8 @@ import Secrets
}
/// Resume network activity after a previous `suspendNetwork()`.
func resume(account: Account) {
if credentials == nil {
func resume() {
if let account, credentials == nil {
credentials = try? account.retrieveCredentials(type: .newsBlurSessionID)
}
caller.resume()
@@ -40,6 +40,8 @@ public enum ReaderAPIAccountDelegateError: LocalizedError {
final class ReaderAPIAccountDelegate: AccountDelegate {
weak var account: Account?
private let variant: ReaderAPIVariant
private let syncDatabase: SyncDatabase
@@ -111,10 +113,13 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
}
func refreshAll(for account: Account) async throws {
func refreshAll() async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: refreshAll")
retrieveCredentialsIfNeeded(account)
@@ -125,7 +130,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
try await account.logActivity(kind: .refreshAll) {
try await refreshAccount(account)
try await sendArticleStatus(for: account)
try await sendArticleStatus()
refreshProgress.completeTask()
let articleIDs = try await account.logActivity(kind: .fetchArticleIDs, detail: "All articles", successMessage: { "\($0.count) article IDs" }, {
@@ -134,7 +139,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
refreshProgress.completeTask()
_ = await account.markAsReadAsync(articleIDs: Set(articleIDs))
try? await refreshArticleStatus(for: account)
try? await refreshArticleStatus()
refreshProgress.completeTask()
await refreshMissingArticles(account)
@@ -153,7 +158,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
if let apiCredentials = try await caller.validateCredentials(endpoint: endpoint) {
try? account.storeCredentials(apiCredentials)
caller.credentials = apiCredentials
try await refreshAll(for: account)
try await refreshAll()
return
}
throw wrappedError
@@ -168,7 +173,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
@MainActor func syncArticleStatus(for account: Account) async throws -> Bool {
@MainActor func syncArticleStatus() async throws -> Bool {
guard let account else {
return false
}
guard variant != .inoreader else {
// Inoreader: no-op for this delegate.
return false
@@ -181,7 +189,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
return sentCount > 0 || refreshChangedCount > 0
}
public func sendArticleStatus(for account: Account) async throws {
public func sendArticleStatus() async throws {
guard let account else {
return
}
_ = try await sendArticleStatusReturningCount(for: account)
}
@@ -232,7 +243,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
@MainActor func refreshArticleStatus(for account: Account) async throws {
@MainActor func refreshArticleStatus() async throws {
guard let account else {
return
}
_ = try await refreshArticleStatusReturningCount(for: account)
}
@@ -265,14 +279,20 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
@MainActor func importOPML(for account: Account, opmlFile: URL) async throws {
@MainActor func importOPML(opmlFile: URL) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .importOPML, detail: opmlFile.lastPathComponent) {
let opmlData = try Data(contentsOf: opmlFile)
try await caller.importOPML(opmlData: opmlData)
}
}
@MainActor func createFolder(for account: Account, name: String) async throws -> Folder {
@MainActor func createFolder(name: String) async throws -> Folder {
guard let account else {
throw AccountError.invalidParameter
}
Self.logger.debug("ReaderAPIAccountDelegate: createFolder — name \(name)")
return try account.logActivity(kind: .createFolder, detail: name) {
@@ -284,7 +304,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
func renameFolder(with folder: Folder, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: renameFolder — name \(folder.nameForDisplay) to \(name)")
refreshProgress.addTask()
@@ -302,7 +325,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func removeFolder(for account: Account, with folder: Folder) async throws {
func removeFolder(with folder: Folder) async throws {
guard let account else {
return
}
try await account.logActivity(kind: .removeFolder, detail: folder.name ?? "") {
try await removeFolderImpl(for: account, with: folder)
}
@@ -360,7 +386,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
@discardableResult
func createFeed(for account: Account, url: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
func createFeed(url: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
guard let account else {
throw AccountError.invalidParameter
}
retrieveCredentialsIfNeeded(account)
Self.logger.debug("ReaderAPIAccountDelegate: createFeed — url \(url) name \(name ?? "")")
@@ -399,7 +428,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
func renameFeed(with feed: Feed, to name: String) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: renameFeed — name \(feed.nameForDisplay) to name \(name)")
// This error should never happen
@@ -423,7 +455,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func removeFeed(account: Account, feed: Feed, container: any Container) async throws {
func removeFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: removeFeed — url \(feed.url)")
guard let subscriptionID = feed.externalID else {
@@ -446,12 +481,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: moveFeed — url \(feed.url)")
try await account.logActivity(kind: .moveFeed, detail: feed.url) {
if sourceContainer is Account {
try await addFeed(account: account, feed: feed, container: destinationContainer)
try await addFeed(feed: feed, container: destinationContainer)
} else {
guard
@@ -477,7 +515,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func addFeed(account: Account, feed: Feed, container: any Container) async throws {
func addFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: addFeed — url \(feed.url)")
try await account.logActivity(kind: .addFeed, detail: feed.url) {
@@ -509,17 +550,23 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws {
func restoreFeed(feed: Feed, container: any Container) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: restoreFeed — url \(feed.url)")
if let existingFeed = account.existingFeed(withURL: feed.url) {
try await account.addFeed(existingFeed, container: container)
} else {
try await createFeed(for: account, url: feed.url, name: feed.editedName, container: container, validateFeed: true)
try await createFeed(url: feed.url, name: feed.editedName, container: container, validateFeed: true)
}
}
func restoreFolder(for account: Account, folder: Folder) async throws {
func restoreFolder(folder: Folder) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: restoreFolder — name \(folder.nameForDisplay)")
await account.logActivity(kind: .restoreFolder, detail: folder.name ?? "") {
@@ -528,7 +575,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
folder.topLevelFeeds.remove(feed)
do {
try await restoreFeed(for: account, feed: feed, container: folder)
try await restoreFeed(feed: feed, container: folder)
} catch {
Self.logger.error("ReaderAPIAccountDelegate: restoreFolder error: \(error.localizedDescription)")
postSyncError(error, account: account, operation: "Restoring feed to folder")
@@ -539,7 +586,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
@MainActor func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
@MainActor func markArticles(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws {
guard let account else {
return
}
Self.logger.debug("ReaderAPIAccountDelegate: markArticles — statusKey \(statusKey.rawValue)")
let updatedArticles = await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag)
@@ -552,15 +602,18 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account)
}
if let count = await syncDatabase.selectPendingCount(), count > 100 {
try? await sendArticleStatus(for: account)
try? await sendArticleStatus()
}
}
func accountDidInitialize(_ account: Account) {
func accountDidInitialize() {
guard let account else {
return
}
retrieveCredentialsIfNeeded(account)
}
func accountWillBeDeleted(_ account: Account) {
func accountWillBeDeleted() {
}
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
@@ -575,7 +628,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
return try await caller.validateCredentials(endpoint: endpoint)
}
func vacuumDatabases(for account: Account) async {
func vacuumDatabases() async {
guard let account else {
return
}
await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) {
await syncDatabase.vacuum()
}
@@ -591,10 +647,12 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
/// Resume network activity after a previous `suspendNetwork()`.
func resume(account: Account) {
func resume() {
Self.logger.debug("ReaderAPIAccountDelegate: resume")
retrieveCredentialsIfNeeded(account)
if let account {
retrieveCredentialsIfNeeded(account)
}
}
// MARK: - Notifications
@@ -899,7 +957,7 @@ private extension ReaderAPIAccountDelegate {
try await account.addFeed(feed, container: container)
if let name {
try await renameFeed(for: account, with: feed, to: name)
try await renameFeed(with: feed, to: name)
}
try await initialFeedDownload(account: account, feed: feed)
@@ -921,7 +979,7 @@ private extension ReaderAPIAccountDelegate {
_ = await account.markAsReadAsync(articleIDs: Set(articleIDs))
refreshProgress.completeTask()
try? await refreshArticleStatus(for: account)
try? await refreshArticleStatus()
refreshProgress.completeTask()
await refreshMissingArticles(account)