Merge branch 'feature/new-progress'

This commit is contained in:
Brent Simmons committed 2026-01-04 10:53:34 -08:00
commit fe36db8534
24 files changed
+503 -442

No files matched your search

+1 -1
View File
@@ -95,7 +95,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidBegin, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidFinish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
@@ -33,7 +33,7 @@ final class SidebarStatusBarView: NSView {
progressLabel.font = NSFont.monospacedDigitSystemFont(ofSize: progressLabelFontSize, weight: NSFont.Weight.regular)
progressLabel.stringValue = ""
NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
}
}
@@ -45,8 +45,7 @@ final class SidebarStatusBarView: NSView {
// MARK: Notifications
@objc dynamic func progressDidChange(_ notification: Notification) {
@objc func progressInfoDidChange(_ notification: Notification) {
CoalescingQueue.standard.add(self, #selector(updateUI))
}
}
@@ -99,21 +98,21 @@ private extension SidebarStatusBarView {
func updateProgressIndicator() {
let progress = AccountManager.shared.combinedRefreshProgress
let progressInfo = CombinedRefreshProgress.shared.progressInfo
if progress.isComplete {
if progressInfo.isComplete {
stopProgressIfNeeded()
return
}
startProgressIfNeeded()
let maxValue = Double(progress.numberOfTasks)
let maxValue = Double(progressInfo.numberOfTasks)
if progressIndicator.maxValue != maxValue {
progressIndicator.maxValue = maxValue
}
let doubleValue = Double(progress.numberCompleted)
let doubleValue = Double(progressInfo.numberCompleted)
if progressIndicator.doubleValue != doubleValue {
progressIndicator.doubleValue = doubleValue
}
@@ -121,15 +120,15 @@ private extension SidebarStatusBarView {
func updateProgressLabel() {
let progress = AccountManager.shared.combinedRefreshProgress
let progressInfo = CombinedRefreshProgress.shared.progressInfo
if progress.isComplete {
if progressInfo.isComplete {
progressLabel.stringValue = ""
return
}
let formatString = NSLocalizedString("%@ of %@", comment: "Status bar progress")
let s = String(format: formatString, NSNumber(value: progress.numberCompleted), NSNumber(value: progress.numberOfTasks))
let s = String(format: formatString, NSNumber(value: progressInfo.numberCompleted), NSNumber(value: progressInfo.numberOfTasks))
progressLabel.stringValue = s
}
+11 -12
View File
@@ -26,7 +26,6 @@ public extension Notification.Name {
static let UserDidDeleteAccount = Notification.Name("UserDidDeleteAccount")
static let AccountRefreshDidBegin = Notification.Name(rawValue: "AccountRefreshDidBegin")
static let AccountRefreshDidFinish = Notification.Name(rawValue: "AccountRefreshDidFinish")
static let AccountRefreshProgressDidChange = Notification.Name(rawValue: "AccountRefreshProgressDidChange")
static let AccountDidDownloadArticles = Notification.Name(rawValue: "AccountDidDownloadArticles")
static let AccountStateDidChange = Notification.Name(rawValue: "AccountStateDidChange")
static let StatusesDidChange = Notification.Name(rawValue: "StatusesDidChange")
@@ -60,7 +59,7 @@ public enum FetchType {
case searchWithArticleIDs(String, Set<String>)
}
@MainActor public final class Account: DisplayNameProvider, UnreadCountProvider, Container, Hashable {
@MainActor public final class Account: ProgressInfoReporter, DisplayNameProvider, UnreadCountProvider, Container, Hashable {
public struct UserInfoKey {
public static let account = "account" // UserDidAddAccount, UserDidDeleteAccount
public static let newArticles = "newArticles" // AccountDidDownloadArticles
@@ -238,8 +237,13 @@ public enum FetchType {
}
}
var refreshProgress: DownloadProgress {
return delegate.refreshProgress
public var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
refreshInProgress = !progressInfo.isComplete
}
}
init(dataFolder: String, type: AccountType, accountID: String, transport: Transport? = nil) {
@@ -295,7 +299,7 @@ public enum FetchType {
defaultName = NSLocalizedString("The Old Reader", comment: "The Old Reader")
}
NotificationCenter.default.addObserver(self, selector: #selector(downloadProgressDidChange(_:)), name: .DownloadProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: delegate)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batchUpdateDidPerform(_:)), name: .BatchUpdateDidPerform, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
@@ -993,13 +997,8 @@ public enum FetchType {
// MARK: - Notifications
@objc func downloadProgressDidChange(_ note: Notification) {
guard let noteObject = note.object as? DownloadProgress, noteObject === refreshProgress else {
return
}
refreshInProgress = !refreshProgress.isComplete
NotificationCenter.default.post(name: .AccountRefreshProgressDidChange, object: self)
@objc func progressInfoDidChange(_ note: Notification) {
progressInfo = delegate.progressInfo
}
@objc func unreadCountDidChange(_ note: Notification) {
@@ -7,11 +7,12 @@
//
import Foundation
import Articles
import RSCore
import RSWeb
import Articles
import Secrets
@MainActor protocol AccountDelegate {
@MainActor protocol AccountDelegate: ProgressInfoReporter {
var behaviors: AccountBehaviors { get }
@@ -21,8 +22,6 @@ import Secrets
var credentials: Credentials? { get set }
var accountMetadata: AccountMetadata? { get set }
var refreshProgress: DownloadProgress { get }
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async
func refreshAll(for account: Account) async throws
@@ -100,8 +100,6 @@ import RSDatabase
return false
}
public let combinedRefreshProgress = CombinedRefreshProgress()
private var isActive = false
public init() {
@@ -281,9 +279,9 @@ import RSDatabase
return
}
combinedRefreshProgress.start()
CombinedRefreshProgress.shared.start()
defer {
combinedRefreshProgress.stop()
CombinedRefreshProgress.shared.stop()
}
await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in
@@ -10,12 +10,12 @@ import Foundation
import CloudKit
import SystemConfiguration
import os.log
import SyncDatabase
import RSCore
import RSParser
import RSWeb
import SyncDatabase
import Articles
import ArticlesDatabase
import RSWeb
import Secrets
import CloudKitSync
import FeedFinder
@@ -54,9 +54,26 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
var credentials: Credentials?
var accountMetadata: AccountMetadata?
/// refreshProgress is combined sync progress and feed download progress.
let refreshProgress = DownloadProgress(numberOfTasks: 0)
private let syncProgress = DownloadProgress(numberOfTasks: 0)
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
private let syncProgress = RSProgress()
private var syncProgressInfo = ProgressInfo() {
didSet {
updateProgress()
}
}
private var refreshProgressInfo = ProgressInfo() {
didSet {
updateProgress()
}
}
init(dataFolder: String) {
@@ -69,8 +86,8 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
self.refresher = LocalAccountRefresher()
self.refresher.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(downloadProgressDidChange(_:)), name: .DownloadProgressDidChange, object: refresher.downloadProgress)
NotificationCenter.default.addObserver(self, selector: #selector(syncProgressDidChange(_:)), name: .DownloadProgressDidChange, object: syncProgress)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .progressInfoDidChange, object: refresher)
NotificationCenter.default.addObserver(self, selector: #selector(syncProgressDidChange(_:)), name: .progressInfoDidChange, object: syncProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
@@ -84,7 +101,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
func refreshAll(for account: Account) async throws {
guard refreshProgress.isComplete else {
guard refreshProgressInfo.isComplete else {
return
}
@@ -121,7 +138,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
}
func importOPML(for account: Account, opmlFile: URL) async throws {
guard refreshProgress.isComplete else {
guard refreshProgressInfo.isComplete else {
return
}
@@ -324,10 +341,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
group.addTask {
do {
try await self.restoreFeed(for: account, feed: feed, container: folder)
self.syncProgress.completeTask()
await self.syncProgress.completeTask()
} catch {
Self.logger.error("CloudKit: Restore folder feed error: \(error.localizedDescription)")
self.syncProgress.completeTask()
await self.syncProgress.completeTask()
}
}
}
@@ -407,26 +424,16 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
private extension CloudKitAccountDelegate {
func updateRefreshProgress() {
// refreshProgress.numberOfTasks = refresher.downloadProgress.numberOfTasks + syncProgress.numberOfTasks
// refreshProgress.numberRemaining = refresher.downloadProgress.numberRemaining + syncProgress.numberRemaining
// Complete?
if refreshProgress.isComplete {
refresher.downloadProgress.reset()
syncProgress.reset()
}
func updateProgress() {
progressInfo = ProgressInfo.combined([refreshProgressInfo, syncProgressInfo])
}
@objc func downloadProgressDidChange(_ note: Notification) {
updateRefreshProgress()
@objc func refreshProgressDidChange(_ note: Notification) {
refreshProgressInfo = refresher.progressInfo
}
@objc func syncProgressDidChange(_ note: Notification) {
updateRefreshProgress()
syncProgressInfo = syncProgress.progressInfo
}
}
@@ -639,8 +646,6 @@ private extension CloudKitAccountDelegate {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
let op = CloudKitSendStatusOperation(account: account,
articlesZone: articlesZone,
refreshProgress: refreshProgress,
showProgress: showProgress,
database: syncDatabase)
op.completionBlock = { mainThreadOperation in
if mainThreadOperation.isCanceled {
@@ -18,46 +18,23 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl
private let blockSize = 150
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
init(account: Account, articlesZone: CloudKitArticlesZone, refreshProgress: DownloadProgress, showProgress: Bool, database: SyncDatabase) {
init(account: Account, articlesZone: CloudKitArticlesZone, database: SyncDatabase) {
self.account = account
self.articlesZone = articlesZone
self.refreshProgress = refreshProgress
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")
Task { @MainActor in
defer {
localProgress.completeAll()
didComplete()
}
do {
if showProgress {
let count = (try await syncDatabase.selectPendingCount()) ?? 0
let ticks = count / blockSize
localProgress.addTasks(ticks)
}
await selectForProcessing()
Self.logger.debug("iCloud: Finished sending article statuses")
} catch {
Self.logger.debug("iCloud: Send status error: \(error.localizedDescription)")
}
await selectForProcessing()
Self.logger.debug("iCloud: Finished sending article statuses")
didComplete()
}
}
}
@@ -65,12 +42,6 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl
@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 {
@@ -7,105 +7,81 @@
//
import Foundation
import RSCore
import RSWeb
extension Notification.Name {
public static let combinedRefreshProgressDidChange = Notification.Name("combinedRefreshProgressDidChange")
}
/// Combine the refresh progress of multiple accounts into one place,
/// for use by refresh status view and so on.
public final class CombinedRefreshProgress {
public private(set) var numberOfTasks = 0
public private(set) var numberRemaining = 0
public private(set) var numberCompleted = 0
public var isComplete: Bool {
!isStarted || numberRemaining < 1
@MainActor public final class CombinedRefreshProgress: ProgressInfoReporter {
public static let shared = CombinedRefreshProgress()
public var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
var isStarted = false
public var isComplete: Bool {
!isStarted || progressInfo.numberRemaining < 1
}
private var isStarted = false {
didSet {
if isStarted != oldValue {
progressInfo = ProgressInfo()
}
}
}
init() {
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .DownloadProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: nil)
}
func start() {
reset()
isStarted = true
}
func stop() {
reset()
isStarted = false
}
@MainActor @objc func refreshProgressDidChange(_ notification: Notification) {
@objc func progressInfoDidChange(_ notification: Notification) {
guard isStarted else {
return
}
var updatedNumberOfTasks = 0
var updatedNumberRemaining = 0
var updatedNumberCompleted = 0
var didMakeChange = false
let downloadProgresses = AccountManager.shared.activeAccounts.map { $0.refreshProgress }
for downloadProgress in downloadProgresses {
let progressInfo = downloadProgress.progressInfo
updatedNumberOfTasks += progressInfo.numberOfTasks
updatedNumberRemaining += progressInfo.numberRemaining
updatedNumberCompleted += progressInfo.numberCompleted
guard notification.object is Account else {
return
}
if updatedNumberOfTasks > numberOfTasks {
numberOfTasks = updatedNumberOfTasks
didMakeChange = true
}
let currentProgressInfo = progressInfo
assert(updatedNumberRemaining <= numberOfTasks)
updatedNumberRemaining = max(updatedNumberRemaining, numberRemaining)
updatedNumberRemaining = min(updatedNumberRemaining, numberOfTasks)
if updatedNumberRemaining != numberRemaining {
numberRemaining = updatedNumberRemaining
didMakeChange = true
}
let progressInfos = AccountManager.shared.activeAccounts.map { $0.progressInfo }
let updatedProgressInfo = ProgressInfo.combined(progressInfos)
var updatedNumberOfTasks = updatedProgressInfo.numberOfTasks
var updatedNumberCompleted = updatedProgressInfo.numberCompleted
var updatedNumberRemaining = updatedProgressInfo.numberRemaining
assert(updatedNumberCompleted <= numberOfTasks)
updatedNumberCompleted = max(updatedNumberCompleted, numberCompleted)
updatedNumberCompleted = min(updatedNumberCompleted, numberOfTasks)
if updatedNumberCompleted != numberCompleted {
numberCompleted = updatedNumberCompleted
didMakeChange = true
if updatedNumberOfTasks < currentProgressInfo.numberOfTasks {
updatedNumberOfTasks = currentProgressInfo.numberOfTasks
}
if updatedNumberCompleted < currentProgressInfo.numberCompleted {
updatedNumberCompleted = currentProgressInfo.numberCompleted
}
if updatedNumberCompleted > updatedProgressInfo.numberOfTasks {
updatedNumberOfTasks = updatedNumberCompleted
}
updatedNumberRemaining = updatedNumberOfTasks - updatedNumberCompleted
if didMakeChange {
postDidChangeNotification()
}
progressInfo = ProgressInfo(numberOfTasks: updatedNumberOfTasks,
numberCompleted: updatedNumberCompleted,
numberRemaining: updatedNumberRemaining)
}
}
private extension CombinedRefreshProgress {
func reset() {
let didMakeChange = numberOfTasks != 0 || numberRemaining != 0 || numberCompleted != 0
numberOfTasks = 0
numberRemaining = 0
numberCompleted = 0
if didMakeChange {
postDidChangeNotification()
}
}
func postDidChangeNotification() {
NotificationCenter.default.post(name: .combinedRefreshProgressDidChange, object: self)
progressInfo = ProgressInfo()
}
}
@@ -25,7 +25,15 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
let behaviors: AccountBehaviors = [.disallowFeedCopyInRootFolder]
let server: String? = "api.feedbin.com"
var isOPMLImportInProgress = false
var refreshProgress = DownloadProgress(numberOfTasks: 0)
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
let refreshProgress = RSProgress()
var credentials: Credentials? {
didSet {
@@ -65,6 +73,8 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
caller = FeedbinAPICaller(transport: URLSession(configuration: sessionConfiguration))
}
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
@@ -374,6 +384,11 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
caller.resume()
syncDatabase.resume()
}
// MARK: - Notifications
@objc func progressInfoDidChange(_ notification: Notification) {
progressInfo = refreshProgress.progressInfo
}
}
// MARK: Private
@@ -15,7 +15,6 @@ import os.log
import Secrets
@MainActor final class FeedlyAccountDelegate: AccountDelegate {
/// Feedly has a sandbox API and a production API.
/// This property is referred to when clients need to know which environment it should be pointing to.
/// The value of this property must match any `OAuthAuthorizationClient` used.
@@ -24,6 +23,14 @@ import Secrets
return .cloud
}
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
// TODO: Kiel, if you decide not to support OPML import you will have to disallow it in the behaviors
// See https://developer.feedly.com/v3/opml/
var behaviors: AccountBehaviors = [.disallowFeedInRootFolder, .disallowMarkAsUnreadAfterPeriod(31)]
@@ -53,8 +60,6 @@ import Secrets
var accountMetadata: AccountMetadata?
nonisolated let refreshProgress = DownloadProgress(numberOfTasks: 0)
/// Set on `accountDidInitialize` for the purposes of refreshing OAuth tokens when they expire.
/// See the implementation for `FeedlyAPICallerDelegate`.
private weak var initializedAccount: Account?
@@ -100,6 +105,8 @@ import Secrets
self.oauthAuthorizationClient = api.oauthAuthorizationClient
self.caller.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(syncProgressDidChange(_:)), name: .progressInfoDidChange, object: operationQueue)
}
// MARK: Account API
@@ -135,11 +142,9 @@ import Secrets
return
}
refreshProgress.reset()
progressInfo = ProgressInfo()
let syncAllOperation = FeedlySyncAllOperation(account: account, feedlyUserId: credentials.username, caller: caller, database: syncDatabase, lastSuccessfulFetchStartDate: accountMetadata?.lastArticleFetchStartTime, downloadProgress: refreshProgress, operationQueue: operationQueue)
syncAllOperation.downloadProgress = refreshProgress
let syncAllOperation = FeedlySyncAllOperation(account: account, feedlyUserId: credentials.username, caller: caller, database: syncDatabase, lastSuccessfulFetchStartDate: accountMetadata?.lastArticleFetchStartTime, operationQueue: operationQueue)
let date = Date()
syncAllOperation.syncCompletionHandler = { [weak self] result in
@@ -150,11 +155,13 @@ import Secrets
Self.logger.debug("Feedly: Sync took \(-date.timeIntervalSinceNow, privacy: .public) seconds")
completion(result)
self?.refreshProgress.reset()
self?.operationQueue.isTrackingProgress = false
self?.progressInfo = ProgressInfo()
}
currentSyncAllOperation = syncAllOperation
operationQueue.isTrackingProgress = true
operationQueue.suspend()
operationQueue.add(syncAllOperation)
}
@@ -246,21 +253,18 @@ import Secrets
Self.logger.info("Feedly: Begin importing OPML")
isOPMLImportInProgress = true
refreshProgress.addTask()
caller.importOpml(data) { result in
Task { @MainActor in
switch result {
case .success:
Self.logger.info("Feedly: OPML import finished")
self.refreshProgress.completeTask()
self.isOPMLImportInProgress = false
DispatchQueue.main.async {
completion(.success(()))
}
case .failure(let error):
Self.logger.error("Feedly: OPML import failed: \(error.localizedDescription)")
self.refreshProgress.completeTask()
self.isOPMLImportInProgress = false
DispatchQueue.main.async {
let wrappedError = AccountError.wrapped(error, account)
@@ -281,13 +285,8 @@ import Secrets
@MainActor func createFolder(for account: Account, name: String, completion: @escaping @Sendable (Result<Folder, Error>) -> Void) {
let progress = refreshProgress
progress.addTask()
caller.createCollection(named: name) { result in
Task { @MainActor in
progress.completeTask()
switch result {
case .success(let collection):
if let folder = account.ensureFolder(with: collection.label) {
@@ -352,12 +351,8 @@ import Secrets
}
}
let progress = refreshProgress
progress.addTask()
caller.deleteCollection(with: id) { result in
Task { @MainActor in
progress.completeTask()
switch result {
case .success:
@@ -395,7 +390,6 @@ import Secrets
getStreamContentsService: caller,
database: syncDatabase,
container: container,
progress: refreshProgress,
operationQueue: operationQueue)
addNewFeed.addCompletionHandler = { result in
@@ -469,7 +463,6 @@ import Secrets
resource: resource,
service: caller,
container: container,
progress: refreshProgress,
customFeedName: feed.editedName,
operationQueue: operationQueue)
@@ -670,6 +663,16 @@ import Secrets
syncDatabase.resume()
caller.resume()
}
// MARK: - Notifications
@objc func syncProgressDidChange(_ notification: Notification) {
if operationQueue.isTrackingProgress {
progressInfo = operationQueue.progressInfo
} else {
progressInfo = ProgressInfo()
}
}
}
extension FeedlyAccountDelegate: FeedlyAPICallerDelegate {
@@ -691,7 +694,6 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate {
}
let refreshAccessToken = FeedlyRefreshAccessTokenOperation(account: account, service: self, oauthClient: oauthAuthorizationClient)
refreshAccessToken.downloadProgress = refreshProgress
/// This must be strongly referenced by the completionBlock of the `FeedlyRefreshAccessTokenOperation`.
let refreshAccessTokenDelegate = RefreshAccessTokenOperationDelegate()
@@ -15,7 +15,7 @@ import Secrets
final class FeedlyAddExistingFeedOperation: FeedlyOperation, FeedlyOperationDelegate, FeedlyCheckpointOperationDelegate, @unchecked Sendable {
var addCompletionHandler: ((Result<Void, Error>) -> ())?
init(account: Account, credentials: Credentials, resource: FeedlyFeedResourceId, service: FeedlyAddFeedToCollectionService, container: Container, progress: DownloadProgress, customFeedName: String? = nil, operationQueue: MainThreadOperationQueue) throws {
init(account: Account, credentials: Credentials, resource: FeedlyFeedResourceId, service: FeedlyAddFeedToCollectionService, container: Container, customFeedName: String? = nil, operationQueue: MainThreadOperationQueue) throws {
let validator = FeedlyFeedContainerValidator(container: container)
let (folder, collectionId) = try validator.getValidContainer()
@@ -24,21 +24,16 @@ final class FeedlyAddExistingFeedOperation: FeedlyOperation, FeedlyOperationDele
super.init()
self.downloadProgress = progress
let addRequest = FeedlyAddFeedToCollectionOperation(account: account, folder: folder, feedResource: resource, feedName: customFeedName, collectionId: collectionId, service: service)
addRequest.delegate = self
addRequest.downloadProgress = progress
operationQueue.add(addRequest)
let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: addRequest)
createFeeds.downloadProgress = progress
createFeeds.addDependency(addRequest)
operationQueue.add(createFeeds)
let finishOperation = FeedlyCheckpointOperation()
finishOperation.checkpointDelegate = self
finishOperation.downloadProgress = progress
finishOperation.addDependency(createFeeds)
operationQueue.add(finishOperation)
}
@@ -27,7 +27,7 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate,
private var feedResourceId: FeedlyFeedResourceId?
var addCompletionHandler: ((Result<Feed, Error>) -> ())?
@MainActor init(account: Account, credentials: Credentials, url: String, feedName: String?, searchService: FeedlySearchService, addToCollectionService: FeedlyAddFeedToCollectionService, syncUnreadIdsService: FeedlyGetStreamIdsService, getStreamContentsService: FeedlyGetStreamContentsService, database: SyncDatabase, container: Container, progress: DownloadProgress, operationQueue: MainThreadOperationQueue) throws {
@MainActor init(account: Account, credentials: Credentials, url: String, feedName: String?, searchService: FeedlySearchService, addToCollectionService: FeedlyAddFeedToCollectionService, syncUnreadIdsService: FeedlyGetStreamIdsService, getStreamContentsService: FeedlyGetStreamContentsService, database: SyncDatabase, container: Container, operationQueue: MainThreadOperationQueue) throws {
let validator = FeedlyFeedContainerValidator(container: container)
(self.folder, self.collectionId) = try validator.getValidContainer()
@@ -44,12 +44,10 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate,
super.init()
operationQueue.suspend()
self.downloadProgress = progress
let search = FeedlySearchOperation(query: url, locale: .current, service: searchService)
search.delegate = self
search.searchDelegate = self
search.downloadProgress = progress
operationQueue.add(search)
operationQueue.resume()
}
@@ -89,30 +87,25 @@ final class FeedlyAddNewFeedOperation: FeedlyOperation, FeedlyOperationDelegate,
let addRequest = FeedlyAddFeedToCollectionOperation(account: account, folder: folder, feedResource: feedResourceId, feedName: feedName, collectionId: collectionId, service: addToCollectionService)
addRequest.delegate = self
addRequest.downloadProgress = downloadProgress
operationQueue.add(addRequest)
let createFeeds = FeedlyCreateFeedsForCollectionFoldersOperation(account: account, feedsAndFoldersProvider: addRequest)
createFeeds.delegate = self
createFeeds.addDependency(addRequest)
createFeeds.downloadProgress = downloadProgress
operationQueue.add(createFeeds)
let syncUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: credentials.username, service: syncUnreadIdsService, database: database, newerThan: nil)
syncUnread.addDependency(createFeeds)
syncUnread.downloadProgress = downloadProgress
syncUnread.delegate = self
operationQueue.add(syncUnread)
let syncFeed = FeedlySyncStreamContentsOperation(account: account, resource: feedResourceId, service: getStreamContentsService, isPagingEnabled: false, newerThan: nil, operationQueue: operationQueue)
syncFeed.addDependency(syncUnread)
syncFeed.downloadProgress = downloadProgress
syncFeed.delegate = self
operationQueue.add(syncFeed)
let finishOperation = FeedlyCheckpointOperation()
finishOperation.checkpointDelegate = self
finishOperation.downloadProgress = downloadProgress
finishOperation.addDependency(syncFeed)
finishOperation.delegate = self
operationQueue.add(finishOperation)
@@ -21,12 +21,6 @@ protocol FeedlyOperationDelegate: AnyObject {
open class FeedlyOperation: MainThreadOperation, @unchecked Sendable {
weak var delegate: FeedlyOperationDelegate?
var error: Error?
var downloadProgress: DownloadProgress? {
didSet {
oldValue?.completeTask()
downloadProgress?.addTask()
}
}
nonisolated func didComplete(with error: Error) {
if Thread.isMainThread {
@@ -42,7 +36,6 @@ open class FeedlyOperation: MainThreadOperation, @unchecked Sendable {
}
@MainActor open override func noteDidComplete() {
downloadProgress?.completeTask()
if let error {
delegate?.feedlyOperation(self, didFailWith: error)
}
@@ -31,25 +31,21 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable {
///
/// Download articles for statuses at the union of those statuses without its corresponding article and those included in 3 (changed since last successful sync).
///
@MainActor init(account: Account, feedlyUserId: String, lastSuccessfulFetchStartDate: Date?, markArticlesService: FeedlyMarkArticlesService, getUnreadService: FeedlyGetStreamIdsService, getCollectionsService: FeedlyGetCollectionsService, getStreamContentsService: FeedlyGetStreamContentsService, getStarredService: FeedlyGetStreamIdsService, getStreamIdsService: FeedlyGetStreamIdsService, getEntriesService: FeedlyGetEntriesService, database: SyncDatabase, downloadProgress: DownloadProgress, operationQueue: MainThreadOperationQueue) {
@MainActor init(account: Account, feedlyUserId: String, lastSuccessfulFetchStartDate: Date?, markArticlesService: FeedlyMarkArticlesService, getUnreadService: FeedlyGetStreamIdsService, getCollectionsService: FeedlyGetCollectionsService, getStreamContentsService: FeedlyGetStreamContentsService, getStarredService: FeedlyGetStreamIdsService, getStreamIdsService: FeedlyGetStreamIdsService, getEntriesService: FeedlyGetEntriesService, database: SyncDatabase, operationQueue: MainThreadOperationQueue) {
self.syncUUID = UUID()
super.init(name: "FeedlySyncAllOperation")
operationQueue.suspend()
self.downloadProgress = downloadProgress
// Send any read/unread/starred article statuses to Feedly before anything else.
let sendArticleStatuses = FeedlySendArticleStatusesOperation(database: database, service: markArticlesService)
sendArticleStatuses.delegate = self
sendArticleStatuses.downloadProgress = downloadProgress
operationQueue.add(sendArticleStatuses)
// Get all the Collections the user has.
let getCollections = FeedlyGetCollectionsOperation(service: getCollectionsService)
getCollections.delegate = self
getCollections.downloadProgress = downloadProgress
getCollections.addDependency(sendArticleStatuses)
operationQueue.add(getCollections)
@@ -67,7 +63,6 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable {
let getAllArticleIds = FeedlyIngestStreamArticleIdsOperation(account: account, userId: feedlyUserId, service: getStreamIdsService)
getAllArticleIds.delegate = self
getAllArticleIds.downloadProgress = downloadProgress
getAllArticleIds.addDependency(createFeedsOperation)
operationQueue.add(getAllArticleIds)
@@ -75,28 +70,24 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable {
let getUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: feedlyUserId, service: getUnreadService, database: database, newerThan: nil)
getUnread.delegate = self
getUnread.addDependency(getAllArticleIds)
getUnread.downloadProgress = downloadProgress
operationQueue.add(getUnread)
// Get each page of the article ids which have been update since the last successful fetch start date.
// If the date is nil, this operation provides an empty set (everything is new, nothing is updated).
let getUpdated = FeedlyGetUpdatedArticleIdsOperation(account: account, userId: feedlyUserId, service: getStreamIdsService, newerThan: lastSuccessfulFetchStartDate)
getUpdated.delegate = self
getUpdated.downloadProgress = downloadProgress
getUpdated.addDependency(createFeedsOperation)
operationQueue.add(getUpdated)
// Get each page of the article ids for starred articles.
let getStarred = FeedlyIngestStarredArticleIdsOperation(account: account, userId: feedlyUserId, service: getStarredService, database: database, newerThan: nil)
getStarred.delegate = self
getStarred.downloadProgress = downloadProgress
getStarred.addDependency(createFeedsOperation)
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)
@@ -112,7 +103,6 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable {
operationQueue: operationQueue
)
downloadMissingArticles.delegate = self
downloadMissingArticles.downloadProgress = downloadProgress
downloadMissingArticles.addDependency(getMissingIDs)
downloadMissingArticles.addDependency(getUpdated)
operationQueue.add(downloadMissingArticles)
@@ -120,13 +110,12 @@ final class FeedlySyncAllOperation: FeedlyOperation, @unchecked Sendable {
// Once this operation's dependencies, their dependencies etc finish, we can finish.
let finishOperation = FeedlyCheckpointOperation()
finishOperation.checkpointDelegate = self
finishOperation.downloadProgress = downloadProgress
finishOperation.addDependency(downloadMissingArticles)
operationQueue.add(finishOperation)
}
@MainActor convenience init(account: Account, feedlyUserId: String, caller: FeedlyAPICaller, database: SyncDatabase, lastSuccessfulFetchStartDate: Date?, downloadProgress: DownloadProgress, operationQueue: MainThreadOperationQueue) {
self.init(account: account, feedlyUserId: feedlyUserId, lastSuccessfulFetchStartDate: lastSuccessfulFetchStartDate, markArticlesService: caller, getUnreadService: caller, getCollectionsService: caller, getStreamContentsService: caller, getStarredService: caller, getStreamIdsService: caller, getEntriesService: caller, database: database, downloadProgress: downloadProgress, operationQueue: operationQueue)
@MainActor convenience init(account: Account, feedlyUserId: String, caller: FeedlyAPICaller, database: SyncDatabase, lastSuccessfulFetchStartDate: Date?, operationQueue: MainThreadOperationQueue) {
self.init(account: account, feedlyUserId: feedlyUserId, lastSuccessfulFetchStartDate: lastSuccessfulFetchStartDate, markArticlesService: caller, getUnreadService: caller, getCollectionsService: caller, getStreamContentsService: caller, getStarredService: caller, getStreamIdsService: caller, getEntriesService: caller, database: database, operationQueue: operationQueue)
}
@MainActor override func run() {
@@ -16,12 +16,19 @@ import RSWeb
import Secrets
@MainActor final class LocalAccountDelegate: AccountDelegate {
weak var account: Account?
let behaviors: AccountBehaviors = []
let isOPMLImportInProgress = false
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
let server: String? = nil
var credentials: Credentials?
var accountMetadata: AccountMetadata?
@@ -29,18 +36,15 @@ import Secrets
private lazy var refresher: LocalAccountRefresher = {
let refresher = LocalAccountRefresher()
refresher.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refresher)
return refresher
}()
lazy var refreshProgress: DownloadProgress = {
refresher.downloadProgress
}()
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
}
@MainActor func refreshAll(for account: Account) async throws {
guard refreshProgress.isComplete, !Platform.isRunningUnitTests else {
guard progressInfo.isComplete, !Platform.isRunningUnitTests else {
return
}
@@ -149,6 +153,12 @@ import Secrets
@MainActor func resume() {
refresher.resume()
}
// MARK: - Notifications
@objc func progressInfoDidChange(_ notification: Notification) {
progressInfo = refresher.progressInfo
}
}
extension LocalAccountDelegate: LocalAccountRefresherDelegate {
@@ -18,17 +18,24 @@ import os
func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges)
}
@MainActor final class LocalAccountRefresher {
@MainActor final class LocalAccountRefresher: ProgressInfoReporter {
var delegate: LocalAccountRefresherDelegate?
var downloadProgress: DownloadProgress {
downloadSession.downloadProgress
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
private var completion: (() -> Void)?
private var isSuspended = false
private lazy var downloadSession: DownloadSession = {
return DownloadSession(delegate: self)
let session = DownloadSession(delegate: self)
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: session)
return session
}()
private var urlToFeedDictionary = [String: Feed]()
@@ -75,6 +82,12 @@ import os
@MainActor public func resume() {
isSuspended = false
}
// MARK: - Notifications
@objc func progressInfoDidChange(_ notification: Notification) {
progressInfo = downloadSession.progressInfo
}
}
// MARK: - DownloadSessionDelegate
@@ -28,7 +28,15 @@ import Secrets
}
var accountMetadata: AccountMetadata?
var refreshProgress = DownloadProgress(numberOfTasks: 0)
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
let refreshProgress = RSProgress()
let caller: NewsBlurAPICaller
let syncDatabase: SyncDatabase
@@ -57,6 +65,7 @@ import Secrets
}
syncDatabase = SyncDatabase(databasePath: dataFolder.appending("/DB.sqlite3"))
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
@@ -429,7 +438,7 @@ import Secrets
return try await caller.validateCredentials()
}
// MARK: Suspend and Resume (for iOS)
// MARK: - Suspend and Resume (for iOS)
/// Suspend all network activity
func suspendNetwork() {
@@ -446,4 +455,10 @@ import Secrets
caller.resume()
syncDatabase.resume()
}
// MARK: - Notifications
@objc func progressInfoDidChange(_ notification: Notification) {
progressInfo = refreshProgress.progressInfo
}
}
@@ -44,6 +44,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
private let caller: ReaderAPICaller
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ReaderAPI")
var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
let refreshProgress = RSProgress()
var behaviors: AccountBehaviors {
var behaviors: AccountBehaviors = [.disallowOPMLImports, .disallowFeedInMultipleFolders]
if variant == .freshRSS {
@@ -70,8 +79,6 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
}
}
var refreshProgress = DownloadProgress(numberOfTasks: 0)
init(dataFolder: String, transport: Transport?, variant: ReaderAPIVariant) {
let databasePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3")
syncDatabase = SyncDatabase(databasePath: databasePath)
@@ -97,6 +104,8 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
self.caller.variant = variant
self.variant = variant
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress)
}
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async {
@@ -477,6 +486,12 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
func resume() {
syncDatabase.resume()
}
// MARK: - Notifications
@objc func progressInfoDidChange(_ notification: Notification) {
progressInfo = refreshProgress.progressInfo
}
}
// MARK: Private
@@ -16,15 +16,39 @@ import Foundation
///
/// The operation queue can be suspended and resumed.
/// It is *not* suspended on creation — it is active.
@MainActor public final class MainThreadOperationQueue {
@MainActor public final class MainThreadOperationQueue: ProgressInfoReporter {
/// Use the shared queue when you don’t need to create a separate queue.
public static let shared: MainThreadOperationQueue = MainThreadOperationQueue()
private var pendingOperations = [MainThreadOperation]()
private var currentOperation: MainThreadOperation?
private var completedOrCanceledOperationIDs = Set<Int>()
private var isSuspended = false
private var hasPendingRunScheduled = false
/// Controls whether or not `progressInfo` is reported.
///
/// Normally you would use this only for a private queue —
/// for a sync queue private to a specific account, for instance.
/// You would set it to true at the beginning of a sync session
/// and set it false when the sync session completes.
public var isTrackingProgress = false {
didSet {
if isTrackingProgress != oldValue {
completedOrCanceledOperationIDs = Set<Int>()
}
}
}
/// Reports progress. Valid only when `trackingProgress` is true.
public var progressInfo = ProgressInfo() {
didSet {
if isTrackingProgress && progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
public var pendingOperationsCount: Int {
let pendingNonCanceledOperations = pendingOperations.filter({ !$0.isCanceled })
return pendingNonCanceledOperations.count
@@ -74,6 +98,9 @@ import Foundation
precondition(Thread.isMainThread)
for operation in operations {
operation.cancel()
if isTrackingProgress {
completedOrCanceledOperationIDs.insert(operation.id)
}
}
runNextOperationIfNeeded()
@@ -113,6 +140,10 @@ import Foundation
operation.callCompletionBlock()
operation.noteDidComplete()
if isTrackingProgress {
completedOrCanceledOperationIDs.insert(operation.id)
}
pendingOperations.removeAll { $0 == operation }
if currentOperation == operation {
currentOperation = nil
@@ -140,6 +171,7 @@ private extension MainThreadOperationQueue {
for canceledOperation in canceledOperations {
pendingOperations.removeAll { $0 == canceledOperation }
}
updateProgressInfo()
}
func pendingAndCurrentOperations(named name: String) -> [MainThreadOperation]? {
@@ -151,7 +183,9 @@ private extension MainThreadOperationQueue {
}
func runNextOperationIfNeeded() {
guard !hasPendingRunScheduled else {
updateProgressInfo()
guard !isSuspended && !hasPendingRunScheduled else {
return
}
hasPendingRunScheduled = true
@@ -165,6 +199,7 @@ private extension MainThreadOperationQueue {
return
}
currentOperation = operation
updateProgressInfo()
operation.run()
}
}
@@ -184,4 +219,26 @@ private extension MainThreadOperationQueue {
func operationIsAvailable(_ operation: MainThreadOperation) -> Bool {
!operation.isCanceled && operation.dependencies.isEmpty
}
func updateProgressInfo() {
guard isTrackingProgress else {
return
}
let pendingOperationIDs: Set<Int> = {
var ids = Set(pendingOperations.map(\.id))
if let currentOperationID = currentOperation?.id {
ids.insert(currentOperationID)
}
return ids.filter { !completedOrCanceledOperationIDs.contains($0) }
}()
let numberCompleted = completedOrCanceledOperationIDs.count
let numberRemaining = pendingOperationIDs.count
let numberOfTasks = numberCompleted + numberRemaining
progressInfo = ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
}
}
@@ -0,0 +1,176 @@
//
// RSProgress.swift
// RSCore
//
// Created by Brent Simmons on 1/2/26.
//
import Foundation
public struct ProgressInfo: Sendable, Equatable {
public let numberOfTasks: Int
public let numberCompleted: Int
public let numberRemaining: Int
public var isComplete: Bool {
numberRemaining < 1
}
public init(numberOfTasks: Int = 0, numberCompleted: Int = 0, numberRemaining: Int = 0) {
assert(numberOfTasks >= 0 && numberCompleted >= 0 && numberRemaining >= 0)
assert(numberOfTasks == numberCompleted + numberRemaining)
self.numberOfTasks = numberOfTasks
self.numberCompleted = numberCompleted
self.numberRemaining = numberRemaining
}
public static func combined(_ progressInfos: [ProgressInfo]) -> ProgressInfo {
var numberOfTasks = 0
var numberCompleted = 0
var numberRemaining = 0
for progressInfo in progressInfos {
numberOfTasks += progressInfo.numberOfTasks
numberCompleted += progressInfo.numberCompleted
numberRemaining += progressInfo.numberRemaining
}
return ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
}
}
/// A ProgressInfoReporter provides a ProgressInfo struct and sends a .progressDidChange notification.
@MainActor public protocol ProgressInfoReporter: AnyObject {
var progressInfo: ProgressInfo { get }
}
public extension Notification.Name {
static let progressInfoDidChange = Notification.Name(rawValue: "ProgressInfoDidChangeNotification")
}
@MainActor public extension ProgressInfoReporter {
func postProgressInfoDidChangeNotification() {
NotificationCenter.default.post(name: .progressInfoDidChange, object: self)
}
}
@MainActor public final class RSProgress: ProgressInfoReporter {
public var numberOfTasks = 0
public var numberCompleted = 0
public var numberRemaining = 0
public var children: [RSProgress]?
/// Report progress including all children.
public var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
public var hasNoRemainingTasks: Bool {
assert(numberRemaining >= 0)
return numberRemaining < 1
}
public init(numberOfTasks: Int = 0) {
assert(numberOfTasks >= 0)
self.numberOfTasks = numberOfTasks
}
/// Directly set the number of remaining tasks, instead of calling `completeTasks`.
/// Updates `numberCompleted`.
public func updateNumberRemaining(_ newNumberRemaining: Int) {
if newNumberRemaining == numberRemaining {
return
}
assert(newNumberRemaining <= numberOfTasks)
numberRemaining = newNumberRemaining
numberCompleted = numberOfTasks - numberRemaining
updateProgressInfo()
}
/// Directly set the number of completed tasks, instead of calling `completeTasks`.
/// Updates `numberRemaining`.
public func updateNumberCompleted(_ newNumberCompleted: Int) {
if newNumberCompleted == numberCompleted {
return
}
assert(newNumberCompleted <= numberOfTasks)
numberCompleted = newNumberCompleted
numberRemaining = numberOfTasks - numberCompleted
updateProgressInfo()
}
public func addTasks(_ count: Int) {
numberOfTasks += count
numberRemaining += count
updateProgressInfo()
}
public func addTask() {
addTasks(1)
}
public func completeTasks(_ count: Int) {
numberCompleted += count
numberRemaining -= count
assert(numberRemaining >= 0)
if numberRemaining < 0 {
numberRemaining = 0
}
assert(numberOfTasks == numberRemaining + numberCompleted)
updateProgressInfo()
}
public func completeTask() {
completeTasks(1)
}
public func completeAll() {
numberCompleted = numberOfTasks
numberRemaining = 0
updateProgressInfo()
}
public func reset() {
numberOfTasks = 0
numberCompleted = 0
numberRemaining = 0
updateProgressInfo()
}
public func addChild(_ child: RSProgress) {
children = (children ?? []) + [child]
updateProgressInfo()
}
}
private extension RSProgress {
func updateProgressInfo() {
var numberOfTasks = self.numberOfTasks
var numberCompleted = self.numberCompleted
var numberRemaining = self.numberRemaining
if let children {
for child in children {
let childProgressInfo = child.progressInfo
numberOfTasks += childProgressInfo.numberOfTasks
numberCompleted += childProgressInfo.numberCompleted
numberRemaining += childProgressInfo.numberRemaining
}
}
progressInfo = ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
}
}
@@ -1,178 +0,0 @@
//
// DownloadProgress.swift
// RSWeb
//
// Created by Brent Simmons on 9/17/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import Synchronization
public extension Notification.Name {
static let DownloadProgressDidChange = Notification.Name(rawValue: "DownloadProgressDidChange")
}
nonisolated public final class DownloadProgress: Hashable, Sendable {
public struct ProgressInfo: Sendable {
public let numberOfTasks: Int
public let numberCompleted: Int
public let numberRemaining: Int
}
private let id: Int
private static let nextID = Mutex(0)
private struct State {
var numberOfTasks = 0
var numberCompleted = 0
var numberRemaining: Int {
let n = numberOfTasks - numberCompleted
assert(n >= 0)
return n
}
var children = Set<DownloadProgress>()
init(_ numberOfTasks: Int) {
self.numberOfTasks = numberOfTasks
}
}
private let state: Mutex<State>
public init(numberOfTasks: Int) {
assert(numberOfTasks >= 0)
self.state = Mutex(State(numberOfTasks))
self.id = Self.autoincrementingID()
}
public var progressInfo: ProgressInfo {
var numberOfTasks = 0
var numberCompleted = 0
var numberRemaining = 0
state.withLock { state in
numberOfTasks = state.numberOfTasks
numberCompleted = state.numberCompleted
numberRemaining = state.numberRemaining
for child in state.children {
let childProgressInfo = child.progressInfo
numberOfTasks += childProgressInfo.numberOfTasks
numberCompleted += childProgressInfo.numberCompleted
numberRemaining += childProgressInfo.numberRemaining
}
}
return ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
}
public var isComplete: Bool {
state.withLock { state in
state.numberRemaining < 1
}
}
public func addChild(_ childDownloadProgress: DownloadProgress) {
precondition(self != childDownloadProgress)
state.withLock { state in
_ = state.children.insert(childDownloadProgress)
}
}
public func addTask() {
addTasks(1)
}
public func addTasks(_ n: Int) {
assert(n > 0)
state.withLock { state in
state.numberOfTasks += n
}
postDidChangeNotification()
}
public func completeTask() {
completeTasks(1)
}
public func completeTasks(_ tasks: Int) {
state.withLock { state in
state.numberCompleted += tasks
assert(state.numberCompleted <= state.numberOfTasks)
}
postDidChangeNotification()
}
public func completeAll() {
state.withLock { state in
state.numberCompleted = state.numberOfTasks
for child in state.children {
child.completeAll()
}
}
}
@discardableResult
public func reset() -> Bool {
state.withLock { state in
var didChange = false
if state.numberOfTasks != 0 {
state.numberOfTasks = 0
didChange = true
}
if state.numberCompleted != 0 {
state.numberCompleted = 0
didChange = true
}
for child in state.children {
didChange = child.reset()
}
if didChange {
postDidChangeNotification()
}
return didChange
}
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
// MARK: - Equatable
public static func ==(lhs: DownloadProgress, rhs: DownloadProgress) -> Bool {
lhs.id == rhs.id
}
}
// MARK: - Private
nonisolated private extension DownloadProgress {
func postDidChangeNotification() {
DispatchQueue.main.async {
NotificationCenter.default.post(name: .DownloadProgressDidChange, object: self)
}
}
static func autoincrementingID() -> Int {
nextID.withLock { id in
defer {
id += 1
}
return id
}
}
}
@@ -31,8 +31,7 @@ struct HTTP4xxResponse {
}
}
@MainActor @objc public final class DownloadSession: NSObject {
public let downloadProgress = DownloadProgress(numberOfTasks: 0)
@MainActor @objc public final class DownloadSession: NSObject, ProgressInfoReporter {
private var urlSession: URLSession!
private var tasksInProgress = Set<URLSessionTask>()
private var tasksPending = Set<URLSessionTask>()
@@ -43,6 +42,14 @@ struct HTTP4xxResponse {
private var queue = [URL]()
private let cache = DownloadCache.shared
public var progressInfo = ProgressInfo() {
didSet {
if progressInfo != oldValue {
postProgressInfoDidChangeNotification()
}
}
}
// 429 Too Many Requests responses
private var retryAfterMessages = [String: HTTPResponse429]()
@@ -85,6 +92,9 @@ struct HTTP4xxResponse {
dataTasks.forEach { $0.cancel() }
uploadTasks.forEach { $0.cancel() }
downloadTasks.forEach { $0.cancel() }
Task { @MainActor in
self.updateProgress()
}
}
}
@@ -97,7 +107,7 @@ struct HTTP4xxResponse {
}
urlsInSession = filteredURLs
updateDownloadProgress()
updateProgress()
}
}
@@ -154,7 +164,7 @@ extension DownloadSession: @preconcurrency URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
MainActor.assumeIsolated {
defer {
updateDownloadProgress()
updateProgress()
}
tasksInProgress.insert(dataTask)
@@ -273,7 +283,7 @@ private extension DownloadSession {
addDataTaskFromQueueIfNecessary()
updateDownloadProgress()
updateProgress()
}
func urlStringIsDisallowedRedirect(_ urlString: String) -> Bool {
@@ -331,18 +341,27 @@ private extension DownloadSession {
// MARK: - Download Progress
@MainActor func updateDownloadProgress() {
// TODO
// downloadProgress.numberOfTasks = urlsInSession.count
//
// let numberRemaining = tasksPending.count + tasksInProgress.count + queue.count
// downloadProgress.numberRemaining = min(numberRemaining, downloadProgress.numberOfTasks)
//
// // Complete?
// if downloadProgress.numberOfTasks > 0 && downloadProgress.numberRemaining < 1 {
// delegate.downloadSessionDidComplete(self)
// urlsInSession.removeAll()
// }
@MainActor func updateProgress() {
let numberOfTasks = urlsInSession.count
let numberRemaining: Int
let numberCompleted: Int
if numberOfTasks == 0 {
numberRemaining = 0
numberCompleted = 0
} else {
numberRemaining = tasksPending.count + tasksInProgress.count + queue.count
numberCompleted = numberOfTasks - numberRemaining
}
progressInfo = ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
// Completed?
if progressInfo.numberOfTasks > 0 && progressInfo.numberRemaining < 1 {
delegate.downloadSessionDidComplete(self)
urlsInSession.removeAll()
}
}
// MARK: - 429 Too Many Requests
+7 -7
View File
@@ -15,7 +15,7 @@ final class RefreshProgressView: UIView {
override func awakeFromNib() {
MainActor.assumeIsolated {
NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
update()
scheduleUpdateRefreshLabel()
@@ -26,7 +26,7 @@ final class RefreshProgressView: UIView {
}
func update() {
if !AccountManager.shared.combinedRefreshProgress.isComplete {
if !CombinedRefreshProgress.shared.isComplete {
progressChanged(animated: false)
} else {
updateRefreshLabel()
@@ -37,7 +37,7 @@ final class RefreshProgressView: UIView {
progressChanged(animated: false)
}
@objc func progressDidChange(_ note: Notification) {
@objc func progressInfoDidChange(_ note: Notification) {
progressChanged(animated: true)
}
@@ -62,16 +62,16 @@ private extension RefreshProgressView {
// https://github.com/Ranchero-Software/NetNewsWire/issues/1764
let isInViewHierarchy = self.superview != nil
let progress = AccountManager.shared.combinedRefreshProgress
let progressInfo = CombinedRefreshProgress.shared.progressInfo
if progress.isComplete {
if progressInfo.isComplete {
if isInViewHierarchy {
progressView.setProgress(1, animated: animated)
}
func completeLabel() {
// Check that there are no pending downloads.
if AccountManager.shared.combinedRefreshProgress.isComplete {
if CombinedRefreshProgress.shared.isComplete {
self.updateRefreshLabel()
self.label.isHidden = false
self.progressView.isHidden = true
@@ -92,7 +92,7 @@ private extension RefreshProgressView {
label.isHidden = true
progressView.isHidden = false
if isInViewHierarchy {
let percent = Float(progress.numberCompleted) / Float(progress.numberOfTasks)
let percent = Float(progressInfo.numberCompleted) / Float(progressInfo.numberOfTasks)
// Don't let the progress bar go backwards unless we need to go back more than 25%
if percent > progressView.progress || progressView.progress - percent > 0.25 {
+4 -4
View File
@@ -326,7 +326,7 @@ struct FeedNode: Hashable, Sendable {
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(themeDownloadDidFail(_:)), name: .didFailToImportThemeWithError, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateNavigationBarSubtitles(_:)), name: .combinedRefreshProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateNavigationBarSubtitles(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in
@@ -584,7 +584,7 @@ struct FeedNode: Hashable, Sendable {
}
/// Updates navigation bar subtitles in response to feed selection, unread count changes,
/// `combinedRefreshProgressDidChange` notifications, and a timed refresh every
/// `progressInfoDidChange` notifications, and a timed refresh every
/// 60s.
///
/// Subtitles are handled differently on iPhone and iPad.
@@ -601,9 +601,9 @@ struct FeedNode: Hashable, Sendable {
///
/// - Parameter note: Optional `Notification`
@objc func updateNavigationBarSubtitles(_ note: Notification?) {
let progress = AccountManager.shared.combinedRefreshProgress
let progressInfo = CombinedRefreshProgress.shared.progressInfo
if progress.isComplete {
if progressInfo.isComplete {
if let accountLastArticleFetchEndTime = AccountManager.shared.lastArticleFetchEndTime {
if Date.now > accountLastArticleFetchEndTime.addingTimeInterval(60) {
let relativeDateTimeFormatter = RelativeDateTimeFormatter()