Config.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. namespace MeloongCore;
  2. public interface IConfigProvider {
  3. void Write(string key, JToken value);
  4. JToken? Read(string key, JToken? defaultValue = null);
  5. bool HasValue(string key);
  6. void Remove(string key);
  7. void Save();
  8. }
  9. public class JsonConfigProvider(string filePath) : IConfigProvider {
  10. public readonly Lazy<JObject> Content = new(() => {
  11. try {
  12. return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
  13. } catch (Exception ex) {
  14. Logger.Error(ex, $"读取配置文件失败:{filePath}", LogBehavior.Toast);
  15. return [];
  16. }
  17. });
  18. public void Write(string key, JToken value)
  19. => Content.Value[key] = value;
  20. public JToken? Read(string key, JToken? defaultValue = null)
  21. => Content.Value.TryGetValue(key, out var value) ? value : defaultValue;
  22. public bool HasValue(string key)
  23. => Content.Value.ContainsKey(key);
  24. public void Remove(string key)
  25. => Content.Value.Remove(key);
  26. public void Save()
  27. => FileUtils.Write(filePath, Content.Value.ToString(Formatting.Indented));
  28. }
  29. public static class Configs {
  30. public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
  31. /// <summary>
  32. /// 从 secret.json 中读取特定密钥,如果不存在则抛出异常。
  33. /// </summary>
  34. public static string GetSecret(string key) => secret.Read(key)?.ToString() ?? throw new KeyNotFoundException($"Secret not found: {key}");
  35. private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
  36. }
  37. public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
  38. private readonly IConfigProvider defaultProvider = defaultProvider ?? Configs.AppData;
  39. public string Key = key;
  40. public bool Encrypted = encrypted;
  41. public T? DefaultValue = defaultValue;
  42. /// <summary>
  43. /// 当设置项的值实际被改变时触发,参数为新值。
  44. /// </summary>
  45. public event Action<T?>? OnChanged;
  46. public bool HasValue(IConfigProvider? provider = null)
  47. => (provider ?? defaultProvider).HasValue(Key);
  48. public void Remove(IConfigProvider? provider = null)
  49. => (provider ?? defaultProvider).Remove(Key);
  50. public void Save(IConfigProvider? provider = null)
  51. => (provider ?? defaultProvider).Save();
  52. }