mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-12-01 09:50:16 +00:00
Convert validateCredentials to async await.
This commit is contained in:
1 parent
5915faa18d
commit
c8df04d8a0
15 files changed
+475
-481
No files matched your search
@@ -58,56 +58,55 @@ final class AccountsFeedbinWindowController: NSWindowController {
|
||||
hostWindow.beginSheet(window, completionHandler: completion)
|
||||
}
|
||||
|
||||
// MARK: Actions
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
@IBAction func cancel(_ sender: Any) {
|
||||
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
|
||||
}
|
||||
|
||||
@IBAction func action(_ sender: Any) {
|
||||
|
||||
self.errorMessageLabel.stringValue = ""
|
||||
errorMessageLabel.stringValue = ""
|
||||
|
||||
guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error")
|
||||
return
|
||||
}
|
||||
|
||||
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .feedbin, username: usernameTextField.stringValue) else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("There is already a Feedbin account with that username created.", comment: "Duplicate Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("There is already a Feedbin account with that username created.", comment: "Duplicate Error")
|
||||
return
|
||||
}
|
||||
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
let credentials = Credentials(type: .basic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
Account.validateCredentials(type: .feedbin, credentials: credentials) { [weak self] result in
|
||||
|
||||
guard let self = self else { return }
|
||||
|
||||
self.actionButton.isEnabled = true
|
||||
self.progressIndicator.isHidden = true
|
||||
self.progressIndicator.stopAnimation(self)
|
||||
|
||||
switch result {
|
||||
case .success(let validatedCredentials):
|
||||
|
||||
guard let validatedCredentials = validatedCredentials else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
|
||||
Task { @MainActor in
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
@MainActor func stopAnimation() {
|
||||
actionButton.isEnabled = true
|
||||
progressIndicator.isHidden = true
|
||||
progressIndicator.stopAnimation(self)
|
||||
}
|
||||
|
||||
let credentials = Credentials(type: .basic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
do {
|
||||
let validatedCredentials = try await Account.validateCredentials(type: .feedbin, credentials: credentials)
|
||||
stopAnimation()
|
||||
|
||||
guard let validatedCredentials else {
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
return
|
||||
}
|
||||
|
||||
if self.account == nil {
|
||||
self.account = AccountManager.shared.createAccount(type: .feedbin)
|
||||
}
|
||||
|
||||
do {
|
||||
try self.account?.removeCredentials(type: .basic)
|
||||
try self.account?.storeCredentials(validatedCredentials)
|
||||
|
||||
self.account?.refreshAll() { result in
|
||||
if account == nil {
|
||||
account = AccountManager.shared.createAccount(type: .feedbin)
|
||||
}
|
||||
|
||||
do {
|
||||
try account?.removeCredentials(type: .basic)
|
||||
try account?.storeCredentials(validatedCredentials)
|
||||
|
||||
account?.refreshAll() { result in
|
||||
switch result {
|
||||
case .success:
|
||||
break
|
||||
@@ -115,20 +114,17 @@ final class AccountsFeedbinWindowController: NSWindowController {
|
||||
NSApplication.shared.presentError(error)
|
||||
}
|
||||
}
|
||||
|
||||
self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
|
||||
hostWindow?.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
} catch {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
|
||||
}
|
||||
|
||||
case .failure:
|
||||
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
|
||||
|
||||
} catch {
|
||||
stopAnimation()
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@IBAction func createAccountWithProvider(_ sender: Any) {
|
||||
@@ -140,5 +136,4 @@ final class AccountsFeedbinWindowController: NSWindowController {
|
||||
usernameTextField.contentType = .username
|
||||
passwordTextField.contentType = .password
|
||||
}
|
||||
|
||||
}
|
||||
@@ -63,49 +63,50 @@ final class AccountsNewsBlurWindowController: NSWindowController {
|
||||
}
|
||||
|
||||
@IBAction func action(_ sender: Any) {
|
||||
self.errorMessageLabel.stringValue = ""
|
||||
errorMessageLabel.stringValue = ""
|
||||
|
||||
guard !usernameTextField.stringValue.isEmpty else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Username required.", comment: "Credentials Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Username required.", comment: "Credentials Error")
|
||||
return
|
||||
}
|
||||
|
||||
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .newsBlur, username: usernameTextField.stringValue) else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("There is already a NewsBlur account with that username created.", comment: "Duplicate Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("There is already a NewsBlur account with that username created.", comment: "Duplicate Error")
|
||||
return
|
||||
}
|
||||
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
let credentials = Credentials(type: .newsBlurBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
Account.validateCredentials(type: .newsBlur, credentials: credentials) { [weak self] result in
|
||||
|
||||
guard let self = self else { return }
|
||||
|
||||
self.actionButton.isEnabled = true
|
||||
self.progressIndicator.isHidden = true
|
||||
self.progressIndicator.stopAnimation(self)
|
||||
|
||||
switch result {
|
||||
case .success(let validatedCredentials):
|
||||
guard let validatedCredentials = validatedCredentials else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
Task { @MainActor in
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
@MainActor func stopAnimation() {
|
||||
actionButton.isEnabled = true
|
||||
progressIndicator.isHidden = true
|
||||
progressIndicator.stopAnimation(self)
|
||||
}
|
||||
|
||||
let credentials = Credentials(type: .newsBlurBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
do {
|
||||
let validatedCredentials = try await Account.validateCredentials(type: .newsBlur, credentials: credentials)
|
||||
stopAnimation()
|
||||
|
||||
guard let validatedCredentials else {
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
return
|
||||
}
|
||||
|
||||
if self.account == nil {
|
||||
self.account = AccountManager.shared.createAccount(type: .newsBlur)
|
||||
|
||||
if account == nil {
|
||||
account = AccountManager.shared.createAccount(type: .newsBlur)
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
try self.account?.removeCredentials(type: .newsBlurBasic)
|
||||
try self.account?.removeCredentials(type: .newsBlurSessionId)
|
||||
try self.account?.storeCredentials(credentials)
|
||||
try self.account?.storeCredentials(validatedCredentials)
|
||||
|
||||
self.account?.refreshAll() { result in
|
||||
try account?.removeCredentials(type: .newsBlurBasic)
|
||||
try account?.removeCredentials(type: .newsBlurSessionId)
|
||||
try account?.storeCredentials(credentials)
|
||||
try account?.storeCredentials(validatedCredentials)
|
||||
|
||||
account?.refreshAll() { result in
|
||||
switch result {
|
||||
case .success:
|
||||
break
|
||||
@@ -114,15 +115,13 @@ final class AccountsNewsBlurWindowController: NSWindowController {
|
||||
}
|
||||
}
|
||||
|
||||
self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
hostWindow?.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
} catch {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
|
||||
}
|
||||
|
||||
case .failure:
|
||||
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
|
||||
} catch {
|
||||
stopAnimation()
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,40 +129,41 @@ final class AccountsReaderAPIWindowController: NSWindowController {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Unrecognized account type.", comment: "Bad account type")
|
||||
return
|
||||
}
|
||||
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
let credentials = Credentials(type: .readerBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
Account.validateCredentials(type: accountType, credentials: credentials, endpoint: apiURL) { [weak self] result in
|
||||
|
||||
guard let self = self else { return }
|
||||
|
||||
self.actionButton.isEnabled = true
|
||||
self.progressIndicator.isHidden = true
|
||||
self.progressIndicator.stopAnimation(self)
|
||||
|
||||
switch result {
|
||||
case .success(let validatedCredentials):
|
||||
guard let validatedCredentials = validatedCredentials else {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
|
||||
Task { @MainActor in
|
||||
actionButton.isEnabled = false
|
||||
progressIndicator.isHidden = false
|
||||
progressIndicator.startAnimation(self)
|
||||
|
||||
@MainActor func stopAnimation() {
|
||||
actionButton.isEnabled = true
|
||||
progressIndicator.isHidden = true
|
||||
progressIndicator.stopAnimation(self)
|
||||
}
|
||||
|
||||
let credentials = Credentials(type: .readerBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
|
||||
do {
|
||||
let validatedCredentials = try await Account.validateCredentials(type: accountType, credentials: credentials, endpoint: apiURL)
|
||||
stopAnimation()
|
||||
|
||||
guard let validatedCredentials else {
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
|
||||
return
|
||||
}
|
||||
|
||||
if self.account == nil {
|
||||
self.account = AccountManager.shared.createAccount(type: self.accountType!)
|
||||
}
|
||||
|
||||
do {
|
||||
self.account?.endpointURL = apiURL
|
||||
|
||||
try self.account?.removeCredentials(type: .readerBasic)
|
||||
try self.account?.removeCredentials(type: .readerAPIKey)
|
||||
try self.account?.storeCredentials(credentials)
|
||||
try self.account?.storeCredentials(validatedCredentials)
|
||||
|
||||
self.account?.refreshAll() { result in
|
||||
if account == nil {
|
||||
account = AccountManager.shared.createAccount(type: accountType)
|
||||
}
|
||||
|
||||
do {
|
||||
account?.endpointURL = apiURL
|
||||
|
||||
try account?.removeCredentials(type: .readerBasic)
|
||||
try account?.removeCredentials(type: .readerAPIKey)
|
||||
try account?.storeCredentials(credentials)
|
||||
try account?.storeCredentials(validatedCredentials)
|
||||
|
||||
account?.refreshAll() { result in
|
||||
switch result {
|
||||
case .success:
|
||||
break
|
||||
@@ -170,18 +171,18 @@ final class AccountsReaderAPIWindowController: NSWindowController {
|
||||
NSApplication.shared.presentError(error)
|
||||
}
|
||||
}
|
||||
|
||||
self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
|
||||
hostWindow?.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
|
||||
} catch {
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
|
||||
}
|
||||
|
||||
case .failure:
|
||||
self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
|
||||
|
||||
} catch {
|
||||
stopAnimation()
|
||||
errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@IBAction func createAccountWithProvider(_ sender: Any) {
|
||||
|
||||
@@ -338,17 +338,17 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container,
|
||||
}
|
||||
try CredentialsManager.removeCredentials(type: type, server: server, username: username)
|
||||
}
|
||||
|
||||
public static func validateCredentials(transport: Transport = URLSession.webserviceTransport(), type: AccountType, credentials: Credentials, endpoint: URL? = nil, completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
|
||||
public static func validateCredentials(transport: Transport = URLSession.webserviceTransport(), type: AccountType, credentials: Credentials, endpoint: URL? = nil) async throws -> Credentials? {
|
||||
switch type {
|
||||
case .feedbin:
|
||||
FeedbinAccountDelegate.validateCredentials(transport: transport, credentials: credentials, completion: completion)
|
||||
return try await FeedbinAccountDelegate.validateCredentials(transport: transport, credentials: credentials, endpoint: endpoint)
|
||||
case .newsBlur:
|
||||
NewsBlurAccountDelegate.validateCredentials(transport: transport, credentials: credentials, completion: completion)
|
||||
return try await NewsBlurAccountDelegate.validateCredentials(transport: transport, credentials: credentials, endpoint: endpoint)
|
||||
case .freshRSS, .inoreader, .bazQux, .theOldReader:
|
||||
ReaderAPIAccountDelegate.validateCredentials(transport: transport, credentials: credentials, endpoint: endpoint, completion: completion)
|
||||
return try await ReaderAPIAccountDelegate.validateCredentials(transport: transport, credentials: credentials, endpoint: endpoint)
|
||||
default:
|
||||
break
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ protocol AccountDelegate {
|
||||
|
||||
func accountWillBeDeleted(_ account: Account)
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?, completion: @escaping (Result<Credentials?, Error>) -> Void)
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials?
|
||||
|
||||
/// Suspend all network activity
|
||||
func suspendNetwork()
|
||||
|
||||
@@ -456,8 +456,8 @@ final class CloudKitAccountDelegate: AccountDelegate {
|
||||
articlesZone.resetChangeToken()
|
||||
}
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: (Result<Credentials?, Error>) -> Void) {
|
||||
return completion(.success(nil))
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
nil
|
||||
}
|
||||
|
||||
// MARK: - Suspend and Resume (for iOS)
|
||||
|
||||
@@ -22,7 +22,7 @@ enum CreateSubscriptionResult {
|
||||
}
|
||||
|
||||
final class FeedbinAPICaller: NSObject {
|
||||
|
||||
|
||||
struct ConditionalGetKeys {
|
||||
static let subscriptions = "subscriptions"
|
||||
static let tags = "tags"
|
||||
@@ -30,12 +30,12 @@ final class FeedbinAPICaller: NSObject {
|
||||
static let unreadEntries = "unreadEntries"
|
||||
static let starredEntries = "starredEntries"
|
||||
}
|
||||
|
||||
|
||||
private let feedbinBaseURL = URL(string: "https://api.feedbin.com/v2/")!
|
||||
private var transport: Transport!
|
||||
private var suspended = false
|
||||
private var lastBackdateStartTime: Date?
|
||||
|
||||
|
||||
var credentials: Credentials?
|
||||
weak var accountMetadata: AccountMetadata?
|
||||
|
||||
@@ -43,69 +43,56 @@ final class FeedbinAPICaller: NSObject {
|
||||
super.init()
|
||||
self.transport = transport
|
||||
}
|
||||
|
||||
|
||||
/// Cancels all pending requests rejects any that come in later
|
||||
func suspend() {
|
||||
transport.cancelAll()
|
||||
suspended = true
|
||||
}
|
||||
|
||||
|
||||
func resume() {
|
||||
suspended = false
|
||||
}
|
||||
|
||||
func validateCredentials(completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
|
||||
|
||||
func validateCredentials() async throws -> Credentials? {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("authentication.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
|
||||
transport.send(request: request) { result in
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
|
||||
do {
|
||||
try await transport.send(request: request)
|
||||
if suspended {
|
||||
throw TransportError.suspended
|
||||
}
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(self.credentials))
|
||||
case .failure(let error):
|
||||
switch error {
|
||||
case TransportError.httpError(let status):
|
||||
if status == 401 {
|
||||
completion(.success(nil))
|
||||
} else {
|
||||
completion(.failure(error))
|
||||
}
|
||||
default:
|
||||
completion(.failure(error))
|
||||
}
|
||||
return credentials
|
||||
} catch {
|
||||
if case TransportError.httpError(let status) = error, status == 401 {
|
||||
return nil
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
func importOPML(opmlData: Data, completion: @escaping (Result<FeedbinImportResult, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("imports.json")
|
||||
var request = URLRequest(url: callURL, credentials: credentials)
|
||||
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType)
|
||||
|
||||
transport.send(request: request, method: HTTPMethod.post, payload: opmlData) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (_, data)):
|
||||
|
||||
|
||||
guard let resultData = data else {
|
||||
completion(.failure(TransportError.noData))
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let result = try JSONDecoder().decode(FeedbinImportResult.self, from: resultData)
|
||||
completion(.success(result))
|
||||
@@ -116,47 +103,47 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func retrieveOPMLImportResult(importID: Int, completion: @escaping (Result<FeedbinImportResult?, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("imports/\(importID).json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: FeedbinImportResult.self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (_, importResult)):
|
||||
completion(.success(importResult))
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func retrieveTags(completion: @escaping (Result<[FeedbinTag]?, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("tags.json")
|
||||
let conditionalGet = accountMetadata?.conditionalGetInfo[ConditionalGetKeys.tags]
|
||||
let request = URLRequest(url: callURL, credentials: credentials, conditionalGet: conditionalGet)
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinTag].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (response, tags)):
|
||||
self.storeConditionalGet(key: ConditionalGetKeys.tags, headers: response.allHeaderFields)
|
||||
@@ -164,22 +151,22 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func renameTag(oldName: String, newName: String, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("tags.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
let payload = FeedbinRenameTag(oldName: oldName, newName: newName)
|
||||
|
||||
|
||||
transport.send(request: request, method: HTTPMethod.post, payload: payload) { result in
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -188,22 +175,22 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func retrieveSubscriptions(completion: @escaping (Result<[FeedbinSubscription]?, Error>) -> Void) {
|
||||
|
||||
|
||||
var callComponents = URLComponents(url: feedbinBaseURL.appendingPathComponent("subscriptions.json"), resolvingAgainstBaseURL: false)!
|
||||
callComponents.queryItems = [URLQueryItem(name: "mode", value: "extended")]
|
||||
|
||||
let conditionalGet = accountMetadata?.conditionalGetInfo[ConditionalGetKeys.subscriptions]
|
||||
let request = URLRequest(url: callComponents.url!, credentials: credentials, conditionalGet: conditionalGet)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinSubscription].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (response, subscriptions)):
|
||||
self.storeConditionalGet(key: ConditionalGetKeys.subscriptions, headers: response.allHeaderFields)
|
||||
@@ -211,19 +198,19 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createSubscription(url: String, completion: @escaping (Result<CreateSubscriptionResult, Error>) -> Void) {
|
||||
|
||||
|
||||
var callComponents = URLComponents(url: feedbinBaseURL.appendingPathComponent("subscriptions.json"), resolvingAgainstBaseURL: false)!
|
||||
callComponents.queryItems = [URLQueryItem(name: "mode", value: "extended")]
|
||||
|
||||
var request = URLRequest(url: callComponents.url!, credentials: credentials)
|
||||
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType)
|
||||
|
||||
|
||||
let payload: Data
|
||||
do {
|
||||
payload = try JSONEncoder().encode(FeedbinCreateSubscription(feedURL: url))
|
||||
@@ -231,17 +218,17 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
transport.send(request: request, method: HTTPMethod.post, payload: payload) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (response, data)):
|
||||
|
||||
|
||||
switch response.forcedStatusCode {
|
||||
case 201:
|
||||
guard let subData = data else {
|
||||
@@ -270,9 +257,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
default:
|
||||
completion(.failure(TransportError.httpError(status: response.forcedStatusCode)))
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
|
||||
|
||||
switch error {
|
||||
case TransportError.httpError(let status):
|
||||
switch status {
|
||||
@@ -288,24 +275,24 @@ final class FeedbinAPICaller: NSObject {
|
||||
default:
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func renameSubscription(subscriptionID: String, newName: String, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("subscriptions/\(subscriptionID)/update.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
let payload = FeedbinUpdateSubscription(title: newName)
|
||||
|
||||
|
||||
transport.send(request: request, method: HTTPMethod.post, payload: payload) { result in
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -314,7 +301,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func deleteSubscription(subscriptionID: String, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("subscriptions/\(subscriptionID).json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
@@ -323,7 +310,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -332,13 +319,13 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func retrieveTaggings(completion: @escaping (Result<[FeedbinTagging]?, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("taggings.json")
|
||||
let conditionalGet = accountMetadata?.conditionalGetInfo[ConditionalGetKeys.taggings]
|
||||
let request = URLRequest(url: callURL, credentials: credentials, conditionalGet: conditionalGet)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinTagging].self) { result in
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
@@ -352,13 +339,13 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createTagging(feedID: Int, name: String, completion: @escaping (Result<Int, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("taggings.json")
|
||||
var request = URLRequest(url: callURL, credentials: credentials)
|
||||
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType)
|
||||
@@ -370,9 +357,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
transport.send(request: request, method: HTTPMethod.post, payload:payload) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -391,9 +378,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func deleteTagging(taggingID: String, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
@@ -405,7 +392,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -414,17 +401,17 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func retrieveEntries(articleIDs: [String], completion: @escaping (Result<([FeedbinEntry]?), Error>) -> Void) {
|
||||
|
||||
|
||||
guard !articleIDs.isEmpty else {
|
||||
completion(.success(([FeedbinEntry]())))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let concatIDs = articleIDs.reduce("") { param, articleID in return param + ",\(articleID)" }
|
||||
let paramIDs = String(concatIDs.dropFirst())
|
||||
|
||||
|
||||
let url = feedbinBaseURL
|
||||
.appendingPathComponent("entries.json")
|
||||
.appendingQueryItems([
|
||||
@@ -432,9 +419,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
URLQueryItem(name: "mode", value: "extended")
|
||||
])
|
||||
let request = URLRequest(url: url!, credentials: credentials)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinEntry].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -446,16 +433,16 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func retrieveEntries(feedID: String, completion: @escaping (Result<([FeedbinEntry]?, String?), Error>) -> Void) {
|
||||
|
||||
|
||||
let since = Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date()
|
||||
let sinceString = FeedbinDate.formatter.string(from: since)
|
||||
|
||||
|
||||
let url = feedbinBaseURL
|
||||
.appendingPathComponent("feeds/\(feedID)/entries.json")
|
||||
.appendingQueryItems([
|
||||
@@ -464,9 +451,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
URLQueryItem(name: "mode", value: "extended")
|
||||
])
|
||||
let request = URLRequest(url: url!, credentials: credentials)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinEntry].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -474,16 +461,16 @@ final class FeedbinAPICaller: NSObject {
|
||||
|
||||
switch result {
|
||||
case .success(let (response, entries)):
|
||||
|
||||
|
||||
let pagingInfo = HTTPLinkPagingInfo(urlResponse: response)
|
||||
completion(.success((entries, pagingInfo.nextPage)))
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func retrieveEntries(completion: @escaping (Result<([FeedbinEntry]?, String?, Date?, Int?), Error>) -> Void) {
|
||||
@@ -511,7 +498,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
return Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date()
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
let sinceString = FeedbinDate.formatter.string(from: since)
|
||||
let url = feedbinBaseURL
|
||||
.appendingPathComponent("entries.json")
|
||||
@@ -521,9 +508,9 @@ final class FeedbinAPICaller: NSObject {
|
||||
URLQueryItem(name: "mode", value: "extended")
|
||||
])
|
||||
let request = URLRequest(url: url!, credentials: credentials)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinEntry].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -531,32 +518,32 @@ final class FeedbinAPICaller: NSObject {
|
||||
|
||||
switch result {
|
||||
case .success(let (response, entries)):
|
||||
|
||||
|
||||
let dateInfo = HTTPDateInfo(urlResponse: response)
|
||||
|
||||
let pagingInfo = HTTPLinkPagingInfo(urlResponse: response)
|
||||
let lastPageNumber = self.extractPageNumber(link: pagingInfo.lastPage)
|
||||
completion(.success((entries, pagingInfo.nextPage, dateInfo?.date, lastPageNumber)))
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func retrieveEntries(page: String, completion: @escaping (Result<([FeedbinEntry]?, String?), Error>) -> Void) {
|
||||
|
||||
|
||||
guard let url = URL(string: page) else {
|
||||
completion(.success((nil, nil)))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let request = URLRequest(url: url, credentials: credentials)
|
||||
|
||||
transport.send(request: request, resultType: [FeedbinEntry].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -564,26 +551,26 @@ final class FeedbinAPICaller: NSObject {
|
||||
|
||||
switch result {
|
||||
case .success(let (response, entries)):
|
||||
|
||||
|
||||
let pagingInfo = HTTPLinkPagingInfo(urlResponse: response)
|
||||
completion(.success((entries, pagingInfo.nextPage)))
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func retrieveUnreadEntries(completion: @escaping (Result<[Int]?, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("unread_entries.json")
|
||||
let conditionalGet = accountMetadata?.conditionalGetInfo[ConditionalGetKeys.unreadEntries]
|
||||
let request = URLRequest(url: callURL, credentials: credentials, conditionalGet: conditionalGet)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [Int].self) { result in
|
||||
|
||||
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
@@ -596,11 +583,11 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createUnreadEntries(entries: [Int], completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("unread_entries.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
@@ -610,7 +597,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -619,7 +606,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func deleteUnreadEntries(entries: [Int], completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("unread_entries.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
@@ -629,7 +616,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -638,13 +625,13 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func retrieveStarredEntries(completion: @escaping (Result<[Int]?, Error>) -> Void) {
|
||||
|
||||
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("starred_entries.json")
|
||||
let conditionalGet = accountMetadata?.conditionalGetInfo[ConditionalGetKeys.starredEntries]
|
||||
let request = URLRequest(url: callURL, credentials: credentials, conditionalGet: conditionalGet)
|
||||
|
||||
|
||||
transport.send(request: request, resultType: [Int].self) { result in
|
||||
if self.suspended {
|
||||
completion(.failure(TransportError.suspended))
|
||||
@@ -658,11 +645,11 @@ final class FeedbinAPICaller: NSObject {
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createStarredEntries(entries: [Int], completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("starred_entries.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
@@ -672,7 +659,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -681,7 +668,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func deleteStarredEntries(entries: [Int], completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
let callURL = feedbinBaseURL.appendingPathComponent("starred_entries.json")
|
||||
let request = URLRequest(url: callURL, credentials: credentials)
|
||||
@@ -691,7 +678,7 @@ final class FeedbinAPICaller: NSObject {
|
||||
completion(.failure(TransportError.suspended))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
completion(.success(()))
|
||||
@@ -700,26 +687,26 @@ final class FeedbinAPICaller: NSObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// MARK: Private
|
||||
|
||||
extension FeedbinAPICaller {
|
||||
|
||||
|
||||
func storeConditionalGet(key: String, headers: [AnyHashable : Any]) {
|
||||
if var conditionalGet = accountMetadata?.conditionalGetInfo {
|
||||
conditionalGet[key] = HTTPConditionalGetInfo(headers: headers)
|
||||
accountMetadata?.conditionalGetInfo = conditionalGet
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func extractPageNumber(link: String?) -> Int? {
|
||||
|
||||
|
||||
guard let link = link else {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
if let lowerBound = link.range(of: "page=")?.upperBound {
|
||||
let partialLink = link[lowerBound..<link.endIndex]
|
||||
if let upperBound = partialLink.firstIndex(of: "&") {
|
||||
@@ -729,9 +716,9 @@ extension FeedbinAPICaller {
|
||||
return Int(partialLink[partialLink.startIndex..<upperBound])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -23,39 +23,39 @@ public enum FeedbinAccountDelegateError: String, Error {
|
||||
final class FeedbinAccountDelegate: AccountDelegate {
|
||||
|
||||
private let database: SyncDatabase
|
||||
|
||||
|
||||
private let caller: FeedbinAPICaller
|
||||
private static let logger = Feedbin.logger
|
||||
|
||||
|
||||
let behaviors: AccountBehaviors = [.disallowFeedCopyInRootFolder]
|
||||
let server: String? = "api.feedbin.com"
|
||||
var isOPMLImportInProgress = false
|
||||
|
||||
|
||||
var credentials: Credentials? {
|
||||
didSet {
|
||||
caller.credentials = credentials
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
weak var accountMetadata: AccountMetadata? {
|
||||
didSet {
|
||||
caller.accountMetadata = accountMetadata
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var refreshProgress = DownloadProgress(numberOfTasks: 0)
|
||||
|
||||
init(dataFolder: String, transport: Transport?) {
|
||||
|
||||
|
||||
let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3")
|
||||
database = SyncDatabase(databaseFilePath: databaseFilePath)
|
||||
|
||||
|
||||
if transport != nil {
|
||||
|
||||
|
||||
caller = FeedbinAPICaller(transport: transport!)
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
|
||||
let sessionConfiguration = URLSessionConfiguration.default
|
||||
sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
||||
sessionConfiguration.timeoutIntervalForRequest = 60.0
|
||||
@@ -64,17 +64,17 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
sessionConfiguration.httpMaximumConnectionsPerHost = 1
|
||||
sessionConfiguration.httpCookieStorage = nil
|
||||
sessionConfiguration.urlCache = nil
|
||||
|
||||
|
||||
if let userAgentHeaders = UserAgent.headers() {
|
||||
sessionConfiguration.httpAdditionalHeaders = userAgentHeaders
|
||||
}
|
||||
|
||||
|
||||
caller = FeedbinAPICaller(transport: URLSession(configuration: sessionConfiguration))
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) {
|
||||
completion()
|
||||
}
|
||||
@@ -83,7 +83,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
|
||||
refreshProgress.reset()
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(5)
|
||||
|
||||
|
||||
refreshAccount(account) { result in
|
||||
switch result {
|
||||
case .success():
|
||||
@@ -100,7 +100,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
DispatchQueue.main.async {
|
||||
self.refreshProgress.reset()
|
||||
@@ -108,9 +108,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
completion(.failure(wrappedError))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func syncArticleStatus(for account: Account, completion: ((Result<Void, Error>) -> Void)? = nil) {
|
||||
@@ -130,7 +130,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func sendArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
|
||||
|
||||
Self.logger.info("Feedbin: Sending article statuses")
|
||||
@@ -196,7 +196,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func refreshArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
|
||||
|
||||
Self.logger.info("Feedbin: Refreshing article statuses")
|
||||
@@ -216,9 +216,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
Self.logger.error("Feedbin: Retrieving unread entries failed: \(error.localizedDescription)")
|
||||
group.leave()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
group.enter()
|
||||
caller.retrieveStarredEntries() { result in
|
||||
switch result {
|
||||
@@ -231,9 +231,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
Self.logger.error("Feedbin: Retrieving starred entries failed: \(error.localizedDescription)")
|
||||
group.leave()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
group.notify(queue: DispatchQueue.main) {
|
||||
Self.logger.info("Feedbin: Finished refreshing article statuses")
|
||||
if errorOccurred {
|
||||
@@ -242,29 +242,29 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
completion(.success(()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func importOPML(for account:Account, opmlFile: URL, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
var fileData: Data?
|
||||
|
||||
|
||||
do {
|
||||
fileData = try Data(contentsOf: opmlFile)
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
guard let opmlData = fileData else {
|
||||
completion(.success(()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Self.logger.info("Feedbin: Did begin importing OPML")
|
||||
isOPMLImportInProgress = true
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
|
||||
|
||||
caller.importOPML(opmlData: opmlData) { result in
|
||||
switch result {
|
||||
case .success(let importResult):
|
||||
@@ -288,9 +288,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createFolder(for account: Account, name: String, completion: @escaping (Result<Folder, Error>) -> Void) {
|
||||
if let folder = account.ensureFolder(with: name) {
|
||||
completion(.success(folder))
|
||||
@@ -305,7 +305,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
folder.name = name
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
caller.renameTag(oldName: folder.name ?? "", newName: name) { result in
|
||||
self.refreshProgress.completeTask()
|
||||
@@ -323,7 +323,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
@@ -334,13 +334,13 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
completion(.success(()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let group = DispatchGroup()
|
||||
|
||||
|
||||
for feed in folder.topLevelFeeds {
|
||||
|
||||
|
||||
if feed.folderRelationship?.count ?? 0 > 1 {
|
||||
|
||||
|
||||
if let feedTaggingID = feed.folderRelationship?[folder.name ?? ""] {
|
||||
group.enter()
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
@@ -357,9 +357,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
|
||||
if let subscriptionID = feed.externalID {
|
||||
group.enter()
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
@@ -375,20 +375,20 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
Self.logger.error("Feedbin: Remove feed error: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
group.notify(queue: DispatchQueue.main) {
|
||||
account.removeFolder(folder)
|
||||
completion(.success(()))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func createFeed(for account: Account, url: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result<Feed, Error>) -> Void) {
|
||||
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
@@ -418,7 +418,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func renameFeed(for account: Account, with feed: Feed, to name: String, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
@@ -428,7 +428,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
completion(.failure(FeedbinAccountDelegateError.invalidParameter))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
caller.renameSubscription(subscriptionID: subscriptionID, newName: name) { result in
|
||||
self.refreshProgress.completeTask()
|
||||
@@ -445,7 +445,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func removeFeed(for account: Account, with feed: Feed, from container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
@@ -455,7 +455,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
deleteSubscription(for: account, with: feed, from: container, completion: completion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func moveFeed(for account: Account, with feed: Feed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
if from is Account {
|
||||
addFeed(for: account, with: feed, to: to, completion: completion)
|
||||
@@ -500,9 +500,9 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
completion(.success(()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func restoreFeed(for account: Account, feed: Feed, container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
if let existingFeed = account.existingFeed(withURL: feed.url) {
|
||||
@@ -524,17 +524,17 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
let group = DispatchGroup()
|
||||
|
||||
|
||||
for feed in folder.topLevelFeeds {
|
||||
|
||||
|
||||
folder.topLevelFeeds.remove(feed)
|
||||
|
||||
|
||||
group.enter()
|
||||
restoreFeed(for: account, feed: feed, container: folder) { result in
|
||||
group.leave()
|
||||
@@ -545,16 +545,16 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
Self.logger.error("Feedbin: Restore folder feed error: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
group.notify(queue: DispatchQueue.main) {
|
||||
account.addFolder(folder)
|
||||
completion(.success(()))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
account.update(articles, statusKey: statusKey, flag: flag) { result in
|
||||
switch result {
|
||||
@@ -580,20 +580,14 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
func accountDidInitialize(_ account: Account) {
|
||||
credentials = try? account.retrieveCredentials(type: .basic)
|
||||
}
|
||||
|
||||
|
||||
func accountWillBeDeleted(_ account: Account) {
|
||||
}
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
let caller = FeedbinAPICaller(transport: transport)
|
||||
caller.credentials = credentials
|
||||
caller.validateCredentials() { result in
|
||||
DispatchQueue.main.async {
|
||||
completion(result)
|
||||
}
|
||||
}
|
||||
|
||||
return try await caller.validateCredentials()
|
||||
}
|
||||
|
||||
// MARK: Suspend and Resume (for iOS)
|
||||
@@ -602,12 +596,12 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
func suspendNetwork() {
|
||||
caller.suspend()
|
||||
}
|
||||
|
||||
|
||||
/// Suspend the SQLLite databases
|
||||
func suspendDatabase() {
|
||||
database.suspend()
|
||||
}
|
||||
|
||||
|
||||
/// Make sure no SQLite databases are open and we are ready to issue network requests.
|
||||
func resume() {
|
||||
caller.resume()
|
||||
@@ -618,11 +612,11 @@ final class FeedbinAccountDelegate: AccountDelegate {
|
||||
// MARK: Private
|
||||
|
||||
private extension FeedbinAccountDelegate {
|
||||
|
||||
|
||||
func checkImportResult(opmlImportResultID: Int, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
|
||||
DispatchQueue.main.async {
|
||||
|
||||
|
||||
Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { timer in
|
||||
|
||||
Self.logger.info("Feedbin: Checking status of OPML import")
|
||||
@@ -649,30 +643,30 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func refreshAccount(_ account: Account, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
|
||||
caller.retrieveTags { result in
|
||||
switch result {
|
||||
case .success(let tags):
|
||||
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
self.caller.retrieveSubscriptions { result in
|
||||
switch result {
|
||||
case .success(let subscriptions):
|
||||
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
self.forceExpireFolderFeedRelationship(account, tags)
|
||||
self.caller.retrieveTaggings { result in
|
||||
switch result {
|
||||
case .success(let taggings):
|
||||
|
||||
|
||||
BatchUpdate.shared.perform {
|
||||
self.syncFolders(account, tags)
|
||||
self.syncFeeds(account, subscriptions)
|
||||
@@ -681,25 +675,25 @@ private extension FeedbinAccountDelegate {
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
completion(.success(()))
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func refreshArticlesAndStatuses(_ account: Account, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
@@ -710,7 +704,7 @@ private extension FeedbinAccountDelegate {
|
||||
self.refreshArticleStatus(for: account) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
|
||||
|
||||
self.refreshArticles(account) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
@@ -718,27 +712,27 @@ private extension FeedbinAccountDelegate {
|
||||
self.refreshMissingArticles(account) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.refreshProgress.reset()
|
||||
completion(.success(()))
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
@@ -768,7 +762,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
func syncFolders(_ account: Account, _ tags: [FeedbinTag]?) {
|
||||
guard let tags = tags else { return }
|
||||
assert(Thread.isMainThread)
|
||||
@@ -789,7 +783,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let folderNames: [String] = {
|
||||
if let folders = account.folders {
|
||||
return folders.map { $0.name ?? "" }
|
||||
@@ -804,18 +798,18 @@ private extension FeedbinAccountDelegate {
|
||||
_ = account.ensureFolder(with: tagName)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func syncFeeds(_ account: Account, _ subscriptions: [FeedbinSubscription]?) {
|
||||
|
||||
|
||||
guard let subscriptions = subscriptions else { return }
|
||||
assert(Thread.isMainThread)
|
||||
|
||||
Self.logger.info("Feedbin: Syncing feeds with \(subscriptions.count) subscriptions")
|
||||
|
||||
let subFeedIds = subscriptions.map { String($0.feedID) }
|
||||
|
||||
|
||||
// Remove any feeds that are no longer in the subscriptions
|
||||
if let folders = account.folders {
|
||||
for folder in folders {
|
||||
@@ -826,13 +820,13 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for feed in account.topLevelFeeds {
|
||||
if !subFeedIds.contains(feed.feedID) {
|
||||
account.removeFeed(feed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Add any feeds we don't have and update any we do
|
||||
var subscriptionsToAdd = Set<FeedbinSubscription>()
|
||||
subscriptions.forEach { subscription in
|
||||
@@ -862,7 +856,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
|
||||
func syncFeedFolderRelationship(_ account: Account, _ taggings: [FeedbinTagging]?) {
|
||||
|
||||
|
||||
guard let taggings = taggings else { return }
|
||||
assert(Thread.isMainThread)
|
||||
|
||||
@@ -883,11 +877,11 @@ private extension FeedbinAccountDelegate {
|
||||
|
||||
// Sync the folders
|
||||
for (folderName, groupedTaggings) in taggingsDict {
|
||||
|
||||
|
||||
guard let folder = folderDict[folderName] else { return }
|
||||
|
||||
|
||||
let taggingFeedIDs = groupedTaggings.map { String($0.feedID) }
|
||||
|
||||
|
||||
// Move any feeds not in the folder to the account
|
||||
for feed in folder.topLevelFeeds {
|
||||
if !taggingFeedIDs.contains(feed.feedID) {
|
||||
@@ -896,10 +890,10 @@ private extension FeedbinAccountDelegate {
|
||||
account.addFeed(feed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Add any feeds not in the folder
|
||||
let folderFeedIds = folder.topLevelFeeds.map { $0.feedID }
|
||||
|
||||
|
||||
for tagging in groupedTaggings {
|
||||
let taggingFeedID = String(tagging.feedID)
|
||||
if !folderFeedIds.contains(taggingFeedID) {
|
||||
@@ -910,11 +904,11 @@ private extension FeedbinAccountDelegate {
|
||||
folder.addFeed(feed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
let taggedFeedIDs = Set(taggings.map { String($0.feedID) })
|
||||
|
||||
|
||||
// Remove all feeds from the account container that have a tag
|
||||
for feed in account.topLevelFeeds {
|
||||
if taggedFeedIDs.contains(feed.feedID) {
|
||||
@@ -941,19 +935,19 @@ private extension FeedbinAccountDelegate {
|
||||
func sendArticleStatuses(_ statuses: [SyncStatus],
|
||||
apiCall: ([Int], @escaping (Result<Void, Error>) -> Void) -> Void,
|
||||
completion: @escaping ((Result<Void, Error>) -> Void)) {
|
||||
|
||||
|
||||
guard !statuses.isEmpty else {
|
||||
completion(.success(()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let group = DispatchGroup()
|
||||
var errorOccurred = false
|
||||
|
||||
|
||||
let articleIDs = statuses.compactMap { Int($0.articleID) }
|
||||
let articleIDGroups = articleIDs.chunked(into: 1000)
|
||||
for articleIDGroup in articleIDGroups {
|
||||
|
||||
|
||||
group.enter()
|
||||
apiCall(articleIDGroup) { result in
|
||||
switch result {
|
||||
@@ -968,9 +962,9 @@ private extension FeedbinAccountDelegate {
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
group.notify(queue: DispatchQueue.main) {
|
||||
if errorOccurred {
|
||||
completion(.failure(FeedbinAccountDelegateError.unknown))
|
||||
@@ -978,9 +972,9 @@ private extension FeedbinAccountDelegate {
|
||||
completion(.success(()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func renameFolderRelationship(for account: Account, fromName: String, toName: String) {
|
||||
for feed in account.flattenedFeeds() {
|
||||
if var folderRelationship = feed.folderRelationship {
|
||||
@@ -991,14 +985,14 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) {
|
||||
if var folderRelationship = feed.folderRelationship {
|
||||
folderRelationship[folderName] = nil
|
||||
feed.folderRelationship = folderRelationship
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func saveFolderRelationship(for feed: Feed, withFolderName folderName: String, id: String) {
|
||||
if var folderRelationship = feed.folderRelationship {
|
||||
folderRelationship[folderName] = id
|
||||
@@ -1010,7 +1004,7 @@ private extension FeedbinAccountDelegate {
|
||||
|
||||
func decideBestFeedChoice(account: Account, url: String, name: String?, container: Container, choices: [FeedbinSubscriptionChoice], completion: @escaping (Result<Feed, Error>) -> Void) {
|
||||
var orderFound = 0
|
||||
|
||||
|
||||
let feedSpecifiers: [FeedSpecifier] = choices.map { choice in
|
||||
let source = url == choice.url ? FeedSpecifier.Source.UserEntered : FeedSpecifier.Source.HTMLLink
|
||||
orderFound = orderFound + 1
|
||||
@@ -1026,16 +1020,16 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func createFeed( account: Account, subscription sub: FeedbinSubscription, name: String?, container: Container, completion: @escaping (Result<Feed, Error>) -> Void) {
|
||||
|
||||
|
||||
DispatchQueue.main.async {
|
||||
|
||||
|
||||
let feed = account.createFeed(with: sub.name, url: sub.url, feedID: String(sub.feedID), homePageURL: sub.homePageURL)
|
||||
feed.externalID = String(sub.subscriptionID)
|
||||
feed.iconURL = sub.jsonFeed?.icon
|
||||
feed.faviconURL = sub.jsonFeed?.favicon
|
||||
|
||||
|
||||
account.addFeed(feed, to: container) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
@@ -1055,9 +1049,9 @@ private extension FeedbinAccountDelegate {
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func initialFeedDownload( account: Account, feed: Feed, completion: @escaping (Result<Feed, Error>) -> Void) {
|
||||
@@ -1068,10 +1062,10 @@ private extension FeedbinAccountDelegate {
|
||||
// Download the initial articles
|
||||
self.caller.retrieveEntries(feedID: feed.feedID) { result in
|
||||
self.refreshProgress.completeTask()
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (entries, page)):
|
||||
|
||||
|
||||
self.processEntries(account: account, entries: entries) { error in
|
||||
if let error = error {
|
||||
completion(.failure(error))
|
||||
@@ -1081,62 +1075,62 @@ private extension FeedbinAccountDelegate {
|
||||
self.refreshArticleStatus(for: account) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
|
||||
|
||||
self.refreshArticles(account, page: page, updateFetchDate: nil) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
self.refreshMissingArticles(account) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
DispatchQueue.main.async {
|
||||
completion(.success(feed))
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func refreshArticles(_ account: Account, completion: @escaping VoidResultCompletionBlock) {
|
||||
|
||||
Self.logger.info("Feedbin: Refreshing articles")
|
||||
|
||||
caller.retrieveEntries() { result in
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (entries, page, updateFetchDate, lastPageNumber)):
|
||||
|
||||
|
||||
if let last = lastPageNumber {
|
||||
self.refreshProgress.addToNumberOfTasksAndRemaining(last - 1)
|
||||
}
|
||||
|
||||
|
||||
self.processEntries(account: account, entries: entries) { error in
|
||||
|
||||
|
||||
self.refreshProgress.completeTask()
|
||||
|
||||
if let error = error {
|
||||
@@ -1160,16 +1154,16 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func refreshMissingArticles(_ account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
|
||||
Self.logger.info("Feedbin: Refreshing missing articles")
|
||||
|
||||
account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in
|
||||
|
||||
|
||||
func process(_ fetchedArticleIDs: Set<String>) {
|
||||
let group = DispatchGroup()
|
||||
var errorOccurred = false
|
||||
|
||||
|
||||
let articleIDs = Array(fetchedArticleIDs)
|
||||
let chunkedArticleIDs = articleIDs.chunked(into: 100)
|
||||
|
||||
@@ -1225,12 +1219,12 @@ private extension FeedbinAccountDelegate {
|
||||
completion(.success(()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
caller.retrieveEntries(page: page) { result in
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let (entries, nextPage)):
|
||||
|
||||
|
||||
self.processEntries(account: account, entries: entries) { error in
|
||||
self.refreshProgress.completeTask()
|
||||
|
||||
@@ -1238,36 +1232,36 @@ private extension FeedbinAccountDelegate {
|
||||
completion(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
self.refreshArticles(account, page: nextPage, updateFetchDate: updateFetchDate, completion: completion)
|
||||
}
|
||||
|
||||
|
||||
case .failure(let error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func processEntries(account: Account, entries: [FeedbinEntry]?, completion: @escaping DatabaseCompletionBlock) {
|
||||
let parsedItems = mapEntriesToParsedItems(entries: entries)
|
||||
let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL } ).mapValues { Set($0) }
|
||||
account.update(feedIDsAndItems: feedIDsAndItems, defaultRead: true, completion: completion)
|
||||
}
|
||||
|
||||
|
||||
func mapEntriesToParsedItems(entries: [FeedbinEntry]?) -> Set<ParsedItem> {
|
||||
guard let entries = entries else {
|
||||
return Set<ParsedItem>()
|
||||
}
|
||||
|
||||
|
||||
let parsedItems: [ParsedItem] = entries.map { entry in
|
||||
let authors = Set([ParsedAuthor(name: entry.authorName, url: entry.jsonFeed?.jsonFeedAuthor?.url, avatarURL: entry.jsonFeed?.jsonFeedAuthor?.avatarURL, emailAddress: nil)])
|
||||
return ParsedItem(syncServiceID: String(entry.articleID), uniqueID: String(entry.articleID), feedURL: String(entry.feedID), url: entry.url, externalURL: entry.jsonFeed?.jsonFeedExternalURL, title: entry.title, language: nil, contentHTML: entry.contentHTML, contentText: nil, markdown: nil, summary: entry.summary, imageURL: nil, bannerImageURL: nil, datePublished: entry.parsedDatePublished, dateModified: nil, authors: authors, tags: nil, attachments: nil)
|
||||
}
|
||||
|
||||
|
||||
return Set(parsedItems)
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
func syncArticleReadState(account: Account, articleIDs: [Int]?, completion: @escaping (() -> Void)) {
|
||||
guard let articleIDs = articleIDs else {
|
||||
completion()
|
||||
@@ -1277,17 +1271,17 @@ private extension FeedbinAccountDelegate {
|
||||
database.selectPendingReadStatusArticleIDs() { result in
|
||||
|
||||
func process(_ pendingArticleIDs: Set<String>) {
|
||||
|
||||
|
||||
let feedbinUnreadArticleIDs = Set(articleIDs.map { String($0) } )
|
||||
let updatableFeedbinUnreadArticleIDs = feedbinUnreadArticleIDs.subtracting(pendingArticleIDs)
|
||||
|
||||
|
||||
account.fetchUnreadArticleIDs { articleIDsResult in
|
||||
guard let currentUnreadArticleIDs = try? articleIDsResult.get() else {
|
||||
return
|
||||
}
|
||||
|
||||
let group = DispatchGroup()
|
||||
|
||||
|
||||
// Mark articles as unread
|
||||
let deltaUnreadArticleIDs = updatableFeedbinUnreadArticleIDs.subtracting(currentUnreadArticleIDs)
|
||||
group.enter()
|
||||
@@ -1301,15 +1295,15 @@ private extension FeedbinAccountDelegate {
|
||||
account.markAsRead(deltaReadArticleIDs) { _ in
|
||||
group.leave()
|
||||
}
|
||||
|
||||
|
||||
group.notify(queue: DispatchQueue.main) {
|
||||
completion()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let pendingArticleIDs):
|
||||
process(pendingArticleIDs)
|
||||
@@ -1318,7 +1312,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func syncArticleStarredState(account: Account, articleIDs: [Int]?, completion: @escaping (() -> Void)) {
|
||||
guard let articleIDs = articleIDs else {
|
||||
completion()
|
||||
@@ -1328,7 +1322,7 @@ private extension FeedbinAccountDelegate {
|
||||
database.selectPendingStarredStatusArticleIDs() { result in
|
||||
|
||||
func process(_ pendingArticleIDs: Set<String>) {
|
||||
|
||||
|
||||
let feedbinStarredArticleIDs = Set(articleIDs.map { String($0) } )
|
||||
let updatableFeedbinStarredArticleIDs = feedbinStarredArticleIDs.subtracting(pendingArticleIDs)
|
||||
|
||||
@@ -1338,7 +1332,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
|
||||
let group = DispatchGroup()
|
||||
|
||||
|
||||
// Mark articles as starred
|
||||
let deltaStarredArticleIDs = updatableFeedbinStarredArticleIDs.subtracting(currentStarredArticleIDs)
|
||||
group.enter()
|
||||
@@ -1357,9 +1351,9 @@ private extension FeedbinAccountDelegate {
|
||||
completion()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
switch result {
|
||||
case .success(let pendingArticleIDs):
|
||||
process(pendingArticleIDs)
|
||||
@@ -1370,7 +1364,7 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
|
||||
func deleteTagging(for account: Account, with feed: Feed, from container: Container?, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
|
||||
if let folder = container as? Folder, let feedTaggingID = feed.folderRelationship?[folder.name ?? ""] {
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
caller.deleteTagging(taggingID: feedTaggingID) { result in
|
||||
@@ -1396,11 +1390,11 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
completion(.success(()))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func deleteSubscription(for account: Account, with feed: Feed, from container: Container?, completion: @escaping (Result<Void, Error>) -> Void) {
|
||||
|
||||
|
||||
// This error should never happen
|
||||
guard let subscriptionID = feed.externalID else {
|
||||
completion(.failure(FeedbinAccountDelegateError.invalidParameter))
|
||||
@@ -1419,7 +1413,7 @@ private extension FeedbinAccountDelegate {
|
||||
completion(.success(()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
refreshProgress.addToNumberOfTasksAndRemaining(1)
|
||||
caller.deleteSubscription(subscriptionID: subscriptionID) { result in
|
||||
self.refreshProgress.completeTask()
|
||||
|
||||
@@ -541,10 +541,10 @@ final class FeedlyAccountDelegate: AccountDelegate {
|
||||
// Dispatch on the shared queue because the lifetime of the account delegate is uncertain.
|
||||
MainThreadOperationQueue.shared.add(logout)
|
||||
}
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?, completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
assertionFailure("An `account` instance should enqueue an \(FeedlyRefreshAccessTokenOperation.self) instead.")
|
||||
completion(.success(credentials))
|
||||
|
||||
static func validateCredentials(transport: any Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
assertionFailure("An account instance should enqueue an \(FeedlyRefreshAccessTokenOperation.self) instead.")
|
||||
return credentials
|
||||
}
|
||||
|
||||
// MARK: Suspend and Resume (for iOS)
|
||||
|
||||
@@ -192,8 +192,8 @@ final class LocalAccountDelegate: AccountDelegate {
|
||||
func accountWillBeDeleted(_ account: Account) {
|
||||
}
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: (Result<Credentials?, Error>) -> Void) {
|
||||
return completion(.success(nil))
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
nil
|
||||
}
|
||||
|
||||
// MARK: Suspend and Resume (for iOS)
|
||||
|
||||
@@ -35,7 +35,15 @@ final class NewsBlurAPICaller: NSObject {
|
||||
suspended = false
|
||||
}
|
||||
|
||||
func validateCredentials(completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
func validateCredentials() async throws -> Credentials? {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
validateCredentials { result in
|
||||
continuation.resume(with: result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func validateCredentials(completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
requestData(endpoint: "api/login", resultType: NewsBlurLoginResponse.self) { result in
|
||||
switch result {
|
||||
case .success((let response, let payload)):
|
||||
|
||||
@@ -614,14 +614,10 @@ final class NewsBlurAccountDelegate: AccountDelegate {
|
||||
caller.logout() { _ in }
|
||||
}
|
||||
|
||||
class func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: @escaping (Result<Credentials?, Error>) -> ()) {
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
let caller = NewsBlurAPICaller(transport: transport)
|
||||
caller.credentials = credentials
|
||||
caller.validateCredentials() { result in
|
||||
DispatchQueue.main.async {
|
||||
completion(result)
|
||||
}
|
||||
}
|
||||
return try await caller.validateCredentials()
|
||||
}
|
||||
|
||||
// MARK: Suspend and Resume (for iOS)
|
||||
|
||||
@@ -631,21 +631,15 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
|
||||
|
||||
func accountWillBeDeleted(_ account: Account) {
|
||||
}
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?, completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
guard let endpoint = endpoint else {
|
||||
completion(.failure(TransportError.noURL))
|
||||
return
|
||||
|
||||
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? {
|
||||
guard let endpoint else {
|
||||
throw TransportError.noURL
|
||||
}
|
||||
|
||||
|
||||
let caller = ReaderAPICaller(transport: transport)
|
||||
caller.credentials = credentials
|
||||
caller.validateCredentials(endpoint: endpoint) { result in
|
||||
DispatchQueue.main.async {
|
||||
completion(result)
|
||||
}
|
||||
}
|
||||
|
||||
return try await caller.validateCredentials(endpoint: endpoint)
|
||||
}
|
||||
|
||||
// MARK: Suspend and Resume (for iOS)
|
||||
|
||||
@@ -90,7 +90,15 @@ final class ReaderAPICaller: NSObject {
|
||||
func cancelAll() {
|
||||
transport.cancelAll()
|
||||
}
|
||||
|
||||
|
||||
func validateCredentials(endpoint: URL) async throws -> Credentials? {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
validateCredentials(endpoint: endpoint) { result in
|
||||
continuation.resume(with: result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateCredentials(endpoint: URL, completion: @escaping (Result<Credentials?, Error>) -> Void) {
|
||||
guard let credentials = credentials else {
|
||||
completion(.failure(CredentialsError.incompleteCredentials))
|
||||
|
||||
@@ -118,7 +118,11 @@ public protocol Transport {
|
||||
|
||||
/// Cancels all pending requests
|
||||
func cancelAll()
|
||||
|
||||
|
||||
/// Sends URLRequest and returns the HTTP headers and the data payload.
|
||||
@discardableResult
|
||||
func send(request: URLRequest) async throws -> (HTTPURLResponse, Data?)
|
||||
|
||||
/// Sends URLRequest and returns the HTTP headers and the data payload.
|
||||
func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void)
|
||||
|
||||
@@ -139,7 +143,15 @@ extension URLSession: Transport {
|
||||
downloadTasks.forEach { $0.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func send(request: URLRequest) async throws -> (HTTPURLResponse, Data?) {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
self.send(request: request) { result in
|
||||
continuation.resume(with: result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) {
|
||||
let task = self.dataTask(with: request) { (data, response, error) in
|
||||
DispatchQueue.main.async {
|
||||
|
||||
Reference in new issue
Block a user