FlurSchnaps-Server/Sources/App/TokenStorage.swift
2022-09-05 19:28:44 +02:00

48 lines
1.2 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 {
log(info: "No tokens loaded")
return
}
do {
let data = try Data(contentsOf: fileUrl)
tokens = try BinaryDecoder().decode(from: data)
log(info: "\(tokens.count) tokens loaded")
} 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)")
}
}
}