Ignore token if dev, pass through request cancellation token, tweak word wrapping

main
exsersewo 2 years ago
parent 42c9abba3f
commit 4ee98fa551
Signed by: exsersewo
GPG Key ID: 9C6DDF9AC9BA14A0
  1. 2
      src/Attributes/RequireTokenAttribute.cs
  2. 2
      src/Controllers/ImageGenerationController.cs
  3. 4
      src/Controllers/ImageManipulationController.cs
  4. 17
      src/Helpers/RequestHelper.cs
  5. 11
      src/Helpers/StreamResult.cs
  6. 1
      src/Kynareth.csproj
  7. 26
      src/Managers/ImageManager.Generation.cs
  8. 10
      src/Managers/ImageManager.Magik.cs
  9. 10
      src/Managers/ImageManager.Manipulation.cs
  10. 81
      src/Managers/ImageManager.cs
  11. 1
      src/Program.cs
  12. 2
      src/appsettings.json

@ -20,7 +20,7 @@ public class RequireTokenAttribute : ActionFilterAttribute
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
var invalidRequest = EventResult.FromFailure("Unauthorized request");
await context.HttpContext.Response.WriteAsync(invalidRequest.ToJson());
await context.HttpContext.Response.WriteAsync(invalidRequest.ToJson(), context.HttpContext.RequestAborted);
return;
}
}

