Newsbot.Cli/Newsbot.Services/ConfigClient.cs

55 lines
1.5 KiB
C#

using System.Text.Json;
using jtom38.Newsbot.Domain.Models;
namespace jtom38.Newsbot.Services;
public static class ConfigClient
{
public static async Task<ConfigModel> LoadAsync()
{
var blank = new ConfigModel();
try
{
var cfg = await LoadFileAsync();
return cfg;
}
catch (DirectoryNotFoundException)
{
Directory.CreateDirectory(GetConfigPath());
await SaveAsync(blank);
return blank;
}
catch (FileNotFoundException)
{
await SaveAsync(blank);
return blank;
}
}
public static async Task SaveAsync(ConfigModel config)
{
var jsonString = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true});
await File.WriteAllTextAsync(GetConfigPath(), jsonString);
}
private static string GetConfigDirectory()
{
var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var path = Path.Join(appDataPath, "newsbot-cli");
return path;
}
private static string GetConfigPath()
{
var path = Path.Join(GetConfigDirectory(), "config.json");
return path;
}
private static async Task<ConfigModel> LoadFileAsync()
{
var content = await File.ReadAllTextAsync(GetConfigPath());
var res = JsonSerializer.Deserialize<ConfigModel>(content);
return res ?? new ConfigModel();
}
}