Config.cs 6.5 KB

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