frenzy-ios/Persistence/Sources/Persistence/LocalData.swift

84 lines
2.5 KiB
Swift
Raw Normal View History

2021-12-08 02:58:02 +00:00
//
// LocalData.swift
// Reader
//
// Created by Shadowfacts on 11/25/21.
//
import Foundation
2022-03-06 20:34:30 +00:00
import Fervor
import CryptoKit
2021-12-08 02:58:02 +00:00
public struct LocalData {
2021-12-08 02:58:02 +00:00
private init() {}
private static let encoder = JSONEncoder()
private static let decoder = JSONDecoder()
public static var defaults = UserDefaults(suiteName: "group.net.shadowfacts.Reader")!
2022-06-15 22:37:53 +00:00
public static var accounts: [Account] {
2021-12-08 02:58:02 +00:00
get {
2022-06-15 22:37:53 +00:00
guard let data = defaults.data(forKey: "accounts"),
2022-01-12 18:48:52 +00:00
let accounts = try? decoder.decode([Account].self, from: data) else {
return []
2021-12-08 02:58:02 +00:00
}
2022-01-12 18:48:52 +00:00
return accounts
2021-12-08 02:58:02 +00:00
}
set {
let data = try! encoder.encode(newValue)
2022-06-15 22:37:53 +00:00
defaults.set(data, forKey: "accounts")
2022-01-12 18:48:52 +00:00
}
}
public static var mostRecentAccountID: Data? {
2022-01-12 18:48:52 +00:00
get {
2022-06-15 22:37:53 +00:00
return defaults.data(forKey: "mostRecentAccountID")
2022-01-12 18:48:52 +00:00
}
set {
2022-06-15 22:37:53 +00:00
defaults.set(newValue, forKey: "mostRecentAccountID")
2022-01-12 18:48:52 +00:00
}
}
public static func mostRecentAccount() -> Account? {
2022-01-12 18:48:52 +00:00
guard let id = mostRecentAccountID else {
return nil
2021-12-08 02:58:02 +00:00
}
2022-03-06 20:34:30 +00:00
return account(with: id)
}
public static func account(with id: Data) -> Account? {
2022-01-12 18:48:52 +00:00
return accounts.first(where: { $0.id == id })
2021-12-08 02:58:02 +00:00
}
public struct Account: Codable {
public let id: Data
public let instanceURL: URL
public let clientID: String
public let clientSecret: String
public let token: Token
2021-12-25 19:04:45 +00:00
2022-06-20 15:32:58 +00:00
/// A filename-safe string for this account
public var persistenceKey: String {
// slashes the base64 string turn into subdirectories which we don't want
id.base64EncodedString().replacingOccurrences(of: "/", with: "_")
}
public init(instanceURL: URL, clientID: String, clientSecret: String, token: Token) {
2022-03-06 20:34:30 +00:00
// we use a hash of instance host and account id rather than random ids so that
// user activites can uniquely identify accounts across devices
var hasher = SHA256()
hasher.update(data: instanceURL.host!.data(using: .utf8)!)
hasher.update(data: token.owner!.data(using: .utf8)!)
self.id = Data(hasher.finalize())
2021-12-25 19:04:45 +00:00
self.instanceURL = instanceURL
self.clientID = clientID
self.clientSecret = clientSecret
2022-03-06 20:34:30 +00:00
self.token = token
2021-12-25 19:04:45 +00:00
}
2021-12-08 02:58:02 +00:00
}
}