LANCommander/LANCommander.Server.Services/SettingService.cs

89 lines
2.6 KiB
C#
Raw Permalink Normal View History

2024-08-04 18:44:33 -05:00
using LANCommander.Server.Models;
2025-06-21 23:16:18 +02:00
using Microsoft.Extensions.DependencyInjection;
2023-01-09 18:58:27 -06:00
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
2024-08-04 18:44:33 -05:00
namespace LANCommander.Server.Services
2023-01-09 18:58:27 -06:00
{
public class SettingService
{
2025-03-07 20:44:32 -06:00
public static string WorkingDirectory { get; set; } = "";
private const string FileName = "Settings.yml";
public static string SettingsFile
{
get
{
if (!string.IsNullOrWhiteSpace(WorkingDirectory))
return Path.Combine(WorkingDirectory, FileName);
else
return FileName;
}
}
2023-01-09 18:58:27 -06:00
2024-10-07 18:38:27 -05:00
private static Models.Settings Settings { get; set; }
2024-10-07 18:38:27 -05:00
public static Models.Settings LoadSettings()
2023-01-09 18:58:27 -06:00
{
2025-03-07 20:44:32 -06:00
if (File.Exists(SettingsFile))
2023-01-09 18:58:27 -06:00
{
2025-03-07 20:44:32 -06:00
var contents = File.ReadAllText(SettingsFile);
2023-01-09 18:58:27 -06:00
var deserializer = new DeserializerBuilder()
.IgnoreUnmatchedProperties()
2025-06-21 23:16:18 +02:00
.WithNamingConvention(PascalCaseNamingConvention.Instance)
2023-01-09 18:58:27 -06:00
.Build();
2024-10-07 18:38:27 -05:00
Settings = deserializer.Deserialize<Models.Settings>(contents);
2023-01-09 18:58:27 -06:00
}
else
{
2024-10-07 18:38:27 -05:00
Settings = new Models.Settings();
SaveSettings(Settings);
}
return Settings;
}
2025-06-21 23:16:18 +02:00
public static void WriteSettings(Models.Settings settings)
{
if (settings == null)
return;
var serializer = new SerializerBuilder()
.WithNamingConvention(PascalCaseNamingConvention.Instance)
.Build();
File.WriteAllText(SettingsFile, serializer.Serialize(settings));
}
2024-10-07 18:38:27 -05:00
public static Models.Settings GetSettings(bool forceLoad = false)
{
if (Settings == null || forceLoad)
Settings = LoadSettings();
return Settings;
2023-01-09 18:58:27 -06:00
}
2025-06-21 23:16:18 +02:00
public static void SaveSettings(Models.Settings settings, IServiceProvider? serviceProvider = null)
2023-01-09 18:58:27 -06:00
{
2025-06-21 23:16:18 +02:00
WriteSettings(settings);
Settings = settings;
ReloadSettings(settings, serviceProvider);
}
2023-01-09 18:58:27 -06:00
2025-06-21 23:16:18 +02:00
private static void ReloadSettings(Models.Settings settings, IServiceProvider? serviceProvider)
{
if (serviceProvider == null || settings == null)
return;
2025-06-21 23:16:18 +02:00
if (serviceProvider.GetService<UserService>() is var service)
{
service!.Reconfigure(settings);
}
2023-01-09 18:58:27 -06:00
}
}
}