46 lines
1.1 KiB
Swift
46 lines
1.1 KiB
Swift
|
import Foundation
|
||
|
import BinaryCodable
|
||
|
|
||
|
struct TokenStorage {
|
||
|
|
||
|
private(set) var tokens: Set<String>
|
||
|
|
||
|
private let fileUrl: URL
|
||
|
|
||
|
private let encoder = BinaryEncoder()
|
||
|
|
||
|
init(in folder: URL) {
|
||
|
tokens = []
|
||
|
fileUrl = folder.appendingPathComponent("tokens")
|
||
|
|
||
|
loadTokensFromDisk()
|
||
|
}
|
||
|
|
||
|
private mutating func loadTokensFromDisk() {
|
||
|
guard FileManager.default.fileExists(atPath: fileUrl.path) else {
|
||
|
return
|
||
|
}
|
||
|
do {
|
||
|
let data = try Data(contentsOf: fileUrl)
|
||
|
tokens = try BinaryDecoder().decode(from: data)
|
||
|
} catch {
|
||
|
log(error: "Failed to read token file: \(error)")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
mutating func add(_ tokenUpload: TokenUpload) {
|
||
|
if let oldToken = tokenUpload.previousToken {
|
||
|
tokens.remove(oldToken.hex)
|
||
|
}
|
||
|
tokens.insert(tokenUpload.currentToken.hex)
|
||
|
do {
|
||
|
let data = try encoder.encode(tokens)
|
||
|
try data.write(to: fileUrl)
|
||
|
} catch {
|
||
|
log(error: "Failed to write token file: \(error)")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|