frenzy-ios/Reader/LocalData.swift

76 lines
2.1 KiB
Swift

//
// LocalData.swift
// Reader
//
// Created by Shadowfacts on 11/25/21.
//
import Foundation
import Fervor
import CryptoKit
struct LocalData {
private init() {}
private static let encoder = JSONEncoder()
private static let decoder = JSONDecoder()
static var accounts: [Account] {
get {
guard let data = UserDefaults.standard.data(forKey: "accounts"),
let accounts = try? decoder.decode([Account].self, from: data) else {
return []
}
return accounts
}
set {
let data = try! encoder.encode(newValue)
UserDefaults.standard.set(data, forKey: "accounts")
}
}
static var mostRecentAccountID: Data? {
get {
return UserDefaults.standard.data(forKey: "mostRecentAccountID")
}
set {
UserDefaults.standard.set(newValue, forKey: "mostRecentAccountID")
}
}
static func mostRecentAccount() -> Account? {
guard let id = mostRecentAccountID else {
return nil
}
return account(with: id)
}
static func account(with id: Data) -> Account? {
return accounts.first(where: { $0.id == id })
}
struct Account: Codable {
let id: Data
let instanceURL: URL
let clientID: String
let clientSecret: String
let token: Token
init(instanceURL: URL, clientID: String, clientSecret: String, token: Token) {
// 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())
self.instanceURL = instanceURL
self.clientID = clientID
self.clientSecret = clientSecret
self.token = token
}
}
}