From 2515eb578163b6998a8fc763821351477110ccce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com>
Date: Fri, 19 Jun 2026 19:49:03 +0800
Subject: [PATCH] =?UTF-8?q?Config=20=E5=BA=8F=E5=88=97=E5=8C=96=E8=B0=83?=
=?UTF-8?q?=E6=95=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Shared/General/Config.cs | 68 +++++++++++++++++--------------------
Tests/General/ConfigTest.cs | 36 --------------------
2 files changed, 32 insertions(+), 72 deletions(-)
delete mode 100644 Tests/General/ConfigTest.cs
diff --git a/Shared/General/Config.cs b/Shared/General/Config.cs
index 88f320a..59a3ed6 100644
--- a/Shared/General/Config.cs
+++ b/Shared/General/Config.cs
@@ -8,15 +8,15 @@ public interface IConfigProvider {
/// 将数据写入缓存。
/// 这不会写入数据,还需要调用 以保存。
///
- void SetToCache(string key, string? value, bool encrypted = false);
+ void SetToCache(string key, string? value, bool encrypted);
///
/// 将指定数据从缓存中移除。
/// 这不会写入数据,还需要调用 以保存。
///
void RemoveFromCache(string key);
- string? Read(string key, string? defaultValue = null, bool encrypted = false);
+ string? Read(string key, string? defaultValue, bool encrypted);
bool HasValue(string key);
- void ClearCache();
+ void DiscardCache();
void Save();
}
@@ -29,40 +29,37 @@ public class JsonConfigProvider : IConfigProvider {
ResetContent();
}
- ///
- /// 读取到的原始内容。
- ///
- public Lazy Content { get; private set; }
+ private Lazy content;
private void ResetContent() {
- Content = new(() => {
+ content = new(() => {
try {
return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
} catch (Exception ex) {
- Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Toast);
+ Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Alert);
return [];
}
});
}
- public void SetToCache(string key, string? value, bool encrypted = false) {
+ public void SetToCache(string key, string? value, bool encrypted) {
if (encrypted) {
- Content.Value[key] = CryptographyUtils.AesEncrypt(value); // UNDONE: 改为识别码
+ content.Value[key] = CryptographyUtils.AesEncrypt(value); // UNDONE: 改为识别码
decryptedContentCache[key] = value;
} else {
- Content.Value[key] = value;
+ content.Value[key] = value;
}
}
- public string? Read(string key, string? defaultValue = null, bool encrypted = false) {
- if (!Content.Value.ContainsKey(key)) return defaultValue;
+ public string? Read(string key, string? defaultValue, bool encrypted) {
if (encrypted && decryptedContentCache.TryGetValue(key, out var cachedValue)) return cachedValue; // 读取缓存中已经解密的值
- // 读取值
- string? value = Content.Value[key]?.ToString();
- if (!encrypted) return value;
- // 解密读取的数据
try {
- return decryptedContentCache.GetOrAdd(key, _ => CryptographyUtils.AesDecrypt(value));
+ if (!content.Value.TryGetValue(key, out var result)) return defaultValue;
+ if (encrypted) { // 解密
+ result = CryptographyUtils.AesDecrypt(result?.ToString());
+ decryptedContentCache.TryAdd(key, result?.ToString());
+ }
+ return result?.ToString();
} catch (CryptographicException ex) {
- Logger.Error(ex, $"解密配置失败({key})", LogBehavior.Toast);
+ Logger.Error(ex, $"解密配置失败,该配置将被重置({key})", LogBehavior.Alert);
RemoveFromCache(key);
Save();
return defaultValue;
@@ -70,37 +67,38 @@ public class JsonConfigProvider : IConfigProvider {
}
public bool HasValue(string key)
- => Content.Value.ContainsKey(key);
+ => content.Value.ContainsKey(key);
public void RemoveFromCache(string key) {
- Content.Value.Remove(key);
+ content.Value.Remove(key);
decryptedContentCache.TryRemove(key, out _);
}
- public void ClearCache() {
+ public void DiscardCache() {
ResetContent();
decryptedContentCache.Clear();
}
public void Save()
- => FileUtils.Write(filePath, Content.Value.ToString(Formatting.Indented));
+ => FileUtils.Write(filePath, content.Value.ToString(Formatting.Indented));
}
-public static class Configs {
+public static class ConfigUtils {
public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
///
/// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
///
- public static string GetSecret(string key) => secret.Read(key)?.ToString() ?? throw new KeyNotFoundException($"Secret not found: {key}");
+ public static string GetSecret(string key)
+ => secret.Read(key, null, false)?.ToString() ?? throw new KeyNotFoundException($"Secret not found: {key}");
private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
}
-public class ConfigEntry(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) where T : IEquatable {
+public class ConfigEntry(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
private IConfigProvider GetProvider(IConfigProvider? provider)
- => provider ?? defaultProvider ?? Configs.AppData;
+ => provider ?? defaultProvider ?? ConfigUtils.AppData;
///
/// 当设置项的值实际被改变时触发,参数为新值。
///
- public event Action? OnChanged;
+ public event Action? Changed;
public T? Get(IConfigProvider? providerOverride = null) {
var provider = GetProvider(providerOverride);
@@ -108,10 +106,7 @@ public class ConfigEntry(string key, T? defaultValue, IConfigProvider? defaul
string? value = provider.Read(key, defaultValue?.ToString(), encrypted);
try {
if (value is null) return default;
- var type = typeof(T);
- if (type == typeof(string)) return (T) (object) value;
- if (typeof(JToken).IsAssignableFrom(type)) return (T) (object) value.DeserializeJson()!;
- return (T) Convert.ChangeType(value, type);
+ return typeof(T) == typeof(string) ? ((T) (object) value) : JsonConvert.DeserializeObject(value);
} catch (Exception ex) {
Logger.Error(ex, $"读取配置项失败({key})", LogBehavior.Toast);
return defaultValue;
@@ -121,9 +116,10 @@ public class ConfigEntry(string key, T? defaultValue, IConfigProvider? defaul
var provider = GetProvider(providerOverride);
T? current = Get(provider);
if ((current is null && value is null) || (current is not null && value is not null && current.Equals(value))) return; // 值未改变,无需更新
- provider.SetToCache(key, value?.ToString(), encrypted);
+ provider.SetToCache(key,
+ typeof(T) == typeof(string) ? (value as string) : JsonConvert.SerializeObject(value), encrypted);
provider.Save();
- OnChanged?.Invoke(value);
+ Changed?.Invoke(value);
}
public bool HasValue(IConfigProvider? providerOverride = null) {
var provider = GetProvider(providerOverride);
@@ -134,7 +130,7 @@ public class ConfigEntry(string key, T? defaultValue, IConfigProvider? defaul
if (!provider.HasValue(key)) return; // 值未设置,无需重置
provider.RemoveFromCache(key);
provider.Save();
- OnChanged?.Invoke(defaultValue);
+ Changed?.Invoke(defaultValue);
}
public void Save(IConfigProvider? providerOverride = null) {
var provider = GetProvider(providerOverride);
diff --git a/Tests/General/ConfigTest.cs b/Tests/General/ConfigTest.cs
deleted file mode 100644
index 7b24323..0000000
--- a/Tests/General/ConfigTest.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-namespace MeloongCore.Tests;
-
-public class ConfigTest : TestWithFolder {
-
- [Test]
- public async Task JsonConfigProvider_EncryptedReadWrite() {
- var filePath = Path.Combine(tempFolder, "config.json");
- var provider = new JsonConfigProvider(filePath);
-
- provider.SetToCache("token", "plain token", encrypted: true);
- provider.Save();
-
- await Assert.That(FileUtils.ReadAsString(filePath).Contains("plain token")).IsFalse();
- await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("plain token");
- await Assert.That(provider.DecryptedContent.TryGetValue("token", out var decrypted) && decrypted == "plain token").IsTrue();
- }
-
- [Test]
- public async Task JsonConfigProvider_ClearCache() {
- var filePath = Path.Combine(tempFolder, "config.json");
- var provider = new JsonConfigProvider(filePath);
-
- provider.SetToCache("token", "old token", encrypted: true);
- provider.Save();
- await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("old token");
-
- var secondProvider = new JsonConfigProvider(filePath);
- secondProvider.SetToCache("token", "new token", encrypted: true);
- secondProvider.Save();
- provider.ClearCache();
-
- await Assert.That(provider.DecryptedContent.IsEmpty).IsTrue();
- await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("new token");
- }
-
-}