frenzy-ios/Reader/FervorController.swift

163 lines
5.6 KiB
Swift
Raw Normal View History

2021-12-08 02:58:02 +00:00
//
// FervorController.swift
// Reader
//
// Created by Shadowfacts on 11/25/21.
//
import Foundation
import Fervor
2022-01-09 22:13:30 +00:00
import OSLog
2022-01-27 03:37:10 +00:00
import Combine
2021-12-08 02:58:02 +00:00
class FervorController {
static let oauthRedirectURI = URL(string: "frenzy://oauth-callback")!
let instanceURL: URL
2022-01-09 22:13:30 +00:00
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FervorController")
let client: FervorClient
2022-01-12 18:48:52 +00:00
private(set) var account: LocalData.Account?
2021-12-08 02:58:02 +00:00
private(set) var clientID: String?
private(set) var clientSecret: String?
private(set) var accessToken: String?
2021-12-25 19:04:45 +00:00
private(set) var persistentContainer: PersistentContainer!
2022-01-27 03:37:10 +00:00
let syncStateSubject = PassthroughSubject<SyncState, Never>()
2021-12-08 02:58:02 +00:00
init(instanceURL: URL) {
self.instanceURL = instanceURL
self.client = FervorClient(instanceURL: instanceURL, accessToken: nil)
}
convenience init(account: LocalData.Account) {
self.init(instanceURL: account.instanceURL)
2022-01-12 18:48:52 +00:00
self.account = account
2021-12-08 02:58:02 +00:00
self.clientID = account.clientID
self.clientSecret = account.clientSecret
self.accessToken = account.accessToken
2021-12-25 19:04:45 +00:00
self.client.accessToken = account.accessToken
2022-01-09 22:13:30 +00:00
self.persistentContainer = PersistentContainer(account: account, fervorController: self)
2021-12-08 02:58:02 +00:00
}
2022-01-27 03:37:10 +00:00
private func setSyncState(_ state: SyncState) {
DispatchQueue.main.async {
self.syncStateSubject.send(state)
}
}
2021-12-08 02:58:02 +00:00
func register() async throws -> ClientRegistration {
let registration = try await client.register(clientName: "Frenzy iOS", website: nil, redirectURI: FervorController.oauthRedirectURI)
clientID = registration.clientID
clientSecret = registration.clientSecret
return registration
}
func getToken(authCode: String) async throws {
let token = try await client.token(authCode: authCode, redirectURI: FervorController.oauthRedirectURI, clientID: clientID!, clientSecret: clientSecret!)
client.accessToken = token.accessToken
accessToken = token.accessToken
}
func syncAll() async throws {
2022-01-27 03:37:10 +00:00
setSyncState(.groupsAndFeeds)
2022-01-09 22:13:30 +00:00
logger.info("Syncing groups and feeds")
async let groups = try client.groups()
async let feeds = try client.feeds()
try await persistentContainer.sync(serverGroups: groups, serverFeeds: feeds)
2022-01-09 22:13:30 +00:00
2022-01-27 03:37:10 +00:00
setSyncState(.items)
let lastSync = try await persistentContainer.lastSyncDate()
2022-01-09 22:13:30 +00:00
logger.info("Syncing items with last sync date: \(String(describing: lastSync), privacy: .public)")
let update = try await client.syncItems(lastSync: lastSync)
2022-01-27 03:37:10 +00:00
try await persistentContainer.syncItems(update, setSyncState: setSyncState(_:))
try await persistentContainer.updateLastSyncDate(update.syncTimestamp)
2022-01-27 03:37:10 +00:00
setSyncState(.excerpts)
await ExcerptGenerator.generateAll(self)
setSyncState(.done)
2021-12-25 19:04:45 +00:00
}
2022-01-11 16:54:57 +00:00
@MainActor
func syncReadToServer() async throws {
var count = 0
// todo: there should be a batch update api endpoint
for case let item as Item in persistentContainer.viewContext.updatedObjects {
2022-01-11 16:54:57 +00:00
let f = item.read ? client.read(item:) : client.unread(item:)
do {
let _ = try await f(item.id!)
count += 1
} catch {
2022-01-27 02:22:15 +00:00
logger.error("Failed to sync read state: \(String(describing: error), privacy: .public)")
item.needsReadStateSync = true
}
2022-01-11 16:54:57 +00:00
}
// try to sync items which failed last time
let req = Item.fetchRequest()
req.predicate = NSPredicate(format: "needsReadStateSync = YES")
if let needsSync = try? persistentContainer.viewContext.fetch(req) {
for item in needsSync {
let f = item.read ? client.read(item:) : client.unread(item:)
do {
let _ = try await f(item.id!)
count += 1
item.needsReadStateSync = false
} catch {
2022-01-27 02:22:15 +00:00
logger.error("Failed to sync read state again: \(String(describing: error), privacy: .public)")
item.needsReadStateSync = true
// todo: this should probably fail after a certain number of attempts
}
}
}
2022-01-11 16:54:57 +00:00
logger.info("Synced \(count, privacy: .public) read/unread to server")
do {
try persistentContainer.viewContext.save()
} catch {
2022-01-27 02:22:15 +00:00
logger.error("Failed to save view context: \(String(describing: error), privacy: .public)")
}
2022-01-11 16:54:57 +00:00
}
@MainActor
func markItem(_ item: Item, read: Bool) async {
item.read = read
do {
let f = item.read ? client.read(item:) : client.unread(item:)
_ = try await f(item.id!)
item.needsReadStateSync = false
} catch {
2022-01-27 02:22:15 +00:00
logger.error("Failed to mark item (un)read: \(String(describing: error), privacy: .public)")
item.needsReadStateSync = true
}
if persistentContainer.viewContext.hasChanges {
do {
try persistentContainer.viewContext.save()
} catch {
2022-01-27 02:22:15 +00:00
logger.error("Failed to save view context: \(String(describing: error), privacy: .public)")
}
}
}
2021-12-08 02:58:02 +00:00
}
2022-01-27 03:37:10 +00:00
extension FervorController {
enum SyncState: Equatable {
case groupsAndFeeds
case items
case updateItems(current: Int, total: Int)
case excerpts
case done
}
}