summaryrefslogtreecommitdiff
path: root/Sora/Data/Settings
diff options
context:
space:
mode:
Diffstat (limited to 'Sora/Data/Settings')
-rw-r--r--Sora/Data/Settings/SettingsManager.swift47
1 files changed, 47 insertions, 0 deletions
diff --git a/Sora/Data/Settings/SettingsManager.swift b/Sora/Data/Settings/SettingsManager.swift
index 007c1d8..ff284f3 100644
--- a/Sora/Data/Settings/SettingsManager.swift
+++ b/Sora/Data/Settings/SettingsManager.swift
@@ -83,6 +83,53 @@ class SettingsManager: ObservableObject { // swiftlint:disable:this type_body_l
identifier: { $0.id }
)
loadBookmarksCache()
+ backupBookmarks()
+ }
+ }
+
+ private func backupBookmarks() {
+ guard
+ let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
+ .first
+ else { return }
+ let backupDirectory = cachesDirectory.appendingPathComponent("bookmarks_backups")
+ let fileManager = FileManager.default
+
+ try? fileManager.createDirectory(at: backupDirectory, withIntermediateDirectories: true)
+
+ let timestamp = Int(Date().timeIntervalSince1970)
+ let backupFile = backupDirectory.appendingPathComponent("bookmarks_backup_\(timestamp).json")
+
+ if let data = Self.encode(self.bookmarksCache) {
+ 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("bookmarks_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)
+ }
+ }
}
}