refactored responses
This commit is contained in:
@@ -13,42 +13,56 @@ global using File = DTLib.Filesystem.File;
|
||||
global using Path = DTLib.Filesystem.Path;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using DTLib.Console;
|
||||
using DTLib.Dtsod;
|
||||
using DTLib.Web;
|
||||
using DTLib.Web.Routes;
|
||||
using ParadoxSaveParser.WebAPI.BackgroundTasks;
|
||||
using ParadoxSaveParser.WebAPI.Routes;
|
||||
|
||||
namespace ParadoxSaveParser.WebAPI;
|
||||
|
||||
public static partial class Program
|
||||
public static class Program
|
||||
{
|
||||
private static readonly IOPath _configPath = "./config.dtsod";
|
||||
private static Config _config = new();
|
||||
|
||||
private static readonly ILogger _loggerRoot = new CompositeLogger(
|
||||
new ConsoleLogger(),
|
||||
new FileLogger("logs", "ParadoxSaveParser.WebAPI"));
|
||||
|
||||
private static bool IsDebug = true;
|
||||
private static readonly CancellationTokenSource _mainCancel = new();
|
||||
private static readonly ConcurrentDictionary<string, SaveFileMetadata> _saveMetadataStorage = new();
|
||||
internal static readonly ConcurrentDictionary<string, SaveFileMetadata> _saveMetadataStorage = new();
|
||||
|
||||
private static readonly JsonSerializerOptions _saveSerializerOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
MaxDepth = 1024
|
||||
};
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
Console.InputEncoding = Encoding.UTF8;
|
||||
Console.OutputEncoding = Encoding.UTF8;
|
||||
Console.CursorVisible = false;
|
||||
var logger = new ContextLogger(nameof(Main), _loggerRoot);
|
||||
|
||||
#if DEBUG
|
||||
IsDebug = true;
|
||||
#endif
|
||||
|
||||
new LaunchArgumentParser(
|
||||
new LaunchArgument(["-d", "--debug"],
|
||||
"enables debug log output to console",
|
||||
() => IsDebug = true)
|
||||
).AllowNoArguments().ParseAndHandle(args);
|
||||
|
||||
var loggerRoot = new CompositeLogger(
|
||||
new ConsoleLogger
|
||||
{
|
||||
DebugLogEnabled = IsDebug
|
||||
},
|
||||
new FileLogger("logs", "ParadoxSaveParser.WebAPI")
|
||||
{
|
||||
DebugLogEnabled = true
|
||||
});
|
||||
var loggerMain = new ContextLogger(nameof(Main), loggerRoot);
|
||||
loggerMain.LogDebug("Debug log is enabled");
|
||||
|
||||
Console.CancelKeyPress += (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
logger.LogInfo("Ctrl+C Pressed");
|
||||
loggerMain.LogInfo("Ctrl+C Pressed");
|
||||
_mainCancel.Cancel();
|
||||
};
|
||||
|
||||
@@ -57,54 +71,57 @@ public static partial class Program
|
||||
// config
|
||||
if (!File.Exists(_configPath))
|
||||
{
|
||||
logger.LogWarn("config file not found.");
|
||||
loggerMain.LogWarn("config file not found.");
|
||||
File.WriteAllText(_configPath, _config.ToString());
|
||||
logger.LogWarn($"created default at {_configPath}.");
|
||||
loggerMain.LogWarn($"created default at {_configPath}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_config = Config.FromDtsod(new DtsodV23(File.ReadAllText(_configPath)));
|
||||
}
|
||||
|
||||
PrepareLocalFiles();
|
||||
PathHelper.CreateProgramDirectories();
|
||||
|
||||
var metaFiles = System.IO.Directory.GetFiles(
|
||||
PathHelper.SAVES_DIR.Str, "*.meta.json",
|
||||
SearchOption.TopDirectoryOnly);
|
||||
foreach (string metaFilePath in metaFiles)
|
||||
{
|
||||
using var metaFile = File.OpenRead(metaFilePath);
|
||||
var meta = JsonSerializer.Deserialize<SaveFileMetadata>(metaFile) ??
|
||||
throw new NullReferenceException(metaFilePath);
|
||||
if (meta.status != SaveFileProcessingStatus.Done)
|
||||
loggerMain.LogWarn(nameof(Main),
|
||||
$"metadata file '{metaFilePath}' status has invalid status {meta.status}");
|
||||
|
||||
if (!_saveMetadataStorage.TryAdd(meta.id, meta))
|
||||
throw new Exception("Guid collision!");
|
||||
}
|
||||
|
||||
var bgJobManager = new BackgroundJobManager(loggerRoot);
|
||||
var saveParsingSearchExpressions = new Dictionary<Game, ISearchExpression>
|
||||
{
|
||||
{ Game.EU4, SearchExpressionCompiler.Compile("*.~") },
|
||||
};
|
||||
|
||||
// http server
|
||||
var router = new SimpleRouter(_loggerRoot);
|
||||
var router = new SimpleRouter(loggerRoot);
|
||||
router.DefaultRoute = new ServeFilesRouteHandler("public");
|
||||
router.MapRoute("/getSaveStatus", HttpMethod.GET, GetSaveStatusHandler);
|
||||
router.MapRoute("/uploadSave/eu4", HttpMethod.POST, UploadSaveHandler);
|
||||
router.MapRoute("/parseSave/eu4", HttpMethod.POST, ParseSaveEU4Handler);
|
||||
router.MapRoute("/getSaveStatus", HttpMethod.GET, new GetSaveStatusHandler(_mainCancel.Token));
|
||||
router.MapRoute("/uploadSave/eu4", HttpMethod.POST, new UploadSaveHandler(_mainCancel.Token, bgJobManager, saveParsingSearchExpressions));
|
||||
|
||||
var app = new WebApp(_config.BaseUrl, _loggerRoot, router, _mainCancel.Token);
|
||||
var app = new WebApp(_config.BaseUrl, loggerRoot, router, _mainCancel.Token);
|
||||
app.Run().GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogWarn($"catched OperationCanceledException from {ex.Source}");
|
||||
loggerMain.LogWarn($"catched OperationCanceledException from {ex.Source}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex.ToStringDemystified());
|
||||
loggerMain.LogError(ex.ToStringDemystified());
|
||||
}
|
||||
}
|
||||
|
||||
public static void PrepareLocalFiles()
|
||||
{
|
||||
Directory.Create(PathHelper.DATA_DIR);
|
||||
Directory.Create(PathHelper.SAVES_DIR);
|
||||
foreach (string 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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user