diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index f386d2dec..c96796f6c 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -300,8 +300,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat ArticleThemeDownloader.shared.cleanUp() - AccountManager.shared.sendArticleStatusAll() { - self.isShutDownSyncDone = true + Task { @MainActor in + await AccountManager.shared.sendArticleStatusAll() + isShutDownSyncDone = true } let timeout = Date().addingTimeInterval(2) @@ -502,7 +503,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat } @IBAction func refreshAll(_ sender: Any?) { - AccountManager.shared.refreshAll(errorHandler: ErrorHandler.present) + AccountManager.shared.refreshAllWithoutWaiting(errorHandler: ErrorHandler.present) } @IBAction func showAddFeedWindow(_ sender: Any?) { diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index bbe74f5f2..5ae0333eb 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -47,7 +47,6 @@ public enum AccountType: Int, Codable { public var isDeveloperRestricted: Bool { return self == .cloudKit || self == .feedbin || self == .feedly || self == .inoreader } - } public enum FetchType { @@ -62,7 +61,6 @@ public enum FetchType { } public final class Account: DisplayNameProvider, UnreadCountProvider, Container, Hashable { - public struct UserInfoKey { public static let account = "account" // UserDidAddAccount, UserDidDeleteAccount public static let newArticles = "newArticles" // AccountDidDownloadArticles @@ -317,7 +315,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - // MARK: - API + // MARK: - Credentials @MainActor public func storeCredentials(_ credentials: Credentials) throws { username = credentials.username @@ -398,10 +396,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, await delegate.receiveRemoteNotification(for: self, userInfo: userInfo) } + // MARK: - Refreshing + @MainActor public func refreshAll() async throws { try await delegate.refreshAll(for: self) } + // MARK: - Syncing Article Status + @MainActor public func sendArticleStatus() async throws { try await delegate.sendArticleStatus(for: self) } @@ -410,6 +412,8 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, try await delegate.syncArticleStatus(for: self) } + // MARK: - OPML + public func importOPML(_ opmlFile: URL, completion: @escaping (Result) -> Void) { guard !delegate.isOPMLImportInProgress else { completion(.failure(AccountError.opmlImportInProgress)) @@ -429,6 +433,8 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } + // MARK: - Suspend/Resume + @MainActor public func suspendNetwork() { delegate.suspendNetwork() } @@ -454,6 +460,8 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, fetchAllUnreadCounts() } + // MARK: - Data + public func save() { MainActor.assumeIsolated { metadataFile.save() @@ -680,119 +688,86 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, structureDidChange() } - public func updateUnreadCounts(for feeds: Set, completion: VoidCompletionBlock? = nil) { - fetchUnreadCounts(for: feeds, completion: completion) + public func updateUnreadCounts(feeds: Set) { + fetchUnreadCounts(for: feeds) } + // MARK: - Fetching Articles + @MainActor public func fetchArticles(_ fetchType: FetchType) throws -> Set
{ switch fetchType { case .starred(let limit): - return try fetchStarredArticles(limit: limit) + return try _fetchStarredArticles(limit: limit) case .unread(let limit): - return try fetchUnreadArticles(limit: limit) + return try _fetchUnreadArticles(limit: limit) case .today(let limit): - return try fetchTodayArticles(limit: limit) + return try _fetchTodayArticles(limit: limit) case .folder(let folder, let readFilter): if readFilter { - return try fetchUnreadArticles(folder: folder) + return try _fetchUnreadArticles(container: folder) } else { - return try fetchArticles(folder: folder) + return try _fetchArticles(container: folder) } case .feed(let feed): - return try fetchArticles(feed: feed) + return try _fetchArticles(feed: feed) case .articleIDs(let articleIDs): - return try fetchArticles(articleIDs: articleIDs) + return try _fetchArticles(articleIDs: articleIDs) case .search(let searchString): - return try fetchArticlesMatching(searchString) + return try _fetchArticlesMatching(searchString) case .searchWithArticleIDs(let searchString, let articleIDs): - return try fetchArticlesMatchingWithArticleIDs(searchString, articleIDs) + return try _fetchArticlesMatchingWithArticleIDs(searchString, articleIDs) } } - @MainActor public func fetchArticles(_ fetchType: FetchType) async throws -> Set
{ - try await withCheckedThrowingContinuation { continuation in - fetchArticlesAsync(fetchType) { result in - continuation.resume(with: result) - } - } - } - - @MainActor public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { + @MainActor public func fetchArticlesAsync(_ fetchType: FetchType) async throws -> Set
{ switch fetchType { case .starred(let limit): - fetchStarredArticlesAsync(limit: limit, completion) + return try await _fetchStarredArticlesAsync(limit: limit) case .unread(let limit): - fetchUnreadArticlesAsync(limit: limit, completion) + return try await _fetchUnreadArticlesAsync(limit: limit) case .today(let limit): - fetchTodayArticlesAsync(limit: limit, completion) + return try await _fetchTodayArticlesAsync(limit: limit) case .folder(let folder, let readFilter): if readFilter { - return fetchUnreadArticlesAsync(folder: folder, completion) + return try await _fetchUnreadArticlesAsync(container: folder) } else { - return fetchArticlesAsync(folder: folder, completion) + return try await _fetchArticlesAsync(container: folder) } case .feed(let feed): - fetchArticlesAsync(feed: feed, completion) + return try await _fetchArticlesAsync(feed: feed) case .articleIDs(let articleIDs): - fetchArticlesAsync(articleIDs: articleIDs, completion) + return try await _fetchArticlesAsync(articleIDs: articleIDs) case .search(let searchString): - fetchArticlesMatchingAsync(searchString, completion) + return try await _fetchArticlesMatchingAsync(searchString) case .searchWithArticleIDs(let searchString, let articleIDs): - return fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs, completion) + return try await _FetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs) } } - public func fetchUnreadCountForToday(_ completion: @escaping SingleUnreadCountCompletionBlock) { - database.fetchUnreadCountForToday(for: flattenedFeeds().feedIDs(), completion: completion) - } - - public func fetchUnreadCountForStarredArticles(_ completion: @escaping SingleUnreadCountCompletionBlock) { - database.fetchStarredAndUnreadCount(for: flattenedFeeds().feedIDs(), completion: completion) - } - - public func fetchCountForStarredArticles() throws -> Int { - return try database.fetchStarredArticlesCount(flattenedFeeds().feedIDs()) - } - - public func fetchUnreadArticleIDs() async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - fetchUnreadArticleIDs { result in - continuation.resume(with: result) - } - } + public func fetchUnreadCountForStarredArticlesAsync() async throws -> Int? { + try await database.fetchUnreadCountForStarredArticlesAsync(feedIDs: flattenedFeeds().feedIDs()) } - public func fetchUnreadArticleIDs(_ completion: @escaping ArticleIDsCompletionBlock) { - database.fetchUnreadArticleIDsAsync(completion: completion) + public func fetchCountForStarredArticles() throws -> Int { + try database.fetchStarredArticlesCount(feedIDs: flattenedFeeds().feedIDs()) } - public func fetchStarredArticleIDs() async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - fetchStarredArticleIDs { result in - continuation.resume(with: result) - } - } + public func fetchUnreadArticleIDsAsync() async throws -> Set { + try await database.fetchUnreadArticleIDsAsync() } - public func fetchStarredArticleIDs(_ completion: @escaping ArticleIDsCompletionBlock) { - database.fetchStarredArticleIDsAsync(completion: completion) + public func fetchStarredArticleIDsAsync() async throws -> Set { + try await database.fetchStarredArticleIDsAsync() } - + /// Fetch articleIDs for articles that we should have, but don’t. These articles are either (starred) or (newer than the article cutoff date). - @MainActor public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate() async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in - continuation.resume(with: result) - } - } - } - - public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { - database.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(completion) + @MainActor public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() async throws -> Set { + try await database.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() } + // MARK: - Unread Counts public func unreadCount(for feed: Feed) -> Int { - return unreadCounts[feed.feedID] ?? 0 + unreadCounts[feed.feedID] ?? 0 } public func setUnreadCount(_ unreadCount: Int, for feed: Feed) { @@ -807,247 +782,125 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, feedDictionariesNeedUpdate = true } - @discardableResult - @MainActor func update(_ feed: Feed, with parsedFeed: ParsedFeed) async throws -> ArticleChanges { - try await withCheckedThrowingContinuation { continuation in - update(feed, with: parsedFeed) { result in - switch result { - case .success(let articleChanges): - continuation.resume(returning: articleChanges) - case .failure(let error): - continuation.resume(throwing: error) - } - } - } - } + // MARK: - Updating Feeds - @MainActor func update(_ feed: Feed, with parsedFeed: ParsedFeed, _ completion: @escaping UpdateArticlesCompletionBlock) { - // Used only by an On My Mac or iCloud account. + @discardableResult + @MainActor func updateAsync(feed: Feed, with parsedFeed: ParsedFeed) async throws -> ArticleChanges { precondition(Thread.isMainThread) precondition(type == .onMyMac || type == .cloudKit) feed.takeSettings(from: parsedFeed) let parsedItems = parsedFeed.items guard !parsedItems.isEmpty else { - completion(.success(ArticleChanges())) - return + return ArticleChanges() } - update(feed.feedID, with: parsedItems, completion: completion) + return try await updateAsync(feedID: feed.feedID, parsedItems: parsedItems) } - @MainActor func update(_ feedID: String, with parsedItems: Set, deleteOlder: Bool = true) async throws -> ArticleChanges { - try await withCheckedThrowingContinuation { continuation in - update(feedID, with: parsedItems, deleteOlder: deleteOlder) { result in - continuation.resume(with: result) - } - } - } - - @MainActor func update(_ feedID: String, with parsedItems: Set, deleteOlder: Bool = true, completion: @escaping UpdateArticlesCompletionBlock) { + @MainActor func updateAsync(feedID: String, parsedItems: Set, deleteOlder: Bool = true) async throws -> ArticleChanges { // 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 - Task { @MainActor in - switch updateArticlesResult { - case .success(let articleChanges): - self.sendNotificationAbout(articleChanges) - completion(.success(articleChanges)) - case .failure(let databaseError): - completion(.failure(databaseError)) - } - } - } + let articleChanges = try await database.updateAsync(parsedItems: parsedItems, feedID: feedID, deleteOlder: deleteOlder) + sendNotificationAbout(articleChanges) + return articleChanges } - @MainActor func update(feedIDsAndItems: [String: Set], defaultRead: Bool) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - update(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead) { error in - if let error { - continuation.resume(throwing: error) - } else { - continuation.resume(returning: ()) - } - } - } - } - - @MainActor private func update(feedIDsAndItems: [String: Set], defaultRead: Bool, completion: @escaping DatabaseCompletionBlock) { + @MainActor func updateAsync(feedIDsAndItems: [String: Set], defaultRead: Bool) async throws { // Used only by syncing systems. precondition(Thread.isMainThread) precondition(type != .onMyMac && type != .cloudKit) guard !feedIDsAndItems.isEmpty else { - completion(nil) return } - database.update(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead) { updateArticlesResult in - Task { @MainActor in - switch updateArticlesResult { - case .success(let newAndUpdatedArticles): - self.sendNotificationAbout(newAndUpdatedArticles) - completion(nil) - case .failure(let databaseError): - completion(databaseError) - } - } - } + let newAndUpdatedArticles = try await database.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead) + sendNotificationAbout(newAndUpdatedArticles) } + /// Returns set of Article whose statuses did change. @discardableResult - @MainActor func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set
{ - try await withCheckedThrowingContinuation { continuation in - update(articles, statusKey: statusKey, flag: flag) { result in - continuation.resume(with: result) - } - } - } - - @MainActor func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleSetResultBlock) { - // Returns set of Articles whose statuses did change. + @MainActor func updateAsync(articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set
{ guard !articles.isEmpty else { - completion(.success(Set
())) - return + return Set
() } - Task { @MainActor in - do { - let updatedStatuses = try await database.mark(articles, statusKey: statusKey, flag: flag) - let updatedArticleIDs = updatedStatuses.articleIDs() - let updatedArticles = Set(articles.filter{ updatedArticleIDs.contains($0.articleID) }) - self.noteStatusesForArticlesDidChange(updatedArticles) + let updatedStatuses = try await database.markAsync(articles: articles, statusKey: statusKey, flag: flag) + let updatedArticleIDs = updatedStatuses.articleIDs() + let updatedArticles = Set(articles.filter{ updatedArticleIDs.contains($0.articleID) }) + noteStatusesForArticlesDidChange(updatedArticles) - completion(.success(updatedArticles)) - } catch let error as DatabaseError { - completion(.failure(error)) - } - } + return updatedArticles } + // MARK: - Article Statuses + /// Make sure statuses exist. Any existing statuses won’t be touched. /// All created statuses will be marked as read and not starred. /// Sends a .StatusesDidChange notification. - func createStatusesIfNeeded(articleIDs: Set) async throws { - try await database.createStatusesIfNeeded(articleIDs: articleIDs) + func createStatusesIfNeededAsync(articleIDs: Set) async throws { + guard !articleIDs.isEmpty else { + return + } + try await database.createStatusesIfNeededAsync(articleIDs: articleIDs) noteStatusesForArticleIDsDidChange(articleIDs) } -// func createStatusesIfNeeded(articleIDs: Set, completion: DatabaseCompletionBlock? = nil) { -// guard !articleIDs.isEmpty else { -// completion?(nil) -// return -// } -// database.createStatusesIfNeeded(articleIDs: articleIDs) { error in -// if let error = error { -// completion?(error) -// return -// } -// self.noteStatusesForArticleIDsDidChange(articleIDs) -// completion?(nil) -// } -// } - /// Mark articleIDs statuses based on statusKey and flag. + /// /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. - func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool, completion: ArticleIDsCompletionBlock? = nil) { + func markAndFetchNewAsync(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { guard !articleIDs.isEmpty else { - completion?(.success(Set())) - return - } - Task { @MainActor in - do { - let newArticleStatusIDs = try await database.markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) - self.noteStatusesForArticleIDsDidChange(articleIDs: articleIDs, statusKey: statusKey, flag: flag) - completion?(.success(newArticleStatusIDs)) - } catch { - completion?(.failure(error)) - } + return Set() } + + let newArticleStatusIDs = try await database.markAndFetchNewAsync(articleIDs: articleIDs, statusKey: statusKey, flag: flag) + noteStatusesForArticleIDsDidChange(articleIDs: articleIDs, statusKey: statusKey, flag: flag) + return newArticleStatusIDs } - /// Mark articleIDs as read. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. - /// Returns a set of new article statuses. + /// Mark articleIDs as read. + /// + /// - Returns: Set of new article statuses. + /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. @discardableResult - func markAsRead(_ articleIDs: Set) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - markAsRead(articleIDs) { result in - continuation.resume(with: result) - } - } + func markAsReadAsync(articleIDs: Set) async throws -> Set { + try await markAndFetchNewAsync(articleIDs: articleIDs, statusKey: .read, flag: true) } - func markAsRead(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { - markAndFetchNew(articleIDs: articleIDs, statusKey: .read, flag: true, completion: completion) - } - - /// Mark articleIDs as unread. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. - /// Returns a set of new article statuses. + /// Mark articleIDs as unread. + /// - Returns: Set of new article statuses. + /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. @discardableResult - func markAsUnread(_ articleIDs: Set) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - markAsUnread(articleIDs) { result in - continuation.resume(with: result) - } - } - } - - func markAsUnread(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { - markAndFetchNew(articleIDs: articleIDs, statusKey: .read, flag: false, completion: completion) + func markAsUnreadAsync(articleIDs: Set) async throws -> Set { + try await markAndFetchNewAsync(articleIDs: articleIDs, statusKey: .read, flag: false) } - /// Mark articleIDs as starred. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. - /// Returns a set of new article statuses. + /// Mark articleIDs as starred. + /// - Returns: Set of new article statuses. + /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. @discardableResult - func markAsStarred(_ articleIDs: Set) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - markAsStarred(articleIDs) { result in - continuation.resume(with: result) - } - } + func markAsStarredAsync(articleIDs: Set) async throws -> Set { + try await markAndFetchNewAsync(articleIDs: articleIDs, statusKey: .starred, flag: true) } - func markAsStarred(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { - markAndFetchNew(articleIDs: articleIDs, statusKey: .starred, flag: true, completion: completion) - } - - /// Mark articleIDs as unstarred. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. - /// Returns a set of new article statuses. + /// Mark articleIDs as unstarred. + /// - Returns: Set of new article statuses. + /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. @discardableResult - func markAsUnstarred(_ articleIDs: Set) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - markAsUnstarred(articleIDs) { result in - continuation.resume(with: result) - } - } - } - - func markAsUnstarred(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { - markAndFetchNew(articleIDs: articleIDs, statusKey: .starred, flag: false, completion: completion) + func markAsUnstarredAsync(articleIDs: Set) async throws -> Set { + try await markAndFetchNewAsync(articleIDs: articleIDs, statusKey: .starred, flag: false) } // Delete the articles associated with the given set of articleIDs func delete(articleIDs: Set) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) - in - delete(articleIDs: articleIDs) { error in - if let error { - continuation.resume(throwing: error) - } else { - continuation.resume(returning: ()) - } - } - } - } - - func delete(articleIDs: Set, completion: DatabaseCompletionBlock? = nil) { guard !articleIDs.isEmpty else { - completion?(nil) return } - database.delete(articleIDs: articleIDs, completion: completion) + try await database.deleteAsync(articleIDs: articleIDs) } /// Empty caches that can reasonably be emptied. Call when the app goes in the background, for instance. @@ -1189,17 +1042,18 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, // MARK: - AccountMetadataDelegate -extension Account: AccountMetadataDelegate { - @MainActor func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) { +@MainActor extension Account: AccountMetadataDelegate { + + func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) { metadataFile.markAsDirty() } } // MARK: - FeedMetadataDelegate -extension Account: FeedMetadataDelegate { +@MainActor extension Account: FeedMetadataDelegate { - @MainActor func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) { + func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) { feedMetadataFile.markAsDirty() guard let feed = existingFeed(withFeedID: feedMetadata.feedID) else { return @@ -1208,123 +1062,57 @@ extension Account: FeedMetadataDelegate { } } -// MARK: - Fetching (Private) +// MARK: - Fetching Articles (Private) -private extension Account { +@MainActor private extension Account { - func fetchStarredArticles(limit: Int?) throws -> Set
{ - return try database.fetchStarredArticles(flattenedFeeds().feedIDs(), limit) + // MARK: - Starred Articles + + func _fetchStarredArticles(limit: Int? = nil) throws -> Set
{ + try database.fetchStarredArticles(feedIDs: flattenedFeeds().feedIDs(), limit: limit) } - func fetchStarredArticlesAsync(limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - database.fetchedStarredArticlesAsync(flattenedFeeds().feedIDs(), limit, completion) + func _fetchStarredArticlesAsync(limit: Int? = nil) async throws -> Set
{ + try await database.fetchedStarredArticlesAsync(feedIDs: flattenedFeeds().feedIDs(), limit: limit) } - func fetchUnreadArticles(limit: Int?) throws -> Set
{ - return try fetchUnreadArticles(forContainer: self, limit: limit) + // MARK: - Account Unread Articles + + func _fetchUnreadArticles(limit: Int? = nil) throws -> Set
{ + try fetchUnreadArticles(container: self, limit: limit) } - func fetchUnreadArticlesAsync(limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - fetchUnreadArticlesAsync(forContainer: self, limit: limit, completion) + func _fetchUnreadArticlesAsync(limit: Int? = nil) async throws -> Set
{ + try await fetchUnreadArticlesAsync(container: self, limit: limit) } - func fetchTodayArticles(limit: Int?) throws -> Set
{ - return try database.fetchTodayArticles(flattenedFeeds().feedIDs(), limit) + // MARK: - Today Articles + + func _fetchTodayArticles(limit: Int? = nil) throws -> Set
{ + try database.fetchTodayArticles(flattenedFeeds().feedIDs(), limit) } - func fetchTodayArticlesAsync(limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - database.fetchTodayArticlesAsync(flattenedFeeds().feedIDs(), limit, completion) + func _fetchTodayArticlesAsync(limit: Int? = nil) async throws -> Set
{ + try await database.fetchTodayArticlesAsync(flattenedFeeds().feedIDs(), limit) } - func fetchArticles(folder: Folder) throws -> Set
{ - return try fetchArticles(forContainer: folder) - } + // MARK: - Container Articles - func fetchArticlesAsync(folder: Folder, _ completion: @escaping ArticleSetResultBlock) { - fetchArticlesAsync(forContainer: folder, completion) - } - - func fetchUnreadArticles(folder: Folder) throws -> Set
{ - return try fetchUnreadArticles(forContainer: folder, limit: nil) - } - - func fetchUnreadArticlesAsync(folder: Folder, _ completion: @escaping ArticleSetResultBlock) { - fetchUnreadArticlesAsync(forContainer: folder, limit: nil, completion) - } - - @MainActor func fetchArticles(feed: Feed) throws -> Set
{ - let articles = try database.fetchArticles(feed.feedID) - validateUnreadCount(feed, articles) - return articles - } - - @MainActor func fetchArticlesAsync(feed: Feed, _ completion: @escaping ArticleSetResultBlock) { - database.fetchArticlesAsync(feed.feedID) { [weak self] articleSetResult in - Task { @MainActor in - switch articleSetResult { - case .success(let articles): - self?.validateUnreadCount(feed, articles) - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) - } - } - } - } - - func fetchArticlesMatching(_ searchString: String) throws -> Set
{ - return try database.fetchArticlesMatching(searchString, flattenedFeeds().feedIDs()) - } - - 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) - } - - func fetchArticlesMatchingWithArticleIDsAsync(_ searchString: String, _ articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - database.fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs, completion) - } - - func fetchArticles(articleIDs: Set) throws -> Set
{ - return try database.fetchArticles(articleIDs: articleIDs) - } - - func fetchArticlesAsync(articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - return database.fetchArticlesAsync(articleIDs: articleIDs, completion) - } - - @MainActor func fetchUnreadArticles(feed: Feed) throws -> Set
{ - let articles = try database.fetchUnreadArticles(Set([feed.feedID]), nil) - validateUnreadCount(feed, articles) - return articles - } - - func fetchArticles(forContainer container: Container) throws -> Set
{ + func _fetchArticles(container: Container) throws -> Set
{ let feeds = container.flattenedFeeds() let articles = try database.fetchArticles(feeds.feedIDs()) validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) return articles } - func fetchArticlesAsync(forContainer container: Container, _ completion: @escaping ArticleSetResultBlock) { + func _fetchArticlesAsync(container: Container) async throws -> Set
{ let feeds = container.flattenedFeeds() - database.fetchArticlesAsync(feeds.feedIDs()) { [weak self] (articleSetResult) in - Task { @MainActor in - switch articleSetResult { - case .success(let articles): - self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) - } - } - } + let articles = try await database.fetchArticlesAsync(feeds.feedIDs()) + validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) + return articles } - func fetchUnreadArticles(forContainer container: Container, limit: Int?) throws -> Set
{ + func _fetchUnreadArticles(container: Container, limit: Int? = nil) throws -> Set
{ let feeds = container.flattenedFeeds() let articles = try database.fetchUnreadArticles(feeds.feedIDs(), limit) @@ -1337,28 +1125,71 @@ private extension Account { return articles } - func fetchUnreadArticlesAsync(forContainer container: Container, limit: Int?, _ completion: @escaping ArticleSetResultBlock) { + func _fetchUnreadArticlesAsync(container: Container, limit: Int? = nil) async throws -> Set
{ let feeds = container.flattenedFeeds() - database.fetchUnreadArticlesAsync(feeds.feedIDs(), limit) { [weak self] (articleSetResult) in - Task { @MainActor in - switch articleSetResult { - case .success(let articles): + let articles = try await database.fetchUnreadArticlesAsync(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 { - self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) - } - - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) - } - } + // 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 } - func validateUnreadCountsAfterFetchingUnreadArticles(_ feeds: Set, _ articles: Set
) { + + // MARK: - Feed Articles + + func _fetchArticles(feed: Feed) throws -> Set
{ + let articles = try database.fetchArticles(feed.feedID) + validateUnreadCount(feed, articles) + return articles + } + + func _fetchArticlesAsync(feed: Feed) async throws -> Set
{ + let articles = try await database.fetchArticlesAsync(feed.feedID) + validateUnreadCount(feed, articles) + return articles + } + + func _fetchUnreadArticles(feed: Feed) throws -> Set
{ + let articles = try database.fetchUnreadArticles(Set([feed.feedID]), nil) + validateUnreadCount(feed, articles) + return articles + } + + // MARK: - ArticleIDs Articles + + func _fetchArticles(articleIDs: Set) throws -> Set
{ + try database.fetchArticles(articleIDs: articleIDs) + } + + func _fetchArticlesAsync(articleIDs: Set) async throws -> Set
{ + try await database.fetchArticlesAsync(articleIDs: articleIDs) + } + + // MARK: - Search Articles + + func _fetchArticlesMatching(_ searchString: String) throws -> Set
{ + try database.fetchArticlesMatching(searchString, flattenedFeeds().feedIDs()) + } + + func _fetchArticlesMatchingAsync(_ searchString: String) async throws -> Set
{ + try await database.fetchArticlesMatchingAsync(searchString, flattenedFeeds().feedIDs()) + } + + func _fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set) throws -> Set
{ + try database.fetchArticlesMatchingWithArticleIDs(searchString, articleIDs) + } + + func _fetchArticlesMatchingWithArticleIDsAsync(_ searchString: String, _ articleIDs: Set) async throws -> Set
{ + try await database.fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs) + } + + // MARK: - Unread Counts + + private func validateUnreadCountsAfterFetchingUnreadArticles(_ feeds: Set, _ articles: Set
) { // Validate unread counts. This was the site of a performance slowdown: // it was calling going through the entire list of articles once per feed: // feeds.forEach { validateUnreadCount($0, articles) } @@ -1368,30 +1199,96 @@ private extension Account { for article in articles where !article.status.read { unreadCountStorage[article.feedID, default: 0] += 1 } - feeds.forEach { (feed) in + for feed in feeds { let unreadCount = unreadCountStorage[feed.feedID, default: 0] feed.unreadCount = unreadCount } } - @MainActor func validateUnreadCount(_ feed: Feed, _ articles: Set
) { + private func validateUnreadCount(_ feed: Feed, _ articles: Set
) { // articles must contain all the unread articles for the feed. // The unread number should match the feed’s unread count. - - let feedUnreadCount = articles.reduce(0) { (result, article) -> Int in + var feedUnreadCount = 0 + for article in articles { if article.feed == feed && !article.status.read { - return result + 1 + feedUnreadCount += 1 } - return result } - feed.unreadCount = feedUnreadCount } } +// MARK: - Fetching Unread Counts (Private) + +@MainActor private extension Account { + + /// Fetch unread counts for zero or more feeds. + /// + /// Uses the most efficient method based on how many feeds were passed in. + func _fetchUnreadCounts(for feeds: Set) { + if feeds.isEmpty { + return + } + if feeds.count == 1, let feed = feeds.first { + fetchUnreadCount(feed: feed) + } + else if feeds.count < 10 { + fetchUnreadCounts(feeds: feeds) + } + else { + fetchAllUnreadCounts() + } + } + + func _fetchUnreadCount(feed: Feed) { + Task { @MainActor in + guard let unreadCount = try? await database.fetchUnreadCountAsync(feedID: feed.feedID) else { + return + } + feed.unreadCount = unreadCount + } + } + + func _fetchUnreadCounts(feeds: Set) { + Task { @MainActor in + guard let unreadCountDictionary = try? await database.fetchUnreadCountsAsync(feedIDs: feeds.feedIDs()) else { + return + } + processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: feeds) + } + } + + func _fetchAllUnreadCounts() { + fetchingAllUnreadCounts = true + + Task { @MainActor in + guard let unreadCountDictionary = try? await database.fetchAllUnreadCountsAsync() else { + return + } + + processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: flattenedFeeds()) + fetchingAllUnreadCounts = false + updateUnreadCount() + + if !self.areUnreadCountsInitialized { + self.areUnreadCountsInitialized = true + self.postUnreadCountDidInitializeNotification() + } + } + } + + private func processUnreadCounts(unreadCountDictionary: UnreadCountDictionary, feeds: Set) { + for feed in feeds { + // When the unread count is zero, it won’t appear in unreadCountDictionary. + let unreadCount = unreadCountDictionary[feed.feedID] ?? 0 + feed.unreadCount = unreadCount + } + } +} + // MARK: - Private -private extension Account { +@MainActor private extension Account { func feedMetadata(feedURL: String, feedID: String) -> FeedMetadata { if let d = feedMetadata[feedURL] { @@ -1442,7 +1339,7 @@ private extension Account { unreadCount = updatedUnreadCount } - @MainActor func noteStatusesForArticlesDidChange(_ articles: Set
) { + func noteStatusesForArticlesDidChange(_ articles: Set
) { let feeds = Set(articles.compactMap { $0.feed }) let statuses = Set(articles.map { $0.status }) let articleIDs = Set(articles.map { $0.articleID }) @@ -1464,88 +1361,13 @@ private extension Account { NotificationCenter.default.post(name: .StatusesDidChange, object: self, userInfo: [UserInfoKey.articleIDs: articleIDs]) } - /// Fetch unread counts for zero or more feeds. - /// - /// Uses the most efficient method based on how many feeds were passed in. - func fetchUnreadCounts(for feeds: Set, completion: VoidCompletionBlock?) { - if feeds.isEmpty { - completion?() - return - } - if feeds.count == 1, let feed = feeds.first { - fetchUnreadCount(feed, completion) - } - else if feeds.count < 10 { - fetchUnreadCounts(feeds, completion) - } - else { - fetchAllUnreadCounts(completion) - } - } - - func fetchUnreadCount(_ feed: Feed, _ completion: VoidCompletionBlock?) { - Task { @MainActor in - database.fetchUnreadCount(feed.feedID) { result in - Task { @MainActor in - if let result, let unreadCount = try? result.get() { - feed.unreadCount = unreadCount - } - completion?() - } - } - } - } - - func fetchUnreadCounts(_ feeds: Set, _ completion: VoidCompletionBlock?) { - let feedIDs = Set(feeds.map { $0.feedID }) - Task { @MainActor in - database.fetchUnreadCounts(for: feedIDs) { result in - Task { @MainActor in - if let result, let unreadCountDictionary = try? result.get() { - self.processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: feeds) - } - completion?() - } - } - } - } - - func fetchAllUnreadCounts(_ completion: VoidCompletionBlock? = nil) { - fetchingAllUnreadCounts = true - Task { @MainActor in - guard let unreadCountDictionary = try? await database.fetchAllUnreadCounts() else { - completion?() - return - } - - processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: flattenedFeeds()) - fetchingAllUnreadCounts = false - updateUnreadCount() - - if !self.areUnreadCountsInitialized { - self.areUnreadCountsInitialized = true - self.postUnreadCountDidInitializeNotification() - } - - completion?() - } - } - - func processUnreadCounts(unreadCountDictionary: UnreadCountDictionary, feeds: Set) { - for feed in feeds { - // When the unread count is zero, it won’t appear in unreadCountDictionary. - let unreadCount = unreadCountDictionary[feed.feedID] ?? 0 - feed.unreadCount = unreadCount - } - } - - @MainActor func sendNotificationAbout(_ articleChanges: ArticleChanges) { + func sendNotificationAbout(_ articleChanges: ArticleChanges) { var feeds = Set() - if let newArticles = articleChanges.newArticles { + if let newArticles = articleChanges.new { feeds.formUnion(Set(newArticles.compactMap { $0.feed })) } - if let updatedArticles = articleChanges.updatedArticles { + if let updatedArticles = articleChanges.updated { feeds.formUnion(Set(updatedArticles.compactMap { $0.feed })) } @@ -1553,23 +1375,23 @@ private extension Account { var shouldUpdateUnreadCounts = false var userInfo = [String: Any]() - if let newArticles = articleChanges.newArticles, !newArticles.isEmpty { + if let newArticles = articleChanges.new, !newArticles.isEmpty { shouldSendNotification = true shouldUpdateUnreadCounts = true userInfo[UserInfoKey.newArticles] = newArticles } - if let updatedArticles = articleChanges.updatedArticles, !updatedArticles.isEmpty { + if let updatedArticles = articleChanges.updated, !updatedArticles.isEmpty { shouldSendNotification = true userInfo[UserInfoKey.updatedArticles] = updatedArticles } - if let deletedArticles = articleChanges.deletedArticles, !deletedArticles.isEmpty { + if let deletedArticles = articleChanges.deleted, !deletedArticles.isEmpty { shouldUpdateUnreadCounts = true } if shouldUpdateUnreadCounts { - self.updateUnreadCounts(for: feeds) + updateUnreadCounts(feeds: feeds) } if shouldSendNotification { @@ -1590,7 +1412,6 @@ extension Account { public func existingFeed(withExternalID externalID: String) -> Feed? { return externalIDToFeedDictionary[externalID] } - } // MARK: - OPMLRepresentable diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index a09851c0d..2b235ce3e 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -7,6 +7,7 @@ // import Foundation +import os import RSCore import RSWeb import Articles @@ -30,6 +31,9 @@ import RSDatabase private let defaultAccountIdentifier = "OnMyMac" public var isSuspended = false + + private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AccountManager") + @MainActor public var areUnreadCountsInitialized: Bool { for account in activeAccounts { if !account.areUnreadCountsInitialized { @@ -269,51 +273,61 @@ import RSDatabase } } - public func refreshAll(errorHandler: ((Error) -> Void)? = nil, completion: (() -> Void)? = nil) { + public typealias ErrorHandlerCallback = (Error) -> Void + @MainActor public func refreshAllWithoutWaiting(errorHandler: ErrorHandlerCallback? = nil) { + Task { @MainActor in + await refreshAll(errorHandler: errorHandler) + } + } + + @MainActor public func refreshAll(errorHandler: ErrorHandlerCallback? = nil) async { guard NetworkMonitor.shared.isConnected else { + Self.logger.info("AccountManager: skipping refreshAll — not connected to internet.") return } combinedRefreshProgress.start() + defer { + combinedRefreshProgress.stop() + } - Task { @MainActor in - await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in - for account in activeAccounts { - group.addTask { @MainActor in - do { - try await account.refreshAll() - } catch { - errorHandler?(error) - } + await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in + for account in activeAccounts { + group.addTask { @MainActor in + do { + try await account.refreshAll() + } catch { + errorHandler?(error) } } } - - self.combinedRefreshProgress.stop() - completion?() } } - public func sendArticleStatusAll(completion: (() -> Void)? = nil) { - Task { @MainActor in + @MainActor public func sendArticleStatusAll() async { + await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in for account in activeAccounts { - try? await account.sendArticleStatus() + group.addTask { @MainActor in + try? await account.sendArticleStatus() + } } - completion?() } } - @MainActor public func syncArticleStatusAll(completion: (() -> Void)? = nil) { - let group = DispatchGroup() + @MainActor public func syncArticleStatusAllWithoutWaiting() { + Task { @MainActor in + await syncArticleStatusAll() + } + } - for account in activeAccounts { - group.enter() - Task { @MainActor in - try? await account.syncArticleStatus() - group.leave() + @MainActor public func syncArticleStatusAll() async { + await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in + for account in activeAccounts { + group.addTask { @MainActor in + try? await account.syncArticleStatus() + } } - completion?() } } @@ -355,48 +369,38 @@ import RSDatabase var articles = Set
() for account in activeAccounts { - articles.formUnion(try account.fetchArticles(fetchType)) + articles.formUnion(try account.fetchArticlesSync(fetchType)) } return articles } - @MainActor public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { - precondition(Thread.isMainThread) + @MainActor public func fetchArticlesAsync(_ fetchType: FetchType) async throws -> Set
{ + precondition(Thread.isMainThread) - guard activeAccounts.count > 0 else { - completion(.success(Set
())) - return - } + guard activeAccounts.count > 0 else { + return Set
() + } - Task { @MainActor in - var allFetchedArticles = Set
() - var databaseError: DatabaseError? - let dispatchGroup = DispatchGroup() + var allFetchedArticles = Set
() + var fetchError: Error? + await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in for account in activeAccounts { - - dispatchGroup.enter() - defer { - dispatchGroup.leave() - } - - do { - let articles = try await account.fetchArticles(fetchType) - allFetchedArticles.formUnion(articles) - } catch { - databaseError = error as? DatabaseError - } - } - - dispatchGroup.notify(queue: .main) { - if let databaseError { - completion(.failure(databaseError)) - } - else { - completion(.success(allFetchedArticles)) + group.addTask { @MainActor in + do { + let articles = try await account.fetchArticles(fetchType) + allFetchedArticles.formUnion(articles) + } catch { + fetchError = error + } } } } + + if let fetchError { + throw fetchError + } + return allFetchedArticles } // MARK: - Fetching Article Counts diff --git a/Modules/Account/Sources/Account/ArticleFetcher.swift b/Modules/Account/Sources/Account/ArticleFetcher.swift index ed600aebb..316bb3d30 100644 --- a/Modules/Account/Sources/Account/ArticleFetcher.swift +++ b/Modules/Account/Sources/Account/ArticleFetcher.swift @@ -11,82 +11,72 @@ import Articles import ArticlesDatabase public protocol ArticleFetcher { - @MainActor func fetchArticles() throws -> Set
- @MainActor func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) + @MainActor func fetchArticlesAsync() async throws -> Set
@MainActor func fetchUnreadArticles() throws -> Set
- @MainActor func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) + @MainActor func fetchUnreadArticlesAsync() async throws -> Set
} @MainActor extension Feed: ArticleFetcher { public func fetchArticles() throws -> Set
{ - return try account?.fetchArticles(.feed(self)) ?? Set
() + return try account?.fetchArticlesSync(.feed(self)) ?? Set
() } - public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - guard let account = account else { + public func fetchArticlesAsync() async throws -> Set
{ + guard let account else { assertionFailure("Expected feed.account, but got nil.") - completion(.success(Set
())) - return + return Set
() } - account.fetchArticlesAsync(.feed(self), completion) + return try await account.fetchArticles(.feed(self)) } public func fetchUnreadArticles() throws -> Set
{ return try fetchArticles().unreadArticles() } - public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - guard let account = account else { + public func fetchUnreadArticlesAsync() async throws -> Set
{ + guard let account else { assertionFailure("Expected feed.account, but got nil.") - completion(.success(Set
())) - return - } - account.fetchArticlesAsync(.feed(self)) { articleSetResult in - switch articleSetResult { - case .success(let articles): - completion(.success(articles.unreadArticles())) - case .failure(let error): - completion(.failure(error)) - } + return Set
() } + // TODO: fetch only unread articles rather than filtering. + let articles = try await account.fetchArticles(.feed(self)) + return articles.unreadArticles() } } -extension Folder: ArticleFetcher { +@MainActor extension Folder: ArticleFetcher { public func fetchArticles() throws -> Set
{ - guard let account = account else { + guard let account else { assertionFailure("Expected folder.account, but got nil.") return Set
() } - return try account.fetchArticles(.folder(self, false)) + return try account.fetchArticlesSync(.folder(self, false)) } - public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - guard let account = account else { + public func fetchArticlesAsync() async throws -> Set
{ + guard let account else { assertionFailure("Expected folder.account, but got nil.") - completion(.success(Set
())) - return + return Set
() } - account.fetchArticlesAsync(.folder(self, false), completion) + return try await account.fetchArticles(.folder(self, false)) } public func fetchUnreadArticles() throws -> Set
{ - guard let account = account else { + guard let account else { assertionFailure("Expected folder.account, but got nil.") return Set
() } - return try account.fetchArticles(.folder(self, true)) + return try account.fetchArticlesSync(.folder(self, true)) } - public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - guard let account = account else { + public func fetchUnreadArticlesAsync() async throws -> Set
{ + guard let account else { assertionFailure("Expected folder.account, but got nil.") - completion(.success(Set
())) - return + return Set
() } - account.fetchArticlesAsync(.folder(self, true), completion) + return try await account.fetchArticles(.folder(self, true)) } } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 86c2bf995..65f4154af 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -335,7 +335,7 @@ enum CloudKitAccountDelegateError: LocalizedError { } @MainActor func markArticles(for account: Account, articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws { - let articles = try await account.update(articles, statusKey: statusKey, flag: flag) + let articles = try 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) }) @@ -541,7 +541,7 @@ private extension CloudKitAccountDelegate { } @MainActor func updateAndCreateFeedInCloud(account: Account, feed: Feed, parsedFeed: ParsedFeed, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws { - let _ = try await account.update(feed, with: parsedFeed) + let _ = try await account.updateAsync(feed: feed, with: parsedFeed) let externalID = try await accountZone.createFeed(url: bestFeedSpecifier.urlString, name: parsedFeed.title, @@ -576,7 +576,7 @@ private extension CloudKitAccountDelegate { func sendNewArticlesToTheCloud(_ account: Account, _ feed: Feed) { Task { do { - let articles = try await account.fetchArticles(.feed(feed)) + let articles = try await account.fetchArticlesAsync(.feed(feed)) await storeArticleChanges(new: articles, updated: Set
(), deleted: Set
()) syncProgress.completeTask() @@ -681,9 +681,9 @@ extension CloudKitAccountDelegate: LocalAccountRefresherDelegate { func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges) { Task { - await storeArticleChanges(new: articleChanges.newArticles, - updated: articleChanges.updatedArticles, - deleted: articleChanges.deletedArticles) + await storeArticleChanges(new: articleChanges.new, + updated: articleChanges.updated, + deleted: articleChanges.deleted) } } } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index ad94335ac..37bad8850 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -85,7 +85,7 @@ private extension CloudKitArticlesZoneDelegate { await withTaskGroup(of: Void.self) { group in group.addTask { @MainActor in do { - try await self.account?.markAsUnread(updateableUnreadArticleIDs) + try await self.account?.markAsUnreadAsync(articleIDs: updateableUnreadArticleIDs) } catch { errorOccurred = true Self.logger.error("CloudKit: Error while storing unread statuses: \(error.localizedDescription)") @@ -94,7 +94,7 @@ private extension CloudKitArticlesZoneDelegate { group.addTask { @MainActor in do { - try await self.account?.markAsRead(updateableReadArticleIDs) + try await self.account?.markAsReadAsync(articleIDs: updateableReadArticleIDs) } catch { errorOccurred = true Self.logger.error("CloudKit: Error while storing read statuses: \(error.localizedDescription)") @@ -103,7 +103,7 @@ private extension CloudKitArticlesZoneDelegate { group.addTask { @MainActor in do { - try await self.account?.markAsUnstarred(updateableUnstarredArticleIDs) + try await self.account?.markAsUnstarredAsync(articleIDs: updateableUnstarredArticleIDs) } catch { errorOccurred = true Self.logger.error("CloudKit: Error while storing unstarred statuses: \(error.localizedDescription)") @@ -112,7 +112,7 @@ private extension CloudKitArticlesZoneDelegate { group.addTask { @MainActor in do { - try await self.account?.markAsStarred(updateableStarredArticleIDs) + try await self.account?.markAsStarredAsync(articleIDs: updateableStarredArticleIDs) } catch { errorOccurred = true Self.logger.error("CloudKit: Error while storing starred statuses: \(error.localizedDescription)") @@ -122,10 +122,10 @@ private extension CloudKitArticlesZoneDelegate { for (feedID, parsedItems) in feedIDsAndItems { group.addTask { @MainActor in do { - guard let articleChanges = try await self.account?.update(feedID, with: parsedItems, deleteOlder: false) else { + guard let articleChanges = try await self.account?.updateAsync(feedID: feedID, parsedItems: parsedItems, deleteOlder: false) else { return } - guard let deletes = articleChanges.deletedArticles, !deletes.isEmpty else { + guard let deletes = articleChanges.deleted, !deletes.isEmpty else { return } let syncStatuses = Set(deletes.map { SyncStatus(articleID: $0.articleID, key: .deleted, flag: true) }) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index eda675f6c..02b676d55 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -19,6 +19,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl private weak var account: Account? private weak var articlesZone: CloudKitArticlesZone? private weak var refreshProgress: DownloadProgress? + private let localProgress = DownloadProgress(numberOfTasks: 0) private var showProgress: Bool private var syncDatabase: SyncDatabase private static let logger = cloudKitLogger @@ -30,126 +31,110 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl self.showProgress = showProgress self.syncDatabase = database super.init(name: "CloudKitSendStatusOperation") + + if showProgress { + refreshProgress.addChild(self.localProgress) + } } @MainActor override func run() { Self.logger.debug("iCloud: Sending article statuses") - if showProgress { - Task { @MainActor in - do { - let count = (try await syncDatabase.selectPendingCount()) ?? 0 - let ticks = count / blockSize - refreshProgress?.addTasks(ticks) - selectForProcessing() - } catch { - Self.logger.debug("iCloud: Send status count pending error: \(error.localizedDescription)") - didComplete() - } - } - } else { - selectForProcessing() - } - } -} - -private extension CloudKitSendStatusOperation { - - func selectForProcessing() { Task { @MainActor in - - @MainActor func stopProcessing() { - if self.showProgress { - self.refreshProgress?.completeTask() - } - Self.logger.debug("iCloud: Finished sending article statuses") + defer { + localProgress.completeAll() didComplete() } do { - guard let syncStatuses = try await self.syncDatabase.selectForProcessing(limit: blockSize), !syncStatuses.isEmpty else { - stopProcessing() - return + if showProgress { + let count = (try await syncDatabase.selectPendingCount()) ?? 0 + let ticks = count / blockSize + localProgress.addTasks(ticks) } - self.processStatuses(Array(syncStatuses)) { stop in - if stop { - stopProcessing() - } else { - self.selectForProcessing() - } - } + await selectForProcessing() + Self.logger.debug("iCloud: Finished sending article statuses") } catch { Self.logger.debug("iCloud: Send status error: \(error.localizedDescription)") - didComplete() } } } +} - @MainActor func processStatuses(_ syncStatuses: [SyncStatus], completion: @escaping (Bool) -> Void) { +@MainActor private extension CloudKitSendStatusOperation { + + func selectForProcessing() async { + defer { + if showProgress { + localProgress.completeTask() + } + } + + do { + guard let syncStatuses = try await syncDatabase.selectForProcessing(limit: blockSize), + !syncStatuses.isEmpty else { + return + } + + let stopProcessing = await processStatuses(Array(syncStatuses)) + if stopProcessing { + return + } + + await selectForProcessing() + } catch { + Self.logger.debug("iCloud: Send status error: \(error.localizedDescription)") + } + } + + /// Returns true if processing should stop. + func processStatuses(_ syncStatuses: [SyncStatus]) async -> Bool { guard let account, let articlesZone else { - completion(true) - return + return true } let articleIDs = syncStatuses.map({ $0.articleID }) - account.fetchArticlesAsync(.articleIDs(Set(articleIDs))) { [syncStatuses] result in + let articles: Set
- func processWithArticles(_ articles: Set
) { - Task { @MainActor [syncStatuses] in + do { + articles = try await account.fetchArticlesAsync(.articleIDs(Set(articleIDs))) + } catch { + try? await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) + Self.logger.error("iCloud: Send article status fetch articles error: \(error.localizedDescription)") + return true + } - let syncStatusesDict = Dictionary(grouping: syncStatuses, by: { $0.articleID }) - let articlesDict = articles.reduce(into: [String: Article]()) { result, article in - result[article.articleID] = article - } - let statusUpdates = syncStatusesDict.compactMap { (key, value) in - return CloudKitArticleStatusUpdate(articleID: key, statuses: value, article: articlesDict[key]) - } + let syncStatusesDict = Dictionary(grouping: syncStatuses, by: { $0.articleID }) + let articlesDict = articles.reduce(into: [String: Article]()) { result, article in + result[article.articleID] = article + } + let statusUpdates = syncStatusesDict.compactMap { (key, value) in + CloudKitArticleStatusUpdate(articleID: key, statuses: value, article: articlesDict[key]) + } - func done(_ stop: Bool) { - if self.showProgress { - self.refreshProgress?.completeTask() - } - Self.logger.debug("iCloud: Finished sending article status block") - completion(stop) - } - // If this happens, we have somehow gotten into a state where we have new status records - // but the articles didn't come back in the fetch. We need to clean up those sync records - // and stop processing. - if statusUpdates.isEmpty { - try? await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDs)) - done(true) - return - } else { - do { - try await articlesZone.modifyArticles(statusUpdates) - try? await self.syncDatabase.deleteSelectedForProcessing(Set(statusUpdates.map({ $0.articleID }))) - done(false) - } catch { - try? await self.syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) - self.processAccountError(account, error) - Self.logger.error("iCloud: Send article status modify articles error: \(error.localizedDescription)") - completion(true) - } - } - } - } - - switch result { - case .success(let articles): - processWithArticles(articles) - case .failure(let databaseError): - Task { @MainActor in - try? await self.syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) - Self.logger.error("iCloud: Send article status fetch articles error: \(databaseError.localizedDescription)") - completion(true) - } + // If this happens, we have somehow gotten into a state where we have new status records + // but the articles didn't come back in the fetch. We need to clean up those sync records + // and stop processing. + if statusUpdates.isEmpty { + try? await syncDatabase.deleteSelectedForProcessing(Set(articleIDs)) + return true + } else { + do { + try await articlesZone.modifyArticles(statusUpdates) + try? await syncDatabase.deleteSelectedForProcessing(Set(statusUpdates.map({ $0.articleID }))) + return false + } catch { + try? await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) + processAccountError(account, error) + Self.logger.error("iCloud: Send article status modify articles error: \(error.localizedDescription)") + return true } } } - @MainActor func processAccountError(_ account: Account, _ error: Error) { + func processAccountError(_ account: Account, _ error: Error) { if case CloudKitZoneError.userDeletedZone = error { account.removeFeedsFromTreeAtTopLevel(account.topLevelFeeds) for folder in account.folders ?? Set() { diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index 18d307834..61a1afda9 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -333,7 +333,7 @@ final class FeedbinAccountDelegate: AccountDelegate { } @MainActor func markArticles(for account: Account, articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws { - let articles = try await account.update(articles, statusKey: statusKey, flag: flag) + let articles = try 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) }) @@ -758,7 +758,7 @@ private extension FeedbinAccountDelegate { var savedError: Error? do { - let fetchedArticleIDs = try await account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate() + let fetchedArticleIDs = try await account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() let articleIDs = Array(fetchedArticleIDs) let chunkedArticleIDs = articleIDs.chunked(into: 100) @@ -801,7 +801,7 @@ private extension FeedbinAccountDelegate { @MainActor func processEntries(account: Account, entries: [FeedbinEntry]?) async throws { let parsedItems = mapEntriesToParsedItems(entries: entries) let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL } ).mapValues { Set($0) } - try await account.update(feedIDsAndItems: feedIDsAndItems, defaultRead: true) + try await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true) } func mapEntriesToParsedItems(entries: [FeedbinEntry]?) -> Set { @@ -831,15 +831,15 @@ private extension FeedbinAccountDelegate { let feedbinUnreadArticleIDs = Set(articleIDs.map { String($0) } ) let updatableFeedbinUnreadArticleIDs = feedbinUnreadArticleIDs.subtracting(pendingArticleIDs) - let currentUnreadArticleIDs = try await account.fetchUnreadArticleIDs() + let currentUnreadArticleIDs = try await account.fetchUnreadArticleIDsAsync() // Mark articles as unread let deltaUnreadArticleIDs = updatableFeedbinUnreadArticleIDs.subtracting(currentUnreadArticleIDs) - try await account.markAsUnread(deltaUnreadArticleIDs) + try await account.markAsUnreadAsync(articleIDs: deltaUnreadArticleIDs) // Mark articles as read let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableFeedbinUnreadArticleIDs) - try await account.markAsRead(deltaReadArticleIDs) + try await account.markAsReadAsync(articleIDs: deltaReadArticleIDs) } catch { Self.logger.error("Feedbin: Sync Article Read Status failed: \(error.localizedDescription)") } @@ -858,15 +858,15 @@ private extension FeedbinAccountDelegate { let feedbinStarredArticleIDs = Set(articleIDs.map { String($0) } ) let updatableFeedbinStarredArticleIDs = feedbinStarredArticleIDs.subtracting(pendingArticleIDs) - let currentStarredArticleIDs = try await account.fetchStarredArticleIDs() + let currentStarredArticleIDs = try await account.fetchStarredArticleIDsAsync() // Mark articles as starred let deltaStarredArticleIDs = updatableFeedbinStarredArticleIDs.subtracting(currentStarredArticleIDs) - try await account.markAsStarred(deltaStarredArticleIDs) + try await account.markAsStarredAsync(articleIDs: deltaStarredArticleIDs) // Mark articles as unstarred let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableFeedbinStarredArticleIDs) - try await account.markAsUnstarred(deltaUnstarredArticleIDs) + try await account.markAsUnstarredAsync(articleIDs: deltaUnstarredArticleIDs) } catch { Self.logger.error("Feedbin: Sync Article Starred Status failed: \(error.localizedDescription)") } diff --git a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift index 0077e32d4..d98108afa 100644 --- a/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift +++ b/Modules/Account/Sources/Account/Feedly/Models/FeedlyEntryIdentifierProviding.swift @@ -9,21 +9,21 @@ import Foundation protocol FeedlyEntryIdentifierProviding: AnyObject { - var entryIds: Set { get } + var entryIDs: Set { get } } final class FeedlyEntryIdentifierProvider: FeedlyEntryIdentifierProviding { - private(set) var entryIds: Set + private(set) var entryIDs: Set - init(entryIds: Set = Set()) { - self.entryIds = entryIds + init(entryIDs: Set = Set()) { + self.entryIDs = entryIDs } - func addEntryIds(from provider: FeedlyEntryIdentifierProviding) { - entryIds.formUnion(provider.entryIds) + func addEntryIDs(from provider: FeedlyEntryIdentifierProviding) { + entryIDs.formUnion(provider.entryIDs) } - func addEntryIds(in articleIds: [String]) { - entryIds.formUnion(articleIds) + func addEntryIDs(in articleIDs: [String]) { + entryIDs.formUnion(articleIDs) } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift index b4d29ed09..2e3f96e1b 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyDownloadArticlesOperation.swift @@ -33,15 +33,15 @@ final class FeedlyDownloadArticlesOperation: FeedlyOperation, @unchecked Sendabl } @MainActor override func run() { - var articleIds = missingArticleEntryIdProvider.entryIds - articleIds.formUnion(updatedArticleEntryIdProvider.entryIds) + var articleIds = missingArticleEntryIdProvider.entryIDs + articleIds.formUnion(updatedArticleEntryIdProvider.entryIDs) Feedly.logger.info("Feedly: Requesting \(articleIds.count) articles") let feedlyAPILimitBatchSize = 1000 for articleIds in Array(articleIds).chunked(into: feedlyAPILimitBatchSize) { - let provider = FeedlyEntryIdentifierProvider(entryIds: Set(articleIds)) + let provider = FeedlyEntryIdentifierProvider(entryIDs: Set(articleIds)) let getEntries = FeedlyGetEntriesOperation(account: account, service: getEntriesService, provider: provider) getEntries.delegate = self self.operationQueue?.add(getEntries) diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift index 7b555f367..b387f53e9 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift @@ -1,5 +1,5 @@ // -// FeedlyFetchIdsForMissingArticlesOperation.swift +// FeedlyFetchIDsForMissingArticlesOperation.swift // Account // // Created by Kiel Gillard on 7/1/20. @@ -9,11 +9,11 @@ import Foundation import os.log -final class FeedlyFetchIdsForMissingArticlesOperation: FeedlyOperation, FeedlyEntryIdentifierProviding, @unchecked Sendable { +final class FeedlyFetchIDsForMissingArticlesOperation: FeedlyOperation, FeedlyEntryIdentifierProviding, @unchecked Sendable { private let account: Account - private(set) var entryIds = Set() + private(set) var entryIDs = Set() @MainActor init(account: Account) { self.account = account @@ -21,16 +21,13 @@ final class FeedlyFetchIdsForMissingArticlesOperation: FeedlyOperation, FeedlyEn } @MainActor override func run() { - account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in - Task { @MainActor in - switch result { - case .success(let articleIds): - self.entryIds.formUnion(articleIds) - self.didComplete() - - case .failure(let error): - self.didComplete(with: error) - } + Task { @MainActor in + do { + let articleIDs = try await account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() + entryIDs.formUnion(articleIDs) + didComplete() + } catch { + didComplete(with: error) } } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift index c1ddbec38..38d82e1d3 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetEntriesOperation.swift @@ -55,7 +55,7 @@ final class FeedlyGetEntriesOperation: FeedlyOperation, FeedlyEntryProviding, Fe } override func run() { - service.getEntries(for: provider.entryIds) { result in + service.getEntries(for: provider.entryIDs) { result in Task { @MainActor in switch result { case .success(let entries): diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift index 8c07439a4..aaebf9763 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetStreamIdsOperation.swift @@ -16,7 +16,7 @@ protocol FeedlyGetStreamIdsOperationDelegate: AnyObject { /// Single responsibility is to get the stream ids from Feedly. final class FeedlyGetStreamIdsOperation: FeedlyOperation, FeedlyEntryIdentifierProviding, @unchecked Sendable { - var entryIds: Set { + var entryIDs: Set { guard let ids = streamIds?.ids else { assertionFailure("Has this operation been addeded as a dependency on the caller?") return [] diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift index 0ce4db2e1..5c8d8eb96 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyGetUpdatedArticleIdsOperation.swift @@ -34,7 +34,7 @@ final class FeedlyGetUpdatedArticleIdsOperation: FeedlyOperation, FeedlyEntryIde self.init(account: account, resource: all, service: service, newerThan: newerThan) } - var entryIds: Set { + var entryIDs: Set { return storedUpdatedArticleIds } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift index cd7673768..0c9f9bcd5 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySyncAllOperation.swift @@ -94,26 +94,26 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable { 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 - getMissingIds.downloadProgress = downloadProgress - getMissingIds.addDependency(getAllArticleIds) - getMissingIds.addDependency(getUnread) - getMissingIds.addDependency(getStarred) - getMissingIds.addDependency(getUpdated) - operationQueue.add(getMissingIds) + let getMissingIDs = FeedlyFetchIDsForMissingArticlesOperation(account: account) + getMissingIDs.delegate = self + getMissingIDs.downloadProgress = downloadProgress + getMissingIDs.addDependency(getAllArticleIds) + getMissingIDs.addDependency(getUnread) + getMissingIDs.addDependency(getStarred) + getMissingIDs.addDependency(getUpdated) + operationQueue.add(getMissingIDs) // Download all the missing and updated articles let downloadMissingArticles = FeedlyDownloadArticlesOperation( account: account, - missingArticleEntryIdProvider: getMissingIds, + missingArticleEntryIdProvider: getMissingIDs, updatedArticleEntryIdProvider: getUpdated, getEntriesService: getEntriesService, operationQueue: operationQueue ) downloadMissingArticles.delegate = self downloadMissingArticles.downloadProgress = downloadProgress - downloadMissingArticles.addDependency(getMissingIds) + downloadMissingArticles.addDependency(getMissingIDs) downloadMissingArticles.addDependency(getUpdated) operationQueue.add(downloadMissingArticles) diff --git a/Modules/Account/Sources/Account/SingleArticleFetcher.swift b/Modules/Account/Sources/Account/SingleArticleFetcher.swift index 78c28357e..641decce8 100644 --- a/Modules/Account/Sources/Account/SingleArticleFetcher.swift +++ b/Modules/Account/Sources/Account/SingleArticleFetcher.swift @@ -21,19 +21,18 @@ public struct SingleArticleFetcher: ArticleFetcher { } public func fetchArticles() throws -> Set
{ - return try account.fetchArticles(.articleIDs(Set([articleID]))) + try account.fetchArticlesSync(.articleIDs(Set([articleID]))) } - public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) + public func fetchArticlesAsync() async throws -> Set
{ + try await account.fetchArticles(.articleIDs(Set([articleID]))) } public func fetchUnreadArticles() throws -> Set
{ - return try account.fetchArticles(.articleIDs(Set([articleID]))) + try account.fetchArticlesSync(.articleIDs(Set([articleID]))) } - public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) + public func fetchUnreadArticlesAsync() async throws -> Set
{ + try await account.fetchArticles(.articleIDs(Set([articleID]))) } - } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index d8f87a80e..1d6c4a6a4 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -16,47 +16,27 @@ import Articles // This file is the entirety of the public API for ArticlesDatabase.framework. // Everything else is implementation. -// Main thread only. - public typealias UnreadCountDictionary = [String: Int] // feedID: unreadCount -public typealias UnreadCountDictionaryCompletionResult = Result -public typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult?) -> Void - -public typealias SingleUnreadCountResult = Result -public typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult?) -> Void nonisolated public struct ArticleChanges: Sendable { - public let newArticles: Set
? - public let updatedArticles: Set
? - public let deletedArticles: Set
? + public let new: Set
? + public let updated: Set
? + public let deleted: Set
? public init() { - self.newArticles = Set
() - self.updatedArticles = Set
() - self.deletedArticles = Set
() + self.new = Set
() + self.updated = Set
() + self.deleted = Set
() } - public init(newArticles: Set
?, updatedArticles: Set
?, deletedArticles: Set
?) { - self.newArticles = newArticles - self.updatedArticles = updatedArticles - self.deletedArticles = deletedArticles + public init(new: Set
?, updated: Set
?, deleted: Set
?) { + self.new = new + self.updated = updated + self.deleted = deleted } } -public typealias UpdateArticlesResult = Result -public typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void - -public typealias ArticleSetResult = Result, DatabaseError> -public typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void - -public typealias ArticleIDsResult = Result, Error> -public typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void - -public typealias ArticleStatusesResult = Result, DatabaseError> -public typealias ArticleStatusesResultBlock = @Sendable (ArticleStatusesResult) -> Void - nonisolated public final class ArticlesDatabase: Sendable { - public enum RetentionStyle: Sendable { case feedBased // Local and iCloud: article retention is defined by contents of feed case syncSystem // Feedbin, Feedly, etc.: article retention is defined by external system @@ -101,12 +81,12 @@ nonisolated public final class ArticlesDatabase: Sendable { // MARK: - Fetching Articles - public func fetchArticles(_ feedID: String) throws -> Set
{ + public func fetchArticles(feedID: String) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticles(feedID) } - public func fetchArticles(_ feedIDs: Set) throws -> Set
{ + public func fetchArticles(feedIDs: Set) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticles(feedIDs) } @@ -116,219 +96,181 @@ nonisolated public final class ArticlesDatabase: Sendable { return try articlesTable.fetchArticles(articleIDs: articleIDs) } - public func fetchUnreadArticles(_ feedIDs: Set, _ limit: Int?) throws -> Set
{ + public func fetchUnreadArticles(feedIDs: Set, limit: Int? = nil) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchUnreadArticles(feedIDs, limit) } - public func fetchTodayArticles(_ feedIDs: Set, _ limit: Int?) throws -> Set
{ + public func fetchTodayArticles(feedIDs: Set, limit: Int? = nil) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticlesSince(feedIDs, todayCutoffDate(), limit) } - public func fetchStarredArticles(_ feedIDs: Set, _ limit: Int?) throws -> Set
{ + public func fetchStarredArticles(feedIDs: Set, limit: Int? = nil) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchStarredArticles(feedIDs, limit) } - public func fetchStarredArticlesCount(_ feedIDs: Set) throws -> Int { + public func fetchStarredArticlesCount(feedIDs: Set) throws -> Int { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchStarredArticlesCount(feedIDs) } - public func fetchArticlesMatching(_ searchString: String, _ feedIDs: Set) throws -> Set
{ + public func fetchArticlesMatching(searchString: String, feedIDs: Set) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticlesMatching(searchString, feedIDs) } - public func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set) throws -> Set
{ + public func fetchArticlesMatchingWithArticleIDs(searchString: String, articleIDs: Set) throws -> Set
{ Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return try articlesTable.fetchArticlesMatchingWithArticleIDs(searchString, articleIDs) } // MARK: - Fetching Articles Async - public func fetchArticlesAsync(_ feedID: String, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesAsync(feedID, completion) + public func fetchArticlesAsync(feedID: String) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchArticlesAsync(feedID: feedID) { result in + continuation.resume(with: result) + } + } } - public func fetchArticlesAsync(_ feedIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesAsync(feedIDs, completion) + public func fetchArticlesAsync(feedIDs: Set) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchArticlesAsync(feedIDs: feedIDs) { result in + continuation.resume(with: result) + } + } } - public func fetchArticlesAsync(articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesAsync(articleIDs: articleIDs, completion) + public func fetchArticlesAsync(articleIDs: Set) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchArticlesAsync(articleIDs: articleIDs) { result in + continuation.resume(with: result) + } + } } - public func fetchUnreadArticlesAsync(_ feedIDs: Set, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchUnreadArticlesAsync(feedIDs, limit, completion) + public func fetchUnreadArticlesAsync(feedIDs: Set, limit: Int? = nil) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchUnreadArticlesAsync(feedIDs: feedIDs, limit: limit) { result in + continuation.resume(with: result) + } + } } - public func fetchTodayArticlesAsync(_ feedIDs: Set, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesSinceAsync(feedIDs, todayCutoffDate(), limit, completion) + public func fetchTodayArticlesAsync(feedIDs: Set, limit: Int? = nil) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchTodayArticlesAsync(feedIDs: feedIDs, limit: limit) { result in + continuation.resume(with: result) + } + } } - public func fetchedStarredArticlesAsync(_ feedIDs: Set, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchStarredArticlesAsync(feedIDs, limit, completion) + public func fetchedStarredArticlesAsync(feedIDs: Set, limit: Int? = nil) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchedStarredArticlesAsync(feedIDs: feedIDs, limit: limit) { result in + continuation.resume(with: result) + } + } } - public func fetchArticlesMatchingAsync(_ searchString: String, _ feedIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesMatchingAsync(searchString, feedIDs, completion) + public func fetchArticlesMatchingAsync(searchString: String, feedIDs: Set) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchArticlesMatchingAsync(searchString: searchString, feedIDs: feedIDs) { result in + continuation.resume(with: result) + } + } } - public func fetchArticlesMatchingWithArticleIDsAsync(_ searchString: String, _ articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs, completion) + public func fetchArticlesMatchingWithArticleIDsAsync(searchString: String, articleIDs: Set) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + _fetchArticlesMatchingWithArticleIDsAsync(searchString: searchString, articleIDs: articleIDs) { result in + continuation.resume(with: result) + } + } } // MARK: - Unread Counts /// Fetch all non-zero unread counts. - @MainActor public func fetchAllUnreadCounts() async throws -> UnreadCountDictionary? { + public func fetchAllUnreadCountsAsync() async throws -> UnreadCountDictionary? { return try await withCheckedThrowingContinuation { continuation in - self.fetchAllUnreadCounts { result in + _fetchAllUnreadCounts { result in + continuation.resume(with: result) + } + } + } + + /// Fetch unread count for a single feed. + public func fetchUnreadCountAsync(feedID: String) async throws -> Int { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + return try await withCheckedThrowingContinuation { continuation in + _fetchUnreadCounts(feedIDs: Set([feedID])) { result in switch result { case .success(let unreadCountDictionary): - continuation.resume(returning: unreadCountDictionary) + if let unreadCount = unreadCountDictionary[feedID] { + continuation.resume(returning: unreadCount) + } else { + continuation.resume(returning: 0) + } case .failure(let error): continuation.resume(throwing: error) - case .none: - continuation.resume(returning: nil) } } } } - @MainActor func fetchAllUnreadCounts(_ completion: @escaping UnreadCountDictionaryCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - let operation = FetchAllUnreadCountsOperation(databaseQueue: queue) - if let operationName = operation.name { - operationQueue.cancel(named: operationName) - } - operation.completionBlock = { operation in - let fetchOperation = operation as! FetchAllUnreadCountsOperation - completion(fetchOperation.result) - } - operationQueue.add(operation) - } - - /// Fetch unread count for a single feed. - @MainActor public func fetchUnreadCount(_ feedID: String, _ completion: @escaping SingleUnreadCountCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - let operation = FetchFeedUnreadCountOperation(feedID: feedID, databaseQueue: queue, cutoffDate: articlesTable.articleCutoffDate) - operation.completionBlock = { operation in - let fetchOperation = operation as! FetchFeedUnreadCountOperation - completion(fetchOperation.result) - } - operationQueue.add(operation) - } - /// Fetch non-zero unread counts for given feedIDs. - @MainActor public func fetchUnreadCounts(for feedIDs: Set, _ completion: @escaping UnreadCountDictionaryCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - let operation = FetchUnreadCountsForFeedsOperation(feedIDs: feedIDs, databaseQueue: queue) - operation.completionBlock = { operation in - let fetchOperation = operation as! FetchUnreadCountsForFeedsOperation - completion(fetchOperation.result) + public func fetchUnreadCountsAsync(feedIDs: Set) async throws -> UnreadCountDictionary { + try await withCheckedThrowingContinuation { continuation in + _fetchUnreadCounts(feedIDs: feedIDs) { result in + continuation.resume(with: result) + } } - operationQueue.add(operation) } - public func fetchUnreadCountForToday(for feedIDs: Set, completion: @escaping SingleUnreadCountCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - fetchUnreadCount(for: feedIDs, since: todayCutoffDate(), completion: completion) + public func fetchUnreadCountForTodayAsync(feedIDs: Set) async throws -> Int { + try await withCheckedThrowingContinuation { continuation in + _fetchUnreadCount(feedIDs: feedIDs, since: todayCutoffDate()) { result in + continuation.resume(with: result) + } + } } - public func fetchUnreadCount(for feedIDs: Set, since: Date, completion: @escaping SingleUnreadCountCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchUnreadCount(feedIDs, since, completion) - } - - public func fetchStarredAndUnreadCount(for feedIDs: Set, completion: @escaping SingleUnreadCountCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchStarredAndUnreadCount(feedIDs, completion) + public func fetchUnreadCountForStarredArticlesAsync(feedIDs: Set) async throws -> Int { + try await withCheckedThrowingContinuation { continuation in + _fetchStarredAndUnreadCount(feedIDs: feedIDs) { result in + continuation.resume(with: result) + } + } } // MARK: - Saving, Updating, and Deleting Articles /// Update articles and save new ones — for feed-based systems (local and iCloud). - public func update(with parsedItems: Set, feedID: String, deleteOlder: Bool, completion: @escaping UpdateArticlesCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - precondition(retentionStyle == .feedBased) - articlesTable.update(parsedItems, feedID, deleteOlder, completion) + public func updateAsync(parsedItems: Set, feedID: String, deleteOlder: Bool) async throws -> ArticleChanges { + try await withCheckedThrowingContinuation { continuation in + _update(parsedItems: parsedItems, feedID: feedID, deleteOlder: deleteOlder) { result in + continuation.resume(with: result) + } + } } /// Update articles and save new ones — for sync systems (Feedbin, Feedly, etc.). - public func update(feedIDsAndItems: [String: Set], defaultRead: Bool, completion: @escaping UpdateArticlesCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - precondition(retentionStyle == .syncSystem) - articlesTable.update(feedIDsAndItems, defaultRead, completion) + public func updateAsync(feedIDsAndItems: [String: Set], defaultRead: Bool) async throws -> ArticleChanges { + try await withCheckedThrowingContinuation { continuation in + _update(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead) { result in + continuation.resume(with: result) + } + } } /// Delete articles - public func delete(articleIDs: Set, completion: DatabaseCompletionBlock?) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.delete(articleIDs: articleIDs, completion: completion) - } - - // MARK: - Status - - /// Fetch the articleIDs of unread articles. - public func fetchUnreadArticleIDsAsync(completion: @escaping ArticleIDsCompletionBlock) { - 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)") - articlesTable.fetchStarredArticleIDsAsync(completion) - } - - /// Fetch articleIDs for articles that we should have, but don’t. These articles are either (starred) or (newer than the article cutoff date). - public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(completion) - } - - public func mark(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - self.mark(articles, statusKey: statusKey, flag: flag) { result in - continuation.resume(with: result) - } - } - } - - public func mark(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleStatusesResultBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - return articlesTable.mark(articles, statusKey, flag, completion) - } - - public func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { - try await withCheckedThrowingContinuation { continuation in - markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) { result in - continuation.resume(with: result) - } - } - } - - private func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleIDsCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.markAndFetchNew(articleIDs, statusKey, flag, completion) - } - - /// Create statuses for specified articleIDs. For existing statuses, don’t do anything. - /// For newly-created statuses, mark them as read and not-starred. - public func createStatusesIfNeeded(articleIDs: Set) async throws { + public func deleteAsync(articleIDs: Set) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self.createStatusesIfNeeded(articleIDs: articleIDs) { error in + _delete(articleIDs: articleIDs) { error in if let error { continuation.resume(throwing: error) } else { @@ -338,9 +280,64 @@ nonisolated public final class ArticlesDatabase: Sendable { } } - func createStatusesIfNeeded(articleIDs: Set, completion: @escaping DatabaseCompletionBlock) { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - articlesTable.createStatusesIfNeeded(articleIDs, completion) + // MARK: - ArticleIDs + + /// Fetch the articleIDs of unread articles. + public func fetchUnreadArticleIDsAsync() async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + _fetchUnreadArticleIDsAsync { result in + continuation.resume(with: result) + } + } + } + + public func fetchStarredArticleIDsAsync() async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + _fetchStarredArticleIDsAsync { result in + continuation.resume(with: result) + } + } + } + + /// Fetch articleIDs for articles that we should have, but don’t. These articles are either starred or newer than the article cutoff date. + public func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + _fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in + continuation.resume(with: result) + } + } + } + + // MARK: - Statuses + + public func markAsync(articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + _mark(articles: articles, statusKey: statusKey, flag: flag) { result in + continuation.resume(with: result) + } + } + } + + public func markAndFetchNewAsync(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + _markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) { result in + continuation.resume(with: result) + } + } + } + + /// Create statuses for specified articleIDs. For existing statuses, don’t do anything. + /// For newly-created statuses, mark them as read and not-starred. + public func createStatusesIfNeededAsync(articleIDs: Set) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + _createStatusesIfNeeded(articleIDs: articleIDs) { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume(returning: ()) + } + } + } } #if os(iOS) @@ -430,3 +427,143 @@ nonisolated private extension ArticlesDatabase { } } } + +// MARK: - Articles Table (Private) + +typealias UnreadCountDictionaryCompletionResult = Result +typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult) -> Void + +typealias UpdateArticlesResult = Result +typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void + +typealias SingleUnreadCountResult = Result +typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult) -> Void + +typealias ArticleSetResult = Result, DatabaseError> +typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void + +typealias ArticleIDsResult = Result, Error> +typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void + +typealias ArticleStatusesResult = Result, DatabaseError> +typealias ArticleStatusesResultBlock = @Sendable (ArticleStatusesResult) -> Void + +nonisolated private extension ArticlesDatabase { + + func _fetchAllUnreadCounts(_ completion: @escaping UnreadCountDictionaryCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + Task { @MainActor in + let operation = FetchAllUnreadCountsOperation(databaseQueue: queue) + if let operationName = operation.name { + operationQueue.cancel(named: operationName) + } + operation.completionBlock = { operation in + let fetchOperation = operation as! FetchAllUnreadCountsOperation + completion(fetchOperation.result ?? .failure(DatabaseError.isSuspended)) + } + operationQueue.add(operation) + } + } + + func _fetchUnreadCounts(feedIDs: Set, _ completion: @escaping UnreadCountDictionaryCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchUnreadCounts(feedIDs, completion) + } + + func _fetchUnreadCount(feedIDs: Set, since: Date, completion: @escaping SingleUnreadCountCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchUnreadCount(feedIDs, since, completion) + } + + func _fetchStarredAndUnreadCount(feedIDs: Set, completion: @escaping SingleUnreadCountCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchStarredAndUnreadCount(feedIDs, completion) + } + + func _mark(articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleStatusesResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + return articlesTable.mark(articles, statusKey, flag, completion) + } + + func _markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleIDsCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.markAndFetchNew(articleIDs, statusKey, flag, completion) + } + + func _createStatusesIfNeeded(articleIDs: Set, completion: @escaping DatabaseCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.createStatusesIfNeeded(articleIDs, completion) + } + + func _fetchArticlesAsync(feedID: String, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesAsync(feedID, completion) + } + + func _fetchArticlesAsync(feedIDs: Set, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesAsync(feedIDs, completion) + } + + func _fetchArticlesAsync(articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesAsync(articleIDs: articleIDs, completion) + } + + func _fetchUnreadArticlesAsync(feedIDs: Set, limit: Int? = nil, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchUnreadArticlesAsync(feedIDs, limit, completion) + } + + func _fetchTodayArticlesAsync(feedIDs: Set, limit: Int? = nil, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesSinceAsync(feedIDs, todayCutoffDate(), limit, completion) + } + + func _fetchedStarredArticlesAsync(feedIDs: Set, limit: Int? = nil, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchStarredArticlesAsync(feedIDs, limit, completion) + } + + func _fetchArticlesMatchingAsync(searchString: String, feedIDs: Set, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesMatchingAsync(searchString, feedIDs, completion) + } + + func _fetchArticlesMatchingWithArticleIDsAsync(searchString: String, articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs, completion) + } + + func _update(parsedItems: Set, feedID: String, deleteOlder: Bool, completion: @escaping UpdateArticlesCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + precondition(retentionStyle == .feedBased) + articlesTable.update(parsedItems, feedID, deleteOlder, completion) + } + + func _update(feedIDsAndItems: [String: Set], defaultRead: Bool, completion: @escaping UpdateArticlesCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + precondition(retentionStyle == .syncSystem) + articlesTable.update(feedIDsAndItems, defaultRead, completion) + } + + func _delete(articleIDs: Set, completion: DatabaseCompletionBlock?) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.delete(articleIDs: articleIDs, completion: completion) + } + + func _fetchUnreadArticleIDsAsync(completion: @escaping ArticleIDsCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchUnreadArticleIDsAsync(completion) + } + + func _fetchStarredArticleIDsAsync(completion: @escaping ArticleIDsCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchStarredArticleIDsAsync(completion) + } + + func _fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(completion) + } +} diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 70216a431..18814c705 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -370,6 +370,58 @@ nonisolated final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Unread Counts + func fetchUnreadCounts(_ feedIDs: Set, _ completion: @escaping UnreadCountDictionaryCompletionBlock) { + if feedIDs.isEmpty { + completion(.success(UnreadCountDictionary())) + return + } + + queue.runInDatabase { databaseResult in + + func makeDatabaseCalls(_ database: FMDatabase) throws -> UnreadCountDictionary { + let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(feedIDs.count))! + let sql = "select distinct feedID, count(*) from articles natural join statuses where feedID in \(placeholders) and read=0 group by feedID;" + + let parameters = Array(feedIDs) as [Any] + + guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { + throw DatabaseError.isSuspended + } + defer { + resultSet.close() + } + + var unreadCountDictionary = UnreadCountDictionary() + while resultSet.next() { + let unreadCount = resultSet.long(forColumnIndex: 1) + if let feedID = resultSet.string(forColumnIndex: 0) { + unreadCountDictionary[feedID] = unreadCount + } + } + return unreadCountDictionary + } + + + switch databaseResult { + case .success(let database): + do { + let unreadCountDictionary = try makeDatabaseCalls(database) + DispatchQueue.main.async { + completion(.success(unreadCountDictionary)) + } + } catch { + DispatchQueue.main.async { + completion(.failure(error)) + } + } + case .failure(let error): + DispatchQueue.main.async { + completion(.failure(error)) + } + } + } + } + func fetchUnreadCount(_ feedIDs: Set, _ since: Date, _ completion: @escaping SingleUnreadCountCompletionBlock) { // Get unread count for today, for instance. if feedIDs.isEmpty { @@ -488,10 +540,15 @@ nonisolated final class ArticlesTable: DatabaseTable, Sendable { } func createStatusesIfNeeded(_ articleIDs: Set, _ completion: @escaping DatabaseCompletionBlock) { + guard !articleIDs.isEmpty else { + completion(nil) + return + } + queue.runInTransaction { databaseResult in switch databaseResult { case .success(let database): - let _ = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, true, database) + self.statusesTable.ensureStatusesForArticleIDs(articleIDs, true, database) DispatchQueue.main.async { completion(nil) } @@ -918,7 +975,7 @@ nonisolated private extension ArticlesTable { // MARK: - Saving Parsed Items func callUpdateArticlesCompletionBlock(_ newArticles: Set
?, _ updatedArticles: Set
?, _ deletedArticles: Set
?, _ completion: @escaping UpdateArticlesCompletionBlock) { - let articleChanges = ArticleChanges(newArticles: newArticles, updatedArticles: updatedArticles, deletedArticles: deletedArticles) + let articleChanges = ArticleChanges(new: newArticles, updated: updatedArticles, deleted: deletedArticles) DispatchQueue.main.async { completion(.success(articleChanges)) } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift index f055d515c..74bd05a84 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift @@ -29,9 +29,13 @@ public final class FetchAllUnreadCountsOperation: MainThreadOperation, @unchecke switch databaseResult { case .success(let database): - self.result = self.fetchUnreadCounts(database) + if let unreadCountDictionary = self.fetchUnreadCounts(database) { + self.result = .success(unreadCountDictionary) + } else { + self.result = .failure(DatabaseError.isSuspended) + } case .failure: - self.result = .failure(.isSuspended) + self.result = .failure(DatabaseError.isSuspended) } self.didComplete() @@ -41,7 +45,7 @@ public final class FetchAllUnreadCountsOperation: MainThreadOperation, @unchecke nonisolated private extension FetchAllUnreadCountsOperation { - func fetchUnreadCounts(_ database: FMDatabase) -> UnreadCountDictionaryCompletionResult? { + func fetchUnreadCounts(_ database: FMDatabase) -> UnreadCountDictionary? { let sql = "select distinct feedID, count(*) from articles natural join statuses where read=0 group by feedID;" guard let resultSet = database.executeQuery(sql, withArgumentsIn: nil) else { @@ -57,6 +61,6 @@ nonisolated private extension FetchAllUnreadCountsOperation { } resultSet.close() - return .success(unreadCountDictionary) + return unreadCountDictionary } } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift index 54589a7fe..c018fa1eb 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift @@ -29,6 +29,7 @@ nonisolated final class StatusesTable: DatabaseTable, Sendable { // MARK: - Creating/Updating + @discardableResult func ensureStatusesForArticleIDs(_ articleIDs: Set, _ read: Bool, _ database: FMDatabase) -> ([String: ArticleStatus], Set) { #if DEBUG diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift index 89c151992..c162f55d7 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift @@ -154,6 +154,7 @@ nonisolated public final class DatabaseQueue: Sendable { error = databaseError } } + if let error { throw(error) } diff --git a/Shared/SmartFeeds/SearchFeedDelegate.swift b/Shared/SmartFeeds/SearchFeedDelegate.swift index cc8060725..19663ed88 100644 --- a/Shared/SmartFeeds/SearchFeedDelegate.swift +++ b/Shared/SmartFeeds/SearchFeedDelegate.swift @@ -32,8 +32,8 @@ struct SearchFeedDelegate: SmartFeedDelegate { self.fetchType = .search(searchString) } - func fetchUnreadCount(for: Account, completion: @escaping SingleUnreadCountCompletionBlock) { + func fetchUnreadCount(account: Account) async throws -> Int? { // TODO: after 5.0 + nil } } - diff --git a/Shared/SmartFeeds/SearchTimelineFeedDelegate.swift b/Shared/SmartFeeds/SearchTimelineFeedDelegate.swift index 53acc7a50..821f5421a 100644 --- a/Shared/SmartFeeds/SearchTimelineFeedDelegate.swift +++ b/Shared/SmartFeeds/SearchTimelineFeedDelegate.swift @@ -32,7 +32,8 @@ struct SearchTimelineFeedDelegate: SmartFeedDelegate { self.fetchType = .searchWithArticleIDs(searchString, articleIDs) } - func fetchUnreadCount(for: Account, completion: @escaping SingleUnreadCountCompletionBlock) { + func fetchUnreadCount(account: Account) async throws -> Int? { // TODO: after 5.0 + nil } } diff --git a/Shared/SmartFeeds/SmartFeed.swift b/Shared/SmartFeeds/SmartFeed.swift index fa75d7ea0..45185af32 100644 --- a/Shared/SmartFeeds/SmartFeed.swift +++ b/Shared/SmartFeeds/SmartFeed.swift @@ -75,7 +75,9 @@ final class SmartFeed: PseudoFeed { if activeAccounts.isEmpty { updateUnreadCount() } else { - activeAccounts.forEach { self.fetchUnreadCount(for: $0) } + for account in activeAccounts { + fetchUnreadCount(account: account) + } } } @@ -84,19 +86,19 @@ final class SmartFeed: PseudoFeed { extension SmartFeed: ArticleFetcher { func fetchArticles() throws -> Set
{ - return try delegate.fetchArticles() + try delegate.fetchArticles() } - func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - delegate.fetchArticlesAsync(completion) + func fetchArticlesAsync() async throws -> Set
{ + try await delegate.fetchArticlesAsync() } func fetchUnreadArticles() throws -> Set
{ - return try delegate.fetchUnreadArticles() + try delegate.fetchUnreadArticles() } - func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - delegate.fetchUnreadArticlesAsync(completion) + func fetchUnreadArticlesAsync() async throws -> Set
{ + try await delegate.fetchUnreadArticlesAsync() } } @@ -106,24 +108,24 @@ private extension SmartFeed { CoalescingQueue.standard.add(self, #selector(fetchUnreadCounts)) } - func fetchUnreadCount(for account: Account) { - delegate.fetchUnreadCount(for: account) { singleUnreadCountResult in - guard let singleUnreadCountResult, let accountUnreadCount = try? singleUnreadCountResult.get() else { + func fetchUnreadCount(account: Account) { + Task { @MainActor in + guard let unreadCount = try? await delegate.fetchUnreadCount(account: account) else { return } - Task { @MainActor in - self.unreadCounts[account.accountID] = accountUnreadCount - self.updateUnreadCount() - } + unreadCounts[account.accountID] = unreadCount + updateUnreadCount() } } func updateUnreadCount() { - unreadCount = AccountManager.shared.activeAccounts.reduce(0) { (result, account) -> Int in + var updatedUnreadCount = 0 + for account in AccountManager.shared.activeAccounts { if let oneUnreadCount = unreadCounts[account.accountID] { - return result + oneUnreadCount + updatedUnreadCount += oneUnreadCount } - return result } + + unreadCount = updatedUnreadCount } } diff --git a/Shared/SmartFeeds/SmartFeedDelegate.swift b/Shared/SmartFeeds/SmartFeedDelegate.swift index 72c173b5a..b317509c7 100644 --- a/Shared/SmartFeeds/SmartFeedDelegate.swift +++ b/Shared/SmartFeeds/SmartFeedDelegate.swift @@ -14,7 +14,7 @@ import RSCore @MainActor protocol SmartFeedDelegate: SidebarItemIdentifiable, DisplayNameProvider, ArticleFetcher, SmallIconProvider { var fetchType: FetchType { get } - func fetchUnreadCount(for: Account, completion: @escaping SingleUnreadCountCompletionBlock) + func fetchUnreadCount(account: Account) async throws -> Int? } @MainActor extension SmartFeedDelegate { @@ -23,22 +23,16 @@ import RSCore return try AccountManager.shared.fetchArticles(fetchType) } - func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - AccountManager.shared.fetchArticlesAsync(fetchType, completion) + func fetchArticlesAsync() async throws -> Set
{ + try await AccountManager.shared.fetchArticlesAsync(fetchType) } func fetchUnreadArticles() throws -> Set
{ - return try fetchArticles().unreadArticles() + try fetchArticles().unreadArticles() } - func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - fetchArticlesAsync{ articleSetResult in - switch articleSetResult { - case .success(let articles): - completion(.success(articles.unreadArticles())) - case .failure(let error): - completion(.failure(error)) - } - } + func fetchUnreadArticlesAsync() async throws -> Set
{ + let articles = try await fetchArticlesAsync() + return articles.unreadArticles() } } diff --git a/Shared/SmartFeeds/StarredFeedDelegate.swift b/Shared/SmartFeeds/StarredFeedDelegate.swift index 569233d04..69effc192 100644 --- a/Shared/SmartFeeds/StarredFeedDelegate.swift +++ b/Shared/SmartFeeds/StarredFeedDelegate.swift @@ -23,8 +23,7 @@ import Account var smallIcon: IconImage? { return AppAssets.starredFeedImage } - - func fetchUnreadCount(for account: Account, completion: @escaping SingleUnreadCountCompletionBlock) { - account.fetchUnreadCountForStarredArticles(completion) + func fetchUnreadCount(account: Account) async throws -> Int? { + try await account.fetchUnreadCountForStarredArticles() } } diff --git a/Shared/SmartFeeds/TodayFeedDelegate.swift b/Shared/SmartFeeds/TodayFeedDelegate.swift index ce1bfb9b6..b78b352d0 100644 --- a/Shared/SmartFeeds/TodayFeedDelegate.swift +++ b/Shared/SmartFeeds/TodayFeedDelegate.swift @@ -13,7 +13,6 @@ import ArticlesDatabase import Account struct TodayFeedDelegate: SmartFeedDelegate { - var sidebarItemID: SidebarItemIdentifier? { return SidebarItemIdentifier.smartFeed(String(describing: TodayFeedDelegate.self)) } @@ -24,8 +23,8 @@ struct TodayFeedDelegate: SmartFeedDelegate { return AppAssets.todayFeedImage } - func fetchUnreadCount(for account: Account, completion: @escaping SingleUnreadCountCompletionBlock) { - account.fetchUnreadCountForToday(completion) + func fetchUnreadCount(account: Account) async throws -> Int? { + try await account.fetchUnreadCountForToday() } } diff --git a/Shared/SmartFeeds/UnreadFeed.swift b/Shared/SmartFeeds/UnreadFeed.swift index 04d313d37..ea28c7959 100644 --- a/Shared/SmartFeeds/UnreadFeed.swift +++ b/Shared/SmartFeeds/UnreadFeed.swift @@ -64,21 +64,21 @@ final class UnreadFeed: PseudoFeed { } } -extension UnreadFeed: ArticleFetcher { +@MainActor extension UnreadFeed: ArticleFetcher { func fetchArticles() throws -> Set
{ return try fetchUnreadArticles() } - func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - fetchUnreadArticlesAsync(completion) + func fetchArticlesAsync() async throws -> Set
{ + try await fetchUnreadArticlesAsync() } func fetchUnreadArticles() throws -> Set
{ - return try AccountManager.shared.fetchArticles(fetchType) + try AccountManager.shared.fetchArticles(fetchType) } - func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { - AccountManager.shared.fetchArticlesAsync(fetchType, completion) + func fetchUnreadArticlesAsync() async throws -> Set
{ + try await AccountManager.shared.fetchArticlesAsync(fetchType) } } diff --git a/Shared/Timer/AccountRefreshTimer.swift b/Shared/Timer/AccountRefreshTimer.swift index 5cfecd112..2f35fc455 100644 --- a/Shared/Timer/AccountRefreshTimer.swift +++ b/Shared/Timer/AccountRefreshTimer.swift @@ -73,6 +73,6 @@ import Account lastTimedRefresh = Date() update() - AccountManager.shared.refreshAll() + AccountManager.shared.refreshAllWithoutWaiting() } } diff --git a/Shared/Timer/ArticleStatusSyncTimer.swift b/Shared/Timer/ArticleStatusSyncTimer.swift index f6b94aebb..f537ca744 100644 --- a/Shared/Timer/ArticleStatusSyncTimer.swift +++ b/Shared/Timer/ArticleStatusSyncTimer.swift @@ -78,8 +78,6 @@ import Account lastTimedRefresh = Date() update() - AccountManager.shared.syncArticleStatusAll() - + AccountManager.shared.syncArticleStatusAllWithoutWaiting() } - } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index a6762ad03..584903eb8 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -36,8 +36,6 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application") - var widgetDataEncoder: WidgetDataEncoder! - var unreadCount = 0 { didSet { if unreadCount != oldValue { @@ -106,8 +104,6 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC ExtensionContainersFile.shared.start() ExtensionFeedAddRequestFile.shared.start() - widgetDataEncoder = WidgetDataEncoder() - #if DEBUG ArticleStatusSyncTimer.shared.update() #endif @@ -157,7 +153,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate } ).forEach { $0.cleanUp(conditional: true) } - AccountManager.shared.refreshAll(errorHandler: errorHandler) + AccountManager.shared.refreshAllWithoutWaiting(errorHandler: errorHandler) } func resumeDatabaseProcessingIfNecessary() { @@ -173,7 +169,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC ArticleStatusSyncTimer.shared.invalidate() scheduleBackgroundFeedRefresh() syncArticleStatus() - widgetDataEncoder.encode() + WidgetDataEncoder.shared?.encode() waitForSyncTasksToFinish() IconImageCache.shared.emptyCache() } @@ -185,12 +181,12 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC if let lastRefresh = AppDefaults.shared.lastRefresh { if Date() > lastRefresh.addingTimeInterval(15 * 60) { - AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) + AccountManager.shared.refreshAllWithoutWaiting(errorHandler: ErrorHandler.log) } else { - AccountManager.shared.syncArticleStatusAll() + AccountManager.shared.syncArticleStatusAllWithoutWaiting() } } else { - AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) + AccountManager.shared.refreshAllWithoutWaiting(errorHandler: ErrorHandler.log) } } @@ -278,7 +274,7 @@ private extension AppDelegate { return } - if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning || widgetDataEncoder.isRunning { + if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning || WidgetDataEncoder.shared?.isRunning ?? false { Self.logger.info("Waiting for sync to finish…") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in self?.waitToComplete(completion: completion) @@ -314,10 +310,9 @@ private extension AppDelegate { Self.logger.info("Accounts sync processing terminated for running too long.") } - DispatchQueue.main.async { - AccountManager.shared.syncArticleStatusAll() { - completeProcessing() - } + Task { @MainActor in + await AccountManager.shared.syncArticleStatusAll() + completeProcessing() } } @@ -375,24 +370,23 @@ private extension AppDelegate { scheduleBackgroundFeedRefresh() // schedule next refresh - Self.logger.info("Woken to perform account refresh.") + Self.logger.info("Performing background refresh.") - DispatchQueue.main.async { + Task { @MainActor in if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() } - AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) { [unowned self] in - if !AccountManager.shared.isSuspended { - self.suspendApplication() - Self.logger.info("Account refresh operation completed.") - task.setTaskCompleted(success: true) - } + await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) + if !AccountManager.shared.isSuspended { + self.suspendApplication() + Self.logger.info("Background refresh completed.") + task.setTaskCompleted(success: true) } } // set expiration handler task.expirationHandler = { [weak task] in - Self.logger.info("Accounts refresh processing terminated for running too long.") + Self.logger.info("Background refresh terminated for running too long.") DispatchQueue.main.async { self.suspendApplication() task?.setTaskCompleted(success: false) @@ -428,7 +422,7 @@ private extension AppDelegate { return } - guard let singleArticleSet = try? account.fetchArticles(.articleIDs([articleID])) else { + guard let singleArticleSet = try? account.fetchArticlesSync(.articleIDs([articleID])) else { assertionFailure("Expected article with \(articleID)") Self.logger.error("No article with articleID found \(articleID) from status notification") return diff --git a/iOS/MainFeed/MainFeedCollectionViewController.swift b/iOS/MainFeed/MainFeedCollectionViewController.swift index 2ddebb20d..e2d76cf98 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController.swift @@ -1112,7 +1112,7 @@ extension MainFeedCollectionViewController { MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in // If you don't have this delay the screen flashes when it executes this code DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { - if let articles = try? account.fetchArticles(.unread()) { + if let articles = try? account.fetchArticlesSync(.unread()) { self?.coordinator.markAllAsRead(Array(articles)) } }