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
@@ -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)
{