Config.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. using System.Collections.Concurrent;
  2. using System.Security.Cryptography;
  3. namespace MeloongCore;
  4. public interface IConfigProvider {
  5. /// <summary>
  6. /// 将数据写入缓存。
  7. /// <para/> 这不会写入数据,还需要调用 <see cref="Save"/> 以保存。
  8. /// </summary>
  9. void SetToCache(string key, string? value, bool encrypted);
  10. /// <summary>
  11. /// 将指定数据从缓存中移除。
  12. /// <para/> 这不会写入数据,还需要调用 <see cref="Save"/> 以保存。
  13. /// </summary>
  14. void RemoveFromCache(string key);
  15. string? Read(string key, string? defaultValue, bool encrypted);
  16. bool HasValue(string key);
  17. void DiscardCache();
  18. void Save();
  19. }
  20. public class JsonConfigProvider : IConfigProvider {
  21. private readonly string filePath;
  22. private readonly ConcurrentDictionary<string, string?> decryptedContentCache = new();
  23. public JsonConfigProvider(string filePath) {
  24. this.filePath = filePath;
  25. ResetContent();
  26. }
  27. private Lazy<JObject> content;
  28. private void ResetContent() {
  29. content = new(() => {
  30. try {
  31. return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
  32. } catch (Exception ex) {
  33. Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Alert);
  34. return [];
  35. }
  36. });
  37. }
  38. public void SetToCache(string key, string? value, bool encrypted) {
  39. if (encrypted) {
  40. content.Value[key] = CryptographyUtils.AesEncrypt(value); // UNDONE: 改为识别码
  41. decryptedContentCache[key] = value;
  42. } else {
  43. content.Value[key] = value;
  44. }
  45. }
  46. public string? Read(string key, string? defaultValue, bool encrypted) {
  47. if (encrypted && decryptedContentCache.TryGetValue(key, out var cachedValue)) return cachedValue; // 读取缓存中已经解密的值
  48. try {
  49. if (!content.Value.TryGetValue(key, out var result)) return defaultValue;
  50. if (encrypted) { // 解密
  51. result = CryptographyUtils.AesDecrypt(result?.ToString());
  52. decryptedContentCache.TryAdd(key, result?.ToString());
  53. }
  54. return result?.ToString();
  55. } catch (CryptographicException ex) {
  56. Logger.Error(ex, $"解密配置失败,该配置将被重置({key})", LogBehavior.Alert);
  57. RemoveFromCache(key);
  58. Save();
  59. return defaultValue;
  60. }
  61. }
  62. public bool HasValue(string key)
  63. => content.Value.ContainsKey(key);
  64. public void RemoveFromCache(string key) {
  65. content.Value.Remove(key);
  66. decryptedContentCache.TryRemove(key, out _);
  67. }
  68. public void DiscardCache() {
  69. ResetContent();
  70. decryptedContentCache.Clear();
  71. }
  72. public void Save()
  73. => FileUtils.Write(filePath, content.Value.ToString(Formatting.Indented));
  74. }
  75. public static class ConfigUtils {
  76. public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
  77. /// <summary>
  78. /// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
  79. /// </summary>
  80. public static string GetSecret(string key)
  81. => secret.Read(key, null, false)?.ToString() ?? throw new KeyNotFoundException($"Secret not found: {key}");
  82. private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
  83. }
  84. public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
  85. private IConfigProvider GetProvider(IConfigProvider? provider)
  86. => provider ?? defaultProvider ?? ConfigUtils.AppData;
  87. /// <summary>
  88. /// 当设置项的值实际被改变时触发,参数为新值。
  89. /// </summary>
  90. public event Action<T?>? Changed;
  91. public T? Get(IConfigProvider? providerOverride = null) {
  92. var provider = GetProvider(providerOverride);
  93. if (!provider.HasValue(key)) return defaultValue;
  94. string? value = provider.Read(key, defaultValue?.ToString(), encrypted);
  95. try {
  96. if (value is null) return default;
  97. return typeof(T) == typeof(string) ? ((T) (object) value) : JsonConvert.DeserializeObject<T>(value);
  98. } catch (Exception ex) {
  99. Logger.Error(ex, $"读取配置项失败({key})", LogBehavior.Toast);
  100. return defaultValue;
  101. }
  102. }
  103. public void Set(T? value, IConfigProvider? providerOverride = null) {
  104. var provider = GetProvider(providerOverride);
  105. T? current = Get(provider);
  106. if ((current is null && value is null) || (current is not null && value is not null && current.Equals(value))) return; // 值未改变,无需更新
  107. provider.SetToCache(key,
  108. typeof(T) == typeof(string) ? (value as string) : JsonConvert.SerializeObject(value), encrypted);
  109. provider.Save();
  110. Changed?.Invoke(value);
  111. }
  112. public bool HasValue(IConfigProvider? providerOverride = null) {
  113. var provider = GetProvider(providerOverride);
  114. return provider.HasValue(key);
  115. }
  116. public void Reset(IConfigProvider? providerOverride = null) {
  117. var provider = GetProvider(providerOverride);
  118. if (!provider.HasValue(key)) return; // 值未设置,无需重置
  119. provider.RemoveFromCache(key);
  120. provider.Save();
  121. Changed?.Invoke(defaultValue);
  122. }
  123. public void Save(IConfigProvider? providerOverride = null) {
  124. var provider = GetProvider(providerOverride);
  125. provider.Save();
  126. }
  127. }