diff options
Diffstat (limited to 'Sora/Data/Settings/SettingsManager.swift')
| -rw-r--r-- | Sora/Data/Settings/SettingsManager.swift | 248 |
1 files changed, 248 insertions, 0 deletions
diff --git a/Sora/Data/Settings/SettingsManager.swift b/Sora/Data/Settings/SettingsManager.swift index 3fba04e..ffe7057 100644 --- a/Sora/Data/Settings/SettingsManager.swift +++ b/Sora/Data/Settings/SettingsManager.swift @@ -44,6 +44,7 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l // MARK: - Private Properties private var bookmarksCache: [SettingsBookmark] = [] + private var favoritesCache: [SettingsFavoritePost] = [] private var searchHistoryCache: [BooruSearchQuery] = [] private var blurRatingsCache: [BooruRating] = [] private var displayRatingsCache: [BooruRating] = [] @@ -56,6 +57,9 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l @AppStorage("bookmarks") private var bookmarksData = Data() + @AppStorage("favorites") + private var favoritesData = Data() + @AppStorage("displayRatings") private var displayRatingsData = SettingsManager.encode(BooruRating.allCases) ?? Data() @@ -101,6 +105,29 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l } } + var favorites: [SettingsFavoritePost] { + get { favoritesCache } + + set { + guard !isUpdatingCache else { return } + + isUpdatingCache = true + + defer { isUpdatingCache = false } + + syncableData( + key: "favorites", + localData: $favoritesData, + newValue: newValue + ) { $0.sorted { $0.date > $1.date } } + + favoritesCache = newValue.sorted { $0.date > $1.date } + + pendingSyncKeys.insert(.favorites) + triggerBatchedSync() + } + } + var uniformThumbnailGrid: Bool { get { uniformThumbnailGridCache } @@ -312,6 +339,7 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l } loadBookmarksCache() + loadFavoritesCache() loadSearchHistoryCache() loadDisplayRatingsCache() loadBlurRatingsCache() @@ -340,6 +368,26 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l triggerBatchedSync() } + func updateFavorites(_ newValue: [SettingsFavoritePost]) async { + guard !isUpdatingCache else { return } + + isUpdatingCache = true + + defer { isUpdatingCache = false } + + syncableData( + key: "favorites", + localData: $favoritesData, + newValue: newValue + ) { $0.sorted { $0.date > $1.date } } + + favoritesCache = newValue.sorted { $0.date > $1.date } + + await backupFavorites() + pendingSyncKeys.insert(.favorites) + triggerBatchedSync() + } + func updateSearchHistory(_ newValue: [BooruSearchQuery]) { guard !isUpdatingCache else { return } @@ -529,6 +577,55 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l }.value } + private func backupFavorites() async { + await Task.detached { + guard + let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) + .first + else { return } + + let backupDirectory = cachesDirectory.appendingPathComponent("favorites_backups") + let fileManager = FileManager.default + + try? fileManager.createDirectory(at: backupDirectory, withIntermediateDirectories: true) + + let timestamp = Int(Date().timeIntervalSince1970) + let backupFile = backupDirectory.appendingPathComponent("favorites_backup_\(timestamp).json") + + if let data = await Self.encode(self.favoritesCache) { + try? data.write(to: backupFile) + } + + if let files = try? fileManager.contentsOfDirectory( + at: backupDirectory, + includingPropertiesForKeys: [.contentModificationDateKey], + options: .skipsHiddenFiles + ) { + let jsonBackups = files.filter { file in + file.lastPathComponent.hasPrefix("favorites_backup_") && file.pathExtension == "json" + } + let sortedBackups = jsonBackups.sorted { firstFile, secondFile in + let firstDate = + (try? firstFile.resourceValues(forKeys: [.contentModificationDateKey]) + .contentModificationDate) + ?? .distantPast + let secondDate = + (try? secondFile.resourceValues(forKeys: [.contentModificationDateKey]) + .contentModificationDate) + ?? .distantPast + + return firstDate > secondDate + } + + if sortedBackups.count > 10 { + for url in sortedBackups[10...] { + try? fileManager.removeItem(at: url) + } + } + } + }.value + } + // swiftlint:disable:next cyclomatic_complexity private func triggerSyncIfNeeded(for key: SettingsSyncKey) { guard enableSync else { return } @@ -626,10 +723,43 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l self.customProvidersData = encoded } } + + case .favorites: + var iCloudFavorites: [SettingsFavoritePost] = [] + + if let iCloudData = NSUbiquitousKeyValueStore.default.data(forKey: "favorites") { + iCloudFavorites = + await Self + .decode([SettingsFavoritePost].self, from: iCloudData) ?? [] + } + + let localFavorites = + await Self.decode([SettingsFavoritePost].self, from: favoritesData) ?? [] + let mergedFavoritesDict = (localFavorites + iCloudFavorites).reduce( + into: [UUID: SettingsFavoritePost]() + ) { dict, favorite in + if let existing = dict[favorite.id] { + if favorite.date > existing.date { + dict[favorite.id] = favorite + } + } else { + dict[favorite.id] = favorite + } + } + let mergedFavorites = Array(mergedFavoritesDict.values).sorted { $0.date > $1.date } + + if let encoded = await Self.encode(mergedFavorites) { + NSUbiquitousKeyValueStore.default.set(encoded, forKey: "favorites") + + await MainActor.run { + self.favoritesData = encoded + } + } } await MainActor.run { self.loadBookmarksCache() + self.loadFavoritesCache() self.loadSearchHistoryCache() self.objectWillChange.send() } @@ -656,6 +786,14 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l ) } + private func loadFavoritesCache() { + loadCache( + from: favoritesData, + sort: { $0.sorted { $0.date > $1.date } }, + assign: { [weak self] in self?.favoritesCache = $0 } + ) + } + private func loadSearchHistoryCache() { loadCache( from: searchHistoryData, @@ -742,6 +880,7 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l func triggerSyncIfNeededForAll() { self.triggerSyncIfNeeded(for: .bookmarks) + self.triggerSyncIfNeeded(for: .favorites) self.triggerSyncIfNeeded(for: .searchHistory) self.triggerSyncIfNeeded(for: .customProviders) } @@ -851,6 +990,115 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l triggerBatchedSync() } + // MARK: Favourites Management + func addFavorite(post: BooruPost, provider: BooruProvider, folder: UUID? = nil) { + var updatedFavorites = favorites + + updatedFavorites.append( + SettingsFavoritePost(post: post, provider: provider, folder: folder) + ) + + if let data = Self.encode(updatedFavorites), data.count < 1_000_000 { // 1 MB + Task { + await updateFavorites(updatedFavorites) + } + } else { + debugPrint("SettingsManager.addFavorite: iCloud data limit exceeded") + } + } + + func removeFavorite(at offsets: IndexSet) { + var updated = favorites + + updated.remove(atOffsets: offsets) + + Task { + await updateFavorites(updated) + } + } + + func removeFavorite(withPostId postId: String, provider: BooruProvider) { + let updated = favorites.filter { !($0.postId == postId && $0.provider == provider) } + + Task { + await updateFavorites(updated) + } + } + + func removeFavorite(withID id: UUID) { + let updated = favorites.filter { $0.id != id } + + Task { + await updateFavorites(updated) + } + } + + func isFavorite(postId: String, provider: BooruProvider) -> Bool { + favorites.contains { $0.postId == postId && $0.provider == provider } + } + + func exportFavorites() throws -> Data { + try JSONEncoder().encode(favorites) + } + + func importFavorites(from data: Data) throws { + let importedFavorites = try JSONDecoder().decode([SettingsFavoritePost].self, from: data) + let existingFavoriteIDs = Set(favorites.map(\.id)) + let newFavorites = importedFavorites.filter { !existingFavoriteIDs.contains($0.id) } + var updated = favorites + + updated.append(contentsOf: newFavorites) + + Task { + await updateFavorites(updated) + } + } + + func updateFavoriteFolder(withID id: UUID, folder: UUID?) { + guard let index = favorites.firstIndex(where: { $0.id == id }) else { return } + + var updated = favorites + + updated[index].folder = folder + + Task { + await updateFavorites(updated) + } + + pendingSyncKeys.insert(.favorites) + triggerBatchedSync() + } + + func updateFavoriteLastVisit(withID id: UUID, date: Date = Date()) { + guard let index = favorites.firstIndex(where: { $0.id == id }) else { return } + + var updated = favorites + + updated[index].lastVisit = date + + Task { + await updateFavorites(updated) + } + + pendingSyncKeys.insert(.favorites) + triggerBatchedSync() + } + + func incrementFavoriteVisitCount(withID id: UUID) { + guard let index = favorites.firstIndex(where: { $0.id == id }) else { return } + + var updated = favorites + + updated[index].visitedCount += 1 + + Task { + await updateFavorites(updated) + } + + pendingSyncKeys.insert(.favorites) + triggerBatchedSync() + } + func folderName(forID id: UUID) -> String? { folders.first { $0.id == id }?.name } |