Compare commits

...

20 Commits

Author SHA1 Message Date
8c23f974c3 commented protobuf compilation 2025-05-23 03:06:29 +05:00
36d39b524c moved data to public dir 2025-05-23 01:24:22 +05:00
9415c60287 invalid data deletion fix 2025-05-23 01:22:11 +05:00
4d7fbeae42 updated dependencies 2025-05-22 21:44:21 +05:00
d7dcd7afc9 added database to store metadata 2025-04-10 19:56:35 +05:00
c4af1f31e8 implemented boolean values parsing 2025-04-10 16:22:21 +05:00
74d09c51a0 Parser now creates lists only when it is necessary 2025-04-10 16:13:03 +05:00
08f1d7b0f5 made SearchArgs a struct to reduce allocations count 2025-04-10 16:12:00 +05:00
d5b6061cc7 SaveDataFilter 2025-04-10 15:42:39 +05:00
95c0403362 created data_filtering.txt 2025-04-08 18:04:22 +05:00
7353cbcd49 fixed some bugs 2025-04-08 18:03:56 +05:00
890166ebce began Protobuf integration 2025-04-06 17:45:54 +05:00
2c094bab3b created README.md 2025-04-06 16:32:19 +05:00
34cfebf89c documented routes 2025-04-06 16:19:03 +05:00
daa8305dde implemented /getSaveData route 2025-04-06 15:56:19 +05:00
da27f84d68 disabled null values serialization 2025-04-06 15:55:58 +05:00
d70b605127 refactored responses 2025-04-06 15:37:32 +05:00
3c1d195849 split CLI modes to separate files 2025-04-06 13:53:21 +05:00
eeb8f43d3d CLI zip file extract to memory 2025-04-06 11:24:25 +05:00
21b7671426 newline fix 2025-04-06 01:48:32 +05:00
39 changed files with 1026 additions and 419 deletions

View File

@@ -1,5 +1,4 @@
using System.Text.Json;
using ParadoxSaveParser.Lib;
using Path = DTLib.Filesystem.Path;
namespace ParadoxSaveParser.CLI;
@@ -8,27 +7,11 @@ internal enum Mode
Unset, Search, Interactive
}
internal static class Modes
internal static partial class Modes
{
internal static void Search(string searchQuery, IOPath inputPath, IOPath? outputPath)
{
using var inputStream = File.OpenRead(inputPath);
using var outputStream = outputPath is null
? Console.OpenStandardOutput()
: File.OpenWrite(outputPath.Value);
var searchExpression = SearchExpressionCompiler.Compile(searchQuery);
var parser = new SaveParserEU4(inputStream, searchExpression);
var parsedValue = parser.Parse();
JsonSerializer.Serialize(outputStream, parsedValue, ParsedValueJsonContext.Default.DictionaryStringListObject);
}
internal static void Interactive()
{
Console.Clear();
Console.ResetColor();
ColoredConsole.Clear();
ColoredConsole.WriteTitle("interactive mode", fg: ConsoleColor.Cyan);
ColoredConsole.WriteLine($"working directory: '{Environment.CurrentDirectory}'", ConsoleColor.Gray);
IOPath? inputPath = null;
@@ -39,8 +22,7 @@ internal static class Modes
try
{
ColoredConsole.Write("> ", ConsoleColor.Blue);
Console.ForegroundColor = ConsoleColor.Gray;
string? input = Console.ReadLine();
string input = ColoredConsole.ReadLine(ConsoleColor.Gray);
if (string.IsNullOrEmpty(input))
continue;
@@ -80,25 +62,25 @@ internal static class Modes
case "h":
case "help":
ColoredConsole.WriteLine(helpMessage, fg: ConsoleColor.White);
ColoredConsole.WriteLine(helpMessage, ConsoleColor.White);
break;
case "i":
case "input":
input = ColoredConsole.ReadLine("Input file path",
ConsoleColor.Blue);
ColoredConsole.Write("Input file path: ", ConsoleColor.Blue);
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
if (string.IsNullOrEmpty(input))
throw new NullReferenceException();
throw new ArgumentException("Input file path is required");
inputPath = input;
break;
case "o":
case "output":
input = ColoredConsole.ReadLine("Output file path [default=stdout]",
ConsoleColor.Blue);
ColoredConsole.Write("Output file path [default=stdout]: ", ConsoleColor.Blue);
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
if(string.IsNullOrEmpty(input))
throw new ArgumentException("Input file path is required");
inputPath = input;
outputPath = null;
else outputPath = input;
break;
case "s":
@@ -106,8 +88,8 @@ internal static class Modes
if (inputPath is null)
throw new ArgumentException("Input file path is required");
var searchQuery = ColoredConsole.ReadLine("search expression",
ConsoleColor.Blue);
ColoredConsole.Write("search expression: ", ConsoleColor.Blue);
var searchQuery = ColoredConsole.ReadLine(ConsoleColor.Gray);
if (string.IsNullOrEmpty(searchQuery))
throw new ArgumentException("Search expression is required");
@@ -122,8 +104,8 @@ internal static class Modes
break;
case "cd":
input = ColoredConsole.ReadLine("Change working directory to",
ConsoleColor.Blue);
ColoredConsole.Write("Change working directory to: ", ConsoleColor.Blue);
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
if (!string.IsNullOrEmpty(input))
{
Environment.CurrentDirectory = new IOPath(input).Str;

View File

@@ -0,0 +1,49 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using ParadoxSaveParser.Lib;
namespace ParadoxSaveParser.CLI;
internal static partial class Modes
{
internal static void Search(string searchQuery, IOPath inputPath, IOPath? outputPath)
{
Stream inputStream = File.OpenRead(inputPath);
try
{
byte[] head4 = new byte[4];
inputStream.ReadExactly(head4);
inputStream.Seek(0, SeekOrigin.Begin);
if (head4.SequenceEqual<byte>([(byte)'P', (byte)'K', 3, 4]))
{
var zipArchive = new ZipArchive(inputStream, ZipArchiveMode.Read);
var zipEntry = zipArchive.Entries.FirstOrDefault(e => e.Name == "gamestate");
if (zipEntry is null)
throw new Exception("'gamestate' file not found in zip archive");
var unzipped = new MemoryStream((int)zipEntry.Length);
zipEntry.Open().CopyTo(unzipped);
zipArchive.Dispose(); // closes inputStream
unzipped.Seek(0, SeekOrigin.Begin);
inputStream = unzipped;
}
using var outputStream = outputPath is null
? Console.OpenStandardOutput()
: File.OpenWrite(outputPath.Value);
var searchExpression = SearchExpressionCompiler.Compile(searchQuery);
var parser = new SaveParserEU4(inputStream, searchExpression);
var parsedValue = parser.Parse();
JsonSerializer.Serialize(outputStream, parsedValue,
ParsedValueJsonContext.Default.DictionaryStringObject);
outputStream.WriteByte((byte)'\n');
}
finally
{
inputStream.Dispose();
}
}
}

View File

@@ -14,6 +14,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="DTLib" Version="1.6.5"/>
<PackageReference Include="DTLib" Version="1.7.4" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=modes/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -33,7 +33,7 @@ try
},
"search expression")
)
.WithNoExit()
.AllowNoArguments()
.ParseAndHandle(args);
if (args.Length == 0)
@@ -57,6 +57,10 @@ try
break;
}
}
catch (LaunchArgumentParser.ExitAfterHelpException)
{
// this exception is throwed after -h argument to close the program
}
catch (Exception ex)
{
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);

