Skip to content

Commit

Permalink
feat: 换回 ASP
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Jul 14, 2024
1 parent c03bd8d commit e77f8a7
Show file tree
Hide file tree
Showing 27 changed files with 171 additions and 705 deletions.
9 changes: 9 additions & 0 deletions BangbangAsp/BangbangAsp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
34 changes: 34 additions & 0 deletions BangbangAsp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
namespace BangbangAsp
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
}
}
}
38 changes: 38 additions & 0 deletions BangbangAsp/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12008",
"sslPort": 44375
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5139",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7177;http://localhost:5139",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
9 changes: 9 additions & 0 deletions BangbangAsp/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions BangbangAsp/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
6 changes: 6 additions & 0 deletions CSharp-OpenBMCLAPI.sln
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docker compose", "Docker co
docker-compose.yml = docker-compose.yml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BangbangAsp", "BangbangAsp\BangbangAsp.csproj", "{3ABB5430-C505-42F6-A7FD-AAB8FFD94063}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -35,6 +37,10 @@ Global
{F01E0E3F-BF3E-4D0D-BCB7-7DFEF1926310}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F01E0E3F-BF3E-4D0D-BCB7-7DFEF1926310}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F01E0E3F-BF3E-4D0D-BCB7-7DFEF1926310}.Release|Any CPU.Build.0 = Release|Any CPU
{3ABB5430-C505-42F6-A7FD-AAB8FFD94063}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3ABB5430-C505-42F6-A7FD-AAB8FFD94063}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3ABB5430-C505-42F6-A7FD-AAB8FFD94063}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3ABB5430-C505-42F6-A7FD-AAB8FFD94063}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
4 changes: 4 additions & 0 deletions CSharp-OpenBMCLAPI/CSharp-OpenBMCLAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
<PackageReference Include="ZstdSharp.Port" Version="0.8.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BangbangAsp\BangbangAsp.csproj" />
</ItemGroup>

<ItemGroup>
<None Update=".env.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
Expand Down
46 changes: 20 additions & 26 deletions CSharp-OpenBMCLAPI/Modules/Cluster.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using CSharpOpenBMCLAPI.Modules.Plugin;
using CSharpOpenBMCLAPI.Modules.Storage;
using CSharpOpenBMCLAPI.Modules.WebServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using ShellProgressBar;
using SocketIOClient;
Expand All @@ -12,6 +14,7 @@
using System.Text.RegularExpressions;
using TeraIO.Runnable;
using ZstdSharp;
using static System.Net.Mime.MediaTypeNames;

