Tusker/Packages/TuskerPreferences/Sources/TuskerPreferences/Preferences.swift

44 lines
1.8 KiB
Swift
Raw Normal View History

2018-08-28 23:16:17 +00:00
//
// Preferences.swift
2023-04-18 23:47:49 +00:00
// TuskerPreferences
2018-08-28 23:16:17 +00:00
//
2024-04-13 22:44:43 +00:00
// Created by Shadowfacts on 4/12/24.
2018-08-28 23:16:17 +00:00
//
2024-04-13 22:44:43 +00:00
import Foundation
2018-08-28 23:16:17 +00:00
2024-04-13 22:44:43 +00:00
public struct Preferences {
@MainActor
2024-04-13 22:44:43 +00:00
public static let shared: PreferenceStore = load()
2018-08-28 23:16:17 +00:00
private static var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
2023-04-18 23:47:49 +00:00
private static var appGroupDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.space.vaccor.Tusker")!
2024-04-13 22:44:43 +00:00
private static var legacyURL = appGroupDirectory.appendingPathComponent("preferences").appendingPathExtension("plist")
private static var preferencesURL = appGroupDirectory.appendingPathComponent("preferences.v2").appendingPathExtension("plist")
private static var nonAppGroupURL = documentsDirectory.appendingPathComponent("preferences").appendingPathExtension("plist")
private init() {}
2018-08-28 23:16:17 +00:00
@MainActor
2023-04-18 23:47:49 +00:00
public static func save() {
2018-08-28 23:16:17 +00:00
let encoder = PropertyListEncoder()
2024-04-13 22:44:43 +00:00
let data = try? encoder.encode(PreferenceCoding(wrapped: shared))
try? data?.write(to: preferencesURL, options: .noFileProtection)
2018-08-28 23:16:17 +00:00
}
2024-04-13 22:44:43 +00:00
private static func load() -> PreferenceStore {
2018-08-28 23:16:17 +00:00
let decoder = PropertyListDecoder()
2024-04-13 22:44:43 +00:00
if let data = try? Data(contentsOf: preferencesURL),
let store = try? decoder.decode(PreferenceCoding<PreferenceStore>.self, from: data) {
return store.wrapped
} else if let legacyData = (try? Data(contentsOf: legacyURL)) ?? (try? Data(contentsOf: nonAppGroupURL)),
let legacy = try? decoder.decode(LegacyPreferences.self, from: legacyData) {
let store = PreferenceStore()
store.migrate(from: legacy)
return store
} else {
2024-04-13 22:44:43 +00:00
return PreferenceStore()
2023-01-14 16:27:41 +00:00
}
}
}