165 lines
6.4 KiB
C#
165 lines
6.4 KiB
C#
using System.Security.Cryptography;
|
||
|
||
namespace MeloongCore;
|
||
|
||
public interface IConfigProvider {
|
||
void Set<T>(string key, T? value, bool encrypted);
|
||
void Remove(string key);
|
||
T? Read<T>(string key, T? defaultValue, bool encrypted);
|
||
bool HasValue(string key);
|
||
void DiscardCache();
|
||
void MakeDirty();
|
||
void Save();
|
||
}
|
||
|
||
public class JsonConfigProvider : IConfigProvider {
|
||
public static readonly ConcurrentBag<WeakReference<JsonConfigProvider>> allProviders = [];
|
||
private readonly string filePath;
|
||
|
||
public JsonConfigProvider(string filePath) {
|
||
this.filePath = filePath;
|
||
allProviders.Add(new(this));
|
||
saveAction = Throttler.Throttle(Save, TimeSpan.FromMilliseconds(500), leading: false, trailing: true);
|
||
InitJson();
|
||
}
|
||
|
||
// 原始文件缓存
|
||
private Lazy<JObject> json;
|
||
// 反序列化后的结果缓存
|
||
private readonly ConcurrentDictionary<string, object?> cache = new();
|
||
private void InitJson() {
|
||
json = new(() => {
|
||
try {
|
||
return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
|
||
} catch (Exception ex) {
|
||
Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Alert);
|
||
return [];
|
||
}
|
||
});
|
||
}
|
||
|
||
// ================================= 设置、读取、缓存 =================================
|
||
|
||
public void Set<T>(string key, T? value, bool encrypted) {
|
||
cache[key] = value;
|
||
lock (json) {
|
||
if (value is null) {
|
||
// 直接在 JSON 中表示为 null
|
||
json.Value[key] = JValue.CreateNull();
|
||
} else if (encrypted) {
|
||
// 需要加密,在 JSON 中保存密文字符串
|
||
throw new NotImplementedException("加密需要改为使用识别码,现在尚未实现。");
|
||
json.Value[key] = CryptographyUtils.AesEncrypt(value is string str ? str : JsonConvert.SerializeObject(value));
|
||
} else {
|
||
// 用 JToken 保留原始结构
|
||
json.Value[key] = JToken.FromObject(value);
|
||
}
|
||
}
|
||
MakeDirty();
|
||
}
|
||
public T? Read<T>(string key, T? defaultValue, bool encrypted) {
|
||
if (cache.TryGetValue(key, out var cachedValue)) return (T?) cachedValue; // 读取缓存
|
||
JToken entry;
|
||
lock (json) {
|
||
if (!json.Value.TryGetValue(key, out entry!)) return defaultValue; // 未找到该键
|
||
entry = entry.DeepClone();
|
||
}
|
||
try {
|
||
T? result;
|
||
if (entry.Type is JTokenType.Null or JTokenType.Undefined) {
|
||
result = default;
|
||
} else if (encrypted) {
|
||
string plainText = CryptographyUtils.AesDecrypt(entry.Value<string>())!;
|
||
result = typeof(T) == typeof(string) ? (T) (object) plainText : JsonConvert.DeserializeObject<T>(plainText);
|
||
} else {
|
||
result = entry.ToObject<T>();
|
||
}
|
||
cache[key] = result;
|
||
return result;
|
||
} catch (CryptographicException ex) {
|
||
Logger.Error(ex, $"解密配置失败,该配置将被重置({key})", LogBehavior.Alert);
|
||
Remove(key);
|
||
return defaultValue;
|
||
}
|
||
}
|
||
|
||
public bool HasValue(string key) {
|
||
lock (json) return json.Value.ContainsKey(key);
|
||
}
|
||
public void Remove(string key) {
|
||
lock (json) json.Value.Remove(key);
|
||
cache.TryRemove(key, out _);
|
||
MakeDirty();
|
||
}
|
||
public void DiscardCache() {
|
||
lock (json) InitJson();
|
||
cache.Clear();
|
||
}
|
||
|
||
// ===================================== 保存 =====================================
|
||
|
||
private readonly RateLimitedAction saveAction;
|
||
public void MakeDirty() => saveAction.Invoke();
|
||
public void Save() {
|
||
lock (json) FileUtils.Write(filePath, json.Value.ToString(Formatting.Indented));
|
||
}
|
||
}
|
||
|
||
public static class ConfigUtils {
|
||
public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
|
||
|
||
/// <summary>
|
||
/// 立即保存所有配置。
|
||
/// </summary>
|
||
public static void SaveAll() {
|
||
foreach (var weakRef in JsonConfigProvider.allProviders) {
|
||
if (weakRef.TryGetTarget(out var provider)) provider.Save();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
|
||
/// </summary>
|
||
public static string GetSecret(string key)
|
||
=> secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"Secret not found: {key}");
|
||
private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
|
||
}
|
||
|
||
public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
|
||
|
||
public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
|
||
/// <summary>
|
||
/// 当设置项的值被改变时触发,参数为新值。新值可能和旧值相同。
|
||
/// </summary>
|
||
public event Action<T?, IConfigProvider>? Changed;
|
||
|
||
public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) {
|
||
var provider = providerOverride ?? DefaultProvider;
|
||
Set(editFunc(Get(provider)), provider);
|
||
}
|
||
public void Edit(RefAction editAction, IConfigProvider? providerOverride = null) {
|
||
var provider = providerOverride ?? DefaultProvider;
|
||
var current = Get(provider);
|
||
editAction(ref current);
|
||
Set(current, provider);
|
||
}
|
||
public delegate void RefAction(ref T? value);
|
||
|
||
public void Set(T? value, IConfigProvider? providerOverride = null) {
|
||
var provider = providerOverride ?? DefaultProvider;
|
||
provider.Set(key, value, encrypted);
|
||
Changed?.Invoke(value, provider);
|
||
}
|
||
public void Reset(IConfigProvider? providerOverride = null) {
|
||
var provider = providerOverride ?? DefaultProvider;
|
||
if (!provider.HasValue(key)) return; // 值未设置,无需重置
|
||
provider.Remove(key);
|
||
Changed?.Invoke(defaultValue, provider);
|
||
}
|
||
public T? Get(IConfigProvider? providerOverride = null)
|
||
=> (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted);
|
||
public bool HasValue(IConfigProvider? providerOverride = null)
|
||
=> (providerOverride ?? DefaultProvider).HasValue(key);
|
||
public static implicit operator T?(ConfigEntry<T> entry) => entry.Get();
|
||
}
|