WIP: bulkbalk boven de lijst, definitief verwijderen en prullenbak legen, uitsnede direct zonder opslaan, teller per batch

This commit is contained in:
2026-11-17 16:58:23 +01:00
parent 8ad071da1c
commit 1384cafa7b
28 changed files with 816 additions and 134 deletions
@@ -77,6 +77,25 @@ public class MediaLibraryControllerTests
shorter.Count.Should().Be(2);
}
[Fact]
public async Task Purge_names_the_ids_or_empties_the_whole_trash_and_refuses_an_empty_or_oversized_request()
{
var library = Substitute.For<IMediaLibraryService>();
library.PurgeAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ci => ci.Arg<IReadOnlyCollection<string>>().Select(id => new MediaTrashResult(id, "purged", [])).ToList());
library.PurgeAllAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns([new MediaTrashResult("hero:a", "purged", []), new MediaTrashResult("hero:b", "purged", [])]);
var controller = new MediaLibraryController(library, new Clock());
var some = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(["hero:x"]), CancellationToken.None)).Value!;
var all = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(null, All: true), CancellationToken.None)).Value!;
some.Results.Should().ContainSingle().Which.Status.Should().Be("purged");
all.Results.Should().HaveCount(2);
(await controller.Purge(new MediaPurgeRequest([]), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
(await controller.Purge(new MediaPurgeRequest(null), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
(await controller.Purge(new MediaPurgeRequest(Enumerable.Range(0, 101).Select(i => $"hero:{i}").ToList()), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
}
[Fact]
public async Task Storage_without_a_media_store_reports_zero_and_ok()
{
@@ -159,10 +159,73 @@ public class MediaLibraryTests
CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().ContainSingle();
}
[Fact]
public async Task Purge_reports_per_photo_and_only_removes_what_the_module_accepts()
{
var inTrash = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
var notTrashed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
var used = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
var provider = new FakeProvider("hero", [notTrashed], [], trash: [inTrash, used, broken]) { InUsePurge = used.Id, FailFor = broken.Id };
var library = new MediaLibraryService([provider]);
var results = await library.PurgeAsync([$"hero:{inTrash.Id}", $"hero:{notTrashed.Id}", $"hero:{used.Id}", $"hero:{broken.Id}", "nope", $"gallery:{Guid.NewGuid()}"], Guid.Empty, CancellationToken.None);
results.Select(r => r.Status).Should().Equal("purged", "notInTrash", "inUse", "failed", "notFound", "notFound");
provider.Purged.Should().Equal(inTrash.Id);
}
[Fact]
public async Task Purge_all_empties_the_whole_trash_in_batches_of_100()
{
var trash = Enumerable.Range(0, 250).Select(_ => new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now)).ToArray();
var provider = new FakeProvider("hero", [], [], trash: trash);
var library = new MediaLibraryService([provider]);
var results = await library.PurgeAllAsync(Guid.Empty, CancellationToken.None);
results.Should().HaveCount(250).And.OnlyContain(r => r.Status == "purged");
provider.Purged.Should().HaveCount(250);
}
[Fact]
public async Task Purge_accepts_at_most_100_photos_in_one_request()
{
var library = new MediaLibraryService([new FakeProvider("hero", [], [])]);
var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList();
await FluentActions.Awaiting(() => library.PurgeAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
}
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider
{
public string Module => module;
public List<Guid> Purged { get; } = [];
public Guid? InUsePurge { get; init; }
public Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
{
if (photoId == FailFor)
{
throw new InvalidOperationException("boom");
}
if (photoId == InUsePurge)
{
return Task.FromResult(MediaPurgeOutcome.InUse);
}
if (trash?.Any(p => p.Id == photoId) != true)
{
return Task.FromResult(MediaPurgeOutcome.NotInTrash);
}
Purged.Add(photoId);
return Task.FromResult(MediaPurgeOutcome.Purged);
}
public List<Guid> Trashed { get; } = [];
public Guid? FailFor { get; init; }
@@ -33,6 +33,10 @@ public sealed record MediaTrashRequest(IReadOnlyList<string> Ids, bool Confirmed
public sealed record MediaRestoreRequest(IReadOnlyList<string> Ids);
/// <param name="Ids">Photos in the trash to remove for good (at most 100). Ignored when <paramref name="All"/> is true.</param>
/// <param name="All">Remove everything that is in the trash (the trash is emptied, in batches on the server).</param>
public sealed record MediaPurgeRequest(IReadOnlyList<string>? Ids = null, bool All = false);
public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList<MediaUseDto> Uses);
public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results);
@@ -110,12 +114,34 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
}
/// <summary>Removes photos from the trash for good: not reversible. Only photos in the trash that are used nowhere.</summary>
[HttpPost("purge")]
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Purge([FromBody] MediaPurgeRequest request, CancellationToken cancellationToken)
{
if (request.All)
{
var all = await library.PurgeAllAsync(CallerId(), cancellationToken);
return Ok(new MediaTrashResponse(all.Select(ToDto).ToList()));
}
if (!ValidIds(request.Ids))
{
return BadRequest();
}
var results = await library.PurgeAsync(request.Ids!, CallerId(), cancellationToken);
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
}
private static bool ValidIds(IReadOnlyList<string>? ids)
=> ids is { Count: > 0 and <= MediaLibraryService.MaxIdsPerRequest } && ids.All(id => !string.IsNullOrWhiteSpace(id) && id.Length <= 80);
private Guid CallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
var user = HttpContext?.User;
var claim = user?.FindFirstValue(ClaimTypes.NameIdentifier) ?? user?.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
@@ -27,6 +27,15 @@ public interface IMediaLibraryService
Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken);
Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// Removes photos from the trash for good. Each photo is checked again by its module: only a photo that is in the trash
/// and used nowhere is removed (statuses <c>purged</c>, <c>notInTrash</c>, <c>inUse</c>, <c>notFound</c>, <c>failed</c>).
/// </summary>
Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
/// <summary>Removes everything that is in the trash for good, in batches of <see cref="MediaLibraryService.MaxIdsPerRequest"/>.</summary>
Task<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken);
}
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers, ILogger<MediaLibraryService>? logger = null) : IMediaLibraryService
@@ -129,6 +138,55 @@ public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> provide
return results;
}
public async Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken)
{
EnsureWithinLimit(ids);
var results = new List<MediaTrashResult>();
foreach (var id in ids.Distinct(StringComparer.Ordinal))
{
if (!TryResolve(id, out var provider, out var photoId))
{
results.Add(new MediaTrashResult(id, "notFound", []));
continue;
}
try
{
var outcome = await provider.PurgeAsync(photoId, callerId, cancellationToken);
var status = outcome switch
{
MediaPurgeOutcome.Purged => "purged",
MediaPurgeOutcome.InUse => "inUse",
_ => "notInTrash",
};
results.Add(new MediaTrashResult(id, status, []));
if (outcome == MediaPurgeOutcome.Purged)
{
logger?.LogInformation("Media {Photo} removed for good by user {UserId}", id, callerId);
}
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger?.LogWarning(exception, "Removing media {Photo} for good failed", id);
results.Add(new MediaTrashResult(id, "failed", []));
}
}
return results;
}
public async Task<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken)
{
var ids = (await ListTrashAsync(cancellationToken)).Select(i => $"{i.Photo.Module}:{i.Photo.Id}").ToList();
var results = new List<MediaTrashResult>();
foreach (var batch in ids.Chunk(MaxIdsPerRequest))
{
results.AddRange(await PurgeAsync(batch, callerId, cancellationToken));
}
return results;
}
private static void EnsureWithinLimit(IReadOnlyCollection<string> ids)
{
if (ids.Count > MaxIdsPerRequest)
@@ -56,4 +56,23 @@ public interface IMediaUsageProvider
/// <summary>Takes a photo out of the trash. False when it is not in the trash.</summary>
Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// Removes a photo FOR GOOD: its original and its cut sets (a set another photo still shares stays). Only a photo that is
/// in the trash and used nowhere; the module checks this again itself.
/// </summary>
Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
}
/// <summary>What happened to a photo that was to be removed for good.</summary>
public enum MediaPurgeOutcome
{
/// <summary>Removed: the files and the record are gone.</summary>
Purged,
/// <summary>There is no such photo in the trash (not trashed, or already gone). Nothing was changed.</summary>
NotInTrash,
/// <summary>The photo is used somewhere after all. Nothing was changed.</summary>
InUse,
}
@@ -170,6 +170,81 @@ public class HeroMediaUsageProviderTests
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().Be(rig.Time.Now);
}
[Fact]
public async Task Purging_removes_a_photo_in_the_trash_for_good_with_its_original_and_set()
{
using var rig = new HeroTestRig();
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
var keep = await rig.Upload(HeroTestRig.Photo(seed: 2));
var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id));
var (set, original) = (rowA.SetHash, rowA.OriginalKey);
var keepRow = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(keep.Id));
var provider = Provider(rig);
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
var outcome = await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
outcome.Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged);
rig.Db.HeroImages.Select(i => i.Id).Should().Equal(Guid.Parse(keep.Id));
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set).And.Contain(s => s.SetHash == keepRow.SetHash);
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
(await rig.Store.ExistsAsync(keepRow.OriginalKey, CancellationToken.None)).Should().BeTrue();
}
[Fact]
public async Task Purging_refuses_a_photo_that_is_not_in_the_trash_and_changes_nothing()
{
using var rig = new HeroTestRig();
var a = await rig.Upload(HeroTestRig.Photo());
var original = rig.Db.HeroImages.Single().OriginalKey;
var provider = Provider(rig);
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash);
(await provider.PurgeAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash);
rig.Db.HeroImages.Should().HaveCount(1);
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
}
[Fact]
public async Task Purging_refuses_a_photo_that_a_slide_uses_after_all()
{
using var rig = new HeroTestRig();
var a = await rig.Upload(HeroTestRig.Photo());
await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
var provider = Provider(rig);
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
// A slide that still points at the trashed photo (a race or an old row): the purge must notice.
var hero = rig.Db.Heroes.Single();
rig.Db.HeroSlides.Add(new Data.Entities.HeroSlide { Id = Guid.NewGuid(), HeroId = hero.Id, ImageId = Guid.Parse(a.Id), Alt = "x", SortOrder = 9 });
await rig.Db.SaveChangesAsync();
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.InUse);
rig.Db.HeroImages.Should().HaveCount(1);
}
[Fact]
public async Task Purging_leaves_a_file_another_photo_still_shares()
{
using var rig = new HeroTestRig();
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id));
var rowB = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(b.Id));
// Two records that point at the same files (not created by the hero itself, but possible after a restore).
rowB.SetHash = rowA.SetHash;
rowB.OriginalKey = rowA.OriginalKey;
await rig.Db.SaveChangesAsync();
var provider = Provider(rig);
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged);
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().Contain(s => s.SetHash == rowB.SetHash);
(await rig.Store.ExistsAsync(rowB.OriginalKey, CancellationToken.None)).Should().BeTrue();
}
[Fact]
public async Task A_trashed_photo_is_emptied_from_the_trash_after_the_trash_period_and_its_files_go()
{
@@ -0,0 +1,45 @@
using FluentAssertions;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
using Xunit;
namespace SlpModularCms.Modules.Hero.Tests;
/// <summary>A new crop works at once, without saving the hero (Bryan, 2026-11-17).</summary>
public class HeroSetFocusTests
{
[Fact]
public async Task A_new_crop_starts_processing_at_once_and_goes_live_without_saving_the_hero()
{
using var rig = new HeroTestRig();
var uploaded = await rig.Upload(HeroTestRig.Photo());
var id = Guid.Parse(uploaded.Id);
var before = rig.Db.HeroImages.Single(i => i.Id == id).SetHash;
var answer = await rig.Images.SetFocusAsync(id, new HeroFocusRequest(new FocusDto(0.2, 0.3, 1.5)), HeroTestRig.Admin, CancellationToken.None);
answer.Should().NotBeNull();
answer!.Processing.Should().BeTrue("the new variants still have to be cut");
answer.Focus.Should().Be(new FocusDto(0.2, 0.3, 1.5));
rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().Be(before, "the old set stays live until the new one is complete");
(await rig.RenderPending()).Should().Be(1);
var after = (await rig.Images.GetImageAsync(id, CancellationToken.None))!;
after.Processing.Should().BeFalse();
rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().NotBe(before);
rig.Db.Heroes.Should().BeEmpty("the hero itself was never saved");
}
[Fact]
public async Task An_unknown_image_gives_null_and_a_trashed_image_cannot_be_cropped()
{
using var rig = new HeroTestRig();
var uploaded = await rig.Upload(HeroTestRig.Photo());
await new HeroMediaUsageProvider(rig.Repository, rig.Images).TrashAsync(Guid.Parse(uploaded.Id), HeroTestRig.Admin, CancellationToken.None);
var request = new HeroFocusRequest(new FocusDto(0.5, 0.5, 1));
(await rig.Images.SetFocusAsync(Guid.NewGuid(), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
(await rig.Images.SetFocusAsync(Guid.Parse(uploaded.Id), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
}
}
@@ -105,6 +105,20 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
}
/// <summary>
/// A new crop for an image, applied at once without saving the hero: the new variants are cut in the background and the
/// image switches to them when they are complete. Answers with the image (processing).
/// </summary>
[HttpPut("{id:guid}/focus")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
{
var image = await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken);
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
}
/// <summary>The formats and limits an upload has to meet on this host (what the validation uses).</summary>
[HttpGet("limits")]
[ProducesResponseType<HeroUploadLimitsDto>(StatusCodes.Status200OK)]
@@ -34,6 +34,9 @@ public interface IHeroRepository
/// <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>True when an image other than the given one has this set hash or this original key (the files are shared).</summary>
Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, 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);
@@ -99,6 +102,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
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<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken)
{
var others = (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).Where(i => i.Id != imageId).ToList();
return (setHash.Length > 0 && others.Any(i => i.SetHash == setHash), others.Any(i => i.OriginalKey == originalKey));
}
public async Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken)
=> await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken);
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Core.Media;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Hero.Data.Entities;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Repositories;
@@ -46,6 +47,13 @@ public interface IHeroImageService
/// <summary>The variant the renderer is busy with: (done, total), or null when the image is not being cut right now.</summary>
(int Done, int Total)? RenderProgress(Guid imageId);
/// <summary>
/// Applies a new crop to an image at once, WITHOUT saving the hero (Bryan, 2026-11-17: a new crop must not need another
/// click on Save). The new set is cut in the background and the image switches to it when it is complete, so what is live
/// changes only then. Returns the image as the admin sees it now (processing), or null when there is no such image.
/// </summary>
Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, 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);
@@ -77,6 +85,12 @@ public interface IHeroImageService
/// <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);
/// <summary>
/// Removes an image that is in the trash FOR GOOD: its original and its set (a file another image shares stays) and the
/// record. Refused when the image is not in the trash or a slide uses it after all.
/// </summary>
Task<MediaPurgeOutcome> PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
}
public class HeroImageService(
@@ -188,6 +202,23 @@ public class HeroImageService(
public void NotifyPending() => signal?.Notify();
public async Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageAsync(imageId, cancellationToken);
if (image is null)
{
return null;
}
ApplyFocus(image, request);
await repository.SaveChangesAsync(cancellationToken);
signal?.Reset(imageId);
signal?.Notify();
logger.LogInformation("Hero image {ImageId} got a new crop from user {UserId}; its variants are cut in the background", imageId, callerId);
return await GetImageAsync(imageId, cancellationToken);
}
public async Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken)
{
var image = await repository.GetImageFreshAsync(imageId, cancellationToken);
@@ -369,6 +400,40 @@ public class HeroImageService(
return slides.Count;
}
public async Task<MediaPurgeOutcome> PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
if (image is null || image.DeletedAt is null)
{
return MediaPurgeOutcome.NotInTrash;
}
if (await repository.ImageInUseAsync(imageId, cancellationToken))
{
return MediaPurgeOutcome.InUse;
}
// The row first (nothing refers to it any more), then the files; a file another image still shares stays.
var (setShared, originalShared) = await repository.FilesSharedWithOthersAsync(imageId, image.SetHash, image.OriginalKey, cancellationToken);
var (setHash, originalKey) = (image.SetHash, image.OriginalKey);
repository.RemoveImage(image);
await repository.SaveChangesAsync(cancellationToken);
if (setHash.Length > 0 && !setShared)
{
await store.DeleteSetAsync(HeroMapping.Area, setHash, cancellationToken);
}
if (!originalShared)
{
await store.DeleteAsync(originalKey, cancellationToken);
}
indexCache?.Invalidate();
logger.LogInformation("Hero image {ImageId} removed for good by user {UserId}", imageId, callerId);
return MediaPurgeOutcome.Purged;
}
public async Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
@@ -59,6 +59,9 @@ public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageServic
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
=> images.RestoreAsync(photoId, callerId, cancellationToken);
public Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
=> images.PurgeAsync(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);