@ -34,7 +34,7 @@ public class ImageGenerationController : BaseController<ImageGenerationControlle
{
try
{
var result = await ImageManager.GenerateImageAsync(template, variant, sources);
var result = await ImageManager.GenerateImageAsync(template, variant, sources, Request.HttpContext.RequestAborted);
if (result is byte[] data)
{

@ -28,7 +28,7 @@ public class ImageManipulationController : BaseController<ImageManipulationContr
{
if (!string.IsNullOrWhiteSpace(image))
{
var (data, contentType) = await ImageManager.GetLiquidRescaledImageAsync(image);
var (data, contentType) = await ImageManager.GetLiquidRescaledImageAsync(image, HttpContext.RequestAborted);
return HttpContext.SendStream(data, contentType);
}
@ -68,7 +68,7 @@ public class ImageManipulationController : BaseController<ImageManipulationContr
{
if (!string.IsNullOrWhiteSpace(template))
{
var result = await ImageManager.GenerateMemeImageAsync(template, text);
var result = await ImageManager.GenerateMemeImageAsync(template, text, HttpContext.RequestAborted);
if (result is byte[] data)
{

@ -6,6 +6,13 @@ namespace Kynareth.Helpers;
public static class RequestHelper
{
private static WebApplication _webApplication;
public static void Configure(WebApplication webApp)
{
_webApplication = webApp;
}
public static string GetUrlHostname(this HttpContext context)
{
var origin = context.Request.Headers["X-Original-Host"];
@ -15,6 +22,15 @@ public static class RequestHelper
public static async Task<bool> IsRequestAuthenticatedAsync(this HttpRequest request)
{
if (_webApplication.Environment.IsDevelopment()) return true;
while (true)
{
if(request.HttpContext.RequestAborted.IsCancellationRequested)
{
return false;
}
string key = request.GetToken();
if (string.IsNullOrWhiteSpace(key)) return false;
@ -27,6 +43,7 @@ public static class RequestHelper
return true;
}
}
public static string GetToken(this HttpRequest request)
{

@ -24,6 +24,8 @@ public class StreamResult : ActionResult, IStatusCodeActionResult, IActionResult
throw new ArgumentNullException(nameof(context));
}
try
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCode ?? 200;
@ -34,9 +36,9 @@ public class StreamResult : ActionResult, IStatusCodeActionResult, IActionResult
Value.Position = 0;
await Value.CopyToAsync(response.Body);
await Value.CopyToAsync(response.Body, context.HttpContext.RequestAborted);
await Value.FlushAsync();
await Value.FlushAsync(context.HttpContext.RequestAborted);
await Value.DisposeAsync();
@ -44,4 +46,9 @@ public class StreamResult : ActionResult, IStatusCodeActionResult, IActionResult
GC.Collect();
}
catch (TaskCanceledException)
{
//assume that request was cancelled if this is invoked
}
}
}

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="Exsersewo.Common" Version="2023.1.14" />
<PackageReference Include="ICU4N" Version="60.1.0-alpha.356" />
<PackageReference Include="JwtSharp" Version="1.1.0" />
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="12.2.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.2" />

@ -16,8 +16,15 @@ public static partial class ImageManager
GenerationEndpoints = configuration.GetSection("ShitpostBot:Templates").Get<List<ImageGenerationEndpoint>>();
}
public static async Task<object> GenerateImageAsync(string template, string variant, string[] sources)
public static async Task<object> GenerateImageAsync(string template, string variant, string[] sources, CancellationToken cancellationToken)
{
while (true)
{
if(cancellationToken.IsCancellationRequested)
{
return null;
}
ImageGenerationImage imageTemplate = null;
var endpoint = GenerationEndpoints.FirstOrDefault(e => e.Name.ToLowerInvariant().Equals(template.ToLowerInvariant()));
@ -65,21 +72,31 @@ public static partial class ImageManager
if (imageTemplate.PlaceUnder)
{
await AddSourcesToImage(baseImage, imageTemplate, sources);
await AddSourcesToImage(baseImage, imageTemplate, sources, cancellationToken);
}
baseImage.Composite(templateImage, Gravity.Northwest, CompositeOperator.Over);
if (!imageTemplate.PlaceUnder)
{
await AddSourcesToImage(baseImage, imageTemplate, sources);
await AddSourcesToImage(baseImage, imageTemplate, sources, cancellationToken);
}
return baseImage.ToByteArray();
}
static async Task AddSourcesToImage(MagickImage image, ImageGenerationImage template, IEnumerable<string> sources)
return null;
}
static async Task AddSourcesToImage(MagickImage image, ImageGenerationImage template, IEnumerable<string> sources, CancellationToken cancellationToken)
{
while (true)
{
if(cancellationToken.IsCancellationRequested)
{
return;
}
int img = 0;
foreach (var src in sources)
{
@ -105,6 +122,7 @@ public static partial class ImageManager
img++;
}
}
}
public static IEnumerable<ImageGenerationEndpointRead> GetGenerationEndpoints()
{

@ -9,8 +9,15 @@ public static partial class ImageManager
readonly static Encoding s_defaultEncoding = Encoding.Unicode;
const double c_defaultFontSize = 20;
public static async Task<(MemoryStream data, string contentType)> GetLiquidRescaledImageAsync(string image)
public static async Task<(MemoryStream data, string contentType)> GetLiquidRescaledImageAsync(string image, CancellationToken cancellationToken)
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
return (null, null);
}
var imageStream = await HttpWebClient.GetStreamAsync(new Uri(image)).ConfigureAwait(false);
using var magikImage = new MagickImageCollection(imageStream);
@ -31,6 +38,7 @@ public static partial class ImageManager
return (stream, cType);
}
}
static void LiquidResizeFrame(IMagickImage<byte> frame)
{

@ -26,8 +26,15 @@ public static partial class ImageManager
});
}
public static async Task<object> GenerateMemeImageAsync(string template, string[] texts)
public static async Task<object> GenerateMemeImageAsync(string template, string[] texts, CancellationToken cancellationToken)
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
return null;
}
ImageManipulationImage imageTemplate = ManipulationEndpoints.FirstOrDefault(e => e.Name.ToLowerInvariant().Equals(template.ToLowerInvariant()));
if (imageTemplate is null)
@ -62,4 +69,5 @@ public static partial class ImageManager
return baseImage.ToByteArray();
}
}
}

