H2: Hero-module (tabellen en migratie, beheer-API, publieke GET /hero, afbeeldingsupload met focus, opschoonservice, teksten) en OpenAPI-snapshot
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>The image is still used by a slide (the administrator gets a 409 and a message).</summary>
|
||||
public sealed class HeroImageInUseException() : Exception("The image is still used by a slide.");
|
||||
|
||||
public sealed class HeroImageNotFoundException() : Exception("The image does not exist.");
|
||||
|
||||
/// <summary>There is not enough room in the media directory for the image.</summary>
|
||||
public sealed class MediaStorageFullException() : Exception("The media directory is full.");
|
||||
|
||||
public interface IHeroImageService
|
||||
{
|
||||
/// <summary>Admits, stores and processes an uploaded image (all variants of the default focus). The same photo twice is one image.</summary>
|
||||
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Changes where the subject is (general and optionally per ratio) and cuts the variants again around it.</summary>
|
||||
Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
|
||||
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class HeroImageService(
|
||||
IMediaUploadGuard guard,
|
||||
IImageProcessor processor,
|
||||
IMediaStore store,
|
||||
MediaProcessingGate gate,
|
||||
IHeroRepository repository,
|
||||
IOptions<MediaOptions> mediaOptions,
|
||||
ILogger<HeroImageService> logger,
|
||||
TimeProvider? time = null,
|
||||
IIndexHtmlCache? indexCache = null) : IHeroImageService
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken);
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes));
|
||||
|
||||
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
|
||||
if (existing is not null)
|
||||
{
|
||||
return HeroMapping.ToImageDto(existing);
|
||||
}
|
||||
|
||||
await EnsureRoomAsync(admitted.Bytes.Length, cancellationToken);
|
||||
|
||||
// The original is kept without metadata (GPS and the like); formats that cannot be written back (HEIC) become JPEG.
|
||||
var format = admitted.Info.Format;
|
||||
var stripped = await processor.StripMetadataAsync(admitted.Bytes, format, cancellationToken);
|
||||
var original = stripped ?? admitted.Bytes;
|
||||
var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format;
|
||||
|
||||
var image = new HeroImage
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
OriginalSha256 = sha,
|
||||
OriginalKey = $"originals/{sha}.{storedFormat.Extension()}",
|
||||
SourceFormat = storedFormat.Extension(),
|
||||
Width = admitted.Info.Width,
|
||||
Height = admitted.Info.Height,
|
||||
Bytes = original.Length,
|
||||
CreatedAt = _time.GetUtcNow(),
|
||||
CreatedByUserId = callerId,
|
||||
};
|
||||
|
||||
var files = await RenderSetAsync(image, original, storedFormat, cancellationToken);
|
||||
|
||||
await store.PutAsync(image.OriginalKey, original, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddImage(image);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} uploaded by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, callerId, image.Width, image.Height, image.Variants.Count);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
public async Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
|
||||
var oldSet = image.SetHash;
|
||||
var general = request.Focus.ToSetting().Normalize();
|
||||
image.FocusX = general.X;
|
||||
image.FocusY = general.Y;
|
||||
image.Zoom = general.Zoom;
|
||||
Apply(request.Wide, v => (image.WideFocusX, image.WideFocusY, image.WideZoom) = v);
|
||||
Apply(request.Tall, v => (image.TallFocusX, image.TallFocusY, image.TallZoom) = v);
|
||||
|
||||
var newSet = SetHashOf(image);
|
||||
if (newSet != oldSet)
|
||||
{
|
||||
using var slot = await gate.EnterAsync(cancellationToken);
|
||||
|
||||
var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken)
|
||||
?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing.");
|
||||
using var memory = new MemoryStream();
|
||||
await using (file.Content)
|
||||
{
|
||||
await file.Content.CopyToAsync(memory, cancellationToken);
|
||||
}
|
||||
|
||||
var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.'));
|
||||
|
||||
var files = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero image {ImageId} focus changed by user {UserId}", imageId, callerId);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
if (await repository.ImageInUseAsync(imageId, cancellationToken))
|
||||
{
|
||||
throw new HeroImageInUseException();
|
||||
}
|
||||
|
||||
var now = _time.GetUtcNow();
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = now });
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = now });
|
||||
repository.RemoveImage(image);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId);
|
||||
}
|
||||
|
||||
private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
assign((null, null, null));
|
||||
return;
|
||||
}
|
||||
|
||||
var f = value.ToSetting().Normalize();
|
||||
assign((f.X, f.Y, f.Zoom));
|
||||
}
|
||||
|
||||
private static string SetHashOf(HeroImage image)
|
||||
=> MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]);
|
||||
|
||||
/// <summary>Cuts and encodes every planned variant of the image and fills its set hash and variant list. Returns the files by name.</summary>
|
||||
private async Task<Dictionary<string, byte[]>> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, CancellationToken cancellationToken)
|
||||
{
|
||||
var ratios = new[] { Ratio.Wide, Ratio.Tall }
|
||||
.Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r)))
|
||||
.ToList();
|
||||
var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput);
|
||||
|
||||
var files = new Dictionary<string, byte[]>();
|
||||
var variants = new List<HeroVariant>();
|
||||
foreach (var spec in specs)
|
||||
{
|
||||
var rendered = await processor.RenderAsync(original, storedFormat, spec, cancellationToken);
|
||||
var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format);
|
||||
files[name] = rendered.Bytes;
|
||||
variants.Add(new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength));
|
||||
}
|
||||
|
||||
image.SetHash = SetHashOf(image);
|
||||
image.Variants = variants;
|
||||
return files;
|
||||
}
|
||||
|
||||
private async Task EnsureRoomAsync(long incomingBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
var limits = mediaOptions.Value;
|
||||
// A set is a few times the size of the original at most; keep a margin so the write cannot fill the disk.
|
||||
var needed = incomingBytes * 4;
|
||||
var total = await store.GetTotalBytesAsync(cancellationToken);
|
||||
if (limits.MaxTotalBytes > 0 && total + needed > limits.MaxTotalBytes)
|
||||
{
|
||||
throw new MediaStorageFullException();
|
||||
}
|
||||
|
||||
if (store.GetFreeBytes() is { } free && free < needed + 64L * 1024 * 1024)
|
||||
{
|
||||
throw new MediaStorageFullException();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user