namespace CSharpOpenBMCLAPI.Modules
{
Expand All @@ -35,6 +38,7 @@ public class Cluster
public CancellationTokenSource cancellationSrc = new CancellationTokenSource();
internal ClusterRequiredData requiredData;
internal List<ApiFileInfo> files;
protected WebApplication? application;

//List<Task> tasks = new List<Task>();

Expand Down Expand Up @@ -169,38 +173,28 @@ private async Task _KeepAlive()
/// </summary>
private void InitializeService()
{
X509Certificate2 cert = LoadAndConvertCert();
SimpleWebServer server = new(ClusterRequiredData.Config.PORT, cert, this);//cert);

// 下载路由
server.routes.Add(new Route
X509Certificate2? cert = LoadAndConvertCert();
WebApplicationBuilder builder = WebApplication.CreateBuilder();
builder.WebHost.UseKestrel(options =>
{
MatchRegex = new Regex(@"/download/[0-9a-fA-F]{32,40}?.*"),
ConditionExpressions =
options.ListenAnyIP(9388, cert != null ? configure =>
{
(path) => path.Contains("s=") && path.Contains("e=")
},
Handler = (context, cluster, Match) =>
{
FileAccessInfo fai = HttpServiceProvider.DownloadHash(context, cluster).Result;
this.counter.Add(fai);
configure.UseHttps(cert);
}
: configure => { });
});
application = builder.Build();

// 测速路由
server.routes.Add(new Route
// 下载路由
application.MapGet("/download/{hash}", (HttpContext context, string hash) =>
{
MatchRegex = new Regex(@"/measure/\d"),
Handler = (context, cluster, match) => HttpServiceProvider.Measure(context, cluster).Wait()
FileAccessInfo fai = HttpServiceProvider.DownloadHash(context, this).Result;
this.counter.Add(fai);
return Task.CompletedTask;
});

// API 数据
server.routes.Add(new Route
{
MatchRegex = new Regex(@"/api/(.*)"),
Handler = (context, cluster, match) => HttpServiceProvider.Api(context, match.Groups[1].Value, this).Wait(),
Methods = "GET"
});
// 测速路由
application.MapGet("/measure", (context) => HttpServiceProvider.Measure(context, this));

// 因为暂时禁用面板而注释掉

Expand All @@ -218,7 +212,7 @@ private void InitializeService()
// Handler = (context, cluster, match) => HttpServiceProvider.Dashboard(context).Wait()
// });

server.Start();
application.RunAsync();
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion CSharp-OpenBMCLAPI/Modules/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ [注] 当此项启用时,"startupCheckMode"无效

[YamlMember(Description = "[开发变量]\n指示是否不执行快速上线,若为 true 则每次都不执行", Order = 10)]
public bool noFastEnable;

[YamlMember(Description = "[开发变量]\n是否使用开发环境(需要自己模拟用户请求)", Order = 10)]
public bool StagingMode;

Expand Down
4 changes: 2 additions & 2 deletions CSharp-OpenBMCLAPI/Modules/HttpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ static HttpRequest()
BaseAddress = ClusterRequiredData.Config.StagingMode ?
new Uri("https://openbmclapi.staging.bangbang93.com/") :
new Uri("https://openbmclapi.bangbang93.com/"),


};

};
// 添加UserAgent,用于标识请求来源
client.DefaultRequestHeaders.UserAgent.Add(new("openbmclapi-cluster", ClusterRequiredData.Config.clusterVersion));
}
Expand Down
58 changes: 24 additions & 34 deletions CSharp-OpenBMCLAPI/Modules/HttpServiceProvider.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using CSharpOpenBMCLAPI.Modules.Plugin;
using CSharpOpenBMCLAPI.Modules.Storage;
using CSharpOpenBMCLAPI.Modules.WebServer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

namespace CSharpOpenBMCLAPI.Modules
Expand All @@ -17,7 +18,8 @@ public static void LogAccess(HttpContext context)
{
if (!ClusterRequiredData.Config.disableAccessLog)
{
Logger.Instance.LogInfo($"{context.Request.Method} {context.Request.Path.Split('?').First()} <{context.Response.StatusCode}> - [{context.RemoteIPAddress}] {context.Request.Headers.TryGetValue("user-agent")}");
context.Request.Headers.TryGetValue("user-agent", out StringValues value);
Logger.Instance.LogInfo($"{context.Request.Method} {context.Request.Path.Value} <{context.Response.StatusCode}> - [{context.Connection.RemoteIpAddress}] {value.FirstOrDefault()}");
}
}

Expand All @@ -29,8 +31,8 @@ public static void LogAccess(HttpContext context)
public static async Task Measure(HttpContext context, Cluster cluster)
{
PluginManager.Instance.TriggerHttpEvent(context, HttpEventType.ClientMeasure);
var pairs = Utils.GetQueryStrings(context.Request.Path.Split('?').Last());
bool valid = Utils.CheckSign(context.Request.Path.Split('?').First()
var pairs = Utils.GetQueryStrings(context.Request.Path.Value?.Split('?').Last());
bool valid = Utils.CheckSign(context.Request.Path.Value?.Split('?').First()
, cluster.requiredData.ClusterInfo.ClusterSecret
, pairs.GetValueOrDefault("s")
, pairs.GetValueOrDefault("e")
Expand All @@ -39,14 +41,13 @@ public static async Task Measure(HttpContext context, Cluster cluster)
{
context.Response.StatusCode = 200;
byte[] buffer = new byte[1024];
for (int i = 0; i < Convert.ToInt32(context.Request.Path.Split('/').Last().Split('?').First()); i++)
for (int i = 0; i < Convert.ToInt32(context.Request.Path.Value?.Split('/').Last().Split('?').First()); i++)
{
for (int j = 0; j < 1024; j++)
{
await context.Response.Stream.WriteAsync(buffer);
await context.Response.Body.WriteAsync(buffer);
}
}
context.Response.ResetStreamPosition();
}
else
{
Expand All @@ -67,8 +68,8 @@ public static async Task<FileAccessInfo> DownloadHash(HttpContext context, Clust
PluginManager.Instance.TriggerHttpEvent(context, HttpEventType.ClientDownload);
// 处理用户下载
FileAccessInfo fai = default;
var pairs = Utils.GetQueryStrings(context.Request.Path.Split('?').Last());
string? hash = context.Request.Path.Split('/').LastOrDefault()?.Split('?').First();
var pairs = Utils.GetQueryStrings(context.Request.Path.Value?.Split('?').Last());
string? hash = context.Request.Path.Value?.Split('/').LastOrDefault()?.Split('?').First();
string? s = pairs.GetValueOrDefault("s");
string? e = pairs.GetValueOrDefault("e");

Expand All @@ -88,7 +89,7 @@ public static async Task<FileAccessInfo> DownloadHash(HttpContext context, Clust
{
// 206 处理部分
context.Response.StatusCode = 206;
(from, to) = ToRangeByte(context.Request.Headers["range"].Split("=").Last().Split("-"));
(from, to) = ToRangeByte(context.Request.Headers["range"].FirstOrDefault()?.Split("=").Last().Split("-"));
if (to < from && to != -1) (from, to) = (to, from);
long length = 0;

Expand All @@ -97,25 +98,25 @@ public static async Task<FileAccessInfo> DownloadHash(HttpContext context, Clust
if (to == -1) to = file.Length;

length = (to - from + 1);
context.Response.Header["Content-Length"] = length.ToString();
context.Response.Headers["Content-Length"] = length.ToString();

file.Seek(from, SeekOrigin.Begin);
byte[] buffer = new byte[4096];
for (; file.Position < to;)
{
int count = file.Read(buffer, 0, buffer.Length);
if (file.Position > to && file.Position - count < to) context.Response.Stream.Write(buffer[..(int)(count - file.Position + to + 1)]);
else if (count != buffer.Length) context.Response.Stream.Write(buffer[..(count)]);
else context.Response.Stream.Write(buffer);
if (file.Position > to && file.Position - count < to) await context.Response.Body.WriteAsync(buffer[..(int)(count - file.Position + to + 1)]);
else if (count != buffer.Length) await context.Response.Body.WriteAsync(buffer[..(count)]);
else await context.Response.Body.WriteAsync(buffer);
}
context.Response.Headers["Content-Range"] = $"{from}-{to}/{file.Length}";
}
context.Response.ResetStreamPosition();

context.Response.Header["Content-Range"] = $"{from}-{to}/{context.Response.Stream.Length}";
context.Response.Header["x-bmclapi-hash"] = hash;
context.Response.Header["Accept-Ranges"] = "bytes";
context.Response.Header["Content-Type"] = "application/octet-stream";
context.Response.Header["Connection"] = "closed";

context.Response.Headers["x-bmclapi-hash"] = hash;
context.Response.Headers["Accept-Ranges"] = "bytes";
context.Response.Headers["Content-Type"] = "application/octet-stream";
context.Response.Headers["Connection"] = "closed";
fai = new FileAccessInfo
{
hits = 1,
Expand All @@ -126,14 +127,12 @@ public static async Task<FileAccessInfo> DownloadHash(HttpContext context, Clust
else
{
fai = await cluster.storage.HandleRequest(Utils.HashToFileName(hash), context);
context.Response.ResetStreamPosition();
ClusterRequiredData.DataStatistician.DownloadCount(fai);
}
}
catch (Exception ex)
{
Logger.Instance.LogError(ex.ExceptionToDetail());
Logger.Instance.LogError(context.RemoteIPAddress);
Logger.Instance.LogError(context.Request.Path);
//Logger.Instance.LogError(ex.StackTrace);
context.Response.StatusCode = 404;
Expand All @@ -142,7 +141,7 @@ public static async Task<FileAccessInfo> DownloadHash(HttpContext context, Clust
else
{
context.Response.StatusCode = 403;
context.Response.Header.Remove("Content-Length");
context.Response.Headers.Remove("Content-Length");
await context.Response.WriteAsync($"Access to \"{context.Request.Path}\" has been blocked due to your request timeout or invalidity.");
}
LogAccess(context);
Expand All @@ -166,8 +165,8 @@ private static (long from, long to) ToRangeByte(string[]? rangeHeader)
public static async Task Api(HttpContext context, string query, Cluster cluster)
{
PluginManager.Instance.TriggerHttpEvent(context, HttpEventType.ClientOtherRequest);
context.Response.Header.Set("content-type", "application/json");
context.Response.Header.Set("access-control-allow-origin", "*");
context.Response.Headers["content-type"] = "application/json";
context.Response.Headers["access-control-allow-origin"] = "*";
context.Response.StatusCode = 200;
switch (query)
{
Expand Down Expand Up @@ -228,15 +227,6 @@ await context.Response.WriteAsync(JsonConvert.SerializeObject(new
context.Response.StatusCode = 404;
break;
}
context.Response.ResetStreamPosition();
}

public static Task Dashboard(HttpContext context, string filePath = "index.html")
{
PluginManager.Instance.TriggerHttpEvent(context, HttpEventType.ClientOtherRequest);
context.Response.StatusCode = 200;
context.Response.Stream = Utils.GetEmbeddedFileStream($"Dashboard/{filePath}").ThrowIfNull();
return Task.CompletedTask;
}
}
}
Loading

0 comments on commit e77f8a7

Please sign in to comment.