View File

@@ -23,8 +23,8 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="DTLib" Version="1.6.5"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="DTLib" Version="1.7.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
<PackageReference Include="NUnit" Version="4.3.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
<PrivateAssets>all</PrivateAssets>

View File

@@ -1,6 +1,7 @@
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using DTLib.Extensions;
namespace ParadoxSaveParser.Lib.Tests;
@@ -22,7 +23,8 @@ public class SearchExpressionTests
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = 1024
MaxDepth = 1024,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
internal static string JsonToPdx(string json)

View File

@@ -8,6 +8,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="9.0.3" />
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="9.0.5" />
</ItemGroup>
</Project>

View File

@@ -3,11 +3,12 @@
namespace ParadoxSaveParser.Lib;
[JsonSourceGenerationOptions(MaxDepth = 1024, WriteIndented = true)]
[JsonSerializable(typeof(Dictionary<string, List<object>>))]
[JsonSerializable(typeof(Dictionary<string, object>))]
[JsonSerializable(typeof(List<object>))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(long))]
[JsonSerializable(typeof(double))]
[JsonSerializable(typeof(bool))]
public partial class ParsedValueJsonContext : JsonSerializerContext
{
}

View File

@@ -154,12 +154,17 @@ public class SaveParserEU4
switch (tok.type)
{
case TokenType.StringOrNumber:
try
{
// string values can be empty
if (tok.value!.Length == 0)
return string.Empty;
if (tok.value.Equals("yes"))
return true;
if (tok.value.Equals("no"))
return false;
string tokStr = tok.value.ToString();
_stringBuilderPool.Return(tok.value);
if (tokStr[0] != '-' && !char.IsDigit(tokStr[0]))
return tokStr;
if (tokStr.Contains('.') && double.TryParse(tokStr, out double d))
@@ -167,6 +172,11 @@ public class SaveParserEU4
if (long.TryParse(tokStr, out long l))
return l;
return tokStr;
}
finally
{
_stringBuilderPool.Return(tok.value!);
}
case TokenType.BracketOpen:
object obj = ParseListOrDict();
return obj;
@@ -216,7 +226,7 @@ public class SaveParserEU4
}
private static bool IsEmptyCollection(object value)
=> value is Dictionary<string, List<object>> { Count: 0 } or List<object> { Count: 0 };
=> value is Dictionary<string, object> { Count: 0 } or List<object> { Count: 0 };
// doesn't move next
private object ParseListOrDict()
@@ -264,9 +274,9 @@ public class SaveParserEU4
}
// moves next
private Dictionary<string, List<object>> ParseDict()
private Dictionary<string, object> ParseDict()
{
Dictionary<string, List<object>> dict = new();
Dictionary<string, object> dict = new();
// root is a dict without closing bracket, so this method must check _tokenIndex < _tokens.Count
for (int localIndex = 0; _tokens.MoveNext(); localIndex++)
@@ -327,23 +337,32 @@ public class SaveParserEU4
string keyStr = keySB.ToString();
_stringBuilderPool.Return(keySB);
if (!dict.TryGetValue(keyStr, out var list))
// Paradox save format has another way of defining list:
// a = 1
// a = 2
// It means `a = { 1 2 }`
if (dict.TryGetValue(keyStr, out var firstValue))
{
list = new List<object>();
dict.Add(keyStr, list);
}
// do dot add empty collections into list
// Do dot add empty collections into list.
// `key:{}` is okay, but i don't want to see `key:[{},{},{},{},{},{}]`
if (IsEmptyCollection(value))
continue;
list.Add(value);
if (firstValue is List<object> existingList)
existingList.Add(value);
else dict[keyStr] = new List<object> { firstValue, value };
}
else
{
dict.Add(keyStr, value);
}
}
return dict;
}
public Dictionary<string, List<object>> Parse()
public Dictionary<string, object> Parse()
{
var root = ParseDict();
return root;

View File

@@ -1,6 +1,6 @@
namespace ParadoxSaveParser.Lib;
public record SearchArgs
public readonly record struct SearchArgs
{
public readonly string KeyStr;
public readonly StringBuilder? KeySB;
@@ -41,7 +41,8 @@ public static class SearchExpressionCompiler
var subExprs = new List<ISearchExpression>();
int supExprBegin = 1;
int bracketBalance = 1;
for (int i = supExprBegin; i < query.Length && bracketBalance != 0; i++)
int i = supExprBegin;
for (; i < query.Length && bracketBalance != 0; i++)
{
if (CharEqualsAndNotEscaped('(', query, i))
{
@@ -60,7 +61,7 @@ public static class SearchExpressionCompiler
}
}
if (query[^1] != ')')
if (i != query.Length)
throw new NotImplementedException("Expressions after ')' are not supported");
if (bracketBalance > 0)
@@ -68,7 +69,7 @@ public static class SearchExpressionCompiler
if (bracketBalance < 0)
throw new Exception("Too many closing brackets");
var subPartLast = query.Slice(supExprBegin, query.Length - supExprBegin - 1);
var subPartLast = query.Slice(supExprBegin, i - 1 - supExprBegin);
var subExprLast = Compile(subPartLast);
subExprs.Add(subExprLast);
return new MultipleMatchExpression(subExprs);

View File

@@ -0,0 +1,25 @@
using ParadoxSaveParser.WebAPI.Database;
using ParadoxSaveParser.WebAPI.SaveDataFilters;
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
public class BackgroundJobManager
{
private readonly ILogger _parentLogger;
private long _lastJobId;
public BackgroundJobManager(ILogger logger)
{
_parentLogger = logger;
}
public SaveParsingOperation StartNewParsingOperation(
SaveFileMetadata meta, ISaveDataFilter filter, CancellationToken ct)
{
long nextId = Interlocked.Increment(ref _lastJobId);
var contextLogger = new ContextLogger($"BackgroundJob-{nextId}", _parentLogger);
var op = new SaveParsingOperation(nextId, meta, filter, contextLogger, ct);
op.StartAsync();
return op;
}
}

View File

@@ -0,0 +1,102 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using ParadoxSaveParser.WebAPI.Database;
using ParadoxSaveParser.WebAPI.SaveDataFilters;
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
public class SaveParsingOperation
{
public readonly long OperationId;
private readonly SaveFileMetadata _meta;
private readonly ISaveDataFilter _filter;
private readonly ContextLogger _logger;
private readonly CancellationToken _ct;
private static readonly JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = 1024,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
public SaveParsingOperation(long operationId, SaveFileMetadata meta, ISaveDataFilter filter,
ContextLogger logger, CancellationToken ct)
{
OperationId = operationId;
_meta = meta;
_filter = filter;
_logger = logger;
_ct = ct;
}
public async void StartAsync()
{
try
{
_logger.LogInfo($"Starting background parsing operation of {_meta.game} save {_meta.id}");
switch (_meta.game)
{
case Game.EU4:
await ParseSaveEU4();
break;
default:
throw new ArgumentOutOfRangeException(_meta.game.ToString());
}
_logger.LogInfo($"Finished parsing operation of {_meta.game} save {_meta.id}");
}
catch (Exception ex)
{
string errorMesage = ex.ToStringDemystified();
_logger.LogError(errorMesage);
try
{
await Program.DB.SetMetadataError(_meta, errorMesage);
}
catch (Exception ex2)
{
_logger.LogError(ex2);
}
}
finally
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true);
}
}
private async Task ParseSaveEU4()
{
// wait for save file closing
await Task.Delay(200, _ct);
Dictionary<string, object> parsedData;
await using (var gamestateStream = PathHelper.CreateTempFile())
{
using (var zipArchive = ZipFile.Open(_meta.GetSaveFilePath().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");
await zipEntry.Open().CopyToAsync(gamestateStream, _ct);
gamestateStream.Seek(0, SeekOrigin.Begin);
}
await Program.DB.UpdateMetadataStatus(_meta, SaveFileProcessingStatus.Parsing);
var parser = new SaveParserEU4(gamestateStream, _filter.SearchExpression);
parsedData = parser.Parse();
}
_filter.Apply(parsedData);
await Program.DB.UpdateMetadataStatus(_meta, SaveFileProcessingStatus.SavingResults);
var resultFilePath = _meta.GetParsedDataPath();
await using (var resultFile = File.OpenWrite(resultFilePath))
await JsonSerializer.SerializeAsync(resultFile, parsedData, _jsonOptions, _ct);
await Program.DB.UpdateMetadataStatus(_meta, SaveFileProcessingStatus.Done);
}
}

View File

@@ -0,0 +1,106 @@
using System.Linq;
using SQLite;
namespace ParadoxSaveParser.WebAPI.Database;
public class DatabaseConnector
{
private readonly int _uploadsLifetimeDays;
private readonly SQLiteAsyncConnection _db;
private readonly ContextLogger _logger;
public DatabaseConnector(string databasePath, int uploadsLifetimeDays, ILogger logger)
{
_uploadsLifetimeDays = uploadsLifetimeDays;
_db = new SQLiteAsyncConnection(databasePath);
_logger = new ContextLogger("Database", logger);
}
public async Task InitializeAsync()
{
await _db.CreateTableAsync<SaveFileMetadata>();
}
public async Task<SaveFileMetadata?> GetMetadata(string id)
{
return (await _db.QueryAsync<SaveFileMetadata>(
"select * from SaveFileMetadata where id = ?", id))
.FirstOrDefault();
}
public async Task<SaveFileMetadata> CreateMetadata(Game game)
{
var meta = new SaveFileMetadata
{
id = Guid.NewGuid().ToString(),
game = game,
status = SaveFileProcessingStatus.Initialized,
uploadDateTime = DateTime.Now
};
await _db.InsertAsync(meta);
return meta;
}
public async Task UpdateMetadataStatus(SaveFileMetadata meta, SaveFileProcessingStatus status)
{
meta.status = status;
await _db.UpdateAsync(meta);
}
public async Task SetMetadataError(SaveFileMetadata meta, string errorMessage)
{
meta.errorMessage = errorMessage;
await UpdateMetadataStatus(meta, SaveFileProcessingStatus.Error);
TryDeleteAssociatedFiles(meta);
}
public async Task DeleteMetadata(SaveFileMetadata meta, string reason)
{
_logger.LogDebug($"Deleting save file (id: {meta.id} reason: {reason}" +
$"uploadDate: {meta.uploadDateTime:yyyy/MM/dd})");
await _db.DeleteAsync(meta);
TryDeleteAssociatedFiles(meta);
}
/// <summary>
/// WARNING: Call this method only when no parsing operations are running.
/// </summary>
public async Task DeleteInvalidData()
{
_logger.LogInfo("Deleting invalid data...");
var expirationDate = DateTime.Now.AddDays(-_uploadsLifetimeDays);
var metadataTable = _db.Table<SaveFileMetadata>();
var metadataList = await metadataTable.ToListAsync();
int deleteCount = 0;
foreach (var meta in metadataList)
{
string deletionReason;
if(meta.status != SaveFileProcessingStatus.Done)
deletionReason = $"invalid status ({meta.status})";
else if (meta.uploadDateTime < expirationDate)
deletionReason = "expired";
else if(!meta.AssociatedFilesExist())
deletionReason = "files not found";
else continue;
deleteCount++;
await DeleteMetadata(meta, deletionReason);
}
_logger.LogInfo($"Deleted {deleteCount} invalid records");
}
private void TryDeleteFile(IOPath file)
{
if (!File.Exists(file)) return;
_logger.LogDebug($"Deleting file '{file}'");
File.Delete(file);
}
private void TryDeleteAssociatedFiles(SaveFileMetadata meta)
{
TryDeleteFile(meta.GetSaveFilePath());
TryDeleteFile(meta.GetParsedDataPath());
}
}

View File

@@ -0,0 +1,45 @@
using System.Text.Json.Serialization;
namespace ParadoxSaveParser.WebAPI.Database;
public enum SaveFileProcessingStatus
{
Initialized,
Uploaded,
Parsing,
SavingResults,
Done,
Error,
}
public class SaveFileMetadata
{
[SQLite.PrimaryKey]
[SQLite.NotNull]
public string id { get; init; } = null!;
[JsonConverter(typeof(JsonStringEnumConverter))]
[SQLite.NotNull]
public Game game { get; init; }
[JsonConverter(typeof(JsonStringEnumConverter))]
[SQLite.NotNull]
public SaveFileProcessingStatus status { get; set; }
[SQLite.NotNull]
public DateTime uploadDateTime { get; set; }
// if error occured during parsing, it's message is saved here
// status stays the same as when error occured
public string? errorMessage { get; set; }
public IOPath GetSaveFilePath() => Path.Concat(PathHelper.SAVES_DIR, id + ".eu4");
public IOPath GetParsedDataPath() => Path.Concat(PathHelper.PARSED_DIR, id + ".parsed.json");
public bool AssociatedFilesExist()
{
return File.Exists(GetSaveFilePath()) && File.Exists(GetParsedDataPath());
}
}

View File

@@ -0,0 +1,7 @@
namespace ParadoxSaveParser.WebAPI;
public enum Game
{
Unknown,
EU4
}

View File

@@ -0,0 +1,17 @@
using System.Net;
using System.Text.Json.Serialization;
namespace ParadoxSaveParser.WebAPI.HttpHelpers;
public record ErrorMessage
{
public ErrorMessage(HttpStatusCode statusCode, string message)
{
StatusCode = statusCode;
Message = message;
}
[JsonIgnore] public HttpStatusCode StatusCode { get; }
[JsonPropertyName("errorMessage")] public string Message { get; }
}

View File

@@ -0,0 +1,17 @@
using System.Linq;
using System.Net;
namespace ParadoxSaveParser.WebAPI.HttpHelpers;
public class RequestHelper
{
internal static ValueOrError<string> GetQueryValue(HttpListenerContext ctx, string paramName)
{
string[]? values = ctx.Request.QueryString.GetValues(paramName);
string? value = values?.FirstOrDefault();
if (string.IsNullOrEmpty(value))
return new ErrorMessage(HttpStatusCode.BadRequest,
$"No request parameter '{paramName}' provided");
return value;
}
}

View File

@@ -0,0 +1,96 @@
using System.IO;
using System.Net;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using DTLib.Extensions;
namespace ParadoxSaveParser.WebAPI.HttpHelpers;
public class ReturnHelper
{
private static readonly JsonSerializerOptions _responseJsonSerializerOptions = new()
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = 1024,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private static async Task ResponseShort(HttpListenerContext ctx,
ContextLogger logger,
CancellationToken ct,
byte[] value,
HttpStatusCode statusCode,
string contentType)
{
ctx.Response.StatusCode = (int)statusCode;
ctx.Response.ContentType = contentType;
logger.LogDebug($"short response (length: {value.Length} type: {contentType})");
if (value.Length > 4000)
{
logger.LogWarn($"response (length: {value.Length} type: {contentType})\n"
+ $"Content is too big for {nameof(ResponseShort)}."
+ $"You should send stream instead of byte array.");
}
await ctx.Response.OutputStream.WriteAsync(value, ct);
}
public static async Task<HttpStatusCode> ResponseString(
HttpListenerContext ctx,
ContextLogger logger,
CancellationToken ct,
string value,
HttpStatusCode statusCode = HttpStatusCode.OK,
string contentType = "text/plain")
{
await ResponseShort(ctx, logger, ct, value.ToBytes(), statusCode, contentType);
logger.LogDebug(value);
return statusCode;
}
public static async Task<HttpStatusCode> ResponseJson(
HttpListenerContext ctx,
ContextLogger logger,
CancellationToken ct,
object value,
HttpStatusCode statusCode = HttpStatusCode.OK)
{
string json = JsonSerializer.Serialize(
value,
value.GetType(),
_responseJsonSerializerOptions);
return await ResponseString(ctx, logger, ct, json, statusCode, "application/json");
}
public static async Task<HttpStatusCode> ResponseError(
HttpListenerContext ctx,
ContextLogger logger,
CancellationToken ct,
ErrorMessage error)
{
return await ResponseJson(ctx, logger, ct, error, error.StatusCode);
}
public static async Task<HttpStatusCode> ResponseStream(HttpListenerContext ctx,
ContextLogger logger,
CancellationToken ct,
Stream valueStream,
HttpStatusCode statusCode = HttpStatusCode.OK,
string contentType = "application/octet-stream")
{
try
{
ctx.Response.StatusCode = (int)statusCode;
ctx.Response.ContentType = contentType;
logger.LogDebug($"stream response (type: {contentType})");
await valueStream.CopyToAsync(ctx.Response.OutputStream, ct);
return statusCode;
}
catch (Exception ex)
{
return await ResponseError(ctx, logger, ct,
new ErrorMessage(HttpStatusCode.InternalServerError,
ex.ToStringDemystified()));
}
}
}

View File

@@ -0,0 +1,19 @@
namespace ParadoxSaveParser.WebAPI.HttpHelpers;
public class ValueOrError<T>
{
public readonly ErrorMessage? Error;
public readonly T? Value;
private ValueOrError(T? value, ErrorMessage? error)
{
Value = value;
Error = error;
}
public bool HasError => Error is not null;
public static implicit operator ValueOrError<T>(T v) => new(v, null);
public static implicit operator ValueOrError<T>(ErrorMessage e) => new(default, e);
}

View File

@@ -13,6 +13,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="DTLib.Web" Version="1.2.2"/>
<PackageReference Include="DTLib.Web" Version="1.4.0" />
<!-- <PackageReference Include="Google.Protobuf" Version="3.31.0" />-->
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
</ItemGroup>
<!-- <ItemGroup>-->
<!-- <Compile Include="obj\Protobuf\*.g.cs" />-->
<!-- </ItemGroup>-->
<!-- <Target Name="PreBuild" BeforeTargets="PreBuildEvent">-->
<!-- <Exec Command="sh -c &quot;mkdir -p obj/Protobuf &amp;&amp; protoc Protobuf/*.proto &#45;&#45;csharp_out=obj/Protobuf &#45;&#45;csharp_opt=file_extension=.g.cs&quot;" />-->
<!-- </Target>-->
</Project>

View File

@@ -1,13 +1,37 @@
namespace ParadoxSaveParser.WebAPI;
using System.IO;
namespace ParadoxSaveParser.WebAPI;
public static class PathHelper
{
public static readonly IOPath DATA_DIR = "data";
public static readonly IOPath PUBLIC_DIR = "public";
public static readonly IOPath DATA_DIR = Path.Concat(PUBLIC_DIR, "data");
public static readonly IOPath SAVES_DIR = Path.Concat(DATA_DIR, "saves");
public static readonly IOPath PARSED_DIR = Path.Concat(DATA_DIR, "parsed");
public static readonly IOPath TEMP_DIR = "temp";
public static IOPath GetMetaFilePath(string save_id) => Path.Concat(SAVES_DIR, save_id + ".meta.json");
public static IOPath GetSaveFilePath(string save_id) => Path.Concat(SAVES_DIR, save_id + ".eu4");
public static IOPath GetParsedSaveFilePath(string save_id) => Path.Concat(SAVES_DIR, save_id + ".parsed.json");
public static void CreateProgramDirectories()
{
Directory.Create(DATA_DIR);
Directory.Create(SAVES_DIR);
Directory.Create(PARSED_DIR);
Directory.Create(TEMP_DIR);
}
public static void CleanTempDirectory()
{
Directory.Delete(TEMP_DIR);
Directory.Create(TEMP_DIR);
}
public static Stream CreateTempFile()
{
string fileName = Guid.NewGuid().ToString();
IOPath filePath = Path.Concat(TEMP_DIR, fileName);
var stream = System.IO.File.Open(filePath.Str, FileMode.CreateNew, FileAccess.ReadWrite,
FileShare.Read | FileShare.Delete);
// file stays as a ghost until it is closed
File.Delete(filePath);
return stream;
}
}

View File

@@ -1,97 +0,0 @@
using System.Linq;
using System.Net;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using DTLib.Extensions;
namespace ParadoxSaveParser.WebAPI;
public partial class Program
{
private static readonly JsonSerializerOptions _responseJsonSerializerOptions = new()
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = 1024
};
public static async Task<HttpStatusCode> ReturnResponseString(HttpListenerContext ctx,
string value, HttpStatusCode statusCode = HttpStatusCode.OK)
{
ctx.Response.StatusCode = (int)statusCode;
ctx.Response.ContentType = "text/plain";
await ctx.Response.OutputStream.WriteAsync(
value.ToBytes(),
_mainCancel.Token);
return statusCode;
}
public static async Task<HttpStatusCode> ReturnResponseJson(HttpListenerContext ctx,
object value, HttpStatusCode statusCode = HttpStatusCode.OK)
{
ctx.Response.StatusCode = (int)statusCode;
ctx.Response.ContentType = "application/json";
await JsonSerializer.SerializeAsync(
ctx.Response.OutputStream,
value,
value.GetType(),
_responseJsonSerializerOptions,
_mainCancel.Token);
return statusCode;
}
public static async Task<HttpStatusCode> ReturnResponseError(HttpListenerContext ctx, ErrorMessage error)
{
ctx.Response.StatusCode = (int)error.StatusCode;
ctx.Response.ContentType = "application/json";
await JsonSerializer.SerializeAsync(
ctx.Response.OutputStream,
error,
typeof(ErrorMessage),
_responseJsonSerializerOptions,
_mainCancel.Token);
return error.StatusCode;
}
internal static ValueOrError<string> GetRequestQueryValue(HttpListenerContext ctx, string paramName)
{
string[]? values = ctx.Request.QueryString.GetValues(paramName);
string? value = values?.FirstOrDefault();
if (string.IsNullOrEmpty(value))
return new ErrorMessage(HttpStatusCode.BadRequest,
$"No request parameter '{paramName}' provided");
return value;
}
public record ErrorMessage
{
public ErrorMessage(HttpStatusCode statusCode, string message)
{
StatusCode = statusCode;
Message = message;
}
[JsonIgnore] public HttpStatusCode StatusCode { get; }
[JsonPropertyName("errorMessage")] public string Message { get; }
}
public class ValueOrError<T>
{
public readonly ErrorMessage? Error;
public readonly T? Value;
private ValueOrError(T? value, ErrorMessage? error)
{
Value = value;
Error = error;
}
public bool HasError => Error is not null;
public static implicit operator ValueOrError<T>(T v) => new(v, null);
public static implicit operator ValueOrError<T>(ErrorMessage e) => new(default, e);
}
}

