Compare commits
5 Commits
95c0403362
...
d7dcd7afc9
| Author | SHA1 | Date | |
|---|---|---|---|
| d7dcd7afc9 | |||
| c4af1f31e8 | |||
| 74d09c51a0 | |||
| 08f1d7b0f5 | |||
| d5b6061cc7 |
@ -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
|
||||||
|
|||||||
@ -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.4" />
|
||||||
</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)
|
||||||
string tokStr = tok.value.ToString();
|
return string.Empty;
|
||||||
_stringBuilderPool.Return(tok.value);
|
if (tok.value.Equals("yes"))
|
||||||
if (tokStr[0] != '-' && !char.IsDigit(tokStr[0]))
|
return true;
|
||||||
|
if (tok.value.Equals("no"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string tokStr = tok.value.ToString();
|
||||||
|
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))
|
|
||||||
{
|
|
||||||
list = new List<object>();
|
|
||||||
dict.Add(keyStr, list);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// do dot add empty collections into list
|
// Paradox save format has another way of defining list:
|
||||||
if (IsEmptyCollection(value))
|
// a = 1
|
||||||
continue;
|
// a = 2
|
||||||
list.Add(value);
|
// It means `a = { 1 2 }`
|
||||||
|
if (dict.TryGetValue(keyStr, out var firstValue))
|
||||||
|
{
|
||||||
|
// Do dot add empty collections into 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
|
|||||||
@ -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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
105
ParadoxSaveParser.WebAPI/Database/DatabaseConnector.cs
Normal file
105
ParadoxSaveParser.WebAPI/Database/DatabaseConnector.cs
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
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);
|
||||||
|
DeleteAssociatedFiles(meta);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteMetadata(SaveFileMetadata meta)
|
||||||
|
{
|
||||||
|
_logger.LogDebug($"Deleting save file (id: {meta.id} status: {meta.status} " +
|
||||||
|
$"uploadDate: {meta.uploadDateTime:yyyy/MM/dd})");
|
||||||
|
await _db.DeleteAsync(meta);
|
||||||
|
DeleteAssociatedFiles(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>();
|
||||||
|
int rowCount = await metadataTable.CountAsync();
|
||||||
|
int i = 0;
|
||||||
|
int deleteCount = 0;
|
||||||
|
while(i < rowCount)
|
||||||
|
{
|
||||||
|
var meta = await metadataTable.ElementAtAsync(i)!;
|
||||||
|
if(meta.status != SaveFileProcessingStatus.Done ||
|
||||||
|
meta.uploadDateTime < expirationDate ||
|
||||||
|
!meta.AssociatedFilesExist())
|
||||||
|
{
|
||||||
|
deleteCount++;
|
||||||
|
await DeleteMetadata(meta);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
_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 DeleteAssociatedFiles(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
|
||||||
|
}
|
||||||
@ -15,6 +15,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="DTLib.Web" Version="1.3.0"/>
|
<PackageReference Include="DTLib.Web" Version="1.3.0"/>
|
||||||
<PackageReference Include="Google.Protobuf" Version="3.30.2" />
|
<PackageReference Include="Google.Protobuf" Version="3.30.2" />
|
||||||
|
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@ -6,16 +6,31 @@ public static class PathHelper
|
|||||||
{
|
{
|
||||||
public static readonly IOPath DATA_DIR = "data";
|
public static readonly IOPath DATA_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 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()
|
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;
|
||||||
@ -58,62 +56,54 @@ 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 ServeFilesRouteHandler("public");
|
||||||
router.MapRoute("/getSaveStatus", HttpMethod.GET, new GetSaveStatusHandler(_mainCancel.Token));
|
router.MapRoute("/getSaveStatus", HttpMethod.GET, new GetSaveStatusHandler(mainCancel.Token));
|
||||||
router.MapRoute("/uploadSave/eu4", HttpMethod.POST, new UploadSaveHandler(_mainCancel.Token,
|
router.MapRoute("/uploadSave", HttpMethod.POST, new UploadSaveHandler(mainCancel.Token,
|
||||||
bgJobManager, saveParsingSearchExpressions));
|
bgJobManager, saveFilters));
|
||||||
router.MapRoute("/getSaveData", HttpMethod.GET, new GetSaveDataHandler(_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 +114,4 @@ public static class Program
|
|||||||
loggerMain.LogError(ex.ToStringDemystified());
|
loggerMain.LogError(ex.ToStringDemystified());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -3,11 +3,12 @@ option csharp_namespace = "ParadoxSaveParser.WebAPI.MyProtobuf";
|
|||||||
|
|
||||||
message Item {
|
message Item {
|
||||||
oneof value {
|
oneof value {
|
||||||
int64 i64 = 1;
|
bool b = 1;
|
||||||
double f64 = 2;
|
int64 i64 = 2;
|
||||||
string str = 3;
|
double f64 = 3;
|
||||||
ItemList list = 4;
|
string str = 4;
|
||||||
ItemListMap map = 5;
|
ItemList list = 5;
|
||||||
|
ItemListMap map = 6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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,
|
||||||
|
|||||||
@ -17,8 +17,9 @@ internal class GetSaveStatusHandler : RouteHandlerBase
|
|||||||
if (idOrError.HasError)
|
if (idOrError.HasError)
|
||||||
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,26 @@
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
|
using System.Reflection.Metadata;
|
||||||
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 +30,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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
5
TODO.md
5
TODO.md
@ -1,8 +1,3 @@
|
|||||||
## 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
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user