Compare commits
12 Commits
2c094bab3b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c23f974c3 | |||
| 36d39b524c | |||
| 9415c60287 | |||
| 4d7fbeae42 | |||
| d7dcd7afc9 | |||
| c4af1f31e8 | |||
| 74d09c51a0 | |||
| 08f1d7b0f5 | |||
| d5b6061cc7 | |||
| 95c0403362 | |||
| 7353cbcd49 | |||
| 890166ebce |
@@ -1,9 +1,4 @@
|
|||||||
using System.IO;
|
using Path = DTLib.Filesystem.Path;
|
||||||
using System.IO.Compression;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text.Json;
|
|
||||||
using ParadoxSaveParser.Lib;
|
|
||||||
using Path = DTLib.Filesystem.Path;
|
|
||||||
|
|
||||||
namespace ParadoxSaveParser.CLI;
|
namespace ParadoxSaveParser.CLI;
|
||||||
|
|
||||||
@@ -75,7 +70,7 @@ internal static partial class Modes
|
|||||||
ColoredConsole.Write("Input file path: ", ConsoleColor.Blue);
|
ColoredConsole.Write("Input file path: ", ConsoleColor.Blue);
|
||||||
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
|
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
|
||||||
if (string.IsNullOrEmpty(input))
|
if (string.IsNullOrEmpty(input))
|
||||||
throw new NullReferenceException();
|
throw new ArgumentException("Input file path is required");
|
||||||
inputPath = input;
|
inputPath = input;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -83,9 +78,9 @@ internal static partial class Modes
|
|||||||
case "output":
|
case "output":
|
||||||
ColoredConsole.Write("Output file path [default=stdout]: ", ConsoleColor.Blue);
|
ColoredConsole.Write("Output file path [default=stdout]: ", ConsoleColor.Blue);
|
||||||
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
|
input = ColoredConsole.ReadLine(ConsoleColor.Gray);
|
||||||
if (string.IsNullOrEmpty(input))
|
if(string.IsNullOrEmpty(input))
|
||||||
throw new ArgumentException("Input file path is required");
|
outputPath = null;
|
||||||
inputPath = input;
|
else outputPath = input;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "s":
|
case "s":
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ internal static partial class Modes
|
|||||||
var parser = new SaveParserEU4(inputStream, searchExpression);
|
var parser = new SaveParserEU4(inputStream, searchExpression);
|
||||||
var parsedValue = parser.Parse();
|
var parsedValue = parser.Parse();
|
||||||
JsonSerializer.Serialize(outputStream, parsedValue,
|
JsonSerializer.Serialize(outputStream, parsedValue,
|
||||||
ParsedValueJsonContext.Default.DictionaryStringListObject);
|
ParsedValueJsonContext.Default.DictionaryStringObject);
|
||||||
outputStream.WriteByte((byte)'\n');
|
outputStream.WriteByte((byte)'\n');
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
|
|||||||
@@ -14,6 +14,6 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="DTLib" Version="1.7.1"/>
|
<PackageReference Include="DTLib" Version="1.7.4" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -23,8 +23,8 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="DTLib" Version="1.7.1"/>
|
<PackageReference Include="DTLib" Version="1.7.4" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
|
||||||
<PackageReference Include="NUnit" Version="4.3.2" />
|
<PackageReference Include="NUnit" Version="4.3.2" />
|
||||||
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
|
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
|||||||
@@ -8,6 +8,6 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="9.0.3" />
|
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="9.0.5" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -3,11 +3,12 @@
|
|||||||
namespace ParadoxSaveParser.Lib;
|
namespace ParadoxSaveParser.Lib;
|
||||||
|
|
||||||
[JsonSourceGenerationOptions(MaxDepth = 1024, WriteIndented = true)]
|
[JsonSourceGenerationOptions(MaxDepth = 1024, WriteIndented = true)]
|
||||||
[JsonSerializable(typeof(Dictionary<string, List<object>>))]
|
[JsonSerializable(typeof(Dictionary<string, object>))]
|
||||||
[JsonSerializable(typeof(List<object>))]
|
[JsonSerializable(typeof(List<object>))]
|
||||||
[JsonSerializable(typeof(string))]
|
[JsonSerializable(typeof(string))]
|
||||||
[JsonSerializable(typeof(long))]
|
[JsonSerializable(typeof(long))]
|
||||||
[JsonSerializable(typeof(double))]
|
[JsonSerializable(typeof(double))]
|
||||||
|
[JsonSerializable(typeof(bool))]
|
||||||
public partial class ParsedValueJsonContext : JsonSerializerContext
|
public partial class ParsedValueJsonContext : JsonSerializerContext
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -154,19 +154,29 @@ public class SaveParserEU4
|
|||||||
switch (tok.type)
|
switch (tok.type)
|
||||||
{
|
{
|
||||||
case TokenType.StringOrNumber:
|
case TokenType.StringOrNumber:
|
||||||
// string values can be empty
|
try
|
||||||
if(tok.value!.Length == 0)
|
{
|
||||||
return string.Empty;
|
// 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();
|
string tokStr = tok.value.ToString();
|
||||||
_stringBuilderPool.Return(tok.value);
|
if (tokStr[0] != '-' && !char.IsDigit(tokStr[0]))
|
||||||
if (tokStr[0] != '-' && !char.IsDigit(tokStr[0]))
|
return tokStr;
|
||||||
|
if (tokStr.Contains('.') && double.TryParse(tokStr, out double d))
|
||||||
|
return d;
|
||||||
|
if (long.TryParse(tokStr, out long l))
|
||||||
|
return l;
|
||||||
return tokStr;
|
return tokStr;
|
||||||
if (tokStr.Contains('.') && double.TryParse(tokStr, out double d))
|
}
|
||||||
return d;
|
finally
|
||||||
if (long.TryParse(tokStr, out long l))
|
{
|
||||||
return l;
|
_stringBuilderPool.Return(tok.value!);
|
||||||
return tokStr;
|
}
|
||||||
case TokenType.BracketOpen:
|
case TokenType.BracketOpen:
|
||||||
object obj = ParseListOrDict();
|
object obj = ParseListOrDict();
|
||||||
return obj;
|
return obj;
|
||||||
@@ -216,7 +226,7 @@ public class SaveParserEU4
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsEmptyCollection(object value)
|
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
|
// doesn't move next
|
||||||
private object ParseListOrDict()
|
private object ParseListOrDict()
|
||||||
@@ -264,9 +274,9 @@ public class SaveParserEU4
|
|||||||
}
|
}
|
||||||
|
|
||||||
// moves next
|
// 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
|
// root is a dict without closing bracket, so this method must check _tokenIndex < _tokens.Count
|
||||||
for (int localIndex = 0; _tokens.MoveNext(); localIndex++)
|
for (int localIndex = 0; _tokens.MoveNext(); localIndex++)
|
||||||
@@ -327,23 +337,32 @@ public class SaveParserEU4
|
|||||||
|
|
||||||
string keyStr = keySB.ToString();
|
string keyStr = keySB.ToString();
|
||||||
_stringBuilderPool.Return(keySB);
|
_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>();
|
// Do dot add empty collections into list.
|
||||||
dict.Add(keyStr, list);
|
// `key:{}` is okay, but i don't want to see `key:[{},{},{},{},{},{}]`
|
||||||
|
if (IsEmptyCollection(value))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (firstValue is List<object> existingList)
|
||||||
|
existingList.Add(value);
|
||||||
|
else dict[keyStr] = new List<object> { firstValue, value };
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
dict.Add(keyStr, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// do dot add empty collections into list
|
|
||||||
if (IsEmptyCollection(value))
|
|
||||||
continue;
|
|
||||||
list.Add(value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return dict;
|
return dict;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Dictionary<string, List<object>> Parse()
|
public Dictionary<string, object> Parse()
|
||||||
{
|
{
|
||||||
var root = ParseDict();
|
var root = ParseDict();
|
||||||
return root;
|
return root;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
namespace ParadoxSaveParser.Lib;
|
namespace ParadoxSaveParser.Lib;
|
||||||
|
|
||||||
public record SearchArgs
|
public readonly record struct SearchArgs
|
||||||
{
|
{
|
||||||
public readonly string KeyStr;
|
public readonly string KeyStr;
|
||||||
public readonly StringBuilder? KeySB;
|
public readonly StringBuilder? KeySB;
|
||||||
@@ -41,7 +41,8 @@ public static class SearchExpressionCompiler
|
|||||||
var subExprs = new List<ISearchExpression>();
|
var subExprs = new List<ISearchExpression>();
|
||||||
int supExprBegin = 1;
|
int supExprBegin = 1;
|
||||||
int bracketBalance = 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))
|
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");
|
throw new NotImplementedException("Expressions after ')' are not supported");
|
||||||
|
|
||||||
if (bracketBalance > 0)
|
if (bracketBalance > 0)
|
||||||
@@ -68,7 +69,7 @@ public static class SearchExpressionCompiler
|
|||||||
if (bracketBalance < 0)
|
if (bracketBalance < 0)
|
||||||
throw new Exception("Too many closing brackets");
|
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);
|
var subExprLast = Compile(subPartLast);
|
||||||
subExprs.Add(subExprLast);
|
subExprs.Add(subExprLast);
|
||||||
return new MultipleMatchExpression(subExprs);
|
return new MultipleMatchExpression(subExprs);
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
|
using ParadoxSaveParser.WebAPI.Database;
|
||||||
|
using ParadoxSaveParser.WebAPI.SaveDataFilters;
|
||||||
|
|
||||||
|
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
|
||||||
|
|
||||||
public class BackgroundJobManager
|
public class BackgroundJobManager
|
||||||
{
|
{
|
||||||
@@ -11,11 +14,11 @@ public class BackgroundJobManager
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SaveParsingOperation StartNewParsingOperation(
|
public SaveParsingOperation StartNewParsingOperation(
|
||||||
SaveFileMetadata meta, ISearchExpression searchQuery, CancellationToken ct)
|
SaveFileMetadata meta, ISaveDataFilter filter, CancellationToken ct)
|
||||||
{
|
{
|
||||||
long nextId = Interlocked.Increment(ref _lastJobId);
|
long nextId = Interlocked.Increment(ref _lastJobId);
|
||||||
var contextLogger = new ContextLogger($"BackgroundJob-{nextId}", _parentLogger);
|
var contextLogger = new ContextLogger($"BackgroundJob-{nextId}", _parentLogger);
|
||||||
var op = new SaveParsingOperation(nextId, meta, searchQuery, contextLogger, ct);
|
var op = new SaveParsingOperation(nextId, meta, filter, contextLogger, ct);
|
||||||
op.StartAsync();
|
op.StartAsync();
|
||||||
return op;
|
return op;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,23 @@
|
|||||||
using System.IO.Compression;
|
using System.IO;
|
||||||
|
using System.IO.Compression;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using ParadoxSaveParser.WebAPI.Database;
|
||||||
|
using ParadoxSaveParser.WebAPI.SaveDataFilters;
|
||||||
|
|
||||||
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
|
namespace ParadoxSaveParser.WebAPI.BackgroundTasks;
|
||||||
|
|
||||||
public class SaveParsingOperation
|
public class SaveParsingOperation
|
||||||
{
|
{
|
||||||
public readonly long OperationId;
|
public readonly long OperationId;
|
||||||
public readonly SaveFileMetadata Meta;
|
|
||||||
public readonly ISearchExpression SearchQuery;
|
|
||||||
|
|
||||||
|
private readonly SaveFileMetadata _meta;
|
||||||
|
private readonly ISaveDataFilter _filter;
|
||||||
private readonly ContextLogger _logger;
|
private readonly ContextLogger _logger;
|
||||||
private readonly CancellationToken _cancelToken;
|
private readonly CancellationToken _ct;
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions _saveSerializerOptions = new()
|
private static readonly JsonSerializerOptions _jsonOptions = new()
|
||||||
{
|
{
|
||||||
WriteIndented = false,
|
WriteIndented = false,
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
@@ -22,36 +25,43 @@ public class SaveParsingOperation
|
|||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
};
|
};
|
||||||
|
|
||||||
public SaveParsingOperation(long operationId, SaveFileMetadata meta, ISearchExpression searchQuery,
|
public SaveParsingOperation(long operationId, SaveFileMetadata meta, ISaveDataFilter filter,
|
||||||
ContextLogger logger, CancellationToken cancelToken)
|
ContextLogger logger, CancellationToken ct)
|
||||||
{
|
{
|
||||||
OperationId = operationId;
|
OperationId = operationId;
|
||||||
Meta = meta;
|
_meta = meta;
|
||||||
SearchQuery = searchQuery;
|
_filter = filter;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_cancelToken = cancelToken;
|
_ct = ct;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async void StartAsync()
|
public async void StartAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_logger.LogInfo($"Starting background parsing operation of {Meta.game} save {Meta.id}");
|
_logger.LogInfo($"Starting background parsing operation of {_meta.game} save {_meta.id}");
|
||||||
switch (Meta.game)
|
switch (_meta.game)
|
||||||
{
|
{
|
||||||
case Game.EU4:
|
case Game.EU4:
|
||||||
await ParseSaveEU4();
|
await ParseSaveEU4();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new ArgumentOutOfRangeException(Meta.game.ToString());
|
throw new ArgumentOutOfRangeException(_meta.game.ToString());
|
||||||
}
|
}
|
||||||
_logger.LogInfo($"Finished parsing operation of {Meta.game} save {Meta.id}");
|
_logger.LogInfo($"Finished parsing operation of {_meta.game} save {_meta.id}");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
string errorMesage = ex.ToStringDemystified();
|
string errorMesage = ex.ToStringDemystified();
|
||||||
_logger.LogError(errorMesage);
|
_logger.LogError(errorMesage);
|
||||||
Meta.errorMessage = errorMesage;
|
try
|
||||||
|
{
|
||||||
|
await Program.DB.SetMetadataError(_meta, errorMesage);
|
||||||
|
}
|
||||||
|
catch (Exception ex2)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -62,29 +72,31 @@ public class SaveParsingOperation
|
|||||||
private async Task ParseSaveEU4()
|
private async Task ParseSaveEU4()
|
||||||
{
|
{
|
||||||
// wait for save file closing
|
// wait for save file closing
|
||||||
await Task.Delay(200, _cancelToken);
|
await Task.Delay(200, _ct);
|
||||||
string extractedGamestatePath = PathHelper.GetSaveFilePath(Meta.id) + ".gamestate";
|
Dictionary<string, object> parsedData;
|
||||||
using (var zipArchive = ZipFile.Open(PathHelper.GetSaveFilePath(Meta.id).Str, ZipArchiveMode.Read))
|
await using (var gamestateStream = PathHelper.CreateTempFile())
|
||||||
{
|
{
|
||||||
var zipEntry = zipArchive.Entries.FirstOrDefault(e => e.Name == "gamestate");
|
using (var zipArchive = ZipFile.Open(_meta.GetSaveFilePath().Str, ZipArchiveMode.Read))
|
||||||
if (zipEntry is null)
|
{
|
||||||
throw new Exception("Invalid save format: no 'gamestate' file found");
|
var zipEntry = zipArchive.Entries.FirstOrDefault(e => e.Name == "gamestate");
|
||||||
|
if (zipEntry is null)
|
||||||
|
throw new Exception("Invalid save format: no 'gamestate' file found");
|
||||||
|
|
||||||
zipEntry.ExtractToFile(extractedGamestatePath, true);
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
var gamestateStream = File.OpenRead(extractedGamestatePath);
|
_filter.Apply(parsedData);
|
||||||
|
|
||||||
Meta.status = SaveFileProcessingStatus.Parsing;
|
await Program.DB.UpdateMetadataStatus(_meta, SaveFileProcessingStatus.SavingResults);
|
||||||
var parser = new SaveParserEU4(gamestateStream, SearchQuery);
|
var resultFilePath = _meta.GetParsedDataPath();
|
||||||
var result = parser.Parse();
|
await using (var resultFile = File.OpenWrite(resultFilePath))
|
||||||
|
await JsonSerializer.SerializeAsync(resultFile, parsedData, _jsonOptions, _ct);
|
||||||
Meta.status = SaveFileProcessingStatus.SavingResults;
|
await Program.DB.UpdateMetadataStatus(_meta, SaveFileProcessingStatus.Done);
|
||||||
var resultFilePath = PathHelper.GetParsedSaveFilePath(Meta.id);
|
|
||||||
await using var resultFile = File.OpenWrite(resultFilePath);
|
|
||||||
await JsonSerializer.SerializeAsync(resultFile, result,
|
|
||||||
_saveSerializerOptions, _cancelToken);
|
|
||||||
Meta.status = SaveFileProcessingStatus.Done;
|
|
||||||
Meta.SaveToFile();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
106
ParadoxSaveParser.WebAPI/Database/DatabaseConnector.cs
Normal file
106
ParadoxSaveParser.WebAPI/Database/DatabaseConnector.cs
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
45
ParadoxSaveParser.WebAPI/Database/SaveFileMetadata.cs
Normal file
45
ParadoxSaveParser.WebAPI/Database/SaveFileMetadata.cs
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
7
ParadoxSaveParser.WebAPI/Game.cs
Normal file
7
ParadoxSaveParser.WebAPI/Game.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace ParadoxSaveParser.WebAPI;
|
||||||
|
|
||||||
|
public enum Game
|
||||||
|
{
|
||||||
|
Unknown,
|
||||||
|
EU4
|
||||||
|
}
|
||||||
@@ -13,6 +13,16 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="DTLib.Web" Version="1.3.0"/>
|
<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>
|
||||||
|
|
||||||
|
<!-- <ItemGroup>-->
|
||||||
|
<!-- <Compile Include="obj\Protobuf\*.g.cs" />-->
|
||||||
|
<!-- </ItemGroup>-->
|
||||||
|
|
||||||
|
<!-- <Target Name="PreBuild" BeforeTargets="PreBuildEvent">-->
|
||||||
|
<!-- <Exec Command="sh -c "mkdir -p obj/Protobuf && protoc Protobuf/*.proto --csharp_out=obj/Protobuf --csharp_opt=file_extension=.g.cs"" />-->
|
||||||
|
<!-- </Target>-->
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -4,18 +4,34 @@ namespace ParadoxSaveParser.WebAPI;
|
|||||||
|
|
||||||
public static class PathHelper
|
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 SAVES_DIR = Path.Concat(DATA_DIR, "saves");
|
||||||
|
public static readonly IOPath PARSED_DIR = Path.Concat(DATA_DIR, "parsed");
|
||||||
public static IOPath GetMetaFilePath(string save_id) => Path.Concat(SAVES_DIR, save_id + ".meta.json");
|
public static readonly IOPath TEMP_DIR = "temp";
|
||||||
|
|
||||||
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()
|
public static void CreateProgramDirectories()
|
||||||
{
|
{
|
||||||
Directory.Create(DATA_DIR);
|
Directory.Create(DATA_DIR);
|
||||||
Directory.Create(SAVES_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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,27 +11,25 @@ global using ParadoxSaveParser.Lib;
|
|||||||
global using Directory = DTLib.Filesystem.Directory;
|
global using Directory = DTLib.Filesystem.Directory;
|
||||||
global using File = DTLib.Filesystem.File;
|
global using File = DTLib.Filesystem.File;
|
||||||
global using Path = DTLib.Filesystem.Path;
|
global using Path = DTLib.Filesystem.Path;
|
||||||
using System.Collections.Concurrent;
|
|
||||||
using System.IO;
|
|
||||||
using DTLib.Console;
|
using DTLib.Console;
|
||||||
using DTLib.Dtsod;
|
using DTLib.Dtsod;
|
||||||
using DTLib.Web;
|
using DTLib.Web;
|
||||||
using DTLib.Web.Routes;
|
using DTLib.Web.Routes;
|
||||||
using ParadoxSaveParser.WebAPI.BackgroundTasks;
|
using ParadoxSaveParser.WebAPI.BackgroundTasks;
|
||||||
|
using ParadoxSaveParser.WebAPI.Database;
|
||||||
using ParadoxSaveParser.WebAPI.Routes;
|
using ParadoxSaveParser.WebAPI.Routes;
|
||||||
|
using ParadoxSaveParser.WebAPI.SaveDataFilters;
|
||||||
|
// ReSharper disable MethodHasAsyncOverload
|
||||||
|
|
||||||
namespace ParadoxSaveParser.WebAPI;
|
namespace ParadoxSaveParser.WebAPI;
|
||||||
|
|
||||||
public static class Program
|
public static class Program
|
||||||
{
|
{
|
||||||
private static readonly IOPath _configPath = "./config.dtsod";
|
internal static bool IsDebug = true;
|
||||||
private static Config _config = new();
|
internal static DatabaseConnector DB = null!;
|
||||||
private static bool IsDebug = true;
|
|
||||||
private static readonly CancellationTokenSource _mainCancel = new();
|
|
||||||
internal static readonly ConcurrentDictionary<string, SaveFileMetadata> _saveMetadataStorage = new();
|
|
||||||
|
|
||||||
|
|
||||||
public static void Main(string[] args)
|
public static async Task Main(string[] args)
|
||||||
{
|
{
|
||||||
Console.InputEncoding = Encoding.UTF8;
|
Console.InputEncoding = Encoding.UTF8;
|
||||||
Console.OutputEncoding = Encoding.UTF8;
|
Console.OutputEncoding = Encoding.UTF8;
|
||||||
@@ -59,61 +57,56 @@ public static class Program
|
|||||||
var loggerMain = new ContextLogger(nameof(Main), loggerRoot);
|
var loggerMain = new ContextLogger(nameof(Main), loggerRoot);
|
||||||
loggerMain.LogDebug("Debug log is enabled");
|
loggerMain.LogDebug("Debug log is enabled");
|
||||||
|
|
||||||
|
CancellationTokenSource mainCancel = new();
|
||||||
Console.CancelKeyPress += (_, e) =>
|
Console.CancelKeyPress += (_, e) =>
|
||||||
{
|
{
|
||||||
e.Cancel = true;
|
e.Cancel = true;
|
||||||
loggerMain.LogInfo("Ctrl+C Pressed");
|
loggerMain.LogInfo("Ctrl+C Pressed");
|
||||||
_mainCancel.Cancel();
|
mainCancel.Cancel();
|
||||||
};
|
};
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// config
|
// config
|
||||||
if (!File.Exists(_configPath))
|
IOPath configPath = "./config.dtsod";
|
||||||
|
Config config;
|
||||||
|
if (File.Exists(configPath))
|
||||||
{
|
{
|
||||||
loggerMain.LogWarn("config file not found.");
|
config = Config.FromDtsod(new DtsodV23(File.ReadAllText(configPath)));
|
||||||
File.WriteAllText(_configPath, _config.ToString());
|
|
||||||
loggerMain.LogWarn($"created default at {_configPath}.");
|
|
||||||
}
|
}
|
||||||
else
|
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}.");
|
||||||
}
|
}
|
||||||
|
|
||||||
PathHelper.CreateProgramDirectories();
|
PathHelper.CreateProgramDirectories();
|
||||||
|
PathHelper.CleanTempDirectory();
|
||||||
var metaFiles = System.IO.Directory.GetFiles(
|
DB = new("database.sqlite", 30, loggerRoot);
|
||||||
PathHelper.SAVES_DIR.Str, "*.meta.json",
|
await DB.InitializeAsync();
|
||||||
SearchOption.TopDirectoryOnly);
|
await DB.DeleteInvalidData();
|
||||||
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 bgJobManager = new BackgroundJobManager(loggerRoot);
|
||||||
var saveParsingSearchExpressions = new Dictionary<Game, ISearchExpression>
|
var saveFilters = new Dictionary<Game, ISaveDataFilter>
|
||||||
{
|
{
|
||||||
{ Game.EU4, SearchExpressionCompiler.Compile("*.~") },
|
{ Game.EU4, new SaveDataFilterEU4() },
|
||||||
};
|
};
|
||||||
|
|
||||||
// http server
|
// http server
|
||||||
var router = new SimpleRouter(loggerRoot);
|
var router = new SimpleRouter(loggerRoot);
|
||||||
router.DefaultRoute = new ServeFilesRouteHandler("public");
|
router.DefaultRoute = new SimpleRouter.RouteWithMethod(HttpMethod.GET,
|
||||||
router.MapRoute("/getSaveStatus", HttpMethod.GET, new GetSaveStatusHandler(_mainCancel.Token));
|
new ServeFilesRouteHandler(PathHelper.PUBLIC_DIR));
|
||||||
router.MapRoute("/uploadSave/eu4", HttpMethod.POST, new UploadSaveHandler(_mainCancel.Token,
|
router.MapRoute("/uploadSave", HttpMethod.POST,
|
||||||
bgJobManager, saveParsingSearchExpressions));
|
new UploadSaveHandler(mainCancel.Token, bgJobManager, saveFilters));
|
||||||
router.MapRoute("/getSaveData", HttpMethod.GET, new GetSaveDataHandler(_mainCancel.Token));
|
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);
|
var app = new WebApp(config.BaseUrl, loggerRoot, router, mainCancel.Token);
|
||||||
app.Run().GetAwaiter().GetResult();
|
await app.Run();
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException ex)
|
catch (OperationCanceledException ex)
|
||||||
{
|
{
|
||||||
@@ -124,6 +117,4 @@ public static class Program
|
|||||||
loggerMain.LogError(ex.ToStringDemystified());
|
loggerMain.LogError(ex.ToStringDemystified());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
21
ParadoxSaveParser.WebAPI/Protobuf/ParsedData.proto
Normal file
21
ParadoxSaveParser.WebAPI/Protobuf/ParsedData.proto
Normal 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;
|
||||||
|
}
|
||||||
@@ -1,10 +1,15 @@
|
|||||||
# WebAPI
|
# WebAPI
|
||||||
Simple web application created using DTLib.Web.
|
Simple web application created using DTLib.Web.
|
||||||
|
|
||||||
# Routes
|
|
||||||
|
|
||||||
### POST `/uploadSave/eu4`
|
## Important
|
||||||
- **Request:** `application/octet-stream` - .eu4 file
|
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:**
|
- **Response:**
|
||||||
```json
|
```json
|
||||||
{ "saveId": "string" }
|
{ "saveId": "string" }
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
|
using ParadoxSaveParser.WebAPI.Database;
|
||||||
using ParadoxSaveParser.WebAPI.HttpHelpers;
|
using ParadoxSaveParser.WebAPI.HttpHelpers;
|
||||||
|
|
||||||
namespace ParadoxSaveParser.WebAPI.Routes;
|
namespace ParadoxSaveParser.WebAPI.Routes;
|
||||||
@@ -18,7 +19,17 @@ internal class GetSaveDataHandler : RouteHandlerBase
|
|||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
|
||||||
string id = idOrError.Value!;
|
string id = idOrError.Value!;
|
||||||
|
|
||||||
IOPath dataFilePath = PathHelper.GetParsedSaveFilePath(id);
|
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))
|
if (!File.Exists(dataFilePath))
|
||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
||||||
new ErrorMessage(HttpStatusCode.InternalServerError,
|
new ErrorMessage(HttpStatusCode.InternalServerError,
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ internal class GetSaveStatusHandler : RouteHandlerBase
|
|||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken, idOrError.Error!);
|
||||||
string id = idOrError.Value!;
|
string id = idOrError.Value!;
|
||||||
|
|
||||||
if (!Program._saveMetadataStorage.TryGetValue(id, out var meta))
|
var meta = await Program.DB.GetMetadata(id);
|
||||||
|
if (meta is null)
|
||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
||||||
new ErrorMessage(HttpStatusCode.InternalServerError,
|
new ErrorMessage(HttpStatusCode.InternalServerError,
|
||||||
$"Save with id {id} not found")
|
$"Save with id {id} not found")
|
||||||
|
|||||||
@@ -1,23 +1,25 @@
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using ParadoxSaveParser.WebAPI.BackgroundTasks;
|
using ParadoxSaveParser.WebAPI.BackgroundTasks;
|
||||||
|
using ParadoxSaveParser.WebAPI.Database;
|
||||||
using ParadoxSaveParser.WebAPI.HttpHelpers;
|
using ParadoxSaveParser.WebAPI.HttpHelpers;
|
||||||
|
using ParadoxSaveParser.WebAPI.SaveDataFilters;
|
||||||
|
|
||||||
namespace ParadoxSaveParser.WebAPI.Routes;
|
namespace ParadoxSaveParser.WebAPI.Routes;
|
||||||
|
|
||||||
public class UploadSaveHandler : RouteHandlerBase
|
public class UploadSaveHandler : RouteHandlerBase
|
||||||
{
|
{
|
||||||
private readonly BackgroundJobManager _bgJobManager;
|
private readonly BackgroundJobManager _bgJobManager;
|
||||||
private readonly Dictionary<Game, ISearchExpression> _searchQueries;
|
private readonly Dictionary<Game, ISaveDataFilter> _saveFilters;
|
||||||
|
|
||||||
public UploadSaveHandler(
|
public UploadSaveHandler(
|
||||||
CancellationToken cancelAllToken,
|
CancellationToken cancelAllToken,
|
||||||
BackgroundJobManager bgJobManager,
|
BackgroundJobManager bgJobManager,
|
||||||
Dictionary<Game, ISearchExpression> searchQueries)
|
Dictionary<Game, ISaveDataFilter> saveFilters)
|
||||||
: base(cancelAllToken)
|
: base(cancelAllToken)
|
||||||
{
|
{
|
||||||
_bgJobManager = bgJobManager;
|
_bgJobManager = bgJobManager;
|
||||||
_searchQueries = searchQueries;
|
_saveFilters = saveFilters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<HttpStatusCode> HandleRequest(
|
public override async Task<HttpStatusCode> HandleRequest(
|
||||||
@@ -27,34 +29,28 @@ public class UploadSaveHandler : RouteHandlerBase
|
|||||||
if (contentType != "application/octet-stream")
|
if (contentType != "application/octet-stream")
|
||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
||||||
new ErrorMessage(HttpStatusCode.BadRequest,
|
new ErrorMessage(HttpStatusCode.BadRequest,
|
||||||
$"Invalid request Content-Type: '{contentType}'")
|
$"Invalid request Content-Type: '{contentType}'"));
|
||||||
);
|
|
||||||
|
|
||||||
string saveId = Guid.NewGuid().ToString();
|
var gameStrOrError = RequestHelper.GetQueryValue(ctx, "game");
|
||||||
var metaFilePath = PathHelper.GetMetaFilePath(saveId);
|
if (gameStrOrError.HasError)
|
||||||
if (File.Exists(metaFilePath))
|
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,
|
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
||||||
new ErrorMessage(HttpStatusCode.InternalServerError,
|
new ErrorMessage(HttpStatusCode.BadRequest,
|
||||||
$"Guid collision! file' {metaFilePath}' already exists.")
|
$"Invalid requested game: '{gameStrOrError.Value}'"));
|
||||||
);
|
var meta = await Program.DB.CreateMetadata(game);
|
||||||
|
|
||||||
var meta = new SaveFileMetadata
|
var saveFilePath = meta.GetSaveFilePath();
|
||||||
{ id = saveId, game = Game.EU4, status = SaveFileProcessingStatus.Initialized };
|
await using (var saveFile = File.OpenWrite(saveFilePath))
|
||||||
if (!Program._saveMetadataStorage.TryAdd(saveId, meta))
|
{
|
||||||
return await ReturnHelper.ResponseError(ctx, requestLogger, _cancelAllToken,
|
await using (var remoteStream = ctx.Request.InputStream)
|
||||||
new ErrorMessage(HttpStatusCode.InternalServerError,
|
await remoteStream.CopyToAsync(saveFile, _cancelAllToken);
|
||||||
$"Guid collision! Can't create metadata with id {saveId}")
|
}
|
||||||
);
|
await Program.DB.UpdateMetadataStatus(meta, SaveFileProcessingStatus.Uploaded);
|
||||||
|
|
||||||
meta.status = SaveFileProcessingStatus.Uploading;
|
_bgJobManager.StartNewParsingOperation(meta, _saveFilters[meta.game], _cancelAllToken);
|
||||||
var saveFilePath = PathHelper.GetSaveFilePath(meta.id);
|
dynamic responseData = new { meta.id };
|
||||||
await using var saveFile = File.OpenWrite(saveFilePath);
|
|
||||||
await using var remoteStream = ctx.Request.InputStream;
|
|
||||||
await remoteStream.CopyToAsync(saveFile, _cancelAllToken);
|
|
||||||
meta.status = SaveFileProcessingStatus.Uploaded;
|
|
||||||
|
|
||||||
_bgJobManager.StartNewParsingOperation(meta, _searchQueries[meta.game], _cancelAllToken);
|
|
||||||
dynamic responseData = new { saveId };
|
|
||||||
return await ReturnHelper.ResponseJson(ctx, requestLogger, _cancelAllToken, responseData);
|
return await ReturnHelper.ResponseJson(ctx, requestLogger, _cancelAllToken, responseData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
48
ParadoxSaveParser.WebAPI/SaveDataFilters/SaveFilterEU4.cs
Normal file
48
ParadoxSaveParser.WebAPI/SaveDataFilters/SaveFilterEU4.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -1,45 +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 _configSerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true,
|
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
|
||||||
};
|
|
||||||
public required string id { get; init; }
|
|
||||||
|
|
||||||
[JsonConverter(typeof(JsonStringEnumConverter))]
|
|
||||||
public required Game game { get; init; }
|
|
||||||
|
|
||||||
[JsonConverter(typeof(JsonStringEnumConverter))]
|
|
||||||
public required SaveFileProcessingStatus status { 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 void SaveToFile()
|
|
||||||
{
|
|
||||||
using var metaFile = File.OpenWrite(PathHelper.GetMetaFilePath(id));
|
|
||||||
JsonSerializer.Serialize(metaFile, this, _configSerializerOptions);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,3 +14,5 @@ Yet another save files parser.
|
|||||||
- **[ParadoxSaveParser.WebAPI](./ParadoxSaveParser.WebAPI)** -
|
- **[ParadoxSaveParser.WebAPI](./ParadoxSaveParser.WebAPI)** -
|
||||||
Backend for my save file analytics website (TODO: add repo link).
|
Backend for my save file analytics website (TODO: add repo link).
|
||||||
|
|
||||||
|
## Building
|
||||||
|
1. Install protobuf compiler https://protobuf.dev/installation/
|
||||||
|
|||||||
6
TODO.md
6
TODO.md
@@ -1,8 +1,4 @@
|
|||||||
## WebAPI:
|
|
||||||
Temp files management system
|
|
||||||
Database to store metadata (SQLite-Net Extensions)
|
|
||||||
|
|
||||||
## WebAPI.SaveParsingOperation:
|
## WebAPI.SaveParsingOperation:
|
||||||
Add debug log
|
|
||||||
Save parsed data in protobuf
|
Save parsed data in protobuf
|
||||||
Re-parse if saved data was parsed with another query
|
Re-parse if saved data was parsed with another query
|
||||||
|
Implement automatic database cleanup
|
||||||
Reference in New Issue
Block a user