Fase 2 stap B (backend): uitsnede per slide met eigen set, renderer, mapping en endpoints

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 21:34:58 +01:00
co-authored by Claude Sonnet 5.5
parent 6d7948edf7
commit e30d885d64
13 changed files with 1109 additions and 9 deletions
@@ -54,6 +54,16 @@ public interface IHeroImageService
/// </summary>
Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// A crop for ONE slide (crop per use): the same photo can have another crop on another slide. Applied at once, without
/// saving the hero; the slide's own set is cut in the background and the slide switches to it when it is complete (until
/// then it shows the photo's set). Returns the slide as the admin sees it (processing), or null when there is no such slide.
/// </summary>
Task<HeroSlideAdminDto?> SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
/// <summary>Takes the slide's own crop away: it uses the photo's crop and set again. Null when there is no such slide.</summary>
Task<HeroSlideAdminDto?> ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken);
/// <summary>One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image.</summary>
Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken);
@@ -219,6 +229,67 @@ public class HeroImageService(
return await GetImageAsync(imageId, cancellationToken);
}
public async Task<HeroSlideAdminDto?> SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
{
var slide = await repository.GetSlideAsync(slideId, cancellationToken);
if (slide is null)
{
return null;
}
var general = request.Focus.ToSetting().Normalize();
(slide.FocusX, slide.FocusY, slide.Zoom) = (general.X, general.Y, general.Zoom);
Apply(request.Wide, v => (slide.WideFocusX, slide.WideFocusY, slide.WideZoom) = v);
Apply(request.Tall, v => (slide.TallFocusX, slide.TallFocusY, slide.TallZoom) = v);
await repository.SaveChangesAsync(cancellationToken);
signal?.Reset(slideId);
signal?.Notify();
logger.LogInformation("Hero slide {SlideId} got a crop of its own from user {UserId}; its variants are cut in the background", slideId, callerId);
return await GetSlideAsync(slideId, cancellationToken);
}
public async Task<HeroSlideAdminDto?> ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken)
{
var slide = await repository.GetSlideAsync(slideId, cancellationToken);
if (slide is null)
{
return null;
}
var oldSet = slide.SetHash;
slide.ClearOwnCrop();
if (!string.IsNullOrEmpty(oldSet) && oldSet != slide.Image!.SetHash)
{
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
}
await repository.SaveChangesAsync(cancellationToken);
signal?.Reset(slideId);
indexCache?.Invalidate();
logger.LogInformation("Hero slide {SlideId} uses the crop of its photo again (reset by user {UserId})", slideId, callerId);
return await GetSlideAsync(slideId, cancellationToken);
}
private async Task<HeroSlideAdminDto?> GetSlideAsync(Guid slideId, CancellationToken cancellationToken)
{
var slide = await repository.GetSlideFreshAsync(slideId, cancellationToken);
if (slide is null)
{
return null;
}
var dto = HeroMapping.ToSlideAdmin(slide);
if (!slide.HasOwnCrop)
{
return dto;
}
var progress = RenderProgress(slideId);
return dto with { Image = dto.Image with { Failed = IsRenderFailed(slideId), RenderDone = progress?.Done, RenderTotal = progress?.Total } };
}
public async Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken)
{
var image = await repository.GetImageFreshAsync(imageId, cancellationToken);
@@ -238,19 +309,43 @@ public class HeroImageService(
public async Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken)
{
_ = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
// The id is a photo's or the id of a slide with a crop of its own (both are renderer keys).
if (await repository.GetImageAsync(imageId, cancellationToken) is null && await repository.GetSlideAsync(imageId, cancellationToken) is null)
{
throw new HeroImageNotFoundException();
}
signal?.Reset(imageId);
signal?.Notify();
}
public async Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken)
=> (await repository.CountImagesAsync(cancellationToken), (await repository.GetImagesNeedingRenderAsync(cancellationToken)).Count, (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).Count);
=> (await repository.CountImagesAsync(cancellationToken), (await repository.GetImagesNeedingRenderAsync(cancellationToken)).Count + (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).Count, (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).Count);
public async Task<Guid?> RenderNextPendingAsync(IReadOnlySet<Guid> skip, CancellationToken cancellationToken)
{
var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id));
if (image is null)
{
// Then the slides that have a crop of their own.
var slide = (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).FirstOrDefault(s => !skip.Contains(s.Id));
if (slide is not null)
{
try
{
return await RenderSlideAsync(slide, cancellationToken);
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger.LogError(exception, "Hero slide {SlideId}: cutting the variants failed.", slide.Id);
throw new HeroImageRenderException(slide.Id, exception);
}
finally
{
signal?.ClearProgress(slide.Id);
}
}
// Nothing to cut: add the full-frame preview to complete sets that were made before it existed.
var old = (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id));
return old is null ? null : await AddPreviewAsync(old, cancellationToken);
@@ -305,6 +400,65 @@ public class HeroImageService(
}
}
/// <summary>Cuts the set of a slide's own crop. A crop equal to the photo's own crop shares the photo's set (same hash, no cutting).</summary>
private async Task<Guid?> RenderSlideAsync(HeroSlide slide, CancellationToken cancellationToken)
{
var photo = slide.Image!;
var effective = HeroMapping.Effective(slide)!;
var target = HeroMapping.TargetSetHash(effective);
var oldSet = slide.SetHash ?? string.Empty;
if (target == photo.SetHash && photo.Variants.Count > 0)
{
slide.SetHash = target;
slide.Variants = [.. photo.Variants];
await repository.SaveChangesAsync(cancellationToken);
indexCache?.Invalidate();
logger.LogInformation("Hero slide {SlideId}: its crop equals the crop of its photo, so it shares the photo's set.", slide.Id);
return slide.Id;
}
var watch = System.Diagnostics.Stopwatch.StartNew();
logger.LogInformation("Hero slide {SlideId}: cutting the variants of its own crop starts ({Width}x{Height}).", slide.Id, photo.Width, photo.Height);
Dictionary<string, byte[]> files;
List<HeroVariant> variants;
using (await gate.EnterAsync(cancellationToken))
{
var file = await store.OpenReadAsync(photo.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(photo.OriginalKey).TrimStart('.'));
(files, variants) = await RenderSetAsync(effective, memory.ToArray(), storedFormat, (done, total) => signal?.SetProgress(slide.Id, done, total), cancellationToken);
}
await store.PutSetAsync(HeroMapping.Area, target, files, cancellationToken);
// The crop may have changed (or the slide may be gone) while the set was cut: then it stays pending at the newest crop.
var current = await repository.GetSlideFreshAsync(slide.Id, cancellationToken);
if (current is null || !current.HasOwnCrop || HeroMapping.TargetSetHash(HeroMapping.Effective(current)!) != target)
{
logger.LogInformation("Hero slide {SlideId}: recut superseded, its crop changed while its variants were being cut.", slide.Id);
return slide.Id;
}
slide.SetHash = target;
slide.Variants = variants;
if (oldSet.Length > 0 && oldSet != target)
{
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
}
await repository.SaveChangesAsync(cancellationToken);
indexCache?.Invalidate();
logger.LogInformation("Hero slide {SlideId}: {Variants} variants cut in {Seconds:0.0} s", slide.Id, variants.Count, watch.Elapsed.TotalSeconds);
return slide.Id;
}
private async Task<Guid?> RenderAsync(HeroImage image, CancellationToken cancellationToken)
{