@ -1,5 +1,7 @@
using System.Globalization;
using System.Numerics;
using System.Text;
using ICU4N.Text;
using ImageMagick;
using Kynareth.Models;
using Microsoft.AspNetCore.Mvc;
@ -14,22 +16,47 @@ public static partial class ImageManager
ConfigureManipulation(configuration, appEnvironment);
}
private static ObjectResult GetResult(int statusCode, object data)
=> new(data) { StatusCode = statusCode };
static BreakIterator lineBreakIterator = BreakIterator.GetLineInstance(CultureInfo.InvariantCulture);
public static MagickImage WriteText(this MagickImage image, string text, PositionRect rect, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
private static ObjectResult GetResult(int statusCode, object data) => new(data) { StatusCode = statusCode };
private static string GetText(string text)
{
StringBuilder newText = new();
// set the text to be broken
lineBreakIterator.SetText(text);
// get the first boundary
int start = lineBreakIterator.First();
// iterate over all boundaries
for (int end = lineBreakIterator.Next(); end != BreakIterator.Done; start = end, end = lineBreakIterator.Next())
{
// get the current line
string line = text.Substring(start, end - start);
// do something with the line
newText.AppendLine(line);
Console.WriteLine(line);
}
return newText.ToString();
}
public static MagickImage WriteText(this MagickImage image, string text, PositionRect rect, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"label:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = rect.Width,
Height = rect.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
Font = font,
TextEncoding = encoding,
StrokeColor = new MagickColor(strokeColor ?? MagickColors.Black),
StrokeWidth = strokeWidth
StrokeWidth = strokeWidth,
});
image.Composite(label, rect.X, rect.Y, CompositeOperator.Over);
@ -37,15 +64,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, PositionRect rect, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, PositionRect rect, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = rect.Width,
Height = rect.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
FontPointsize = fontSize,
Font = font,
TextEncoding = encoding,
@ -58,15 +85,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, Vector2 position, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, Vector2 position, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
Font = font,
TextEncoding = encoding,
StrokeColor = new MagickColor(strokeColor ?? MagickColors.Black),
@ -78,15 +105,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, Vector2 position, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, Vector2 position, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
FontPointsize = fontSize,
Font = font,
TextEncoding = encoding,
@ -99,15 +126,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, PointD position, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, PointD position, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
Font = font,
TextEncoding = encoding,
StrokeColor = new MagickColor(strokeColor ?? MagickColors.Black),
@ -119,15 +146,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, PointD position, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, PointD position, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
FontPointsize = fontSize,
Font = font,
TextEncoding = encoding,
@ -140,15 +167,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, int x, int y, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, int x, int y, MagickColor fontColor, Encoding encoding, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
Font = font,
TextEncoding = encoding,
StrokeColor = new MagickColor(strokeColor ?? MagickColors.Black),
@ -160,15 +187,15 @@ public static partial class ImageManager
return image;
}
public static MagickImage WriteText(this MagickImage image, string text, int x, int y, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null)
public static MagickImage WriteText(this MagickImage image, string text, int x, int y, MagickColor fontColor, Encoding encoding, double fontSize, string font = "Impact", int strokeWidth = 2, MagickColor? strokeColor = null, bool wrapText = true, Gravity textGravity = Gravity.Northwest)
{
using var label = new MagickImage($"caption:{text}", new MagickReadSettings()
using var label = new MagickImage($"{(wrapText ? "caption" : "label")}:{text}", new MagickReadSettings()
{
Width = image.Width,
Height = image.Height,
BackgroundColor = MagickColors.Transparent,
FillColor = fontColor,
TextGravity = Gravity.Center,
TextGravity = textGravity,
FontPointsize = fontSize,
Font = font,
TextEncoding = encoding,

@ -32,6 +32,7 @@ builder.Services.AddDbContext<KynarethDbContext>(options =>
var app = builder.Build();
RequestHelper.Configure(app);
ImageManager.Configure(app.Configuration, app.Environment);
AmogusHelper.Configure(app.Environment);

@ -1702,7 +1702,7 @@
"x": 593,
"y": 411,
"w": 169,
"h": 75
"h": 300
}
]
},

Loading…
Cancel
Save