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:
@@ -0,0 +1,175 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
/// <summary>A crop per slide (phase 2, step B): the same photo can have another crop on each slide (Bryan, 2026-11-17).</summary>
|
||||
public class HeroSlideCropTests
|
||||
{
|
||||
private static HeroSaveRequest Request(params HeroSlideRequest[] slides)
|
||||
=> new("Titel", null, null, "slideshow", [], slides);
|
||||
|
||||
private static async Task<(HeroTestRig Rig, Guid ImageId, Guid SlideA, Guid SlideB)> TwoSlidesOnOnePhotoAsync()
|
||||
{
|
||||
var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var imageId = Guid.Parse(image.Id);
|
||||
var saved = await rig.Service.SaveAsync(Request(new HeroSlideRequest(null, imageId, "een"), new HeroSlideRequest(null, imageId, "twee")), HeroTestRig.Admin, CancellationToken.None);
|
||||
return (rig, imageId, Guid.Parse(saved.Slides[0].Id), Guid.Parse(saved.Slides[1].Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_slide_without_a_crop_of_its_own_maps_exactly_like_its_photo()
|
||||
{
|
||||
var (rig, imageId, slideA, _) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash;
|
||||
|
||||
admin.Slides.Should().OnlyContain(s => !s.OwnCrop);
|
||||
var publicHero = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
publicHero.Slides.Should().HaveCount(2);
|
||||
publicHero.Slides.SelectMany(s => s.Image.Variants).Should().OnlyContain(v => v.Url.Contains(photoSet));
|
||||
slideA.Should().NotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_slides_with_one_photo_and_different_crops_get_two_sets_and_two_addresses()
|
||||
{
|
||||
var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash;
|
||||
|
||||
var first = await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.1, 0.2, 1.5)), HeroTestRig.Admin, CancellationToken.None);
|
||||
first.Should().NotBeNull();
|
||||
first!.OwnCrop.Should().BeTrue();
|
||||
first.Image.Processing.Should().BeTrue("its own set still has to be cut");
|
||||
first.Image.Focus.Should().Be(new FocusDto(0.1, 0.2, 1.5));
|
||||
|
||||
// Until the slide's set is complete the photo's set stays live.
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides.SelectMany(s => s.Image.Variants).Should().OnlyContain(v => v.Url.Contains(photoSet));
|
||||
|
||||
await rig.Images.SetSlideFocusAsync(slideB, new HeroFocusRequest(new FocusDto(0.8, 0.7, 1.2)), HeroTestRig.Admin, CancellationToken.None);
|
||||
(await rig.RenderPending()).Should().Be(2);
|
||||
|
||||
var slides = rig.Db.HeroSlides.OrderBy(s => s.SortOrder).ToList();
|
||||
slides[0].SetHash.Should().NotBeNullOrEmpty().And.NotBe(photoSet);
|
||||
slides[1].SetHash.Should().NotBeNullOrEmpty().And.NotBe(photoSet).And.NotBe(slides[0].SetHash);
|
||||
|
||||
var publicHero = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
publicHero.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(slides[0].SetHash!));
|
||||
publicHero.Slides[1].Image.Variants.Should().OnlyContain(v => v.Url.Contains(slides[1].SetHash!));
|
||||
publicHero.Slides[0].Image.Focus.Should().Be(new FocusDto(0.1, 0.2, 1.5));
|
||||
rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash.Should().Be(photoSet, "the photo's own set and crop are untouched");
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
admin.Slides.Select(s => s.Image.Processing).Should().AllBeEquivalentTo(false);
|
||||
admin.Slides.Select(s => s.Image.Focus).Should().BeEquivalentTo([new FocusDto(0.1, 0.2, 1.5), new FocusDto(0.8, 0.7, 1.2)], o => o.WithStrictOrdering());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_same_crop_on_two_slides_shares_one_set_and_a_crop_equal_to_the_photos_shares_its_set()
|
||||
{
|
||||
var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
var photo = rig.Db.HeroImages.Single(i => i.Id == imageId);
|
||||
var photoSet = photo.SetHash;
|
||||
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.3, 0.3, 1.3)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.Images.SetSlideFocusAsync(slideB, new HeroFocusRequest(new FocusDto(0.3, 0.3, 1.3)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
var slides = rig.Db.HeroSlides.OrderBy(s => s.SortOrder).ToList();
|
||||
slides[0].SetHash.Should().Be(slides[1].SetHash, "the set hash is computed from the photo and the crop, so equal crops are one set");
|
||||
|
||||
// A crop equal to the photo's own crop needs no cutting at all: it shares the photo's set.
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(photo.FocusX, photo.FocusY, photo.Zoom)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().Be(photoSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_old_set_of_a_slide_stays_live_until_the_new_one_is_complete()
|
||||
{
|
||||
var (rig, _, slideA, _) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
var firstSet = rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash;
|
||||
|
||||
var again = await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.6, 0.6, 1.1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
again!.Image.Processing.Should().BeTrue();
|
||||
rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().Be(firstSet);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(firstSet!));
|
||||
|
||||
await rig.RenderPending();
|
||||
rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().NotBe(firstSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resetting_a_slide_uses_the_photos_crop_and_set_again()
|
||||
{
|
||||
var (rig, imageId, slideA, _) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash;
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
|
||||
var reset = await rig.Images.ResetSlideFocusAsync(slideA, HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
reset!.OwnCrop.Should().BeFalse();
|
||||
reset.Image.Processing.Should().BeFalse();
|
||||
var slide = rig.Db.HeroSlides.Single(s => s.Id == slideA);
|
||||
slide.HasOwnCrop.Should().BeFalse();
|
||||
slide.SetHash.Should().BeNull();
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(photoSet));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_the_hero_keeps_the_crop_of_a_slide_and_another_photo_drops_it()
|
||||
{
|
||||
var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
var other = await rig.Upload(HeroTestRig.Photo(seed: 9));
|
||||
|
||||
await rig.Service.SaveAsync(Request(new HeroSlideRequest(slideA, imageId, "een, aangepast"), new HeroSlideRequest(slideB, Guid.Parse(other.Id), "twee")), HeroTestRig.Admin, CancellationToken.None);
|
||||
rig.Db.HeroSlides.Single(s => s.Id == slideA).HasOwnCrop.Should().BeTrue("saving the texts does not touch the crop");
|
||||
|
||||
await rig.Service.SaveAsync(Request(new HeroSlideRequest(slideA, Guid.Parse(other.Id), "een"), new HeroSlideRequest(slideB, Guid.Parse(other.Id), "twee")), HeroTestRig.Admin, CancellationToken.None);
|
||||
rig.Db.HeroSlides.Single(s => s.Id == slideA).HasOwnCrop.Should().BeFalse("a crop made for another photo means nothing");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_unknown_slide_gives_null()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var request = new HeroFocusRequest(new FocusDto(0.5, 0.5, 1));
|
||||
|
||||
(await rig.Images.SetSlideFocusAsync(Guid.NewGuid(), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
(await rig.Images.ResetSlideFocusAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_clean_up_keeps_the_set_of_a_slide_and_a_slide_set_nobody_uses_goes_after_the_retention()
|
||||
{
|
||||
var (rig, _, slideA, _) = await TwoSlidesOnOnePhotoAsync();
|
||||
using var _r = rig;
|
||||
await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.RenderPending();
|
||||
var slideSet = rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash!;
|
||||
rig.Time.Now = rig.Time.Now.AddDays(30);
|
||||
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(x => x.SetHash).Should().Contain(slideSet, "a slide uses it");
|
||||
|
||||
await rig.Images.ResetSlideFocusAsync(slideA, HeroTestRig.Admin, CancellationToken.None);
|
||||
rig.Time.Now = rig.Time.Now.AddDays(30);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(x => x.SetHash).Should().NotContain(slideSet);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+291
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user