Config.cs 2.4 KB

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