View File

@@ -1,117 +0,0 @@
using System.IO.Compression;
using System.Linq;
using System.Net;
namespace ParadoxSaveParser.WebAPI;
public partial class Program
{
private static async Task<HttpStatusCode> UploadSaveHandler(HttpListenerContext ctx)
{
string? contentType = ctx.Request.Headers.GetValues("Content-Type")?.FirstOrDefault();
if (contentType != "application/octet-stream")
return await ReturnResponseError(ctx, new ErrorMessage(
HttpStatusCode.BadRequest,
$"Invalid request Content-Type: '{contentType}'"));
string saveId = Guid.NewGuid().ToString();
var metaFilePath = PathHelper.GetMetaFilePath(saveId);
if (File.Exists(metaFilePath))
return await ReturnResponseError(ctx, new ErrorMessage(
HttpStatusCode.InternalServerError,
$"Guid collision! file' {metaFilePath}' already exists."));
var meta = new SaveFileMetadata
{ id = saveId, game = Game.EU4, status = SaveFileProcessingStatus.Initialized };
if (!_saveMetadataStorage.TryAdd(saveId, meta))
return await ReturnResponseError(ctx, new ErrorMessage(
HttpStatusCode.InternalServerError,
$"Guid collision! Can't create metadata with id {saveId}"));
meta.status = SaveFileProcessingStatus.Uploading;
var saveFilePath = PathHelper.GetSaveFilePath(meta.id);
await using var saveFile = File.OpenWrite(saveFilePath);
await using var remoteStream = ctx.Request.InputStream;
await remoteStream.CopyToAsync(saveFile, _mainCancel.Token);
meta.status = SaveFileProcessingStatus.Uploaded;
return await ReturnResponseString(ctx, saveId);
}
private static ValueOrError<SaveFileMetadata> GetMetaFromRequestId(HttpListenerContext ctx,
string requestParamName)
{
var idOrError = GetRequestQueryValue(ctx, requestParamName);
if (idOrError.HasError)
return idOrError.Error!;
if (!_saveMetadataStorage.TryGetValue(idOrError.Value!, out var meta))
return new ErrorMessage(HttpStatusCode.InternalServerError,
$"Save with id {idOrError.Value} not found");
return meta;
}
private static async Task<HttpStatusCode> GetSaveStatusHandler(HttpListenerContext ctx)
{
var metaOrError = GetMetaFromRequestId(ctx, "id");
if (metaOrError.HasError)
return await ReturnResponseError(ctx, metaOrError.Error!);
return await ReturnResponseJson(ctx, metaOrError.Value!);
}
private static async Task<HttpStatusCode> ParseSaveEU4Handler(HttpListenerContext ctx)
{
var metaOrError = GetMetaFromRequestId(ctx, "id");
if (metaOrError.HasError)
return await ReturnResponseError(ctx, metaOrError.Error!);
var meta = metaOrError.Value!;
var searchQueryOrError = GetRequestQueryValue(ctx, "search");
if (searchQueryOrError.HasError)
return await ReturnResponseError(ctx, searchQueryOrError.Error!);
string searchQuery = searchQueryOrError.Value!;
try
{
string extractedGamestatePath = PathHelper.GetSaveFilePath(meta.id) + ".gamestate";
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)
return await ReturnResponseError(ctx, new ErrorMessage(
HttpStatusCode.BadRequest,
"Invalid save format: no 'gamestate' file found"));
zipEntry.ExtractToFile(extractedGamestatePath, true);
}
var gamestateStream = File.OpenRead(extractedGamestatePath);
meta.status = SaveFileProcessingStatus.Parsing;
var se = SearchExpressionCompiler.Compile(searchQuery);
var parser = new SaveParserEU4(gamestateStream, se);
var result = parser.Parse();
meta.status = SaveFileProcessingStatus.SavingResults;
var resultFilePath = PathHelper.GetParsedSaveFilePath(meta.id);
await using var resultFile = File.OpenWrite(resultFilePath);
await JsonSerializer.SerializeAsync(resultFile, result, _saveSerializerOptions, _mainCancel.Token);
meta.status = SaveFileProcessingStatus.Done;
meta.SaveToFile();
}
catch (Exception ex)
{
string errorMesage = ex.ToStringDemystified();
_loggerRoot.LogWarn(nameof(ParseSaveEU4Handler), errorMesage);
return await ReturnResponseError(ctx, new ErrorMessage(HttpStatusCode.BadRequest, errorMesage));
}
finally
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true);
}
return await ReturnResponseJson(ctx, meta);
}
}

