2020-04-11 19:31:37 +00:00
|
|
|
//
|
|
|
|
// MastodonCachePersistentStore.swift
|
|
|
|
// Tusker
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 4/11/20.
|
|
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import CoreData
|
2020-04-12 02:23:31 +00:00
|
|
|
import Pachyderm
|
2020-05-02 16:45:28 +00:00
|
|
|
import Combine
|
2022-10-09 21:06:10 +00:00
|
|
|
import OSLog
|
2023-10-20 02:50:20 +00:00
|
|
|
#if canImport(Sentry)
|
2022-10-31 16:26:09 +00:00
|
|
|
import Sentry
|
2023-10-20 02:50:20 +00:00
|
|
|
#endif
|
2022-12-19 15:58:14 +00:00
|
|
|
import CloudKit
|
2023-03-05 19:35:25 +00:00
|
|
|
import UserAccounts
|
2022-10-09 21:06:10 +00:00
|
|
|
|
|
|
|
fileprivate let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "PersistentStore")
|
2020-04-11 19:31:37 +00:00
|
|
|
|
2022-12-19 15:58:14 +00:00
|
|
|
class MastodonCachePersistentStore: NSPersistentCloudKitContainer {
|
2020-04-11 19:31:37 +00:00
|
|
|
|
2023-03-05 19:35:25 +00:00
|
|
|
private let accountInfo: UserAccountInfo?
|
2022-12-23 21:35:58 +00:00
|
|
|
|
2020-05-10 18:54:43 +00:00
|
|
|
private static let managedObjectModel: NSManagedObjectModel = {
|
|
|
|
let url = Bundle.main.url(forResource: "Tusker", withExtension: "momd")!
|
|
|
|
return NSManagedObjectModel(contentsOf: url)!
|
|
|
|
}()
|
|
|
|
|
2020-05-13 23:49:35 +00:00
|
|
|
private(set) lazy var backgroundContext: NSManagedObjectContext = {
|
|
|
|
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
|
2022-09-12 03:00:51 +00:00
|
|
|
context.persistentStoreCoordinator = self.persistentStoreCoordinator
|
|
|
|
context.automaticallyMergesChangesFromParent = true
|
2022-11-03 22:56:06 +00:00
|
|
|
context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
|
2023-05-12 03:03:41 +00:00
|
|
|
context.name = "Background"
|
2020-05-13 23:49:35 +00:00
|
|
|
return context
|
|
|
|
}()
|
2020-04-12 02:23:31 +00:00
|
|
|
|
2023-05-12 03:03:41 +00:00
|
|
|
// remote change processing happens on its own context, since it can sometimes take
|
|
|
|
// a really long time (upwards of a minute) and shouldn't block other things using the background context
|
|
|
|
private lazy var remoteChangesBackgroundContext: NSManagedObjectContext = {
|
2021-01-18 19:29:32 +00:00
|
|
|
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
|
2022-09-12 03:00:51 +00:00
|
|
|
context.persistentStoreCoordinator = self.persistentStoreCoordinator
|
|
|
|
context.automaticallyMergesChangesFromParent = true
|
2022-11-03 22:56:06 +00:00
|
|
|
context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
|
2023-05-12 03:03:41 +00:00
|
|
|
context.name = "RemoteChanges"
|
2021-01-18 19:29:32 +00:00
|
|
|
return context
|
|
|
|
}()
|
|
|
|
|
2022-12-19 18:56:46 +00:00
|
|
|
private var lastRemoteChangeToken: NSPersistentHistoryToken?
|
|
|
|
|
2022-10-29 01:14:46 +00:00
|
|
|
// TODO: consider sending managed objects through this to avoid re-fetching things unnecessarily
|
|
|
|
// would need to audit existing uses to make sure everything happens on the main thread
|
|
|
|
// and when updating things on the background context would need to switch to main, refetch, and then publish
|
2020-05-02 16:45:28 +00:00
|
|
|
let statusSubject = PassthroughSubject<String, Never>()
|
|
|
|
let accountSubject = PassthroughSubject<String, Never>()
|
2020-10-12 22:20:57 +00:00
|
|
|
let relationshipSubject = PassthroughSubject<String, Never>()
|
2020-05-11 21:57:50 +00:00
|
|
|
|
2023-03-05 19:35:25 +00:00
|
|
|
init(for accountInfo: UserAccountInfo?, transient: Bool = false) {
|
2022-12-23 21:35:58 +00:00
|
|
|
self.accountInfo = accountInfo
|
|
|
|
|
2022-12-19 15:58:14 +00:00
|
|
|
let group = DispatchGroup()
|
|
|
|
var instancesToMigrate: [URL]? = nil
|
|
|
|
var hashtagsToMigrate: [Hashtag]? = nil
|
2020-05-11 21:57:50 +00:00
|
|
|
if transient {
|
|
|
|
super.init(name: "transient_cache", managedObjectModel: MastodonCachePersistentStore.managedObjectModel)
|
|
|
|
|
|
|
|
let storeDescription = NSPersistentStoreDescription()
|
|
|
|
storeDescription.type = NSInMemoryStoreType
|
|
|
|
persistentStoreDescriptions = [storeDescription]
|
|
|
|
} else {
|
2022-12-01 02:35:52 +00:00
|
|
|
super.init(name: "\(accountInfo!.persistenceKey)_cache", managedObjectModel: MastodonCachePersistentStore.managedObjectModel)
|
2022-12-04 22:33:09 +00:00
|
|
|
|
2022-12-19 15:58:14 +00:00
|
|
|
var localStoreLocation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
|
|
|
|
localStoreLocation.appendPathComponent("\(accountInfo!.persistenceKey)_cache.sqlite", isDirectory: false)
|
|
|
|
let localStoreDescription = NSPersistentStoreDescription(url: localStoreLocation)
|
|
|
|
localStoreDescription.configuration = "Local"
|
2022-12-19 18:56:46 +00:00
|
|
|
localStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
|
|
|
|
localStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
|
2022-12-19 15:58:14 +00:00
|
|
|
|
|
|
|
var cloudStoreLocation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
|
|
|
|
cloudStoreLocation.appendPathComponent("cloud.sqlite", isDirectory: false)
|
|
|
|
let cloudStoreDescription = NSPersistentStoreDescription(url: cloudStoreLocation)
|
|
|
|
cloudStoreDescription.configuration = "Cloud"
|
|
|
|
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.space.vaccor.Tusker")
|
|
|
|
options.databaseScope = .private
|
|
|
|
cloudStoreDescription.cloudKitContainerOptions = options
|
2022-12-19 18:56:46 +00:00
|
|
|
cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
|
|
|
|
cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
|
2022-12-19 15:58:14 +00:00
|
|
|
|
|
|
|
persistentStoreDescriptions = [
|
|
|
|
cloudStoreDescription,
|
|
|
|
localStoreDescription,
|
|
|
|
]
|
|
|
|
|
2022-12-04 22:33:09 +00:00
|
|
|
// workaround for migrating from using id in name to persistenceKey
|
|
|
|
// can be removed after a sufficient time has passed
|
|
|
|
if accountInfo!.id.contains("/") {
|
|
|
|
for desc in persistentStoreDescriptions {
|
2022-12-06 00:32:59 +00:00
|
|
|
guard let new = desc.url,
|
|
|
|
!FileManager.default.fileExists(atPath: new.path) else {
|
2022-12-04 22:33:09 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-12-06 00:32:59 +00:00
|
|
|
do {
|
|
|
|
for ext in ["sqlite", "sqlite-shm", "sqlite-wal"] {
|
|
|
|
var old = new.deletingLastPathComponent()
|
|
|
|
let components = accountInfo!.id.split(separator: "/")
|
|
|
|
for dir in components.dropLast(1) {
|
|
|
|
old.appendPathComponent(String(dir), isDirectory: true)
|
|
|
|
}
|
|
|
|
old.appendPathComponent("\(components.last!)_cache", isDirectory: false)
|
|
|
|
old.appendPathExtension(ext)
|
|
|
|
if FileManager.default.fileExists(atPath: old.path) {
|
|
|
|
var expected = new.deletingLastPathComponent()
|
|
|
|
expected.appendPathComponent("\(accountInfo!.persistenceKey)_cache", isDirectory: false)
|
|
|
|
expected.appendPathExtension(ext)
|
|
|
|
try FileManager.default.moveItem(at: old, to: expected)
|
|
|
|
}
|
2022-12-04 22:33:09 +00:00
|
|
|
}
|
2022-12-06 00:32:59 +00:00
|
|
|
} catch {}
|
2022-12-04 22:33:09 +00:00
|
|
|
}
|
|
|
|
}
|
2022-12-19 15:58:14 +00:00
|
|
|
|
|
|
|
// migrate saved data from local store to cloud store
|
|
|
|
// this can be removed pre-app store release
|
|
|
|
var defaultPath = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
|
|
|
|
defaultPath.appendPathComponent("\(accountInfo!.persistenceKey)_cache.sqlite", isDirectory: false)
|
|
|
|
if FileManager.default.fileExists(atPath: defaultPath.path) {
|
|
|
|
group.enter()
|
|
|
|
let defaultDesc = NSPersistentStoreDescription(url: defaultPath)
|
|
|
|
defaultDesc.configuration = "Default"
|
|
|
|
let defaultPSC = NSPersistentContainer(name: "\(accountInfo!.persistenceKey)_cache", managedObjectModel: MastodonCachePersistentStore.managedObjectModel)
|
|
|
|
defaultPSC.persistentStoreDescriptions = [defaultDesc]
|
|
|
|
defaultPSC.loadPersistentStores { _, error in
|
|
|
|
guard error == nil else {
|
|
|
|
group.leave()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defaultPSC.performBackgroundTask { context in
|
|
|
|
if let instances = try? context.fetch(SavedInstance.fetchRequestWithoutAccountForMigrating()) {
|
|
|
|
instancesToMigrate = instances.map(\.url)
|
|
|
|
instances.forEach(context.delete(_:))
|
|
|
|
}
|
|
|
|
if let hashtags = try? context.fetch(SavedHashtag.fetchRequestWithoutAccountForMigrating()) {
|
|
|
|
hashtagsToMigrate = hashtags.map { Hashtag(name: $0.name, url: $0.url) }
|
|
|
|
hashtags.forEach(context.delete(_:))
|
|
|
|
}
|
|
|
|
if context.hasChanges {
|
|
|
|
try? context.save()
|
|
|
|
}
|
|
|
|
group.leave()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-11 21:57:50 +00:00
|
|
|
}
|
|
|
|
|
2022-12-19 15:58:14 +00:00
|
|
|
group.wait()
|
2020-04-11 19:31:37 +00:00
|
|
|
loadPersistentStores { (description, error) in
|
|
|
|
if let error = error {
|
2022-10-09 21:06:10 +00:00
|
|
|
logger.error("Unable to load persistent store: \(String(describing: error), privacy: .public)")
|
2022-12-31 21:57:43 +00:00
|
|
|
fatalError("Unable to load persistent store: \(String(describing: error))")
|
2020-04-11 19:31:37 +00:00
|
|
|
}
|
2022-12-19 15:58:14 +00:00
|
|
|
|
|
|
|
if description.configuration == "Cloud" {
|
2022-12-23 21:35:58 +00:00
|
|
|
let context = self.backgroundContext
|
|
|
|
context.perform {
|
2022-12-19 15:58:14 +00:00
|
|
|
instancesToMigrate?.forEach({ url in
|
2022-12-23 21:35:58 +00:00
|
|
|
if !context.objectExists(for: SavedInstance.fetchRequest(url: url, account: accountInfo!)) {
|
|
|
|
_ = SavedInstance(url: url, account: accountInfo!, context: self.backgroundContext)
|
|
|
|
}
|
2022-12-19 15:58:14 +00:00
|
|
|
})
|
|
|
|
hashtagsToMigrate?.forEach({ hashtag in
|
2022-12-23 21:35:58 +00:00
|
|
|
if !context.objectExists(for: SavedHashtag.fetchRequest(name: hashtag.name, account: accountInfo!)) {
|
|
|
|
_ = SavedHashtag(hashtag: hashtag, account: accountInfo!, context: self.backgroundContext)
|
|
|
|
}
|
2022-12-19 15:58:14 +00:00
|
|
|
})
|
|
|
|
self.save(context: self.backgroundContext)
|
|
|
|
}
|
|
|
|
}
|
2020-04-11 19:31:37 +00:00
|
|
|
}
|
2022-05-11 02:57:46 +00:00
|
|
|
|
2022-12-19 15:58:14 +00:00
|
|
|
// changes to the Cloud CD model in development need this to be uncommented to update the CK schema
|
|
|
|
// #if DEBUG
|
|
|
|
// try! initializeCloudKitSchema(options: [])
|
|
|
|
// #endif
|
|
|
|
|
2022-09-12 03:00:51 +00:00
|
|
|
viewContext.automaticallyMergesChangesFromParent = true
|
2022-11-03 22:56:06 +00:00
|
|
|
viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
|
2023-05-12 03:03:41 +00:00
|
|
|
viewContext.name = "View"
|
2022-09-12 03:00:51 +00:00
|
|
|
|
2022-05-11 02:57:46 +00:00
|
|
|
NotificationCenter.default.addObserver(self, selector: #selector(managedObjectsDidChange), name: .NSManagedObjectContextObjectsDidChange, object: viewContext)
|
2022-12-19 18:56:46 +00:00
|
|
|
NotificationCenter.default.addObserver(self, selector: #selector(remoteChanges), name: .NSPersistentStoreRemoteChange, object: persistentStoreCoordinator)
|
2020-04-11 19:31:37 +00:00
|
|
|
}
|
|
|
|
|
2022-10-09 21:06:10 +00:00
|
|
|
func save(context: NSManagedObjectContext) {
|
|
|
|
guard context.hasChanges else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
do {
|
|
|
|
try context.save()
|
2022-11-03 14:27:45 +00:00
|
|
|
} catch let error as NSError {
|
2022-10-09 21:06:10 +00:00
|
|
|
logger.error("Unable to save managed object context: \(String(describing: error), privacy: .public)")
|
2023-10-20 02:50:20 +00:00
|
|
|
#if canImport(Sentry)
|
2022-10-31 16:26:09 +00:00
|
|
|
let crumb = Breadcrumb(level: .fatal, category: "PersistentStore")
|
2022-11-03 14:27:45 +00:00
|
|
|
// note: NSDetailedErrorsKey == "NSDetailedErrorsKey" != "NSDetailedErrors"
|
|
|
|
if let detailed = error.userInfo["NSDetailedErrors"] as? [NSError] {
|
|
|
|
crumb.data = [
|
|
|
|
"errors": detailed.compactMap { error -> [String: Any?]? in
|
|
|
|
guard let object = error.userInfo[NSValidationObjectErrorKey] as? NSManagedObject else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return [
|
|
|
|
"entity": object.entity.name,
|
|
|
|
"key": error.userInfo[NSValidationKeyErrorKey],
|
|
|
|
"value": error.userInfo[NSValidationValueErrorKey],
|
|
|
|
"message": error.localizedDescription,
|
|
|
|
]
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}
|
2023-01-28 03:39:15 +00:00
|
|
|
SentrySDK.addBreadcrumb(crumb)
|
2023-10-20 02:50:20 +00:00
|
|
|
#endif
|
2022-11-03 14:27:45 +00:00
|
|
|
fatalError("Unable to save managed object context: \(String(describing: error))")
|
2022-10-09 21:06:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-12 02:23:31 +00:00
|
|
|
func status(for id: String, in context: NSManagedObjectContext? = nil) -> StatusMO? {
|
|
|
|
let context = context ?? viewContext
|
2020-04-11 19:31:37 +00:00
|
|
|
let request: NSFetchRequest<StatusMO> = StatusMO.fetchRequest()
|
|
|
|
request.predicate = NSPredicate(format: "id = %@", id)
|
|
|
|
request.fetchLimit = 1
|
2020-04-12 02:23:31 +00:00
|
|
|
if let result = try? context.fetch(request), let status = result.first {
|
2020-04-11 19:31:37 +00:00
|
|
|
return status
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-07 03:02:12 +00:00
|
|
|
@discardableResult
|
2022-05-01 19:15:35 +00:00
|
|
|
private func upsert(status: Status, context: NSManagedObjectContext) -> StatusMO {
|
2021-05-05 21:51:11 +00:00
|
|
|
if let statusMO = self.status(for: status.id, in: context) {
|
2020-04-12 16:54:27 +00:00
|
|
|
statusMO.updateFrom(apiStatus: status, container: self)
|
2020-05-07 03:02:12 +00:00
|
|
|
return statusMO
|
2020-04-12 16:54:27 +00:00
|
|
|
} else {
|
2022-05-01 19:15:35 +00:00
|
|
|
return StatusMO(apiStatus: status, container: self, context: context)
|
2020-04-12 16:54:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-01 19:15:35 +00:00
|
|
|
func addOrUpdate(status: Status, context: NSManagedObjectContext? = nil, completion: ((StatusMO) -> Void)? = nil) {
|
2021-05-05 21:51:11 +00:00
|
|
|
let context = context ?? backgroundContext
|
|
|
|
context.perform {
|
2022-05-01 19:15:35 +00:00
|
|
|
let statusMO = self.upsert(status: status, context: context)
|
2022-10-09 21:06:10 +00:00
|
|
|
self.save(context: context)
|
2020-05-07 03:02:12 +00:00
|
|
|
completion?(statusMO)
|
2020-05-02 16:45:28 +00:00
|
|
|
self.statusSubject.send(status.id)
|
2020-04-12 02:23:31 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-11 23:10:38 +00:00
|
|
|
|
|
|
|
@MainActor
|
|
|
|
func addOrUpdateOnViewContext(status: Status) -> StatusMO {
|
|
|
|
let statusMO = self.upsert(status: status, context: viewContext)
|
2022-10-09 21:06:10 +00:00
|
|
|
self.save(context: viewContext)
|
2022-05-11 23:10:38 +00:00
|
|
|
statusSubject.send(status.id)
|
|
|
|
return statusMO
|
|
|
|
}
|
2020-04-12 16:54:27 +00:00
|
|
|
|
2022-12-31 21:57:13 +00:00
|
|
|
func addAll(statuses: [Status], in context: NSManagedObjectContext? = nil, completion: (() -> Void)? = nil) {
|
|
|
|
let context = context ?? backgroundContext
|
|
|
|
context.perform {
|
|
|
|
statuses.forEach { self.upsert(status: $0, context: context) }
|
|
|
|
self.save(context: context)
|
2020-05-02 16:45:28 +00:00
|
|
|
statuses.forEach { self.statusSubject.send($0.id) }
|
2020-05-10 19:47:50 +00:00
|
|
|
completion?()
|
2020-04-12 16:54:27 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-11 23:10:38 +00:00
|
|
|
|
2022-12-31 21:57:13 +00:00
|
|
|
func addAll(statuses: [Status], in context: NSManagedObjectContext? = nil) async {
|
2022-05-11 23:10:38 +00:00
|
|
|
return await withCheckedContinuation { continuation in
|
2022-12-31 21:57:13 +00:00
|
|
|
addAll(statuses: statuses, in: context) {
|
2022-05-11 23:10:38 +00:00
|
|
|
continuation.resume()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-04-12 16:54:27 +00:00
|
|
|
|
2020-04-12 02:23:31 +00:00
|
|
|
func account(for id: String, in context: NSManagedObjectContext? = nil) -> AccountMO? {
|
|
|
|
let context = context ?? viewContext
|
2020-04-11 19:31:37 +00:00
|
|
|
let request: NSFetchRequest<AccountMO> = AccountMO.fetchRequest()
|
|
|
|
request.predicate = NSPredicate(format: "id = %@", id)
|
|
|
|
request.fetchLimit = 1
|
2020-04-12 02:23:31 +00:00
|
|
|
if let result = try? context.fetch(request), let account = result.first {
|
2020-04-11 19:31:37 +00:00
|
|
|
return account
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-07 03:02:12 +00:00
|
|
|
@discardableResult
|
2022-10-29 22:55:13 +00:00
|
|
|
private func upsert(account: Account, in context: NSManagedObjectContext) -> AccountMO {
|
|
|
|
if let accountMO = self.account(for: account.id, in: context) {
|
2020-04-12 16:54:27 +00:00
|
|
|
accountMO.updateFrom(apiAccount: account, container: self)
|
2020-05-07 03:02:12 +00:00
|
|
|
return accountMO
|
2020-04-12 16:54:27 +00:00
|
|
|
} else {
|
2022-10-29 22:55:13 +00:00
|
|
|
return AccountMO(apiAccount: account, container: self, context: context)
|
2020-04-12 16:54:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-29 22:55:13 +00:00
|
|
|
func addOrUpdate(account: Account, in context: NSManagedObjectContext? = nil, completion: ((AccountMO) -> Void)? = nil) {
|
|
|
|
let context = context ?? backgroundContext
|
|
|
|
context.perform {
|
|
|
|
let accountMO = self.upsert(account: account, in: context)
|
|
|
|
self.save(context: context)
|
2020-05-07 03:02:12 +00:00
|
|
|
completion?(accountMO)
|
2020-05-02 16:45:28 +00:00
|
|
|
self.accountSubject.send(account.id)
|
2020-04-12 02:23:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-29 05:23:04 +00:00
|
|
|
/// The caller is responsible for calling this on a queue appropriate for `context`.
|
|
|
|
func addOrUpdateSynchronously(account: Account, in context: NSManagedObjectContext) -> AccountMO {
|
|
|
|
let accountMO = self.upsert(account: account, in: context)
|
|
|
|
self.save(context: context)
|
|
|
|
self.accountSubject.send(account.id)
|
|
|
|
return accountMO
|
|
|
|
}
|
|
|
|
|
2020-10-12 22:20:57 +00:00
|
|
|
func relationship(forAccount id: String, in context: NSManagedObjectContext? = nil) -> RelationshipMO? {
|
|
|
|
let context = context ?? viewContext
|
|
|
|
let request: NSFetchRequest<RelationshipMO> = RelationshipMO.fetchRequest()
|
|
|
|
request.predicate = NSPredicate(format: "accountID = %@", id)
|
|
|
|
request.fetchLimit = 1
|
|
|
|
if let result = try? context.fetch(request), let relationship = result.first {
|
|
|
|
return relationship
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@discardableResult
|
2022-10-30 22:54:14 +00:00
|
|
|
private func upsert(relationship: Relationship, in context: NSManagedObjectContext) -> RelationshipMO {
|
2023-04-16 17:23:13 +00:00
|
|
|
if let relationshipMO = self.relationship(forAccount: relationship.accountID, in: context) {
|
2020-10-12 22:20:57 +00:00
|
|
|
relationshipMO.updateFrom(apiRelationship: relationship, container: self)
|
|
|
|
return relationshipMO
|
|
|
|
} else {
|
2022-10-30 22:54:14 +00:00
|
|
|
let relationshipMO = RelationshipMO(apiRelationship: relationship, container: self, context: context)
|
2020-10-12 22:20:57 +00:00
|
|
|
return relationshipMO
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-30 22:54:14 +00:00
|
|
|
func addOrUpdate(relationship: Relationship, in context: NSManagedObjectContext? = nil, completion: ((RelationshipMO) -> Void)? = nil) {
|
|
|
|
let context = context ?? backgroundContext
|
|
|
|
context.perform {
|
|
|
|
let relationshipMO = self.upsert(relationship: relationship, in: context)
|
|
|
|
self.save(context: context)
|
2020-10-12 22:20:57 +00:00
|
|
|
completion?(relationshipMO)
|
2023-04-16 17:23:13 +00:00
|
|
|
self.relationshipSubject.send(relationship.accountID)
|
2020-10-12 22:20:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-11 22:28:19 +00:00
|
|
|
func addAll(accounts: [Account], in context: NSManagedObjectContext? = nil, completion: (() -> Void)? = nil) {
|
|
|
|
let context = context ?? backgroundContext
|
|
|
|
context.perform {
|
|
|
|
accounts.forEach { self.upsert(account: $0, in: context) }
|
|
|
|
self.save(context: context)
|
2020-04-12 16:54:27 +00:00
|
|
|
completion?()
|
2020-05-02 16:45:28 +00:00
|
|
|
accounts.forEach { self.accountSubject.send($0.id) }
|
2020-04-12 16:54:27 +00:00
|
|
|
}
|
|
|
|
}
|
2023-01-18 19:35:50 +00:00
|
|
|
|
|
|
|
func addAll(accounts: [Account], in context: NSManagedObjectContext? = nil) async {
|
|
|
|
await withCheckedContinuation { continuation in
|
|
|
|
addAll(accounts: accounts, in: context) {
|
|
|
|
continuation.resume()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-06 23:32:32 +00:00
|
|
|
|
|
|
|
func addAll(notifications: [Pachyderm.Notification], completion: (() -> Void)? = nil) {
|
|
|
|
backgroundContext.perform {
|
|
|
|
let statuses = notifications.compactMap { $0.status }
|
2024-04-13 02:47:11 +00:00
|
|
|
let accounts = notifications.map { $0.account }
|
2022-05-01 19:15:35 +00:00
|
|
|
statuses.forEach { self.upsert(status: $0, context: self.backgroundContext) }
|
2022-10-29 22:55:13 +00:00
|
|
|
accounts.forEach { self.upsert(account: $0, in: self.backgroundContext) }
|
2022-10-09 21:06:10 +00:00
|
|
|
self.save(context: self.backgroundContext)
|
2020-05-06 23:32:32 +00:00
|
|
|
completion?()
|
|
|
|
statuses.forEach { self.statusSubject.send($0.id) }
|
|
|
|
accounts.forEach { self.accountSubject.send($0.id) }
|
|
|
|
}
|
|
|
|
}
|
2020-04-12 16:54:27 +00:00
|
|
|
|
2020-05-10 19:47:50 +00:00
|
|
|
func performBatchUpdates(_ block: @escaping (_ context: NSManagedObjectContext, _ addAccounts: ([Account]) -> Void, _ addStatuses: ([Status]) -> Void) -> Void, completion: (() -> Void)? = nil) {
|
|
|
|
backgroundContext.perform {
|
|
|
|
var updatedAccounts = [String]()
|
|
|
|
var updatedStatuses = [String]()
|
|
|
|
|
|
|
|
block(self.backgroundContext, { (accounts) in
|
2022-10-29 22:55:13 +00:00
|
|
|
accounts.forEach { self.upsert(account: $0, in: self.backgroundContext) }
|
2020-05-10 19:47:50 +00:00
|
|
|
updatedAccounts.append(contentsOf: accounts.map { $0.id })
|
|
|
|
}, { (statuses) in
|
2022-05-01 19:15:35 +00:00
|
|
|
statuses.forEach { self.upsert(status: $0, context: self.backgroundContext) }
|
2020-05-10 19:47:50 +00:00
|
|
|
updatedStatuses.append(contentsOf: statuses.map { $0.id })
|
|
|
|
})
|
|
|
|
|
|
|
|
updatedAccounts.forEach(self.accountSubject.send)
|
|
|
|
updatedStatuses.forEach(self.statusSubject.send)
|
|
|
|
|
2022-10-09 21:06:10 +00:00
|
|
|
self.save(context: self.backgroundContext)
|
2020-05-10 19:47:50 +00:00
|
|
|
completion?()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-30 02:43:56 +00:00
|
|
|
func updateFollowedHashtags(_ hashtags: [Hashtag], completion: @escaping (Result<[FollowedHashtag], Error>) -> Void) {
|
|
|
|
viewContext.perform {
|
|
|
|
do {
|
|
|
|
var all = try self.viewContext.fetch(FollowedHashtag.fetchRequest())
|
|
|
|
|
|
|
|
let toDelete = all.filter { existing in !hashtags.contains(where: { $0.name == existing.name }) }.map(\.objectID)
|
|
|
|
if !toDelete.isEmpty {
|
|
|
|
try self.viewContext.execute(NSBatchDeleteRequest(objectIDs: toDelete))
|
|
|
|
}
|
|
|
|
|
|
|
|
for hashtag in hashtags where !all.contains(where: { $0.name == hashtag.name}) {
|
|
|
|
let mo = FollowedHashtag(hashtag: hashtag, context: self.viewContext)
|
|
|
|
all.append(mo)
|
|
|
|
}
|
|
|
|
|
|
|
|
self.save(context: self.viewContext)
|
|
|
|
completion(.success(all))
|
|
|
|
} catch {
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func hasFollowedHashtag(_ hashtag: Hashtag) -> Bool {
|
|
|
|
do {
|
|
|
|
let req = FollowedHashtag.fetchRequest(name: name)
|
|
|
|
return try viewContext.count(for: req) > 0
|
|
|
|
} catch {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-03 17:29:07 +00:00
|
|
|
func updateFilters(_ filters: [AnyFilter], completion: @escaping (Result<[FilterMO], Error>) -> Void) {
|
2022-12-01 03:16:33 +00:00
|
|
|
viewContext.perform {
|
|
|
|
do {
|
|
|
|
var all = try self.viewContext.fetch(FilterMO.fetchRequest())
|
|
|
|
|
|
|
|
let toDelete = all.filter { existing in !filters.contains(where: { $0.id == existing.id }) }.map(\.objectID)
|
|
|
|
if !toDelete.isEmpty {
|
|
|
|
try self.viewContext.execute(NSBatchDeleteRequest(objectIDs: toDelete))
|
|
|
|
}
|
|
|
|
|
2022-12-03 17:29:07 +00:00
|
|
|
for filter in filters {
|
|
|
|
if let existing = all.first(where: { $0.id == filter.id }) {
|
|
|
|
existing.updateFrom(apiFilter: filter, context: self.viewContext)
|
|
|
|
} else {
|
|
|
|
let mo = FilterMO(context: self.viewContext)
|
|
|
|
mo.updateFrom(apiFilter: filter, context: self.viewContext)
|
|
|
|
all.append(mo)
|
|
|
|
}
|
2022-12-01 03:16:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.save(context: self.viewContext)
|
|
|
|
completion(.success(all))
|
|
|
|
} catch {
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-23 21:35:58 +00:00
|
|
|
func getTimelinePosition(timeline: Timeline) -> TimelinePosition? {
|
|
|
|
guard let accountInfo else {
|
|
|
|
return nil
|
|
|
|
}
|
2022-12-13 16:35:09 +00:00
|
|
|
do {
|
2022-12-23 21:35:58 +00:00
|
|
|
let req = TimelinePosition.fetchRequest(timeline: timeline, account: accountInfo)
|
2022-12-13 16:35:09 +00:00
|
|
|
return try viewContext.fetch(req).first
|
|
|
|
} catch {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-11 02:57:46 +00:00
|
|
|
@objc private func managedObjectsDidChange(_ notification: Foundation.Notification) {
|
|
|
|
let changes = hasChangedSavedHashtagsOrInstances(notification)
|
|
|
|
if changes.hashtags {
|
|
|
|
NotificationCenter.default.post(name: .savedHashtagsChanged, object: nil)
|
|
|
|
}
|
|
|
|
if changes.instances {
|
|
|
|
NotificationCenter.default.post(name: .savedInstancesChanged, object: nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func hasChangedSavedHashtagsOrInstances(_ notification: Foundation.Notification) -> (hashtags: Bool, instances: Bool) {
|
|
|
|
var changes: (hashtags: Bool, instances: Bool) = (false, false)
|
|
|
|
if let inserted = notification.userInfo?[NSInsertedObjectsKey] as? Set<NSManagedObject> {
|
|
|
|
for object in inserted {
|
|
|
|
if object is SavedHashtag {
|
|
|
|
changes.hashtags = true
|
|
|
|
} else if object is SavedInstance {
|
|
|
|
changes.instances = true
|
|
|
|
}
|
|
|
|
if changes.hashtags && changes.instances {
|
|
|
|
return changes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let deleted = notification.userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject> {
|
|
|
|
for object in deleted {
|
|
|
|
if object is SavedHashtag {
|
|
|
|
changes.hashtags = true
|
|
|
|
} else if object is SavedInstance {
|
|
|
|
changes.instances = true
|
|
|
|
}
|
|
|
|
if changes.hashtags && changes.instances {
|
|
|
|
return changes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return changes
|
|
|
|
}
|
|
|
|
|
2022-12-19 18:56:46 +00:00
|
|
|
@objc private func remoteChanges(_ notification: Foundation.Notification) {
|
|
|
|
guard let token = notification.userInfo?[NSPersistentHistoryTokenKey] as? NSPersistentHistoryToken else {
|
|
|
|
return
|
|
|
|
}
|
2023-05-12 03:03:41 +00:00
|
|
|
remoteChangesBackgroundContext.perform {
|
2022-12-19 18:56:46 +00:00
|
|
|
defer {
|
|
|
|
self.lastRemoteChangeToken = token
|
|
|
|
}
|
|
|
|
let req = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastRemoteChangeToken)
|
2023-05-12 03:03:41 +00:00
|
|
|
if let result = try? self.remoteChangesBackgroundContext.execute(req) as? NSPersistentHistoryResult,
|
|
|
|
let transactions = result.result as? [NSPersistentHistoryTransaction],
|
|
|
|
!transactions.isEmpty {
|
|
|
|
var changedHashtags = false
|
|
|
|
var changedInstances = false
|
|
|
|
var changedTimelinePositions = Set<NSManagedObjectID>()
|
|
|
|
var changedAccountPrefs = false
|
|
|
|
outer: for transaction in transactions {
|
|
|
|
for change in transaction.changes ?? [] {
|
|
|
|
if change.changedObjectID.entity.name == "SavedHashtag" {
|
|
|
|
changedHashtags = true
|
|
|
|
} else if change.changedObjectID.entity.name == "SavedInstance" {
|
|
|
|
changedInstances = true
|
|
|
|
} else if change.changedObjectID.entity.name == "TimelinePosition" {
|
|
|
|
changedTimelinePositions.insert(change.changedObjectID)
|
|
|
|
} else if change.changedObjectID.entity.name == "AccountPreferences" {
|
|
|
|
changedAccountPrefs = true
|
2022-12-19 18:56:46 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-12 03:03:41 +00:00
|
|
|
}
|
2024-01-27 20:48:58 +00:00
|
|
|
// Can't capture vars in concurrently-executing closure
|
|
|
|
let hashtags = changedHashtags
|
|
|
|
let instances = changedInstances
|
|
|
|
let timelinePositions = changedTimelinePositions
|
|
|
|
let accountPrefs = changedAccountPrefs
|
2023-05-12 03:03:41 +00:00
|
|
|
DispatchQueue.main.async {
|
2024-01-27 20:48:58 +00:00
|
|
|
if hashtags {
|
2023-05-12 03:03:41 +00:00
|
|
|
NotificationCenter.default.post(name: .savedHashtagsChanged, object: nil)
|
|
|
|
}
|
2024-01-27 20:48:58 +00:00
|
|
|
if instances {
|
2023-05-12 03:03:41 +00:00
|
|
|
NotificationCenter.default.post(name: .savedInstancesChanged, object: nil)
|
|
|
|
}
|
2024-01-27 20:48:58 +00:00
|
|
|
for id in timelinePositions {
|
2023-05-12 03:03:41 +00:00
|
|
|
guard let timelinePosition = try? self.viewContext.existingObject(with: id) as? TimelinePosition else {
|
|
|
|
continue
|
2022-12-24 17:20:13 +00:00
|
|
|
}
|
2023-05-12 03:03:41 +00:00
|
|
|
// the kvo observer that clears the LazilyDecoding cache doesn't always fire on remote changes, so do it manually
|
|
|
|
timelinePosition.changedRemotely()
|
|
|
|
NotificationCenter.default.post(name: .timelinePositionChanged, object: timelinePosition)
|
|
|
|
}
|
2024-01-27 20:48:58 +00:00
|
|
|
if accountPrefs {
|
2023-05-12 03:03:41 +00:00
|
|
|
NotificationCenter.default.post(name: .accountPreferencesChangedRemotely, object: nil)
|
2022-12-19 18:56:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-11 19:31:37 +00:00
|
|
|
}
|
2022-12-23 21:35:58 +00:00
|
|
|
|
|
|
|
extension Foundation.Notification.Name {
|
|
|
|
static let timelinePositionChanged = Notification.Name("timelinePositionChanged")
|
2022-12-24 17:20:13 +00:00
|
|
|
static let accountPreferencesChangedRemotely = Notification.Name("accountPreferencesChangedRemotely")
|
2022-12-23 21:35:58 +00:00
|
|
|
}
|