120 lines
5.0 KiB
C#
120 lines
5.0 KiB
C#
global using System;
|
|
global using System.IO;
|
|
global using System.Text.Json;
|
|
global using System.Threading.Tasks;
|
|
global using DTLib.Demystifier;
|
|
global using ParadoxSaveParser.Lib;
|
|
using System.Collections.Concurrent;
|
|
using System.Linq;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace ParadoxSaveParser.WebAPI;
|
|
|
|
public class Program
|
|
{
|
|
private static ConcurrentDictionary<string, SaveFileMetadata> _saveMetadataStorage = new();
|
|
private static WebApplication _app = null!;
|
|
|
|
public static void Main(string[] args)
|
|
{
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
_app = builder.Build();
|
|
|
|
Directory.CreateDirectory(PathHelper.DATA_DIR);
|
|
Directory.CreateDirectory(PathHelper.SAVES_DIR);
|
|
foreach (var metaFilePath in Directory.GetFiles(PathHelper.SAVES_DIR, "*.meta.json", SearchOption.TopDirectoryOnly))
|
|
{
|
|
using var metaFile = File.Open(metaFilePath, FileMode.Open, FileAccess.Read);
|
|
var meta = JsonSerializer.Deserialize<SaveFileMetadata>(metaFile) ?? throw new NullReferenceException(metaFilePath);
|
|
if (meta.status != SaveFileProcessingStatus.Done)
|
|
{
|
|
_app.Logger.Log(LogLevel.Warning, "metadata file '{metaFilePath}' status has invalid status {status}", metaFilePath, meta.status);
|
|
}
|
|
|
|
if(!_saveMetadataStorage.TryAdd(meta.id, meta))
|
|
throw new Exception("Guid collision!");
|
|
}
|
|
|
|
_app.UseHttpsRedirection();
|
|
_app.MapGet("/getSaveStatus", GetSaveStatusHandler);
|
|
_app.MapPost("/parseSave/eu4", ParseSaveEU4Handler);
|
|
_app.Run();
|
|
}
|
|
|
|
private static async Task GetSaveStatusHandler(HttpContext httpContext)
|
|
{
|
|
httpContext.Request.Query.TryGetValue("id", out var ids);
|
|
string? id = ids.FirstOrDefault();
|
|
if (string.IsNullOrEmpty(id))
|
|
{
|
|
throw new BadHttpRequestException("No id provided",
|
|
StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
if (!_saveMetadataStorage.TryGetValue(id, out var meta))
|
|
{
|
|
throw new BadHttpRequestException($"Save with {id} not found",
|
|
StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
}
|
|
|
|
private static async Task ParseSaveEU4Handler(HttpContext httpContext)
|
|
{
|
|
var remoteFile = httpContext.Request.Form.Files.FirstOrDefault();
|
|
if (remoteFile is null || !remoteFile.FileName.EndsWith(".eu4"))
|
|
{
|
|
throw new BadHttpRequestException($"Invalid file format: {remoteFile?.FileName}",
|
|
StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
string saveId = Guid.NewGuid().ToString();
|
|
string metaFilePath = PathHelper.GetMetaFilePath(saveId);
|
|
if (File.Exists(metaFilePath))
|
|
{
|
|
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
throw new BadHttpRequestException($"Guid collision! file {metaFilePath} already exists.", StatusCodes.Status500InternalServerError);
|
|
}
|
|
|
|
var meta = new SaveFileMetadata { id = saveId, game = Game.EU4, status = SaveFileProcessingStatus.Initialized, };
|
|
if (!_saveMetadataStorage.TryAdd(saveId, meta))
|
|
{
|
|
throw new BadHttpRequestException($"Guid collision! Can't create metadata with id {saveId}", StatusCodes.Status500InternalServerError);
|
|
}
|
|
|
|
try
|
|
{
|
|
meta.status = SaveFileProcessingStatus.Uploading;
|
|
string saveFilePath = PathHelper.GetEU4SaveFilePath(meta.id);
|
|
await using var saveFile = File.Open(saveFilePath, FileMode.CreateNew, FileAccess.ReadWrite);
|
|
await using (var remoteStream = remoteFile.OpenReadStream())
|
|
{
|
|
await Task.Delay(50000);
|
|
await remoteStream.CopyToAsync(saveFile);
|
|
}
|
|
|
|
meta.status = SaveFileProcessingStatus.Parsing;
|
|
saveFile.Seek(0, SeekOrigin.Begin);
|
|
var parser = new ParserEU4(saveFile);
|
|
var result = parser.Parse();
|
|
meta.status = SaveFileProcessingStatus.SavingResults;
|
|
string resultFilePath = PathHelper.GetParsedSaveFilePath(meta.id);
|
|
await using var resultFile = File.Open(resultFilePath, FileMode.CreateNew, FileAccess.Write);
|
|
await JsonSerializer.SerializeAsync(resultFile, result);
|
|
meta.status = SaveFileProcessingStatus.Done;
|
|
meta.SaveToFile();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
meta.status = SaveFileProcessingStatus.Error;
|
|
string errorMesage = ex.ToStringDemystified();
|
|
meta.errorMesage = errorMesage;
|
|
_app.Logger.Log(LogLevel.Error, "EU4SaveParse Error: {errorMesage}", errorMesage);
|
|
}
|
|
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
}
|
|
} |