Skip to content

Commit db2d037

Browse files
committed
refactor: 更改名称为 AppContext
1 parent 89a8127 commit db2d037

File tree

11 files changed

+64
-63
lines changed

11 files changed

+64
-63
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
namespace CSharpOpenBMCLAPI.Modules
22
{
3-
public class PublicData(ClusterInfo info)
3+
public class AppContext(ClusterInfo info)
44
{
55
public static Config Config { get; set; } = new Config();
66
public Logger Logger => Logger.Instance;

CSharp-OpenBMCLAPI/Modules/Cluster.cs

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public class Cluster
3636
internal readonly IStorage storage;
3737
protected AccessCounter counter;
3838
public readonly CancellationTokenSource cancellationSrc = new();
39-
internal PublicData requiredData;
39+
internal AppContext context;
4040
private List<ApiFileInfo> files;
4141
private WebApplication? application;
4242

@@ -45,22 +45,22 @@ public class Cluster
4545
/// <summary>
4646
/// 构造函数,实际上 <seealso cref="Exception"/> 根本不可能被抛出
4747
/// </summary>
48-
/// <param name="requiredData"></param>
48+
/// <param name="context"></param>
4949
/// <exception cref="Exception"></exception>
50-
public Cluster(PublicData requiredData)
50+
public Cluster(AppContext context)
5151
{
52-
this.requiredData = requiredData;
53-
this.clusterInfo = requiredData.ClusterInfo;
54-
this.token = requiredData.Token;
52+
this.context = context;
53+
this.clusterInfo = context.ClusterInfo;
54+
this.token = context.Token;
5555
this.guid = Guid.NewGuid();
5656

5757
_client = HttpRequest.client;
58-
_client.DefaultRequestHeaders.Authorization = new("Bearer", requiredData.Token?.Token.token);
58+
_client.DefaultRequestHeaders.Authorization = new("Bearer", context.Token?.Token.token);
5959

60-
switch (PublicData.Config.StorageType)
60+
switch (AppContext.Config.StorageType)
6161
{
6262
case StorageType.File:
63-
this.storage = new FileStorage(PublicData.Config.clusterFileDirectory);
63+
this.storage = new FileStorage(AppContext.Config.clusterFileDirectory);
6464
break;
6565
case StorageType.WebDav:
6666
this.storage = new WebDavStorage();
@@ -69,9 +69,9 @@ public Cluster(PublicData requiredData)
6969
this.storage = new AlistStorage();
7070
break;
7171
default:
72-
throw new ArgumentException($"Argument out of range. {PublicData.Config.StorageType}");
72+
throw new ArgumentException($"Argument out of range. {AppContext.Config.StorageType}");
7373
}
74-
if (PublicData.Config.maxCachedMemory != 0) this.storage = new CachedStorage(this.storage);
74+
if (AppContext.Config.maxCachedMemory != 0) this.storage = new CachedStorage(this.storage);
7575
this.files = new List<ApiFileInfo>();
7676
this.counter = new();
7777
this._socket = InitializeSocket();
@@ -134,11 +134,11 @@ private async Task<int> AsyncRun()
134134
InitializeService();
135135

136136

137-
if (!PublicData.Config.NoEnable) await Enable();
137+
if (!AppContext.Config.NoEnable) await Enable();
138138

139-
Logger.Instance.LogSystem($"工作进程 {guid} 在 <{PublicData.Config.HOST}:{PublicData.Config.PORT}> 提供服务");
139+
Logger.Instance.LogSystem($"工作进程 {guid} 在 <{AppContext.Config.HOST}:{AppContext.Config.PORT}> 提供服务");
140140

141-
Tasks.CheckFile = PublicData.Config.skipCheck ? null : new Timer(state =>
141+
Tasks.CheckFile = AppContext.Config.skipCheck ? null : new Timer(state =>
142142
{
143143
for (int i = 0; i < 36; i++)
144144
{
@@ -179,7 +179,7 @@ private void InitializeService()
179179
WebApplicationBuilder builder = WebApplication.CreateBuilder();
180180
builder.WebHost.UseKestrel(options =>
181181
{
182-
options.ListenAnyIP(PublicData.Config.PORT, cert != null ? configure =>
182+
options.ListenAnyIP(AppContext.Config.PORT, cert != null ? configure =>
183183
{
184184
configure.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
185185
configure.UseHttps(cert);
@@ -225,9 +225,9 @@ private void InitializeService()
225225
/// </returns>
226226
private X509Certificate2? LoadAndConvertCert()
227227
{
228-
if (PublicData.Config.NoCertificate) return null;
229-
(string certPath, string keyPath) = (Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates/cert.pem"),
230-
Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates/key.pem"));
228+
if (AppContext.Config.NoCertificate) return null;
229+
(string certPath, string keyPath) = (Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates/cert.pem"),
230+
Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates/key.pem"));
231231
if (!File.Exists(certPath) || !File.Exists(keyPath))
232232
{
233233
return null;
@@ -236,7 +236,7 @@ private void InitializeService()
236236
//return cert;
237237
byte[] pfxCert = cert.Export(X509ContentType.Pfx);
238238
Logger.Instance.LogDebug($"将 PEM 格式的证书转换为 PFX 格式");
239-
using (var file = File.Create(Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates/cert.pfx")))
239+
using (var file = File.Create(Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates/cert.pfx")))
240240
{
241241
file.Write(pfxCert);
242242
}
@@ -291,11 +291,11 @@ await _socket.EmitAsync("enable", (SocketIOResponse resp) =>
291291
Logger.Instance.LogSystem($"启用成功");
292292
}, new
293293
{
294-
host = PublicData.Config.HOST,
295-
port = PublicData.Config.PORT,
296-
version = PublicData.Config.clusterVersion,
297-
byoc = PublicData.Config.BringYourOwnCertficate,
298-
noFastEnable = PublicData.Config.NoFastEnable,
294+
host = AppContext.Config.HOST,
295+
port = AppContext.Config.PORT,
296+
version = AppContext.Config.clusterVersion,
297+
byoc = AppContext.Config.BringYourOwnCertficate,
298+
noFastEnable = AppContext.Config.NoFastEnable,
299299
flavor = new
300300
{
301301
runtime = Utils.GetRuntime(),
@@ -397,15 +397,15 @@ private async Task GetConfiguration()
397397
var content = await resp.Content.ReadAsStringAsync();
398398
this.Configuration = JsonConvert.DeserializeObject<Configuration>(content);
399399
Logger.Instance.LogDebug($"同步策略:{this.Configuration.Sync.Source},线程数:{this.Configuration.Sync.Concurrency}");
400-
this.requiredData.maxThreadCount = Math.Max(PublicData.Config.DownloadFileThreads, this.Configuration.Sync.Concurrency);
401-
this.requiredData.SemaphoreSlim = new SemaphoreSlim(this.requiredData.maxThreadCount);
400+
this.context.maxThreadCount = Math.Max(AppContext.Config.DownloadFileThreads, this.Configuration.Sync.Concurrency);
401+
this.context.SemaphoreSlim = new SemaphoreSlim(this.context.maxThreadCount);
402402
}
403403

404404
/// <summary>
405405
/// 默认的检查文件行为
406406
/// </summary>
407407
/// <returns></returns>
408-
private async Task CheckFiles() => await CheckFiles(PublicData.Config.skipCheck, PublicData.Config.startupCheckMode);
408+
private async Task CheckFiles() => await CheckFiles(AppContext.Config.skipCheck, AppContext.Config.startupCheckMode);
409409

410410
/// <summary>
411411
/// 获取文件列表、检查文件、下载文件部分
@@ -424,9 +424,9 @@ private async Task CheckFiles(bool skipCheck, FileVerificationMode mode)
424424
this.files = updatedFiles;
425425
}
426426

427-
if (this.Configuration.Sync.Concurrency < requiredData.maxThreadCount)
427+
if (this.Configuration.Sync.Concurrency < context.maxThreadCount)
428428
{
429-
Logger.Instance.LogWarn($"WARNING: 同步策略的线程数小于下载文件线程数,强制覆写线程数为 {requiredData.maxThreadCount}");
429+
Logger.Instance.LogWarn($"WARNING: 同步策略的线程数小于下载文件线程数,强制覆写线程数为 {context.maxThreadCount}");
430430
Logger.Instance.LogWarn($"WARNING: 覆写同步线程数为开发测试功能,无必要请勿使用!");
431431
}
432432

@@ -448,7 +448,7 @@ private async Task CheckFiles(bool skipCheck, FileVerificationMode mode)
448448
CheckSingleFile(file);
449449
lock (countLock)
450450
{
451-
pbar.Tick($"Threads: {requiredData.maxThreadCount - requiredData.SemaphoreSlim.CurrentCount}/{requiredData.maxThreadCount}, Files: {pbar.CurrentTick}/{files.Count}");
451+
pbar.Tick($"Threads: {context.maxThreadCount - context.SemaphoreSlim.CurrentCount}/{context.maxThreadCount}, Files: {pbar.CurrentTick}/{files.Count}");
452452
}
453453
});
454454

@@ -487,7 +487,7 @@ private async Task FetchFiles(bool skipCheck, FileVerificationMode mode)
487487
FetchFileFromCenter(file.hash).Wait();
488488
lock (countLock)
489489
{
490-
pbar.Tick($"Threads: {requiredData.maxThreadCount - requiredData.SemaphoreSlim.CurrentCount}/{requiredData.maxThreadCount}, Files: {pbar.CurrentTick}/{files.Count}");
490+
pbar.Tick($"Threads: {context.maxThreadCount - context.SemaphoreSlim.CurrentCount}/{context.maxThreadCount}, Files: {pbar.CurrentTick}/{files.Count}");
491491
}
492492
});
493493
}
@@ -548,7 +548,7 @@ private async Task<List<ApiFileInfo>> GetFileList(List<ApiFileInfo>? files)
548548
/// 检查单个文件
549549
/// </summary>
550550
/// <param name="file"></param>
551-
void CheckSingleFile(ApiFileInfo file) => CheckSingleFile(file, PublicData.Config.startupCheckMode);
551+
void CheckSingleFile(ApiFileInfo file) => CheckSingleFile(file, AppContext.Config.startupCheckMode);
552552

553553
/// <summary>
554554
/// 检查单个文件,并且额外指定检查模式
@@ -622,15 +622,15 @@ private async Task FetchFileFromCenter(string hash, bool force = false)
622622
return;
623623
}
624624

625-
this.requiredData.SemaphoreSlim.Wait();
625+
this.context.SemaphoreSlim.Wait();
626626
try
627627
{
628628
var resp = await this._client.GetAsync($"openbmclapi/download/{hash}");
629629
this.storage.WriteFileStream(Utils.HashToFileName(hash), await resp.Content.ReadAsStreamAsync());
630630
}
631631
finally
632632
{
633-
this.requiredData.SemaphoreSlim.Release();
633+
this.context.SemaphoreSlim.Release();
634634
}
635635
}
636636

@@ -701,7 +701,7 @@ private async Task DownloadFile(string hash, string path, bool force = false)
701701
return;
702702
}
703703

704-
await this.requiredData.SemaphoreSlim.WaitAsync();
704+
await this.context.SemaphoreSlim.WaitAsync();
705705
List<string> urls = new List<string>();
706706
try
707707
{
@@ -738,7 +738,7 @@ private async Task DownloadFile(string hash, string path, bool force = false)
738738
}
739739
finally
740740
{
741-
this.requiredData.SemaphoreSlim.Release();
741+
this.context.SemaphoreSlim.Release();
742742
}
743743
}
744744

@@ -750,17 +750,17 @@ private async Task RequestCertificate()
750750
{
751751
// File.Delete(Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certificates/cert.pem"));
752752
// File.Delete(Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certificates/key.pem"));
753-
if (PublicData.Config.BringYourOwnCertficate)
753+
if (AppContext.Config.BringYourOwnCertficate)
754754
{
755-
Logger.Instance.LogDebug($"{nameof(PublicData.Config.BringYourOwnCertficate)} 为 true,跳过请求证书……");
755+
Logger.Instance.LogDebug($"{nameof(AppContext.Config.BringYourOwnCertficate)} 为 true,跳过请求证书……");
756756
return;
757757
}
758-
string certPath = Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates/cert.pem");
759-
string keyPath = Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates/key.pem");
758+
string certPath = Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates/cert.pem");
759+
string keyPath = Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates/key.pem");
760760

761761
TaskCompletionSource tcs = new TaskCompletionSource();
762762

763-
Directory.CreateDirectory(Path.Combine(PublicData.Config.clusterWorkingDirectory, $"certificates"));
763+
Directory.CreateDirectory(Path.Combine(AppContext.Config.clusterWorkingDirectory, $"certificates"));
764764
await _socket.EmitAsync("request-cert", (SocketIOResponse resp) =>
765765
{
766766
try

CSharp-OpenBMCLAPI/Modules/HttpRequest.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ static HttpRequest()
99
client = new HttpClient()
1010
{
1111
// 设置基础地址
12-
BaseAddress = new Uri(PublicData.Config.CenterServerAddress),
12+
BaseAddress = new Uri(AppContext.Config.CenterServerAddress),
1313
Timeout = TimeSpan.FromMinutes(5)
1414
};
1515
// 添加UserAgent,用于标识请求来源
16-
string ua = $"openbmclapi-cluster/{PublicData.Config.clusterVersion} (CSharp-OpenBMCLAPI; .NET runtime v{Environment.Version}; {Environment.OSVersion}, {System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}; {System.Globalization.CultureInfo.InstalledUICulture.Name})";
16+
string ua = $"openbmclapi-cluster/{AppContext.Config.clusterVersion} (CSharp-OpenBMCLAPI; .NET runtime v{Environment.Version}; {Environment.OSVersion}, {System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}; {System.Globalization.CultureInfo.InstalledUICulture.Name})";
1717
client.DefaultRequestHeaders.Add("User-Agent", ua);
1818
Console.WriteLine($"User-Agent: {ua}");
1919
}

CSharp-OpenBMCLAPI/Modules/HttpServiceProvider.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public class HttpServiceProvider
1515
/// <returns></returns>
1616
public static void LogAccess(HttpContext context)
1717
{
18-
if (!PublicData.Config.DisableAccessLog)
18+
if (!AppContext.Config.DisableAccessLog)
1919
{
2020
context.Request.Headers.TryGetValue("user-agent", out StringValues value);
2121
Logger.Instance.LogInfo($"{context.Request.Method} {context.Request.Path.Value} {context.Request.Protocol} <{context.Response.StatusCode}> - [{context.Connection.RemoteIpAddress}] {value.FirstOrDefault()}");
@@ -32,7 +32,7 @@ public static async Task Measure(HttpContext context, Cluster cluster, int size)
3232
context.Request.Query.TryGetValue("s", out StringValues s);
3333
context.Request.Query.TryGetValue("e", out StringValues e);
3434
bool valid = Utils.CheckSign(context.Request.Path.Value?.Split('?').First()
35-
, cluster.requiredData.ClusterInfo.clusterSecret
35+
, cluster.context.ClusterInfo.clusterSecret
3636
, s.FirstOrDefault()
3737
, e.FirstOrDefault()
3838
);

CSharp-OpenBMCLAPI/Modules/Storage/AlistStorage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ public AlistStorage()
1414
{
1515
this.client = new HttpClient();
1616
this.baseAddr = "BMCLAPI/cache";
17-
this.client.BaseAddress = new Uri(PublicData.Config.clusterFileDirectory);
18-
this.user = PublicData.Config.storageUser;
17+
this.client.BaseAddress = new Uri(AppContext.Config.clusterFileDirectory);
18+
this.user = AppContext.Config.storageUser;
1919
}
2020

2121
public bool Exists(string hashPath)

CSharp-OpenBMCLAPI/Modules/Storage/CachedStorage.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class CachedStorage : ICachedStorage
3838
public CachedStorage(IStorage storage)
3939
{
4040
this.storage = storage;
41-
if (PublicData.Config.maxCachedMemory == 0) this.cacheEnabled = false;
41+
if (AppContext.Config.maxCachedMemory == 0) this.cacheEnabled = false;
4242
}
4343

4444
public bool Exists(string hashPath)
@@ -146,17 +146,17 @@ public void Initialize()
146146
public void MemoryWatchdog()
147147
{
148148
double memory = GetCachedMemory();
149-
if (memory > 0 && memory > PublicData.Config.maxCachedMemory * 1048576)
149+
if (memory > 0 && memory > AppContext.Config.maxCachedMemory * 1048576)
150150
{
151-
Logger.Instance.LogWarn($"缓存存储已大于 {PublicData.Config.maxCachedMemory}(当前 {memory / 1048576}),已开始清理缓存");
151+
Logger.Instance.LogWarn($"缓存存储已大于 {AppContext.Config.maxCachedMemory}(当前 {memory / 1048576}),已开始清理缓存");
152152
int count = 0;
153153
do
154154
{
155155
string biggestFileKey = this.cache.OrderBy(kvp => kvp.Value.content.Length).Last().Key;
156156
this.cache.Remove(biggestFileKey);
157157
count++;
158158
}
159-
while (GetCachedMemory() > PublicData.Config.maxCachedMemory || count <= 5); // 限制只有清理到内存低于指定值,并且清理次数大于五次才停止
159+
while (GetCachedMemory() > AppContext.Config.maxCachedMemory || count <= 5); // 限制只有清理到内存低于指定值,并且清理次数大于五次才停止
160160
}
161161
}
162162

CSharp-OpenBMCLAPI/Modules/Storage/FileStorage.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public FileStorage(string workingDirectory)
1717
this.workingDirectory = workingDirectory;
1818
if (workingDirectory.StartsWith(@"\\"))
1919
{
20-
StorageUser user = PublicData.Config.storageUser;
20+
StorageUser user = AppContext.Config.storageUser;
2121
this.connection = new SambaConnection(user.UserName, user.Password, Regex.Match(workingDirectory, @"\\\\(.*?)\\").Groups[1].Value);
2222
}
2323
}

CSharp-OpenBMCLAPI/Modules/Storage/WebDavStorage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ public class WebDavStorage : IStorage
1212

1313
public WebDavStorage()
1414
{
15-
this.client = new(PublicData.Config.clusterFileDirectory);
15+
this.client = new(AppContext.Config.clusterFileDirectory);
1616
this.baseAddr = "BMCLAPI/cache";
1717
this.writeLock = new object();
18-
this.user = PublicData.Config.storageUser;
18+
this.user = AppContext.Config.storageUser;
1919
}
2020

2121
public bool Exists(string hashPath)

CSharp-OpenBMCLAPI/Modules/TokenManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public async Task<Token> FetchToken()
6262

6363
this._updateTask = Task.Run(() =>
6464
{
65-
Thread.Sleep(this.token.ttl - PublicData.Config.refreshTokenTime);
65+
Thread.Sleep(this.token.ttl - AppContext.Config.refreshTokenTime);
6666
RefreshToken();
6767
});
6868
}

CSharp-OpenBMCLAPI/Modules/Utils.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ public static bool CheckSign(string? hash, string? secret, string? s, string? e)
217217
var sign = ToUrlSafeBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes($"{secret}{hash}{e}")));
218218
var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
219219
var a = timestamp < (ToDecimal(e) / 1000);
220-
return (sign == s && timestamp < (ToDecimal(e) / 1000)) || PublicData.Config.NoSignatureVerifying;
220+
return (sign == s && timestamp < (ToDecimal(e) / 1000)) || AppContext.Config.NoSignatureVerifying;
221221
}
222222

223223
public static bool IsAdministrator()

0 commit comments

Comments
 (0)