View File

@@ -11,100 +11,110 @@ 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.Text.Encodings.Web;
using DTLib.Console;
using DTLib.Dtsod;
using DTLib.Web;
using DTLib.Web.Routes;
using ParadoxSaveParser.WebAPI.BackgroundTasks;
using ParadoxSaveParser.WebAPI.Database;
using ParadoxSaveParser.WebAPI.Routes;
using ParadoxSaveParser.WebAPI.SaveDataFilters;
// ReSharper disable MethodHasAsyncOverload
namespace ParadoxSaveParser.WebAPI;
public static partial class Program
public static class Program
{
private static readonly IOPath _configPath = "./config.dtsod";
private static Config _config = new();
internal static bool IsDebug = true;
internal static DatabaseConnector DB = null!;
private static readonly ILogger _loggerRoot = new CompositeLogger(
new ConsoleLogger(),
new FileLogger("logs", "ParadoxSaveParser.WebAPI"));
private static readonly CancellationTokenSource _mainCancel = new();
private 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)
public static async Task 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");
CancellationTokenSource mainCancel = new();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
logger.LogInfo("Ctrl+C Pressed");
_mainCancel.Cancel();
loggerMain.LogInfo("Ctrl+C Pressed");
mainCancel.Cancel();
};
try
{
// config
if (!File.Exists(_configPath))
IOPath configPath = "./config.dtsod";
Config config;
if (File.Exists(configPath))
{
logger.LogWarn("config file not found.");
File.WriteAllText(_configPath, _config.ToString());
logger.LogWarn($"created default at {_configPath}.");
config = Config.FromDtsod(new DtsodV23(File.ReadAllText(configPath)));
}
else
{
_config = Config.FromDtsod(new DtsodV23(File.ReadAllText(_configPath)));
loggerMain.LogWarn("config file not found.");
config = new();
File.WriteAllText(configPath, config.ToString());
loggerMain.LogWarn($"created default at {configPath}.");
}
PrepareLocalFiles();
PathHelper.CreateProgramDirectories();
PathHelper.CleanTempDirectory();
DB = new("database.sqlite", 30, loggerRoot);
await DB.InitializeAsync();
await DB.DeleteInvalidData();
var bgJobManager = new BackgroundJobManager(loggerRoot);
var saveFilters = new Dictionary<Game, ISaveDataFilter>
{
{ Game.EU4, new SaveDataFilterEU4() },
};
// http server
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);
var router = new SimpleRouter(loggerRoot);
router.DefaultRoute = new SimpleRouter.RouteWithMethod(HttpMethod.GET,
new ServeFilesRouteHandler(PathHelper.PUBLIC_DIR));
router.MapRoute("/uploadSave", HttpMethod.POST,
new UploadSaveHandler(mainCancel.Token, bgJobManager, saveFilters));
router.MapRoute("/getSaveStatus", HttpMethod.GET,
new GetSaveStatusHandler(mainCancel.Token));
router.MapRoute("/getSaveData", HttpMethod.GET,
new GetSaveDataHandler(mainCancel.Token));
var app = new WebApp(_config.BaseUrl, _loggerRoot, router, _mainCancel.Token);
app.Run().GetAwaiter().GetResult();
var app = new WebApp(config.BaseUrl, loggerRoot, router, mainCancel.Token);
await app.Run();
}
catch (OperationCanceledException ex)
{
logger.LogWarn($"catched OperationCanceledException from {ex.Source}");
loggerMain.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 (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!");
loggerMain.LogError(ex.ToStringDemystified());
}
}
}

