227 lines
9.0 KiB
C#
227 lines
9.0 KiB
C#
global using System;
|
|
global using System.Collections.Generic;
|
|
global using System.Text;
|
|
global using System.Text.Json;
|
|
global using System.Threading;
|
|
global using System.Threading.Tasks;
|
|
global using DTLib;
|
|
global using DTLib.Demystifier;
|
|
global using DTLib.Filesystem;
|
|
global using DTLib.Logging;
|
|
global using ParadoxSaveParser.Lib;
|
|
global using Directory = DTLib.Filesystem.Directory;
|
|
global using File = DTLib.Filesystem.File;
|
|
global using Path = DTLib.Filesystem.Path;
|
|
using System.Collections.Concurrent;
|
|
using System.IO;
|
|
using System.IO.Compression;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Text.Encodings.Web;
|
|
using DTLib.Dtsod;
|
|
using DTLib.Extensions;
|
|
using DTLib.Web;
|
|
using DTLib.Web.Routes;
|
|
|
|
namespace ParadoxSaveParser.WebAPI;
|
|
|
|
public class Program
|
|
{
|
|
private static readonly IOPath _configPath = "./config.dtsod";
|
|
private static Config _config = new();
|
|
private static readonly ILogger _loggerRoot = new ConsoleLogger();
|
|
private static ConcurrentDictionary<string, SaveFileMetadata> _saveMetadataStorage = new();
|
|
|
|
private static JsonSerializerOptions _saveSerializerOptions = new()
|
|
{
|
|
WriteIndented = false,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
|
MaxDepth = 1024,
|
|
};
|
|
|
|
public static void Main(string[] args)
|
|
{
|
|
Console.InputEncoding = Encoding.UTF8;
|
|
Console.OutputEncoding = Encoding.UTF8;
|
|
ContextLogger logger = new ContextLogger(nameof(Main), _loggerRoot);
|
|
CancellationTokenSource mainCancel = new();
|
|
Console.CancelKeyPress += (_, _) =>
|
|
{
|
|
logger.LogInfo("stopping server...");
|
|
mainCancel.Cancel();
|
|
};
|
|
|
|
try
|
|
{
|
|
// config
|
|
if (!File.Exists(_configPath))
|
|
{
|
|
logger.LogWarn("config file not found.");
|
|
File.WriteAllText(_configPath, _config.ToString());
|
|
logger.LogWarn($"created default at {_configPath}.");
|
|
}
|
|
else _config = Config.FromDtsod(new DtsodV23(File.ReadAllText(_configPath)));
|
|
|
|
PrepareLocalFiles();
|
|
|
|
// http server
|
|
var router = new SimpleRouter(_loggerRoot);
|
|
router.DefaultRoute = new ServeFilesRouteHandler("public");
|
|
router.MapRoute("/aaa", async ctx =>
|
|
{
|
|
byte[] buffer =
|
|
"""
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<body>
|
|
<h1>aaa</h1>
|
|
</body>
|
|
</html>
|
|
""".ToBytes();
|
|
ctx.Response.ContentLength64 = buffer.Length;
|
|
await ctx.Response.OutputStream.WriteAsync(buffer);
|
|
return HttpStatusCode.OK;
|
|
});
|
|
// router.MapGet("/getSaveStatus", GetSaveStatusHandler);
|
|
// router.MapPost("/uploadSave/eu4", UploadSaveHandler);
|
|
// app.MapPost("/parseSave/eu4", ParseSaveEU4Handler);
|
|
|
|
var app = new WebApp(_config.BaseUrl, _loggerRoot, router, mainCancel.Token);
|
|
app.Run().GetAwaiter().GetResult();
|
|
}
|
|
catch (OperationCanceledException ex)
|
|
{
|
|
logger.LogWarn($"catched OperationCanceledException from {ex.Source}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex.ToStringDemystified());
|
|
}
|
|
}
|
|
|
|
public static void PrepareLocalFiles()
|
|
{
|
|
Directory.Create(PathHelper.DATA_DIR);
|
|
Directory.Create(PathHelper.SAVES_DIR);
|
|
foreach (var metaFilePath in System.IO.Directory.GetFiles(
|
|
PathHelper.SAVES_DIR.Str, "*.meta.json",
|
|
SearchOption.TopDirectoryOnly))
|
|
{
|
|
using var metaFile = File.OpenRead(metaFilePath);
|
|
var meta = JsonSerializer.Deserialize<SaveFileMetadata>(metaFile) ?? throw new NullReferenceException(metaFilePath);
|
|
if (meta.status != SaveFileProcessingStatus.Done)
|
|
{
|
|
_loggerRoot.LogWarn(nameof(PrepareLocalFiles), $"metadata file '{metaFilePath}' status has invalid status {meta.status}");
|
|
}
|
|
|
|
if(!_saveMetadataStorage.TryAdd(meta.id, meta))
|
|
throw new Exception("Guid collision!");
|
|
}
|
|
}
|
|
|
|
/*
|
|
private static async Task UploadSaveHandler(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();
|
|
IOPath 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);
|
|
}
|
|
|
|
meta.status = SaveFileProcessingStatus.Uploading;
|
|
IOPath saveFilePath = PathHelper.GetSaveFilePath(meta.id);
|
|
await using var saveFile = File.OpenWrite(saveFilePath);
|
|
await using var remoteStream = remoteFile.OpenReadStream();
|
|
await remoteStream.CopyToAsync(saveFile);
|
|
meta.status = SaveFileProcessingStatus.Uploaded;
|
|
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
}
|
|
|
|
private static SaveFileMetadata GetMetaFromRequestId(HttpContext httpContext, string requestParamName)
|
|
{
|
|
httpContext.Request.Query.TryGetValue(requestParamName, out var ids);
|
|
string? id = ids.FirstOrDefault();
|
|
if (string.IsNullOrEmpty(id))
|
|
{
|
|
throw new BadHttpRequestException($"No request parameter '{requestParamName}' provided",
|
|
StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
if (!_saveMetadataStorage.TryGetValue(id, out var meta))
|
|
{
|
|
throw new BadHttpRequestException($"Save with {id} not found",
|
|
StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
return meta;
|
|
}
|
|
|
|
private static async Task GetSaveStatusHandler(HttpContext httpContext)
|
|
{
|
|
var meta = GetMetaFromRequestId(httpContext, "id");
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
}
|
|
|
|
private static async Task ParseSaveEU4Handler(HttpContext httpContext)
|
|
{
|
|
var meta = GetMetaFromRequestId(httpContext, "id");
|
|
if (meta.status == SaveFileProcessingStatus.Error)
|
|
{
|
|
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (meta.status != SaveFileProcessingStatus.Uploaded)
|
|
throw new Exception($"Invalid save processing status: {meta.status}");
|
|
|
|
using var zipArchive = ZipFile.Open(PathHelper.GetSaveFilePath(meta.id).Str, ZipArchiveMode.Read);
|
|
var zipEntry = zipArchive.Entries.FirstOrDefault(e => e.Name == "gamestate");
|
|
if (zipEntry is null)
|
|
throw new Exception("Invalid save format: no gamestate file found");
|
|
string extractedGamestatePath = PathHelper.GetSaveFilePath(meta.id) + ".gamestate";
|
|
zipEntry.ExtractToFile(extractedGamestatePath);
|
|
var gamestateStream = File.OpenRead(extractedGamestatePath);
|
|
|
|
meta.status = SaveFileProcessingStatus.Parsing;
|
|
var parser = new Parser(gamestateStream);
|
|
var result = parser.Parse();
|
|
|
|
meta.status = SaveFileProcessingStatus.SavingResults;
|
|
IOPath resultFilePath = PathHelper.GetParsedSaveFilePath(meta.id);
|
|
await using var resultFile = File.OpenWrite(resultFilePath);
|
|
await JsonSerializer.SerializeAsync(resultFile, result, _saveSerializerOptions);
|
|
meta.status = SaveFileProcessingStatus.Done;
|
|
meta.SaveToFile();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
meta.status = SaveFileProcessingStatus.Error;
|
|
string errorMesage = ex.ToStringDemystified();
|
|
meta.errorMesage = errorMesage;
|
|
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
_app.Logger.Log(LogLevel.Error, "ParseSaveEU4 Error: {errorMesage}", errorMesage);
|
|
}
|
|
|
|
await httpContext.Response.WriteAsJsonAsync(meta);
|
|
}
|
|
*/
|
|
} |