Mediabibliotheek: prullenbak, delete met tweede bevestiging, laatste gebruik, bestandsnaam (backend)
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / changes (pull_request) Successful in 17s
Continuous Integration / config-asf (pull_request) Successful in 9s
Continuous Integration / frontend-prepare (pull_request) Successful in 30s
Continuous Integration / compile-sites (pull_request) Successful in 1m40s
Continuous Integration / frontend-build (pull_request) Successful in 1m9s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m48s
Continuous Integration / frontend-lint (pull_request) Successful in 41s
Continuous Integration / frontend-test (pull_request) Successful in 2m26s
Continuous Integration / backend-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-production (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-test (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-production (pull_request) Canceled after 0s
Continuous Integration / publish-asf-test (pull_request) Canceled after 0s
Continuous Integration / deploy-asf-test (pull_request) Canceled after 0s
Continuous Integration / smoke-sls-test (pull_request) Canceled after 0s
Continuous Integration / smoke-asf-test (pull_request) Canceled after 0s
Continuous Integration / backend-build (pull_request) Canceled after 10m10s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 15:08:05 +01:00
co-authored by Claude Sonnet 5.5
parent a6bef57b9c
commit 7263a9a39a
20 changed files with 1271 additions and 42 deletions
@@ -82,7 +82,7 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
try
{
await using var stream = file.OpenReadStream();
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken);
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken, file.FileName);
return Created($"/api/v1/hero/images/{image.Id}", image);
}
catch (ImageRejectedException rejection)
@@ -65,6 +65,15 @@ public class HeroImage
public DateTimeOffset CreatedAt { get; set; }
public Guid CreatedByUserId { get; set; }
/// <summary>The file name as uploaded (for display only, cleaned; never used as a path). Null for photos uploaded before it was stored.</summary>
public string? OriginalFileName { get; set; }
/// <summary>The moment the photo was last detached from a slide; null while it was never used. The clean-up counts from here (decision 8).</summary>
public DateTimeOffset? LastUsedAt { get; set; }
/// <summary>Set when the photo was moved to the trash; its files stay for <c>Media:TrashDays</c> and it is hidden from the hero.</summary>
public DateTimeOffset? DeletedAt { get; set; }
public FocusSetting General => new FocusSetting(FocusX, FocusY, Zoom).Normalize();
public FocusSetting FocusFor(string ratio) => ratio switch
@@ -60,6 +60,7 @@ public class HeroDbContext(DbContextOptions<HeroDbContext> options) : DbContext(
entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16);
entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.CreatedByUserId).IsRequired();
entity.Property(e => e.OriginalFileName).HasMaxLength(200);
entity.Ignore(e => e.General);
// The variants of the current set: a small list that is always replaced as a whole.
@@ -0,0 +1,257 @@
// <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("20261117140509_AddMediaLibraryColumns")]
partial class AddMediaLibraryColumns
{
/// <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<Guid>("HeroId")
.HasColumnType("char(36)");
b.Property<Guid>("ImageId")
.HasColumnType("char(36)");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<int>("SortOrder")
.HasColumnType("int");
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,50 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Hero.Migrations
{
/// <inheritdoc />
public partial class AddMediaLibraryColumns : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTimeOffset>(
name: "DeletedAt",
table: "HeroImages",
type: "datetime",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "LastUsedAt",
table: "HeroImages",
type: "datetime",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "OriginalFileName",
table: "HeroImages",
type: "varchar(200)",
maxLength: 200,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DeletedAt",
table: "HeroImages");
migrationBuilder.DropColumn(
name: "LastUsedAt",
table: "HeroImages");
migrationBuilder.DropColumn(
name: "OriginalFileName",
table: "HeroImages");
}
}
}
@@ -93,6 +93,9 @@ namespace SlpModularCms.Modules.Hero.Migrations
b.Property<Guid>("CreatedByUserId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<double>("FocusX")
.HasColumnType("double");
@@ -102,6 +105,13 @@ namespace SlpModularCms.Modules.Hero.Migrations
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)
@@ -22,6 +22,18 @@ public interface IHeroRepository
/// <summary>Images whose set is missing or does not match their focus, oldest first (tracked).</summary>
Task<int> CountImagesAsync(CancellationToken cancellationToken);
/// <summary>An image whether or not it is in the trash, tracked (restore, trash).</summary>
Task<HeroImage?> GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken);
/// <summary>The photos in the trash, most recently trashed first, not tracked.</summary>
Task<IReadOnlyList<HeroImage>> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken);
/// <summary>Photos that were trashed before the cutoff, tracked (the trash is emptied for them).</summary>
Task<IReadOnlyList<HeroImage>> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
/// <summary>The slides that use an image, tracked (they are removed when the image goes to the trash).</summary>
Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken);
/// <summary>All images, newest first, not tracked (the media library lists them).</summary>
Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken);
@@ -70,32 +82,44 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
public void RemoveSlide(HeroSlide slide) => context.HeroSlides.Remove(slide);
public Task<HeroImage?> GetImageAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken);
public Task<HeroImage?> GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
public async Task<IReadOnlyList<HeroImage>> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).OrderByDescending(i => i.DeletedAt).ToList();
public async Task<IReadOnlyList<HeroImage>> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
=> (await context.HeroImages.Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).Where(i => i.DeletedAt < cutoff).ToList();
public async Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken)
=> await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken);
public async Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken)
{
// The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they
// are read and filtered here.
var wanted = ids.ToHashSet();
return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
return (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
}
public Task<int> CountImagesAsync(CancellationToken cancellationToken) => context.HeroImages.CountAsync(cancellationToken);
public async Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
=> (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
public async Task<IReadOnlyList<HeroSlide>> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken)
=> await context.HeroSlides.AsNoTracking().ToListAsync(cancellationToken);
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
=> (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList();
=> (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList();
public Task<HeroImage?> GetImageFreshAsync(Guid id, CancellationToken cancellationToken)
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken);
public Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
@@ -110,7 +134,7 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
public async Task<IReadOnlyList<HeroImage>> GetUnattachedImagesCreatedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
{
var used = context.HeroSlides.Select(s => s.ImageId);
var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id)).ToListAsync(cancellationToken);
var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id) && i.DeletedAt == null).ToListAsync(cancellationToken);
return candidates.Where(i => i.CreatedAt < cutoff).ToList();
}
@@ -31,7 +31,7 @@ public interface IHeroImageService
/// image. Until its set exists the image has no variants and is not published.
/// </summary>
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null);
/// <summary>How many images exist, how many wait for their variants and how many only lack the full-frame preview (for the log).</summary>
Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken);
@@ -67,6 +67,16 @@ public interface IHeroImageService
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// Moves an image to the trash: the slides that use it are removed from the hero (and remember the moment as its last use),
/// it disappears from the hero and its files stay for the trash period. Returns how many slides were removed.
/// </summary>
/// <exception cref="HeroImageNotFoundException">There is no such image outside the trash.</exception>
Task<int> TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
/// <summary>Takes an image out of the trash again. False when it is not in the trash.</summary>
Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
}
public class HeroImageService(
@@ -83,7 +93,7 @@ public class HeroImageService(
{
private readonly TimeProvider _time = time ?? TimeProvider.System;
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken)
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null)
{
using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken);
var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes));
@@ -91,8 +101,18 @@ public class HeroImageService(
// The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload
// repairs them from the file that was just sent.
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
var fileName = HeroFileNames.Clean(originalFileName);
// The same photo uploaded again also brings it back from the trash.
if (existing is not null)
{
existing.DeletedAt = null;
existing.OriginalFileName ??= fileName;
}
if (existing is not null && await FilesExistAsync(existing, cancellationToken))
{
await repository.SaveChangesAsync(cancellationToken);
// The same photo again also gives up the failed state: the renderer tries it again when it is still pending.
signal?.Reset(existing.Id);
signal?.Notify();
@@ -118,6 +138,7 @@ public class HeroImageService(
Bytes = original.Length,
CreatedAt = _time.GetUtcNow(),
CreatedByUserId = callerId,
OriginalFileName = fileName,
};
// The files first, the row last: an aborted request leaves at most an original nobody refers to (the clean-up
@@ -323,6 +344,47 @@ public class HeroImageService(
logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId);
}
public async Task<int> TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
var now = _time.GetUtcNow();
// A slide cannot exist without its image, so the slides that use it go with it; the moment counts as its last use.
var slides = await repository.GetSlidesOfImageAsync(imageId, cancellationToken);
foreach (var slide in slides)
{
repository.RemoveSlide(slide);
}
if (slides.Count > 0)
{
image.LastUsedAt = now;
}
image.DeletedAt = now;
await repository.SaveChangesAsync(cancellationToken);
indexCache?.Invalidate();
logger.LogInformation("Hero image {ImageId} moved to the trash by user {UserId} ({Slides} slides removed)", imageId, callerId, slides.Count);
return slides.Count;
}
public async Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
if (image is null || image.DeletedAt is null)
{
return false;
}
image.DeletedAt = null;
await repository.SaveChangesAsync(cancellationToken);
signal?.Notify();
logger.LogInformation("Hero image {ImageId} restored from the trash by user {UserId}", imageId, callerId);
return true;
}
private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign)
{
if (value is null)
@@ -378,3 +440,26 @@ public class HeroImageService(
}
}
}
/// <summary>The file name of an upload as it is shown in the library: cleaned, for display only, never part of a path.</summary>
public static class HeroFileNames
{
public const int MaxLength = 200;
public static string? Clean(string? name)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}
var last = name[(name.LastIndexOfAny(['/', '\\']) + 1)..];
var cleaned = new string(last.Where(c => !char.IsControl(c)).ToArray()).Trim();
if (cleaned.Length > MaxLength)
{
cleaned = cleaned[..MaxLength];
}
return cleaned.Length == 0 ? null : cleaned;
}
}
@@ -40,6 +40,15 @@ public class HeroMediaCleanup(
repository.RemoveImage(image);
}
// 1b. Photos that have been in the trash for the trash period: their files go now (they are retired, immediately due).
var trashCutoff = now.AddDays(-Math.Max(0, options.Value.TrashDays));
foreach (var image in await repository.GetTrashedBeforeAsync(trashCutoff, cancellationToken))
{
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) });
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) });
repository.RemoveImage(image);
}
await repository.SaveChangesAsync(cancellationToken);
// 2. Retired files whose retention has passed, unless an image uses them again.
@@ -7,21 +7,19 @@ namespace SlpModularCms.Modules.Hero.Services;
/// <summary>
/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the
/// hero). Read-only: nothing of the hero changes through this class.
/// hero), and moves them to the trash and back for it. The files are removed by <see cref="HeroMediaCleanup"/> after the trash period.
/// </summary>
public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider
public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageService images) : IMediaUsageProvider
{
public const string SlideKind = "slide";
public string Module => HeroMapping.Area;
public async Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken)
{
var images = await repository.GetAllImagesReadOnlyAsync(cancellationToken);
return images
.Select(i => new MediaPhoto(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i)))
.ToList();
}
=> (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
public async Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken)
=> (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
public async Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
{
@@ -46,6 +44,24 @@ public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsagePro
return uses;
}
public async Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
{
try
{
return await images.TrashAsync(photoId, callerId, cancellationToken);
}
catch (HeroImageNotFoundException)
{
return null;
}
}
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
=> images.RestoreAsync(photoId, callerId, cancellationToken);
private MediaPhoto ToPhoto(HeroImage i)
=> new(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i), i.OriginalFileName, i.LastUsedAt, i.DeletedAt);
/// <summary>The smallest published WebP of the set; null while the set is not cut yet.</summary>
private static string? Thumbnail(HeroImage image)
{
@@ -121,8 +121,15 @@ public class HeroService(
slide.SortOrder = i;
}
// A photo that no slide uses any more remembers when it was last used (the media library counts from there).
var stillUsed = slideRequests.Select(r => r.ImageId).ToHashSet();
foreach (var removed in hero.Slides.Where(s => !keep.Contains(s.Id)).ToList())
{
if (removed.Image is { } detached && !stillUsed.Contains(detached.Id))
{
detached.LastUsedAt = now;
}
hero.Slides.Remove(removed);
if (!created)
{