View File

@@ -0,0 +1,21 @@
syntax = "proto3";
option csharp_namespace = "ParadoxSaveParser.WebAPI.MyProtobuf";
message Item {
oneof value {
bool b = 1;
int64 i64 = 2;
double f64 = 3;
string str = 4;
ItemList list = 5;
ItemListMap map = 6;
}
}
message ItemList {
repeated Item items = 1;
}
message ItemListMap {
map<string, ItemList> items_map = 1;
}

View File

@@ -0,0 +1,44 @@
# WebAPI
Simple web application created using DTLib.Web.
## Important
Restart web application once per day to delete outdated data and clean RAM.
## Routes
### POST `/uploadSave`
- **Query Params:**
- `game` - short name of the game (see [../README.md](../README.md))
- **Request Body:** `application/octet-stream` - .eu4 file
- **Response:**
```json
{ "saveId": "string" }
```
or `{ "errorMessage": "string" }`
### GET `/getSaveStatus`
- **Query Params:**
- `id` - id of uploaded save file
- **Response:** [SaveFileMetadata](./SaveFileMetadata.cs)
```json
{
"id": "string",
"game": "string",
"status": "string",
"errorMessage": "string?"
}
```
### GET `/getSaveData`
- **Query Params:**
- `id` - id of uploaded save file
- **Response:**
```json5
{
"key0": [ "objects" ],
"key1": [ "objects" ],
//...
}
```
or `{ "errorMessage": "string" }`

