2021-10-14 04:46:43 +00:00
|
|
|
using System;
|
|
|
|
using System.IO;
|
|
|
|
using System.Text.Json;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using Wabbajack.Common;
|
|
|
|
using Wabbajack.DTOs.JsonConverters;
|
|
|
|
using Wabbajack.Paths;
|
|
|
|
using Wabbajack.Paths.IO;
|
|
|
|
|
2021-11-10 23:04:57 +00:00
|
|
|
namespace Wabbajack.App.Models;
|
2021-10-14 04:46:43 +00:00
|
|
|
|
|
|
|
public class SettingsManager
|
|
|
|
{
|
|
|
|
private readonly Configuration _configuration;
|
|
|
|
private readonly DTOSerializer _dtos;
|
|
|
|
private readonly ILogger<SettingsManager> _logger;
|
|
|
|
|
|
|
|
public SettingsManager(ILogger<SettingsManager> logger, Configuration configuration, DTOSerializer dtos)
|
|
|
|
{
|
|
|
|
_logger = logger;
|
|
|
|
_dtos = dtos;
|
|
|
|
_configuration = configuration;
|
|
|
|
_configuration.SavedSettingsLocation.CreateDirectory();
|
|
|
|
}
|
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
private AbsolutePath GetPath(string key)
|
|
|
|
{
|
|
|
|
return _configuration.SavedSettingsLocation.Combine(key).WithExtension(Ext.Json);
|
|
|
|
}
|
2021-10-14 04:46:43 +00:00
|
|
|
|
|
|
|
public async Task Save<T>(string key, T value)
|
|
|
|
{
|
|
|
|
var tmp = GetPath(key).WithExtension(Ext.Temp);
|
|
|
|
await using (var s = tmp.Open(FileMode.Create, FileAccess.Write))
|
|
|
|
{
|
2021-11-10 23:04:57 +00:00
|
|
|
await JsonSerializer.SerializeAsync(s, value, _dtos.Options);
|
2021-10-14 04:46:43 +00:00
|
|
|
}
|
2021-10-23 16:51:17 +00:00
|
|
|
|
2021-10-14 04:46:43 +00:00
|
|
|
await tmp.MoveToAsync(GetPath(key), true, CancellationToken.None);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T> Load<T>(string key)
|
2021-10-23 16:51:17 +00:00
|
|
|
where T : new()
|
2021-10-14 04:46:43 +00:00
|
|
|
{
|
|
|
|
var path = GetPath(key);
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (path.FileExists())
|
2021-11-03 05:03:41 +00:00
|
|
|
{
|
2021-10-15 04:20:27 +00:00
|
|
|
await using (var s = path.Open(FileMode.Open))
|
2021-10-14 04:46:43 +00:00
|
|
|
{
|
2021-10-15 04:20:27 +00:00
|
|
|
return (await JsonSerializer.DeserializeAsync<T>(s, _dtos.Options))!;
|
2021-10-14 04:46:43 +00:00
|
|
|
}
|
2021-11-03 05:03:41 +00:00
|
|
|
}
|
2021-10-14 04:46:43 +00:00
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
_logger.LogWarning(ex, "Loading settings {Key}", key);
|
|
|
|
}
|
|
|
|
|
|
|
|
return new T();
|
|
|
|
}
|
|
|
|
}
|