42 lines
1.5 KiB
C#
42 lines
1.5 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using KronaStaffTerminal.Models;
|
|
|
|
namespace KronaStaffTerminal.Services;
|
|
|
|
public sealed class TerminalStore
|
|
{
|
|
private static readonly byte[] Entropy = "Krona.Staff.Terminal.v1"u8.ToArray();
|
|
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
|
|
private readonly string _filePath = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
|
"Krona",
|
|
"StaffTerminal",
|
|
"terminal-state.dat");
|
|
|
|
public async Task<TerminalState> LoadAsync()
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(_filePath)) return new TerminalState();
|
|
var encrypted = await File.ReadAllBytesAsync(_filePath);
|
|
var clear = ProtectedData.Unprotect(encrypted, Entropy, DataProtectionScope.CurrentUser);
|
|
return JsonSerializer.Deserialize<TerminalState>(clear, JsonOptions) ?? new TerminalState();
|
|
}
|
|
catch
|
|
{
|
|
return new TerminalState();
|
|
}
|
|
}
|
|
|
|
public async Task SaveAsync(TerminalState state)
|
|
{
|
|
var directory = Path.GetDirectoryName(_filePath)!;
|
|
Directory.CreateDirectory(directory);
|
|
var clear = JsonSerializer.SerializeToUtf8Bytes(state, JsonOptions);
|
|
var encrypted = ProtectedData.Protect(clear, Entropy, DataProtectionScope.CurrentUser);
|
|
var temporaryPath = _filePath + ".tmp";
|
|
await File.WriteAllBytesAsync(temporaryPath, encrypted);
|
|
File.Move(temporaryPath, _filePath, true);
|
|
}
|
|
}
|