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

44 lines
1.8 KiB
Swift

//
// Preferences.swift
// TuskerPreferences
//
// Created by Shadowfacts on 4/12/24.
//
import Foundation
public struct Preferences {
@MainActor
public static let shared: PreferenceStore = load()
private static var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private static var appGroupDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.space.vaccor.Tusker")!
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() {}
@MainActor
public static func save() {
let encoder = PropertyListEncoder()
let data = try? encoder.encode(PreferenceCoding(wrapped: shared))
try? data?.write(to: preferencesURL, options: .noFileProtection)
}
private static func load() -> PreferenceStore {
let decoder = PropertyListDecoder()
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 {
return PreferenceStore()
}
}
}