Config.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System.Security.Cryptography;
  2. namespace MeloongCore;
  3. public interface IConfigProvider {
  4. void Set<T>(string key, T? value, bool encrypted);
  5. void Remove(string key);
  6. T? Read<T>(string key, T? defaultValue, bool encrypted);
  7. bool HasValue(string key);
  8. void DiscardCache();
  9. }
  10. public class JsonConfigProvider : IConfigProvider {
  11. public static readonly ConcurrentBag<WeakReference<JsonConfigProvider>> allProviders = [];
  12. private readonly string filePath;
  13. #pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
  14. public JsonConfigProvider(string filePath) {
  15. #pragma warning restore CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
  16. this.filePath = filePath;
  17. allProviders.Add(new(this));
  18. saveAction = Throttler.Throttle(Save, TimeSpan.FromMilliseconds(500), leading: false, trailing: true);
  19. InitJson();
  20. }
  21. // 原始文件缓存
  22. private Lazy<JObject> json;
  23. // 反序列化后的结果缓存
  24. private readonly ConcurrentDictionary<string, object?> cache = new();
  25. private void InitJson() {
  26. json = new(() => {
  27. try {
  28. return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
  29. } catch (Exception ex) {
  30. Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Alert);
  31. return [];
  32. }
  33. });
  34. }
  35. // ================================= 设置、读取、缓存 =================================
  36. public void Set<T>(string key, T? value, bool encrypted) {
  37. cache[key] = value;
  38. lock (this) {
  39. if (value is null) {
  40. // 直接在 JSON 中表示为 null
  41. json.Value[key] = JValue.CreateNull();
  42. Logger.Trace($"配置已修改:{key} = null({filePath})");
  43. } else if (encrypted) {
  44. // 需要加密,在 JSON 中保存密文字符串
  45. throw new NotImplementedException("加密需要改为使用识别码,现在尚未实现。");
  46. // Logger.Trace($"配置已修改:{key} = 已加密({filePath})");
  47. // json.Value[key] = CryptographyUtils.AesEncrypt(value is string str ? str : JsonConvert.SerializeObject(value));
  48. } else {
  49. // 用 JToken 保留原始结构
  50. JToken token = JToken.FromObject(value);
  51. json.Value[key] = token;
  52. Logger.Trace($"配置已修改:{key} = {token.ToString(Formatting.None)}({filePath})");
  53. }
  54. }
  55. MakeDirty();
  56. }
  57. public T? Read<T>(string key, T? defaultValue, bool encrypted) {
  58. if (cache.TryGetValue(key, out var cachedValue)) return (T?) cachedValue; // 读取缓存
  59. JToken entry;
  60. lock (this) {
  61. if (!json.Value.TryGetValue(key, out entry!)) return defaultValue; // 未找到该键
  62. entry = entry.DeepClone();
  63. }
  64. try {
  65. T? result;
  66. if (entry.Type is JTokenType.Null or JTokenType.Undefined) {
  67. result = default;
  68. } else if (encrypted) {
  69. string plainText = CryptographyUtils.AesDecrypt(entry.Value<string>())!;
  70. result = typeof(T) == typeof(string) ? (T) (object) plainText : JsonConvert.DeserializeObject<T>(plainText);
  71. } else {
  72. result = entry.ToObject<T>();
  73. }
  74. cache[key] = result;
  75. return result;
  76. } catch (CryptographicException ex) {
  77. Logger.Error(ex, $"解密配置失败,该配置将被重置({key})", LogBehavior.Alert);
  78. Remove(key);
  79. return defaultValue;
  80. }
  81. }
  82. public bool HasValue(string key) {
  83. lock (this) return json.Value.ContainsKey(key);
  84. }
  85. public void Remove(string key) {
  86. lock (this) json.Value.Remove(key);
  87. cache.TryRemove(key, out _);
  88. MakeDirty();
  89. }
  90. public void DiscardCache() {
  91. lock (this) InitJson();
  92. cache.Clear();
  93. }
  94. // ===================================== 保存 =====================================
  95. private readonly RateLimitedAction saveAction;
  96. private bool isDirty = false;
  97. public void MakeDirty() {
  98. isDirty = true;
  99. saveAction.Invoke();
  100. }
  101. public void Save() {
  102. if (!isDirty) return;
  103. isDirty = false;
  104. lock (this) FileUtils.Write(filePath, json.Value.ToString(Formatting.Indented));
  105. }
  106. }
  107. public static class ConfigUtils {
  108. public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
  109. /// <summary>
  110. /// 立即保存所有配置。
  111. /// </summary>
  112. public static void SaveAll() {
  113. foreach (var weakRef in JsonConfigProvider.allProviders) {
  114. if (weakRef.TryGetTarget(out var provider)) provider.Save();
  115. }
  116. }
  117. /// <summary>
  118. /// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
  119. /// </summary>
  120. public static string GetSecret(string key)
  121. => secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
  122. private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
  123. }
  124. public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
  125. public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
  126. /// <summary>
  127. /// 当设置项的值被改变时触发,参数为新值。新值可能和旧值相同。
  128. /// </summary>
  129. public event Action<T?, IConfigProvider>? Changed;
  130. public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) {
  131. var provider = providerOverride ?? DefaultProvider;
  132. Set(editFunc(Get(provider)), provider);
  133. }
  134. public void Edit(RefAction editAction, IConfigProvider? providerOverride = null) {
  135. var provider = providerOverride ?? DefaultProvider;
  136. var current = Get(provider);
  137. editAction(ref current);
  138. Set(current, provider);
  139. }
  140. public delegate void RefAction(ref T? value);
  141. public void Set(T? value, IConfigProvider? providerOverride = null) {
  142. var provider = providerOverride ?? DefaultProvider;
  143. provider.Set(key, value, encrypted);
  144. Changed?.Invoke(value, provider);
  145. }
  146. public void Reset(IConfigProvider? providerOverride = null) {
  147. var provider = providerOverride ?? DefaultProvider;
  148. if (!provider.HasValue(key)) return; // 值未设置,无需重置
  149. provider.Remove(key);
  150. Changed?.Invoke(defaultValue, provider);
  151. }
  152. public T? Get(IConfigProvider? providerOverride = null)
  153. => (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted);
  154. public bool HasValue(IConfigProvider? providerOverride = null)
  155. => (providerOverride ?? DefaultProvider).HasValue(key);
  156. public static implicit operator T?(ConfigEntry<T> entry) => entry.Get();
  157. }