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
@@ -180,6 +180,37 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
}
}
/// <summary>The crop of one slide (crop per use). Administrators only.</summary>
[ApiController]
[Route("hero/slides")]
[Authorize(Policy = "AdminOnly")]
public class HeroSlidesController(IHeroImageService service) : ControllerBase
{
/// <summary>
/// A crop for this slide only, applied at once without saving the hero. The same photo on another slide keeps its own
/// crop. Answers with the slide as the admin sees it (processing while its set is being cut).
/// </summary>
[HttpPut("{id:guid}/focus")]
[ProducesResponseType<HeroSlideAdminDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
{
var slide = await service.SetSlideFocusAsync(id, request, HeroCaller.Id(User), cancellationToken);
return slide is null ? NotFound(new { error = "not_found", message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.NotFound) }) : Ok(slide);
}
/// <summary>Takes the slide's own crop away: it uses the crop of its photo again.</summary>
[HttpDelete("{id:guid}/focus")]
[ProducesResponseType<HeroSlideAdminDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> ResetFocus(Guid id, CancellationToken cancellationToken)
{
var slide = await service.ResetSlideFocusAsync(id, HeroCaller.Id(User), cancellationToken);
return slide is null ? NotFound(new { error = "not_found", message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.NotFound) }) : Ok(slide);
}
}
internal static class HeroCaller
{
public static Guid Id(ClaimsPrincipal user)
@@ -34,6 +34,34 @@ public class HeroSlide
public bool Decorative { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
// The slide's OWN crop (phase 2, crop per use). All null = no override: the slide uses its photo's crop and set exactly
// as before. FocusX/FocusY/Zoom set = the slide has its own crop (the wide and tall overrides are optional on top).
public double? FocusX { get; set; }
public double? FocusY { get; set; }
public double? Zoom { get; set; }
public double? WideFocusX { get; set; }
public double? WideFocusY { get; set; }
public double? WideZoom { get; set; }
public double? TallFocusX { get; set; }
public double? TallFocusY { get; set; }
public double? TallZoom { get; set; }
/// <summary>The set cut for the slide's own crop; empty until it is complete (the photo's set stays live until then).</summary>
public string? SetHash { get; set; }
public List<HeroVariant>? Variants { get; set; }
/// <summary>True when the slide has a crop of its own.</summary>
public bool HasOwnCrop => FocusX is not null && FocusY is not null;
public void ClearOwnCrop()
{
(FocusX, FocusY, Zoom) = (null, null, null);
(WideFocusX, WideFocusY, WideZoom) = (null, null, null);
(TallFocusX, TallFocusY, TallZoom) = (null, null, null);
SetHash = null;
Variants = null;
}
}
/// <summary>A stored image: the original (never served), where the subject is, and the current set of variants.</summary>
@@ -44,6 +44,17 @@ public class HeroDbContext(DbContextOptions<HeroDbContext> options) : DbContext(
// Not unique: re-ordering updates several rows in one save and must not trip over itself.
entity.HasIndex(e => new { e.HeroId, e.SortOrder });
entity.HasIndex(e => e.ImageId);
entity.Ignore(e => e.HasOwnCrop);
entity.Property(e => e.SetHash).HasMaxLength(16);
entity.Property(e => e.Variants)
.HasConversion(
variants => variants == null ? null : JsonSerializer.Serialize(variants, (JsonSerializerOptions?)null),
json => json == null ? null : JsonSerializer.Deserialize<List<HeroVariant>>(json, (JsonSerializerOptions?)null))
.HasColumnType("longtext")
.Metadata.SetValueComparer(new ValueComparer<List<HeroVariant>?>(
(a, b) => (a ?? new List<HeroVariant>()).SequenceEqual(b ?? new List<HeroVariant>()),
v => v == null ? 0 : v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())),
v => v == null ? null : v.ToList()));
// Restrict: an image that a slide still uses cannot be deleted (the service answers 409 first).
entity.HasOne(e => e.Image).WithMany().HasForeignKey(e => e.ImageId).OnDelete(DeleteBehavior.Restrict);
@@ -0,0 +1,291 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Hero.Data;
#nullable disable
namespace SlpModularCms.Modules.Hero.Migrations
{
[DbContext(typeof(HeroDbContext))]
[Migration("20261117202757_AddSlideCrop")]
partial class AddSlideCrop
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Button1Label")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Button1Target")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<string>("Button2Label")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Button2Target")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<string>("Display")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("Lead")
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<string>("Tagline")
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.HasIndex("Language")
.IsUnique();
b.ToTable("Heroes", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<long>("Bytes")
.HasColumnType("bigint");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<Guid>("CreatedByUserId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<double>("FocusX")
.HasColumnType("double");
b.Property<double>("FocusY")
.HasColumnType("double");
b.Property<int>("Height")
.HasColumnType("int");
b.Property<DateTimeOffset?>("LastUsedAt")
.HasColumnType("datetime");
b.Property<string>("OriginalFileName")
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("OriginalKey")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("OriginalSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<string>("SetHash")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("varchar(16)");
b.Property<string>("SourceFormat")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<double?>("TallFocusX")
.HasColumnType("double");
b.Property<double?>("TallFocusY")
.HasColumnType("double");
b.Property<double?>("TallZoom")
.HasColumnType("double");
b.Property<string>("Variants")
.IsRequired()
.HasColumnType("longtext");
b.Property<double?>("WideFocusX")
.HasColumnType("double");
b.Property<double?>("WideFocusY")
.HasColumnType("double");
b.Property<double?>("WideZoom")
.HasColumnType("double");
b.Property<int>("Width")
.HasColumnType("int");
b.Property<double>("Zoom")
.HasColumnType("double");
b.HasKey("Id");
b.HasIndex("OriginalSha256")
.IsUnique();
b.ToTable("HeroImages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroRetiredFile", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<DateTimeOffset>("RetiredAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("HeroRetiredFiles", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Alt")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("varchar(600)");
b.Property<bool>("Decorative")
.HasColumnType("tinyint(1)");
b.Property<double?>("FocusX")
.HasColumnType("double");
b.Property<double?>("FocusY")
.HasColumnType("double");
b.Property<Guid>("HeroId")
.HasColumnType("char(36)");
b.Property<Guid>("ImageId")
.HasColumnType("char(36)");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("SetHash")
.HasMaxLength(16)
.HasColumnType("varchar(16)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<double?>("TallFocusX")
.HasColumnType("double");
b.Property<double?>("TallFocusY")
.HasColumnType("double");
b.Property<double?>("TallZoom")
.HasColumnType("double");
b.Property<string>("Variants")
.HasColumnType("longtext");
b.Property<double?>("WideFocusX")
.HasColumnType("double");
b.Property<double?>("WideFocusY")
.HasColumnType("double");
b.Property<double?>("WideZoom")
.HasColumnType("double");
b.Property<double?>("Zoom")
.HasColumnType("double");
b.HasKey("Id");
b.HasIndex("ImageId");
b.HasIndex("HeroId", "SortOrder");
b.ToTable("HeroSlides", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b =>
{
b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", null)
.WithMany("Slides")
.HasForeignKey("HeroId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", "Image")
.WithMany()
.HasForeignKey("ImageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Image");
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b =>
{
b.Navigation("Slides");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,129 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Hero.Migrations
{
/// <inheritdoc />
public partial class AddSlideCrop : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<double>(
name: "FocusX",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "FocusY",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SetHash",
table: "HeroSlides",
type: "varchar(16)",
maxLength: 16,
nullable: true);
migrationBuilder.AddColumn<double>(
name: "TallFocusX",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "TallFocusY",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "TallZoom",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Variants",
table: "HeroSlides",
type: "longtext",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "WideFocusX",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "WideFocusY",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "WideZoom",
table: "HeroSlides",
type: "double",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "Zoom",
table: "HeroSlides",
type: "double",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FocusX",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "FocusY",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "SetHash",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "TallFocusX",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "TallFocusY",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "TallZoom",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "Variants",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "WideFocusX",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "WideFocusY",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "WideZoom",
table: "HeroSlides");
migrationBuilder.DropColumn(
name: "Zoom",
table: "HeroSlides");
}
}
}
@@ -206,6 +206,12 @@ namespace SlpModularCms.Modules.Hero.Migrations
b.Property<bool>("Decorative")
.HasColumnType("tinyint(1)");
b.Property<double?>("FocusX")
.HasColumnType("double");
b.Property<double?>("FocusY")
.HasColumnType("double");
b.Property<Guid>("HeroId")
.HasColumnType("char(36)");
@@ -215,9 +221,37 @@ namespace SlpModularCms.Modules.Hero.Migrations
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("SetHash")
.HasMaxLength(16)
.HasColumnType("varchar(16)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<double?>("TallFocusX")
.HasColumnType("double");
b.Property<double?>("TallFocusY")
.HasColumnType("double");
b.Property<double?>("TallZoom")
.HasColumnType("double");
b.Property<string>("Variants")
.HasColumnType("longtext");
b.Property<double?>("WideFocusX")
.HasColumnType("double");
b.Property<double?>("WideFocusY")
.HasColumnType("double");
b.Property<double?>("WideZoom")
.HasColumnType("double");
b.Property<double?>("Zoom")
.HasColumnType("double");
b.HasKey("Id");
b.HasIndex("ImageId");
@@ -33,7 +33,8 @@ public record HeroImageDto(
public record HeroButtonDto(string Label, string Target);
public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image);
/// <summary>A slide for the admin. <see cref="Image"/> is the photo as THIS slide shows it (its own crop and set when <see cref="OwnCrop"/>); its Id is always the photo's id.</summary>
public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image, bool OwnCrop = false);
/// <summary>What the admin edits. When no hero exists yet <see cref="Id"/> is null and the fields hold the defaults.</summary>
public record HeroAdminDto(
@@ -48,6 +48,15 @@ public interface IHeroRepository
Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken);
/// <summary>One slide with its photo, tracked (a new crop for the slide); null when there is none or its photo is in the trash.</summary>
Task<HeroSlide?> GetSlideAsync(Guid id, CancellationToken cancellationToken);
/// <summary>The slide as stored right now, with its photo, not tracked.</summary>
Task<HeroSlide?> GetSlideFreshAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Slides with a crop of their own whose set is missing or does not match that crop, in hero order (tracked).</summary>
Task<IReadOnlyList<HeroSlide>> GetSlidesNeedingRenderAsync(CancellationToken cancellationToken);
/// <summary>Images with a complete set made before the full-frame preview existed (tracked).</summary>
Task<IReadOnlyList<HeroImage>> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken);
@@ -133,6 +142,18 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList();
public Task<HeroSlide?> GetSlideAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroSlides.Include(s => s.Image).FirstOrDefaultAsync(s => s.Id == id && s.Image != null && s.Image.DeletedAt == null, cancellationToken);
public Task<HeroSlide?> GetSlideFreshAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroSlides.AsNoTracking().Include(s => s.Image).FirstOrDefaultAsync(s => s.Id == id && s.Image != null && s.Image.DeletedAt == null, cancellationToken);
public async Task<IReadOnlyList<HeroSlide>> GetSlidesNeedingRenderAsync(CancellationToken cancellationToken)
=> (await context.HeroSlides.Include(s => s.Image).Where(s => s.FocusX != null && s.FocusY != null).ToListAsync(cancellationToken))
.Where(s => s.Image is { DeletedAt: null } && HeroMapping.SlideNeedsRender(s))
.OrderBy(s => s.SortOrder)
.ToList();
public Task<HeroImage?> GetImageFreshAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken);
@@ -154,7 +175,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
}
public async Task<HashSet<string>> GetReferencedSetHashesAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
{
// The sets of the photos and the own sets of slides with a crop of their own.
var sets = (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
sets.UnionWith((await context.HeroSlides.Select(s => s.SetHash).ToListAsync(cancellationToken)).Where(h => !string.IsNullOrEmpty(h))!);
return sets;
}
public async Task<HashSet<string>> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.Select(i => i.OriginalKey).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
@@ -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;