View File

@@ -0,0 +1,44 @@
using System.Net;
using ParadoxSaveParser.WebAPI.Database;
using ParadoxSaveParser.WebAPI.HttpHelpers;
namespace ParadoxSaveParser.WebAPI.Routes;
internal class GetSaveDataHandler : RouteHandlerBase
{
public GetSaveDataHandler(CancellationToken cancelAllToken)
: base(cancelAllToken)
{
}
public override async Task<HttpStatusCode> HandleRequest(
HttpListenerContext ctx, ContextLogger requestLogger)
{
var idOrError = RequestHelper.GetQueryValue(ctx, "id");
if (idOrError.HasError)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
string id = idOrError.Value!;
var meta = await Program.DB.GetMetadata(id);
if(meta is null)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.NotFound,
$"Save with id {id} not found"));
if(meta.status != SaveFileProcessingStatus.Done)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.BadRequest,
$"Save with id {id} has status {meta.status}"));
IOPath dataFilePath = meta.GetParsedDataPath();
if (!File.Exists(dataFilePath))
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.InternalServerError,
$"Save with id {id} not found")
);
await using var dataFile = File.OpenRead(dataFilePath);
return await ReturnHelper.ResponseStream(ctx, requestLogger, _cancelAllToken,
dataFile, contentType: "application/json");
}
}

