frenzy-ios/Reader/LocalData.swift

76 lines
2.1 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
struct LocalData {
private init() {}
private static let encoder = JSONEncoder()
private static let decoder = JSONDecoder()
2022-01-12 18:48:52 +00:00
static var accounts: [Account] {
2021-12-08 02:58:02 +00:00
get {
2022-01-12 18:48:52 +00:00
guard let data = UserDefaults.standard.data(forKey: "accounts"),
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-01-12 18:48:52 +00:00
UserDefaults.standard.set(data, forKey: "accounts")
}
}
2022-03-06 20:34:30 +00:00
static var mostRecentAccountID: Data? {
2022-01-12 18:48:52 +00:00
get {
2022-03-06 20:34:30 +00:00
return UserDefaults.standard.data(forKey: "mostRecentAccountID")
2022-01-12 18:48:52 +00:00
}
set {
2022-03-06 20:34:30 +00:00
UserDefaults.standard.set(newValue, forKey: "mostRecentAccountID")
2022-01-12 18:48:52 +00:00
}
}
static func mostRecentAccount() -> Account? {
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)
}
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
}
struct Account: Codable {
2022-03-06 20:34:30 +00:00
let id: Data
2021-12-08 02:58:02 +00:00
let instanceURL: URL
let clientID: String
let clientSecret: String
2022-03-06 20:34:30 +00:00
let token: Token
2021-12-25 19:04:45 +00:00
2022-03-06 20:34:30 +00:00
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())
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
}
}