2025-07-27 20:19:12 +07:00
|
|
|
using System.Buffers;
|
2025-07-27 16:02:56 +07:00
|
|
|
using System.IO.Pipelines;
|
|
|
|
|
using Microsoft.AspNetCore.Http.Json;
|
|
|
|
|
using NetVips;
|
|
|
|
|
using Oh.My.Stitcher;
|
|
|
|
|
using Validation;
|
|
|
|
|
using ZLogger;
|
|
|
|
|
|
|
|
|
|
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(args);
|
|
|
|
|
builder.Logging.ClearProviders().AddZLoggerConsole();
|
|
|
|
|
builder.Services.Configure<JsonOptions>(options =>
|
|
|
|
|
{
|
|
|
|
|
options.SerializerOptions.TypeInfoResolver = StitchSerializerContext.Default;
|
|
|
|
|
});
|
|
|
|
|
WebApplication app = builder.Build();
|
|
|
|
|
|
|
|
|
|
ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
|
|
|
|
|
ILogger logger = loggerFactory.CreateLogger<Program>();
|
|
|
|
|
|
|
|
|
|
string? tilesDirectory = Environment.GetEnvironmentVariable("ASSET_PATH_RO");
|
|
|
|
|
|
|
|
|
|
// sanity check
|
|
|
|
|
Assumes.NotNullOrEmpty(tilesDirectory);
|
|
|
|
|
Assumes.True(File.Exists(Path.Combine(tilesDirectory, "A1.png")));
|
|
|
|
|
Assumes.True(File.Exists(Path.Combine(tilesDirectory, "AE55.png")));
|
|
|
|
|
|
|
|
|
|
app.UseDefaultFiles();
|
|
|
|
|
app.UseStaticFiles();
|
|
|
|
|
app.MapPost("/api/image/generate", (Stitch request) =>
|
|
|
|
|
{
|
|
|
|
|
Pipe pipe = new();
|
|
|
|
|
_ = Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
List<Image> images = [];
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using Image image = Tile.Create(in request, tilesDirectory, images, logger);
|
2025-07-27 20:19:12 +07:00
|
|
|
Pipe innerPipe = new();
|
|
|
|
|
_ = Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
while( true )
|
|
|
|
|
{
|
|
|
|
|
ReadResult result = await innerPipe.Reader.ReadAsync();
|
|
|
|
|
ReadOnlySequence<byte> buffer = result.Buffer;
|
|
|
|
|
if(!buffer.IsEmpty )
|
|
|
|
|
{
|
|
|
|
|
foreach( ReadOnlyMemory<byte> segment in buffer )
|
|
|
|
|
{
|
|
|
|
|
await pipe.Writer.WriteAsync(segment);
|
|
|
|
|
}
|
|
|
|
|
innerPipe.Reader.AdvanceTo(buffer.End);
|
|
|
|
|
if (result.IsCompleted)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
image.WriteToStream(innerPipe.Writer.AsStream(), ".png");
|
2025-07-27 16:02:56 +07:00
|
|
|
}
|
|
|
|
|
catch( Exception e )
|
|
|
|
|
{
|
|
|
|
|
logger.ZLogError(e, $"Error when generating image");
|
|
|
|
|
using Image errorImage = Tile.CreateError(e);
|
|
|
|
|
errorImage.WriteToStream(pipe.Writer.AsStream(), ".png");
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
foreach( Image img in images )
|
|
|
|
|
img.Dispose();
|
|
|
|
|
await pipe.Writer.CompleteAsync();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
return Results.Stream(pipe.Reader.AsStream(), "image/png");
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
app.Run();
|