move card storage/web server handlers to separate files

This commit is contained in:
ppc
2024-09-02 14:14:02 +01:00
parent 31354bd146
commit ec98003d2c
4 changed files with 211 additions and 151 deletions
+78 -2
View File
@@ -1,5 +1,16 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -7,10 +18,14 @@ namespace AMNet.Server;
internal static class WebServer
{
public static WebApplicationBuilder BuildServer()
private const int ApiVersion = 1;
public static WebApplication BuildServer(params string[] listenAddresses)
{
var builder = WebApplication.CreateSlimBuilder([]);
builder.WebHost.UseUrls(listenAddresses);
builder.Logging.ClearProviders();
builder.Logging.AddSimpleConsole(o =>
{
@@ -39,6 +54,67 @@ internal static class WebServer
options.SerializerOptions.TypeInfoResolverChain.Insert(0, SerializerContext.Default);
});
return builder;
builder.Services.AddSingleton<CardPresenter>();
var app = builder.Build();
app.UseCors();
app.MapGet("/amnet/info", () => Results.Ok(new SystemState(ApiVersion, Config.GameId, Config.ServerName)));
app.MapPost("/amnet/signin", ProcessCard);
return app;
}
private static async Task ProcessCard(HttpContext ctx)
{
CardReadRequest request;
try
{
request = await ctx.Request.ReadFromJsonAsync<CardReadRequest>();
}
catch (JsonException e)
{
ctx.Response.StatusCode = 400;
await ctx.Response.WriteAsync(e.Message);
return;
}
if (string.IsNullOrEmpty(request?.MatrixCode))
{
ctx.Response.StatusCode = 400;
await ctx.Response.WriteAsync("Card id not provided.");
return;
}
if (request.MatrixCode.Length is 0 or < 20)
{
ctx.Response.StatusCode = 422;
await ctx.Response.WriteAsync("Invalid card id length.");
return;
}
var cardPresenter = ctx.RequestServices.GetRequiredService<CardPresenter>();
var currentCard = cardPresenter.PeekActiveCard();
if (currentCard?.Expired == false)
{
var timeLeft = Math.Ceiling(TimeSpan.FromMilliseconds(currentCard.ExpiresAt - Environment.TickCount64).TotalSeconds);
ctx.Response.StatusCode = 429;
ctx.Response.Headers.RetryAfter = timeLeft.ToString(CultureInfo.InvariantCulture);
return;
}
if (cardPresenter.SetCard(request.MatrixCode))
{
ctx.Response.StatusCode = 202;
}
else
{
ctx.Response.StatusCode = 422;
await ctx.Response.WriteAsync("Invalid card id format.");
}
}
}