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:
@@ -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)
|
||||
{
|
||||
|
||||
|
||||
@@ -47,6 +47,49 @@ public static class HeroMapping
|
||||
_ => format.ToString().ToUpperInvariant(),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The photo as a slide shows it: the photo itself when the slide has no crop of its own, else a copy of the photo with the
|
||||
/// slide's crop and, once complete, the slide's own set (until then the photo's set stays live). Never saved.
|
||||
/// </summary>
|
||||
public static HeroImage? Effective(HeroSlide slide)
|
||||
{
|
||||
var photo = slide.Image;
|
||||
if (photo is null || !slide.HasOwnCrop)
|
||||
{
|
||||
return photo;
|
||||
}
|
||||
|
||||
var ready = slide.Variants is { Count: > 0 } && !string.IsNullOrEmpty(slide.SetHash);
|
||||
return new HeroImage
|
||||
{
|
||||
Id = photo.Id,
|
||||
OriginalSha256 = photo.OriginalSha256,
|
||||
OriginalKey = photo.OriginalKey,
|
||||
SourceFormat = photo.SourceFormat,
|
||||
Width = photo.Width,
|
||||
Height = photo.Height,
|
||||
Bytes = photo.Bytes,
|
||||
CreatedAt = photo.CreatedAt,
|
||||
CreatedByUserId = photo.CreatedByUserId,
|
||||
FocusX = slide.FocusX!.Value,
|
||||
FocusY = slide.FocusY!.Value,
|
||||
Zoom = slide.Zoom ?? 1.0,
|
||||
WideFocusX = slide.WideFocusX,
|
||||
WideFocusY = slide.WideFocusY,
|
||||
WideZoom = slide.WideZoom,
|
||||
TallFocusX = slide.TallFocusX,
|
||||
TallFocusY = slide.TallFocusY,
|
||||
TallZoom = slide.TallZoom,
|
||||
SetHash = ready ? slide.SetHash! : photo.SetHash,
|
||||
Variants = ready ? slide.Variants! : photo.Variants,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when the slide has its own crop and its own set is missing or was cut for another crop (the work of the renderer).</summary>
|
||||
public static bool SlideNeedsRender(HeroSlide slide)
|
||||
=> slide.HasOwnCrop && slide.Image is not null && Effective(slide) is { } effective
|
||||
&& (slide.Variants is not { Count: > 0 } || slide.SetHash != TargetSetHash(effective));
|
||||
|
||||
/// <summary>The variants websites and the admin lists use: everything except the full-frame preview.</summary>
|
||||
public static IEnumerable<HeroVariant> Published(HeroImage image) => image.Variants.Where(v => v.Ratio != VariantPlanner.PreviewRatioName);
|
||||
|
||||
@@ -121,10 +164,11 @@ public static class HeroMapping
|
||||
}
|
||||
|
||||
var slides = hero.Slides
|
||||
.Where(s => s.IsActive && s.Image is { Variants.Count: > 0 } && (s.Decorative || !string.IsNullOrWhiteSpace(s.Alt)))
|
||||
.OrderBy(s => s.SortOrder)
|
||||
.Select(s => (Slide: s, Image: Effective(s)))
|
||||
.Where(x => x.Slide.IsActive && x.Image is { Variants.Count: > 0 } && (x.Slide.Decorative || !string.IsNullOrWhiteSpace(x.Slide.Alt)))
|
||||
.OrderBy(x => x.Slide.SortOrder)
|
||||
.Take(Math.Max(1, maxPublishedSlides))
|
||||
.Select(s => new PublicSlideDto(s.Id.ToString(), s.Decorative ? string.Empty : s.Alt, s.Decorative, ToPublicImage(s.Image!)))
|
||||
.Select(x => new PublicSlideDto(x.Slide.Id.ToString(), x.Slide.Decorative ? string.Empty : x.Slide.Alt, x.Slide.Decorative, ToPublicImage(x.Image!)))
|
||||
.ToList();
|
||||
|
||||
return new PublicHeroDto(hero.Display, hero.Title, hero.Tagline, hero.Lead, Buttons(hero), slides);
|
||||
@@ -152,6 +196,10 @@ public static class HeroMapping
|
||||
byRatio);
|
||||
}
|
||||
|
||||
/// <summary>One slide for the admin, with the photo as the slide shows it.</summary>
|
||||
public static HeroSlideAdminDto ToSlideAdmin(HeroSlide s)
|
||||
=> new(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(Effective(s)!), s.HasOwnCrop);
|
||||
|
||||
public static HeroAdminDto ToAdmin(HeroContent? hero, DateTimeOffset now, int maxPublishedSlides)
|
||||
{
|
||||
if (hero is null)
|
||||
@@ -162,7 +210,7 @@ public static class HeroMapping
|
||||
var slides = hero.Slides
|
||||
.Where(s => s.Image is not null)
|
||||
.OrderBy(s => s.SortOrder)
|
||||
.Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(s.Image!)))
|
||||
.Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(Effective(s)!), s.HasOwnCrop))
|
||||
.ToList();
|
||||
|
||||
return new HeroAdminDto(
|
||||
|
||||
@@ -44,7 +44,8 @@ public class HeroService(
|
||||
{
|
||||
Slides = dto.Slides.Select(s =>
|
||||
{
|
||||
var id = Guid.Parse(s.ImageId);
|
||||
// A slide with its own crop is cut under its own id (its progress and failures are the slide's, not the photo's).
|
||||
var id = s.OwnCrop ? Guid.Parse(s.Id) : Guid.Parse(s.ImageId);
|
||||
var progress = imageService.RenderProgress(id);
|
||||
var failed = imageService.IsRenderFailed(id);
|
||||
return failed || progress is not null
|
||||
@@ -113,6 +114,12 @@ public class HeroService(
|
||||
}
|
||||
|
||||
keep.Add(slide.Id);
|
||||
if (slide.ImageId != r.ImageId && slide.ImageId != Guid.Empty)
|
||||
{
|
||||
// Another photo on the slide: a crop made for the old photo means nothing for the new one.
|
||||
slide.ClearOwnCrop();
|
||||
}
|
||||
|
||||
slide.ImageId = r.ImageId;
|
||||
slide.Image = images[r.ImageId];
|
||||
slide.Decorative = r.Decorative;
|
||||
|
||||
Reference in New Issue
Block a user