View File

@@ -0,0 +1,30 @@
using System.Net;
using ParadoxSaveParser.WebAPI.HttpHelpers;
namespace ParadoxSaveParser.WebAPI.Routes;
internal class GetSaveStatusHandler : RouteHandlerBase
{
public GetSaveStatusHandler(CancellationToken cancelAllToken)
: base(cancelAllToken)
{
}
public override async Task<HttpStatusCode> HandleRequest(
HttpListenerContext ctx, ContextLogger requestLogger)
{
var idOrError = RequestHelper.GetQueryValue(ctx, "id");
if (idOrError.HasError)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
string id = idOrError.Value!;
var meta = await Program.DB.GetMetadata(id);
if (meta is null)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.InternalServerError,
$"Save with id {id} not found")
);
return await ReturnHelper.ResponseJson(ctx, requestLogger, _cancelAllToken, meta);
}
}

View File

@@ -0,0 +1,16 @@
using System.Net;
using DTLib.Web.Routes;
namespace ParadoxSaveParser.WebAPI.Routes;
public abstract class RouteHandlerBase : IRouteHandler
{
protected readonly CancellationToken _cancelAllToken;
protected RouteHandlerBase(CancellationToken cancelAllToken)
{
_cancelAllToken = cancelAllToken;
}
public abstract Task<HttpStatusCode> HandleRequest(HttpListenerContext ctx, ContextLogger requestLogger);
}

View File

@@ -0,0 +1,56 @@
using System.Linq;
using System.Net;
using ParadoxSaveParser.WebAPI.BackgroundTasks;
using ParadoxSaveParser.WebAPI.Database;
using ParadoxSaveParser.WebAPI.HttpHelpers;
using ParadoxSaveParser.WebAPI.SaveDataFilters;
namespace ParadoxSaveParser.WebAPI.Routes;
public class UploadSaveHandler : RouteHandlerBase
{
private readonly BackgroundJobManager _bgJobManager;
private readonly Dictionary<Game, ISaveDataFilter> _saveFilters;
public UploadSaveHandler(
CancellationToken cancelAllToken,
BackgroundJobManager bgJobManager,
Dictionary<Game, ISaveDataFilter> saveFilters)
: base(cancelAllToken)
{
_bgJobManager = bgJobManager;
_saveFilters = saveFilters;
}
public override async Task<HttpStatusCode> HandleRequest(
HttpListenerContext ctx, ContextLogger requestLogger)
{
string? contentType = ctx.Request.Headers.GetValues("Content-Type")?.FirstOrDefault();
if (contentType != "application/octet-stream")
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.BadRequest,
$"Invalid request Content-Type: '{contentType}'"));
var gameStrOrError = RequestHelper.GetQueryValue(ctx, "game");
if (gameStrOrError.HasError)
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, gameStrOrError.Error!);
if (!Enum.TryParse(gameStrOrError.Value, ignoreCase: true, out Game game))
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
new ErrorMessage(HttpStatusCode.BadRequest,
$"Invalid requested game: '{gameStrOrError.Value}'"));
var meta = await Program.DB.CreateMetadata(game);
var saveFilePath = meta.GetSaveFilePath();
await using (var saveFile = File.OpenWrite(saveFilePath))
{
await using (var remoteStream = ctx.Request.InputStream)
await remoteStream.CopyToAsync(saveFile, _cancelAllToken);
}
await Program.DB.UpdateMetadataStatus(meta, SaveFileProcessingStatus.Uploaded);
_bgJobManager.StartNewParsingOperation(meta, _saveFilters[meta.game], _cancelAllToken);
dynamic responseData = new { meta.id };
return await ReturnHelper.ResponseJson(ctx, requestLogger, _cancelAllToken, responseData);
}
}

