Convert to async/await

This commit is contained in:
Brent Simmons committed 2025-11-16 19:59:48 -08:00
1 parent b681dea6fa
commit 24a2e68fb5
32 files changed
+945 -961

No files matched your search

+4 -3
View File
@@ -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?) {
File diff suppressed because it is too large. Load diff
@@ -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<Article>()
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<Article> {
precondition(Thread.isMainThread)
guard activeAccounts.count > 0 else {
completion(.success(Set<Article>()))
return
}
guard activeAccounts.count > 0 else {
return Set<Article>()
}
Task { @MainActor in
var allFetchedArticles = Set<Article>()
var databaseError: DatabaseError?
let dispatchGroup = DispatchGroup()
var allFetchedArticles = Set<Article>()
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
@@ -11,82 +11,72 @@ import Articles
import ArticlesDatabase
public protocol ArticleFetcher {
@MainActor func fetchArticles() throws -> Set<Article>
@MainActor func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock)
@MainActor func fetchArticlesAsync() async throws -> Set<Article>
@MainActor func fetchUnreadArticles() throws -> Set<Article>
@MainActor func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock)
@MainActor func fetchUnreadArticlesAsync() async throws -> Set<Article>
}
@MainActor extension Feed: ArticleFetcher {
public func fetchArticles() throws -> Set<Article> {
return try account?.fetchArticles(.feed(self)) ?? Set<Article>()
return try account?.fetchArticlesSync(.feed(self)) ?? Set<Article>()
}
public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
guard let account = account else {
public func fetchArticlesAsync() async throws -> Set<Article> {
guard let account else {
assertionFailure("Expected feed.account, but got nil.")
completion(.success(Set<Article>()))
return
return Set<Article>()
}
account.fetchArticlesAsync(.feed(self), completion)
return try await account.fetchArticles(.feed(self))
}
public func fetchUnreadArticles() throws -> Set<Article> {
return try fetchArticles().unreadArticles()
}
public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
guard let account = account else {
public func fetchUnreadArticlesAsync() async throws -> Set<Article> {
guard let account else {
assertionFailure("Expected feed.account, but got nil.")
completion(.success(Set<Article>()))
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<Article>()
}
// 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<Article> {
guard let account = account else {
guard let account else {
assertionFailure("Expected folder.account, but got nil.")
return Set<Article>()
}
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<Article> {
guard let account else {
assertionFailure("Expected folder.account, but got nil.")
completion(.success(Set<Article>()))
return
return Set<Article>()
}
account.fetchArticlesAsync(.folder(self, false), completion)
return try await account.fetchArticles(.folder(self, false))
}
public func fetchUnreadArticles() throws -> Set<Article> {
guard let account = account else {
guard let account else {
assertionFailure("Expected folder.account, but got nil.")
return Set<Article>()
}
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<Article> {
guard let account else {
assertionFailure("Expected folder.account, but got nil.")
completion(.success(Set<Article>()))
return
return Set<Article>()
}
account.fetchArticlesAsync(.folder(self, true), completion)
return try await account.fetchArticles(.folder(self, true))
}
}
@@ -335,7 +335,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func markArticles(for account: Account, articles: Set<Article>, 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<Article>(), deleted: Set<Article>())
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)
}
}
}
@@ -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) })
@@ -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<Article>
func processWithArticles(_ articles: Set<Article>) {
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<Folder>() {
@@ -333,7 +333,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
}
@MainActor func markArticles(for account: Account, articles: Set<Article>, 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<ParsedItem> {
@@ -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)")
}
@@ -9,21 +9,21 @@
import Foundation
protocol FeedlyEntryIdentifierProviding: AnyObject {
var entryIds: Set<String> { get }
var entryIDs: Set<String> { get }
}
final class FeedlyEntryIdentifierProvider: FeedlyEntryIdentifierProviding {
private(set) var entryIds: Set<String>
private(set) var entryIDs: Set<String>
init(entryIds: Set<String> = Set()) {
self.entryIds = entryIds
init(entryIDs: Set<String> = 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)
}
}
@@ -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)
@@ -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<String>()
private(set) var entryIDs = Set<String>()
@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)
}
}
}
@@ -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):
@@ -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<String> {
var entryIDs: Set<String> {
guard let ids = streamIds?.ids else {
assertionFailure("Has this operation been addeded as a dependency on the caller?")
return []
@@ -34,7 +34,7 @@ final class FeedlyGetUpdatedArticleIdsOperation: FeedlyOperation, FeedlyEntryIde
self.init(account: account, resource: all, service: service, newerThan: newerThan)
}
var entryIds: Set<String> {
var entryIDs: Set<String> {
return storedUpdatedArticleIds
}
@@ -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)
@@ -21,19 +21,18 @@ public struct SingleArticleFetcher: ArticleFetcher {
}
public func fetchArticles() throws -> Set<Article> {
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<Article> {
try await account.fetchArticles(.articleIDs(Set([articleID])))
}
public func fetchUnreadArticles() throws -> Set<Article> {
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<Article> {
try await account.fetchArticles(.articleIDs(Set([articleID])))
}
}
@@ -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<UnreadCountDictionary,DatabaseError>
public typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult?) -> Void
public typealias SingleUnreadCountResult = Result<Int, DatabaseError>
public typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult?) -> Void
nonisolated public struct ArticleChanges: Sendable {
public let newArticles: Set<Article>?
public let updatedArticles: Set<Article>?
public let deletedArticles: Set<Article>?
public let new: Set<Article>?
public let updated: Set<Article>?
public let deleted: Set<Article>?
public init() {
self.newArticles = Set<Article>()
self.updatedArticles = Set<Article>()
self.deletedArticles = Set<Article>()
self.new = Set<Article>()
self.updated = Set<Article>()
self.deleted = Set<Article>()
}
public init(newArticles: Set<Article>?, updatedArticles: Set<Article>?, deletedArticles: Set<Article>?) {
self.newArticles = newArticles
self.updatedArticles = updatedArticles
self.deletedArticles = deletedArticles
public init(new: Set<Article>?, updated: Set<Article>?, deleted: Set<Article>?) {
self.new = new
self.updated = updated
self.deleted = deleted
}
}
public typealias UpdateArticlesResult = Result<ArticleChanges, DatabaseError>
public typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void
public typealias ArticleSetResult = Result<Set<Article>, DatabaseError>
public typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void
public typealias ArticleIDsResult = Result<Set<String>, Error>
public typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void
public typealias ArticleStatusesResult = Result<Set<ArticleStatus>, 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<Article> {
public func fetchArticles(feedID: String) throws -> Set<Article> {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
return try articlesTable.fetchArticles(feedID)
}
public func fetchArticles(_ feedIDs: Set<String>) throws -> Set<Article> {
public func fetchArticles(feedIDs: Set<String>) throws -> Set<Article> {
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<String>, _ limit: Int?) throws -> Set<Article> {
public func fetchUnreadArticles(feedIDs: Set<String>, limit: Int? = nil) throws -> Set<Article> {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
return try articlesTable.fetchUnreadArticles(feedIDs, limit)
}
public func fetchTodayArticles(_ feedIDs: Set<String>, _ limit: Int?) throws -> Set<Article> {
public func fetchTodayArticles(feedIDs: Set<String>, limit: Int? = nil) throws -> Set<Article> {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
return try articlesTable.fetchArticlesSince(feedIDs, todayCutoffDate(), limit)
}
public func fetchStarredArticles(_ feedIDs: Set<String>, _ limit: Int?) throws -> Set<Article> {
public func fetchStarredArticles(feedIDs: Set<String>, limit: Int? = nil) throws -> Set<Article> {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
return try articlesTable.fetchStarredArticles(feedIDs, limit)
}
public func fetchStarredArticlesCount(_ feedIDs: Set<String>) throws -> Int {
public func fetchStarredArticlesCount(feedIDs: Set<String>) 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<String>) throws -> Set<Article> {
public func fetchArticlesMatching(searchString: String, feedIDs: Set<String>) throws -> Set<Article> {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
return try articlesTable.fetchArticlesMatching(searchString, feedIDs)
}
public func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set<String>) throws -> Set<Article> {
public func fetchArticlesMatchingWithArticleIDs(searchString: String, articleIDs: Set<String>) throws -> Set<Article> {
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<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchArticlesAsync(feedID: feedID) { result in
continuation.resume(with: result)
}
}
}
public func fetchArticlesAsync(_ feedIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchArticlesAsync(feedIDs, completion)
public func fetchArticlesAsync(feedIDs: Set<String>) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchArticlesAsync(feedIDs: feedIDs) { result in
continuation.resume(with: result)
}
}
}
public func fetchArticlesAsync(articleIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchArticlesAsync(articleIDs: articleIDs, completion)
public func fetchArticlesAsync(articleIDs: Set<String>) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchArticlesAsync(articleIDs: articleIDs) { result in
continuation.resume(with: result)
}
}
}
public func fetchUnreadArticlesAsync(_ feedIDs: Set<String>, _ 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<String>, limit: Int? = nil) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchUnreadArticlesAsync(feedIDs: feedIDs, limit: limit) { result in
continuation.resume(with: result)
}
}
}
public func fetchTodayArticlesAsync(_ feedIDs: Set<String>, _ 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<String>, limit: Int? = nil) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchTodayArticlesAsync(feedIDs: feedIDs, limit: limit) { result in
continuation.resume(with: result)
}
}
}
public func fetchedStarredArticlesAsync(_ feedIDs: Set<String>, _ 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<String>, limit: Int? = nil) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchedStarredArticlesAsync(feedIDs: feedIDs, limit: limit) { result in
continuation.resume(with: result)
}
}
}
public func fetchArticlesMatchingAsync(_ searchString: String, _ feedIDs: Set<String>, _ 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<String>) async throws -> Set<Article> {
try await withCheckedThrowingContinuation { continuation in
_fetchArticlesMatchingAsync(searchString: searchString, feedIDs: feedIDs) { result in
continuation.resume(with: result)
}
}
}
public func fetchArticlesMatchingWithArticleIDsAsync(_ searchString: String, _ articleIDs: Set<String>, _ 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<String>) async throws -> Set<Article> {
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<String>, _ 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<String>) 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<String>, 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<String>) 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<String>, 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<String>, completion: @escaping SingleUnreadCountCompletionBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchStarredAndUnreadCount(feedIDs, completion)
public func fetchUnreadCountForStarredArticlesAsync(feedIDs: Set<String>) 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<ParsedItem>, 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<ParsedItem>, 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<ParsedItem>], 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<ParsedItem>], 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<String>, 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<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set<ArticleStatus> {
try await withCheckedThrowingContinuation { continuation in
self.mark(articles, statusKey: statusKey, flag: flag) { result in
continuation.resume(with: result)
}
}
}
public func mark(_ articles: Set<Article>, 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<String>, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set<String> {
try await withCheckedThrowingContinuation { continuation in
markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) { result in
continuation.resume(with: result)
}
}
}
private func markAndFetchNew(articleIDs: Set<String>, 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<String>) async throws {
public func deleteAsync(articleIDs: Set<String>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) 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<String>, 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<String> {
try await withCheckedThrowingContinuation { continuation in
_fetchUnreadArticleIDsAsync { result in
continuation.resume(with: result)
}
}
}
public func fetchStarredArticleIDsAsync() async throws -> Set<String> {
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<String> {
try await withCheckedThrowingContinuation { continuation in
_fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in
continuation.resume(with: result)
}
}
}
// MARK: - Statuses
public func markAsync(articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set<ArticleStatus> {
try await withCheckedThrowingContinuation { continuation in
_mark(articles: articles, statusKey: statusKey, flag: flag) { result in
continuation.resume(with: result)
}
}
}
public func markAndFetchNewAsync(articleIDs: Set<String>, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set<String> {
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<String>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) 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<UnreadCountDictionary, Error>
typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult) -> Void
typealias UpdateArticlesResult = Result<ArticleChanges, DatabaseError>
typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void
typealias SingleUnreadCountResult = Result<Int, DatabaseError>
typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult) -> Void
typealias ArticleSetResult = Result<Set<Article>, DatabaseError>
typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void
typealias ArticleIDsResult = Result<Set<String>, Error>
typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void
typealias ArticleStatusesResult = Result<Set<ArticleStatus>, 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<String>, _ completion: @escaping UnreadCountDictionaryCompletionBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchUnreadCounts(feedIDs, completion)
}
func _fetchUnreadCount(feedIDs: Set<String>, 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<String>, completion: @escaping SingleUnreadCountCompletionBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchStarredAndUnreadCount(feedIDs, completion)
}
func _mark(articles: Set<Article>, 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<String>, 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<String>, 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<String>, _ completion: @escaping ArticleSetResultBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchArticlesAsync(feedIDs, completion)
}
func _fetchArticlesAsync(articleIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchArticlesAsync(articleIDs: articleIDs, completion)
}
func _fetchUnreadArticlesAsync(feedIDs: Set<String>, 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<String>, 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<String>, 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<String>, _ 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<String>, _ completion: @escaping ArticleSetResultBlock) {
Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)")
articlesTable.fetchArticlesMatchingWithArticleIDsAsync(searchString, articleIDs, completion)
}
func _update(parsedItems: Set<ParsedItem>, 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<ParsedItem>], 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<String>, 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)
}
}
@@ -370,6 +370,58 @@ nonisolated final class ArticlesTable: DatabaseTable, Sendable {
// MARK: - Unread Counts
func fetchUnreadCounts(_ feedIDs: Set<String>, _ 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<String>, _ 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<String>, _ 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<Article>?, _ updatedArticles: Set<Article>?, _ deletedArticles: Set<Article>?, _ 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))
}
@@ -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
}
}
@@ -29,6 +29,7 @@ nonisolated final class StatusesTable: DatabaseTable, Sendable {
// MARK: - Creating/Updating
@discardableResult
func ensureStatusesForArticleIDs(_ articleIDs: Set<String>, _ read: Bool, _ database: FMDatabase) -> ([String: ArticleStatus], Set<String>) {
#if DEBUG
@@ -154,6 +154,7 @@ nonisolated public final class DatabaseQueue: Sendable {
error = databaseError
}
}
if let error {
throw(error)
}
+2 -2
View File
@@ -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
}
}
@@ -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
}
}
+19 -17
View File
@@ -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<Article> {
return try delegate.fetchArticles()
try delegate.fetchArticles()
}
func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
delegate.fetchArticlesAsync(completion)
func fetchArticlesAsync() async throws -> Set<Article> {
try await delegate.fetchArticlesAsync()
}
func fetchUnreadArticles() throws -> Set<Article> {
return try delegate.fetchUnreadArticles()
try delegate.fetchUnreadArticles()
}
func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
delegate.fetchUnreadArticlesAsync(completion)
func fetchUnreadArticlesAsync() async throws -> Set<Article> {
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
}
}
+7 -13
View File
@@ -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<Article> {
try await AccountManager.shared.fetchArticlesAsync(fetchType)
}
func fetchUnreadArticles() throws -> Set<Article> {
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<Article> {
let articles = try await fetchArticlesAsync()
return articles.unreadArticles()
}
}
+2 -3
View File
@@ -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()
}
}
+2 -3
View File
@@ -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()
}
}
+6 -6
View File
@@ -64,21 +64,21 @@ final class UnreadFeed: PseudoFeed {
}
}
extension UnreadFeed: ArticleFetcher {
@MainActor extension UnreadFeed: ArticleFetcher {
func fetchArticles() throws -> Set<Article> {
return try fetchUnreadArticles()
}
func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
fetchUnreadArticlesAsync(completion)
func fetchArticlesAsync() async throws -> Set<Article> {
try await fetchUnreadArticlesAsync()
}
func fetchUnreadArticles() throws -> Set<Article> {
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<Article> {
try await AccountManager.shared.fetchArticlesAsync(fetchType)
}
}
+1 -1
View File
@@ -73,6 +73,6 @@ import Account
lastTimedRefresh = Date()
update()
AccountManager.shared.refreshAll()
AccountManager.shared.refreshAllWithoutWaiting()
}
}
+1 -3
View File
@@ -78,8 +78,6 @@ import Account
lastTimedRefresh = Date()
update()
AccountManager.shared.syncArticleStatusAll()
AccountManager.shared.syncArticleStatusAllWithoutWaiting()
}
}
+18 -24
View File
@@ -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
@@ -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))
}
}