Repository navigation
Expand file tree
/
Copy pathPluginStateStore.cs
More file actions
79 lines (66 loc) · 2.39 KB
/
Copy pathPluginStateStore.cs
File metadata and controls
79 lines (66 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.Text.Json;
namespace SecRandom.ExamplePlugin;
/// <summary>
/// 演示插件的运行时状态。
/// </summary>
public sealed class PluginState
{
/// <summary>插件被加载的次数。</summary>
public int LoadCount { get; set; }
/// <summary>最近一次写入状态的时间。</summary>
public DateTimeOffset? LastUpdated { get; set; }
/// <summary>最近一次操作留下的说明,便于在设置页展示。</summary>
public string LastMessage { get; set; } = string.Empty;
}
/// <summary>
/// 演示如何在插件的专属配置目录中读写自己的数据。
/// <para>
/// <see cref="SecRandom.Core.Plugins.PluginBase.PluginConfigFolder" /> 由宿主在加载插件时创建,
/// 每个插件一个目录,通常位于 <c>data/config/plugins/<插件 id></c>。
/// 插件不应把数据写到主程序目录的其他位置。
/// </para>
/// </summary>
public sealed class PluginStateStore
{
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
private readonly string _filePath;
private readonly object _gate = new();
public PluginStateStore(string configFolder)
{
_filePath = Path.Combine(configFolder, "state.json");
}
/// <summary>状态文件的绝对路径,便于在设置页展示,方便排查问题。</summary>
public string FilePath => _filePath;
public PluginState Load()
{
lock (_gate)
{
try
{
if (!File.Exists(_filePath))
return new PluginState();
var json = File.ReadAllText(_filePath);
return JsonSerializer.Deserialize<PluginState>(json, SerializerOptions) ?? new PluginState();
}
catch (Exception)
{
// 状态文件损坏不影响插件加载,退回默认值。
return new PluginState();
}
}
}
public void Save(PluginState state)
{
lock (_gate)
{
state.LastUpdated = DateTimeOffset.Now;
var directory = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllText(_filePath, JsonSerializer.Serialize(state, SerializerOptions));
}
}
}