View File

@@ -0,0 +1,9 @@
namespace ParadoxSaveParser.WebAPI.SaveDataFilters;
public interface ISaveDataFilter
{
public string SearchString { get; }
public ISearchExpression SearchExpression { get; }
public void Apply(Dictionary<string, object> data);
}

View File

@@ -0,0 +1,48 @@
using System.Linq;
using ParsedDict = System.Collections.Generic.Dictionary<string, object>;
namespace ParadoxSaveParser.WebAPI.SaveDataFilters;
public class SaveDataFilterEU4 : ISaveDataFilter
{
public string SearchString { get; }
public ISearchExpression SearchExpression { get; }
public SaveDataFilterEU4()
{
SearchString =
"""
(
active_war|
previous_war|
income_statistics|
nation_size_statistics|
inflation_statistics|
countries.(
---.~|REB.~|PIR.~|NAT.~|
*.(
flags.~|hidden_flags.~|variables.~|estate.~|active_agenda.~|
power_projection.~|ai.~|history.~|navy.~|army.~|mercenary_company.~|
active_relations.~|border_pct.~|border_sit.~|border_provinces.~|
neighbours.~|home_neighbours.~|core_neighbours.~|inflation_history.~|
opinion_cache.~|owned_provinces.~|controlled_provinces.~|core_provinces.~|
claim_provinces.~|leader.~|*
)
)
)
"""
.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
SearchExpression = SearchExpressionCompiler.Compile(SearchString);
}
public void Apply(ParsedDict data)
{
var countries = (ParsedDict)data["countries"];
var countries_filtered = countries.Where(pair
=> ((ParsedDict)pair.Value).TryGetValue("raw_development", out var raw_development)
&& (double)raw_development > 0
).ToDictionary();
data["countries"] = countries_filtered;
}
}

View File

@@ -0,0 +1,43 @@
countries
filter:
always: exists (has raw_development && raw_development != 0)
optional: is player (was_player == yes)
exclude:
flags
hidden_flags
variables
estate
active_agenda
power_projection
ai
history
navy
army
mercenary_company
active_relations
border_pct
border_sit
border_provinces
neighbours
home_neighbours
core_neighbours
inflation_history
opinion_cache
owned_provinces
controlled_provinces
core_provinces
claim_provinces
leader
query:
countries.(---.~|REB.~|PIR.~|NAT.~|*.(flags.~|hidden_flags.~|variables.~|estate.~|active_agenda.~|power_projection.~|ai.~|history.~|navy.~|army.~|mercenary_company.~|active_relations.~|border_pct.~|border_sit.~|border_provinces.~|neighbours.~|home_neighbours.~|core_neighbours.~|inflation_history.~|opinion_cache.~|owned_provinces.~|controlled_provinces.~|core_provinces.~|claim_provinces.~|leader.~|*))
active_war
filter:
optional: only player wars
previous_war
filter:
optional: only player wars
always: not fictive (has losses and lasts long)
income_statistics
nation_size_statistics
inflation_statistics

View File

@@ -1,37 +0,0 @@
using System.Text.Json.Serialization;
namespace ParadoxSaveParser.WebAPI;
public enum SaveFileProcessingStatus
{
Initialized,
Uploading,
Uploaded,
Parsing,
SavingResults,
Done
}
public enum Game
{
Unknown,
EU4
}
public class SaveFileMetadata
{
private static readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true };
public required string id { get; init; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public required Game game { get; init; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public required SaveFileProcessingStatus status { get; set; }
public void SaveToFile()
{
using var metaFile = File.OpenWrite(PathHelper.GetMetaFilePath(id));
JsonSerializer.Serialize(metaFile, this, _jsonOptions);
}
}

View File

@@ -7,7 +7,8 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{F1D312F1-0620-4E35-8D78-9A2808CDE12C}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
TODO.txt = TODO.txt
TODO.md = TODO.md
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ParadoxSaveParser.Lib.Tests", "ParadoxSaveParser.Lib.Tests\ParadoxSaveParser.Lib.Tests.csproj", "{23F4BE1B-3043-4821-9F65-74FF5F57FA59}"

18
README.md Normal file
View File

@@ -0,0 +1,18 @@
# Paradox Save Parser
Yet another save files parser.
## Supported games:
- EU4
## Project structure
- **[ParadoxSaveParser.Lib](./ParadoxSaveParser.Lib)** -
Parser itself
- **[ParadoxSaveParser.Lib.Tests](./ParadoxSaveParser.Lib.Tests)** -
Tests for parser
- **[ParadoxSaveParser.CLI](./ParadoxSaveParser.CLI)** -
Command line tool to parse save files. Can be used in interactive mode.
- **[ParadoxSaveParser.WebAPI](./ParadoxSaveParser.WebAPI)** -
Backend for my save file analytics website (TODO: add repo link).
## Building
1. Install protobuf compiler https://protobuf.dev/installation/

4
TODO.md Normal file
View File

@@ -0,0 +1,4 @@
## WebAPI.SaveParsingOperation:
Save parsed data in protobuf
Re-parse if saved data was parsed with another query
Implement automatic database cleanup

View File

@@ -1,14 +0,0 @@
Parser.CLI:
Temp files management system
Main:
Temp files management system
Database???
Add query to get parsed data
ParseSaveHandler:
Make this method run as background task instead of POST query
Add debug log
Save parsed data in protobuf
Re-parse if saved data was parsed with another query