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
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:
@@ -79,10 +79,114 @@ public class MediaLibraryTests
|
||||
library.Modules.Should().Equal("gallery", "hero");
|
||||
}
|
||||
|
||||
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses) : IMediaUsageProvider
|
||||
[Fact]
|
||||
public async Task Trash_refuses_a_photo_in_use_until_the_person_confirmed_and_then_names_the_places()
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-40), null);
|
||||
var use = new MediaUse("hero", photo.Id, "slide", 3, true);
|
||||
var provider = new FakeProvider("hero", [photo], [use]);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var refused = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: false, Guid.Empty, CancellationToken.None);
|
||||
var done = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: true, Guid.Empty, CancellationToken.None);
|
||||
|
||||
refused.Should().ContainSingle().Which.Status.Should().Be("inUse");
|
||||
refused.Single().Uses.Should().Equal(use);
|
||||
provider.Trashed.Should().Equal(photo.Id);
|
||||
done.Single().Status.Should().Be("trashed");
|
||||
done.Single().Uses.Should().Equal(use);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trash_reports_every_photo_on_its_own_and_one_failure_does_not_stop_the_others()
|
||||
{
|
||||
var ok = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
|
||||
var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
|
||||
var provider = new FakeProvider("hero", [ok, broken], []) { FailFor = broken.Id };
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var results = await library.TrashAsync([$"hero:{broken.Id}", $"hero:{ok.Id}", "hero:not-a-guid", $"other:{Guid.NewGuid()}", $"hero:{Guid.NewGuid()}"], false, Guid.Empty, CancellationToken.None);
|
||||
|
||||
results.Select(r => r.Status).Should().Equal("failed", "trashed", "notFound", "notFound", "notFound");
|
||||
provider.Trashed.Should().Equal(ok.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trash_and_restore_accept_at_most_100_photos_and_a_photo_once()
|
||||
{
|
||||
var provider = new FakeProvider("hero", [], []);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList();
|
||||
|
||||
await FluentActions.Awaiting(() => library.TrashAsync(tooMany, false, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
|
||||
await FluentActions.Awaiting(() => library.RestoreAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
|
||||
var id = $"hero:{Guid.NewGuid()}";
|
||||
(await library.TrashAsync([id, id], false, Guid.Empty, CancellationToken.None)).Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Restore_gives_the_photo_back_and_lists_the_trash_most_recent_first()
|
||||
{
|
||||
var older = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-3));
|
||||
var newer = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-1));
|
||||
var provider = new FakeProvider("hero", [], [], trash: [older, newer]);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
(await library.ListTrashAsync(CancellationToken.None)).Select(i => i.Photo.Id).Should().Equal(newer.Id, older.Id);
|
||||
(await library.RestoreAsync([$"hero:{older.Id}"], Guid.Empty, CancellationToken.None)).Single().Status.Should().Be("restored");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_clean_up_counts_from_the_last_use_and_falls_back_to_the_upload_date()
|
||||
{
|
||||
var detachedRecently = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-2));
|
||||
var detachedLongAgo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-30));
|
||||
var neverUsed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null);
|
||||
var items = new[] { detachedRecently, detachedLongAgo, neverUsed }.Select(p => new MediaLibraryItem(p, [])).ToList();
|
||||
|
||||
var selected = CleanupSelection.Select(items, Now, 7, onlyUnused: true);
|
||||
|
||||
selected.Select(i => i.Photo.Id).Should().BeEquivalentTo([detachedLongAgo.Id, neverUsed.Id]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_photo_in_use_counts_from_its_upload_date()
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null, UnusedSince: Now.AddDays(-1));
|
||||
var item = new MediaLibraryItem(photo, [new MediaUse("hero", photo.Id, "slide", 1, true)]);
|
||||
|
||||
CleanupSelection.ReferenceDate(item).Should().Be(photo.CreatedAt);
|
||||
CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().ContainSingle();
|
||||
}
|
||||
|
||||
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider
|
||||
{
|
||||
public string Module => module;
|
||||
|
||||
public List<Guid> Trashed { get; } = [];
|
||||
|
||||
public Guid? FailFor { get; init; }
|
||||
|
||||
public Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaPhoto>>(trash ?? []);
|
||||
|
||||
public Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (photoId == FailFor)
|
||||
{
|
||||
throw new InvalidOperationException("boom");
|
||||
}
|
||||
|
||||
if (photos.All(p => p.Id != photoId))
|
||||
{
|
||||
return Task.FromResult<int?>(null);
|
||||
}
|
||||
|
||||
Trashed.Add(photoId);
|
||||
return Task.FromResult<int?>(uses.Count(u => u.PhotoId == photoId));
|
||||
}
|
||||
|
||||
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) => Task.FromResult(trash?.Any(p => p.Id == photoId) == true);
|
||||
|
||||
public Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaPhoto>>(photos);
|
||||
|
||||
public Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
|
||||
|
||||
@@ -73,6 +73,9 @@ public sealed class MediaOptions
|
||||
/// Default <c>true</c> keeps today's behaviour (assumption 3 of the media-library list).
|
||||
/// </summary>
|
||||
public bool AutoCleanupUnattached { get; set; } = true;
|
||||
|
||||
/// <summary>How long a photo stays recoverable in the trash before its files are removed.</summary>
|
||||
public int TrashDays { get; set; } = 7;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -2,7 +2,8 @@ namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>
|
||||
/// The photos a clean-up would preselect: uploaded before the period and, by default, not used anywhere. Pure, so it is
|
||||
/// easy to test. The period is measured from the upload date (assumption 8 of the media-library list).
|
||||
/// easy to test. The period counts from the LAST USE (decision 8): for a photo that is not in use the moment it was last
|
||||
/// detached, else its upload date; for a photo in use right now its upload date (assumption 29).
|
||||
/// </summary>
|
||||
public static class CleanupSelection
|
||||
{
|
||||
@@ -18,13 +19,17 @@ public static class CleanupSelection
|
||||
{
|
||||
var cutoff = now.AddDays(-ClampDays(days));
|
||||
return items
|
||||
.Where(item => item.Photo.CreatedAt < cutoff)
|
||||
.Where(item => ReferenceDate(item) < cutoff)
|
||||
.Where(item => !onlyUnused || !item.InUse)
|
||||
.OrderByDescending(item => item.Photo.CreatedAt)
|
||||
.ThenBy(item => item.Photo.Id)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>The date the period counts from.</summary>
|
||||
public static DateTimeOffset ReferenceDate(MediaLibraryItem item)
|
||||
=> item.InUse ? item.Photo.CreatedAt : item.Photo.UnusedSince ?? item.Photo.CreatedAt;
|
||||
|
||||
/// <summary>The bytes the given items take (originals; the variants are counted by the storage service).</summary>
|
||||
public static long Bytes(IEnumerable<MediaLibraryItem> items) => items.Sum(item => item.Photo.Bytes);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -6,18 +7,40 @@ namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public sealed record MediaUseDto(string Module, string Kind, int? Position, bool Active);
|
||||
|
||||
public sealed record MediaPhotoDto(string Id, string Module, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl, IReadOnlyList<MediaUseDto> Uses);
|
||||
public sealed record MediaPhotoDto(
|
||||
string Id,
|
||||
string Module,
|
||||
long Bytes,
|
||||
int Width,
|
||||
int Height,
|
||||
DateTimeOffset CreatedAt,
|
||||
string? ThumbnailUrl,
|
||||
IReadOnlyList<MediaUseDto> Uses,
|
||||
string? OriginalFileName = null,
|
||||
DateTimeOffset? UnusedSince = null,
|
||||
DateTimeOffset? DeletedAt = null);
|
||||
|
||||
public sealed record MediaLibraryDto(IReadOnlyList<MediaPhotoDto> Photos, IReadOnlyList<string> Modules);
|
||||
|
||||
public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent);
|
||||
|
||||
/// <summary>What a clean-up with these settings would select. A preview only: nothing is deleted.</summary>
|
||||
/// <summary>What a clean-up with these settings would select. A preview: nothing is deleted until the person confirms.</summary>
|
||||
public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList<MediaPhotoDto> Photos);
|
||||
|
||||
/// <param name="Ids">Photo ids as listed (<c>module:guid</c>), at most 100.</param>
|
||||
/// <param name="ConfirmedInUse">True when the person confirmed a second time, knowing where the photos in use are used.</param>
|
||||
public sealed record MediaTrashRequest(IReadOnlyList<string> Ids, bool ConfirmedInUse = false);
|
||||
|
||||
public sealed record MediaRestoreRequest(IReadOnlyList<string> Ids);
|
||||
|
||||
public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList<MediaUseDto> Uses);
|
||||
|
||||
public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results);
|
||||
|
||||
/// <summary>
|
||||
/// The media library for administrators: the photos of all modules with where they are used, the storage against its
|
||||
/// limit, and a preview of the clean-up. Read-only: deleting comes after the assumptions are checked.
|
||||
/// limit, the clean-up preview, and moving photos to the trash and back. Deleting is always "to the trash": the files go
|
||||
/// after the trash period.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("media-library")]
|
||||
@@ -32,6 +55,14 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("trash")]
|
||||
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Trash(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await library.ListTrashAsync(cancellationToken);
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("storage")]
|
||||
[ProducesResponseType<MediaStorageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Storage(CancellationToken cancellationToken)
|
||||
@@ -50,6 +81,47 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
|
||||
return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
/// <summary>Moves photos to the trash. A photo in use is refused (status <c>inUse</c>) unless <c>confirmedInUse</c> is true.</summary>
|
||||
[HttpPost("delete")]
|
||||
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Delete([FromBody] MediaTrashRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ValidIds(request.Ids))
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var results = await library.TrashAsync(request.Ids, request.ConfirmedInUse, CallerId(), cancellationToken);
|
||||
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
[HttpPost("restore")]
|
||||
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Restore([FromBody] MediaRestoreRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ValidIds(request.Ids))
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var results = await library.RestoreAsync(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");
|
||||
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
private static MediaUseResultDto ToDto(MediaTrashResult result)
|
||||
=> new(result.Id, result.Status, result.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList());
|
||||
|
||||
private static MediaPhotoDto ToDto(MediaLibraryItem item)
|
||||
=> new(
|
||||
$"{item.Photo.Module}:{item.Photo.Id}",
|
||||
@@ -59,5 +131,8 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
|
||||
item.Photo.Height,
|
||||
item.Photo.CreatedAt,
|
||||
item.Photo.ThumbnailUrl,
|
||||
item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList());
|
||||
item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList(),
|
||||
item.Photo.OriginalFileName,
|
||||
item.Photo.UnusedSince,
|
||||
item.Photo.DeletedAt);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,39 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only.</summary>
|
||||
/// <summary>The result for one photo of a trash or restore request.</summary>
|
||||
/// <param name="Id">The photo id as the caller sent it (<c>module:guid</c>).</param>
|
||||
/// <param name="Status"><c>trashed</c>, <c>restored</c>, <c>inUse</c> (not done: it is used and the caller did not confirm), <c>notFound</c> or <c>failed</c>.</param>
|
||||
/// <param name="Uses">Where the photo was used when it was refused or trashed.</param>
|
||||
public sealed record MediaTrashResult(string Id, string Status, IReadOnlyList<MediaUse> Uses);
|
||||
|
||||
/// <summary>The library over all modules that report photos: one list, newest first, each photo with its uses.</summary>
|
||||
public interface IMediaLibraryService
|
||||
{
|
||||
/// <summary>All photos of all modules with their uses, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaLibraryItem>> ListAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The photos in the trash, most recently trashed first.</summary>
|
||||
Task<IReadOnlyList<MediaLibraryItem>> ListTrashAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The modules that report photos (the screen warns about a module that is not in this list).</summary>
|
||||
IReadOnlyList<string> Modules { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Moves photos to the trash. The usage is checked again here, at the moment of deleting: a photo that is in use is
|
||||
/// only trashed when <paramref name="confirmedInUse"/> says the person confirmed it knowing where it is used.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers) : IMediaLibraryService
|
||||
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers, ILogger<MediaLibraryService>? logger = null) : IMediaLibraryService
|
||||
{
|
||||
/// <summary>The most photos one trash or restore request may name.</summary>
|
||||
public const int MaxIdsPerRequest = 100;
|
||||
|
||||
private readonly IMediaUsageProvider[] _providers = providers.ToArray();
|
||||
|
||||
public IReadOnlyList<string> Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList();
|
||||
@@ -29,4 +51,111 @@ public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> provide
|
||||
|
||||
return items.OrderByDescending(i => i.Photo.CreatedAt).ThenBy(i => i.Photo.Id).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaLibraryItem>> ListTrashAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = new List<MediaLibraryItem>();
|
||||
foreach (var provider in _providers)
|
||||
{
|
||||
items.AddRange((await provider.ListTrashAsync(cancellationToken)).Select(photo => new MediaLibraryItem(photo, [])));
|
||||
}
|
||||
|
||||
return items.OrderByDescending(i => i.Photo.DeletedAt).ThenBy(i => i.Photo.Id).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, 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 uses = await provider.ListUsesAsync([photoId], cancellationToken);
|
||||
if (uses.Count > 0 && !confirmedInUse)
|
||||
{
|
||||
results.Add(new MediaTrashResult(id, "inUse", uses));
|
||||
continue;
|
||||
}
|
||||
|
||||
var detached = await provider.TrashAsync(photoId, callerId, cancellationToken);
|
||||
results.Add(new MediaTrashResult(id, detached is null ? "notFound" : "trashed", uses));
|
||||
if (detached is not null)
|
||||
{
|
||||
logger?.LogInformation("Media {Photo} moved to the trash by user {UserId} ({Uses} uses removed)", id, callerId, detached);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
// One photo failing never stops the others; the caller sees it per photo.
|
||||
logger?.LogWarning(exception, "Moving media {Photo} to the trash failed", id);
|
||||
results.Add(new MediaTrashResult(id, "failed", []));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(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 restored = await provider.RestoreAsync(photoId, callerId, cancellationToken);
|
||||
results.Add(new MediaTrashResult(id, restored ? "restored" : "notFound", []));
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger?.LogWarning(exception, "Restoring media {Photo} failed", id);
|
||||
results.Add(new MediaTrashResult(id, "failed", []));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void EnsureWithinLimit(IReadOnlyCollection<string> ids)
|
||||
{
|
||||
if (ids.Count > MaxIdsPerRequest)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(ids), $"At most {MaxIdsPerRequest} photos per request.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Splits <c>module:guid</c> and finds the provider of that module.</summary>
|
||||
private bool TryResolve(string id, out IMediaUsageProvider provider, out Guid photoId)
|
||||
{
|
||||
provider = null!;
|
||||
photoId = Guid.Empty;
|
||||
var colon = id.IndexOf(':');
|
||||
if (colon <= 0 || !Guid.TryParse(id.AsSpan(colon + 1), out photoId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var module = id[..colon];
|
||||
var found = _providers.FirstOrDefault(p => string.Equals(p.Module, module, StringComparison.Ordinal));
|
||||
if (found is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
provider = found;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,20 @@ namespace SlpModularCms.Core.Media.Library;
|
||||
/// <summary>A photo as the library shows it. The module that owns it fills it; the library only reads.</summary>
|
||||
/// <param name="Module">The module key (for example <c>hero</c>); with <paramref name="Id"/> it names the photo.</param>
|
||||
/// <param name="ThumbnailUrl">A public address of a small variant, or null while no variant exists yet.</param>
|
||||
public sealed record MediaPhoto(string Module, Guid Id, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl);
|
||||
/// <param name="OriginalFileName">The file name as uploaded, or null for photos uploaded before it was stored.</param>
|
||||
/// <param name="UnusedSince">The moment the photo was last detached from where it was used; null when it was never used.</param>
|
||||
/// <param name="DeletedAt">When the photo was moved to the trash; null for a photo in the library.</param>
|
||||
public sealed record MediaPhoto(
|
||||
string Module,
|
||||
Guid Id,
|
||||
long Bytes,
|
||||
int Width,
|
||||
int Height,
|
||||
DateTimeOffset CreatedAt,
|
||||
string? ThumbnailUrl,
|
||||
string? OriginalFileName = null,
|
||||
DateTimeOffset? UnusedSince = null,
|
||||
DateTimeOffset? DeletedAt = null);
|
||||
|
||||
/// <summary>One place where a photo is used. The library shows it as "module, place kind, position" (for example "Hero, slide 3").</summary>
|
||||
/// <param name="PlaceKind">What kind of place (for example <c>slide</c>); the screen translates it.</param>
|
||||
@@ -18,17 +31,29 @@ public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList<MediaUse>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a module tells the media library. Read-only: the library never changes a module's data through this contract
|
||||
/// (deleting and detaching come in a later step). The answers are computed from the module's own data, never copied.
|
||||
/// What a module tells the media library and does for it. The answers are computed from the module's own data, never copied.
|
||||
/// Deleting always means "to the trash" (recoverable for a while); the module removes the files later itself.
|
||||
/// </summary>
|
||||
public interface IMediaUsageProvider
|
||||
{
|
||||
/// <summary>The module key, lower case, equal to its media area when it has one.</summary>
|
||||
string Module { get; }
|
||||
|
||||
/// <summary>The photos of this module, newest first.</summary>
|
||||
/// <summary>The photos of this module that are not in the trash, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The photos of this module in the trash, most recently trashed first.</summary>
|
||||
Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Where the given photos are used (only photos of this module).</summary>
|
||||
Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a photo to the trash after detaching it from where it is used. Returns how many places lost it, or null when
|
||||
/// there is no such photo outside the trash.
|
||||
/// </summary>
|
||||
Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,12 @@ namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroMediaUsageProviderTests
|
||||
{
|
||||
private static HeroMediaUsageProvider Provider(HeroTestRig rig) => new(rig.Repository, rig.Images);
|
||||
|
||||
private static Task<HeroSaveRequest> NoSlides() => Task.FromResult(Save([]));
|
||||
|
||||
private static HeroSaveRequest Save(params HeroSlideRequest[] slides) => new("Titel", null, null, "single", [], slides);
|
||||
|
||||
[Fact]
|
||||
public async Task Lists_the_images_newest_first_with_a_thumbnail_and_reports_one_use_per_slide_with_its_position()
|
||||
{
|
||||
@@ -18,10 +24,9 @@ public class HeroMediaUsageProviderTests
|
||||
rig.Time.Now = rig.Time.Now.AddMinutes(5);
|
||||
var unused = await rig.Upload(HeroTestRig.Photo(seed: 3));
|
||||
await rig.Service.SaveAsync(
|
||||
new HeroSaveRequest("Titel", null, null, "single", [],
|
||||
[new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)]),
|
||||
Save(new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)),
|
||||
HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = new HeroMediaUsageProvider(rig.Repository);
|
||||
var provider = Provider(rig);
|
||||
|
||||
var photos = await provider.ListPhotosAsync(CancellationToken.None);
|
||||
var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), CancellationToken.None);
|
||||
@@ -40,12 +45,150 @@ public class HeroMediaUsageProviderTests
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var provider = new HeroMediaUsageProvider(rig.Repository);
|
||||
var provider = Provider(rig);
|
||||
|
||||
await provider.ListPhotosAsync(CancellationToken.None);
|
||||
await provider.ListUsesAsync([Guid.Parse(image.Id)], CancellationToken.None);
|
||||
await provider.ListTrashAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Repository.CountImagesAsync(CancellationToken.None)).Should().Be(1);
|
||||
rig.Db.ChangeTracker.HasChanges().Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_upload_remembers_the_cleaned_original_file_name()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = HeroTestRig.Photo();
|
||||
|
||||
await rig.Images.UploadAsync(new MemoryStream(bytes), bytes.Length, HeroTestRig.Admin, CancellationToken.None, "C:\\fotos\\zomer\u0007 2026.jpg");
|
||||
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().OriginalFileName.Should().Be("zomer 2026.jpg");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData(" ", null)]
|
||||
[InlineData("../../etc/passwd", "passwd")]
|
||||
[InlineData("a/b\\c.jpg", "c.jpg")]
|
||||
public void File_names_are_cleaned_for_display_only(string? input, string? expected) => HeroFileNames.Clean(input).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public void A_very_long_file_name_is_cut() => HeroFileNames.Clean(new string('a', 500))!.Length.Should().Be(HeroFileNames.MaxLength);
|
||||
|
||||
[Fact]
|
||||
public async Task Trashing_a_photo_in_use_removes_its_slides_hides_it_and_remembers_the_last_use()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")), HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = Provider(rig);
|
||||
rig.Time.Now = rig.Time.Now.AddDays(3);
|
||||
|
||||
var removed = await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
removed.Should().Be(1);
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Select(p => p.Id).Should().Equal(Guid.Parse(b.Id));
|
||||
var trashed = (await provider.ListTrashAsync(CancellationToken.None)).Single();
|
||||
trashed.Id.Should().Be(Guid.Parse(a.Id));
|
||||
trashed.DeletedAt.Should().Be(rig.Time.Now);
|
||||
trashed.UnusedSince.Should().Be(rig.Time.Now);
|
||||
(await rig.Service.GetAsync(CancellationToken.None)).Slides.Should().ContainSingle().Which.Image.Id.Should().Be(b.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_trashed_photo_cannot_be_put_in_a_slide_and_is_not_cut_in_the_background()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.UploadWithoutRendering(HeroTestRig.Photo());
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var save = () => rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await save.Should().ThrowAsync<HeroSaveRejectedException>();
|
||||
(await rig.RenderPending()).Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trashing_an_unknown_or_already_trashed_photo_gives_null()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
var provider = Provider(rig);
|
||||
|
||||
(await provider.TrashAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
(await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Restoring_brings_the_photo_back_without_its_slides()
|
||||
{
|
||||
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);
|
||||
|
||||
(await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeTrue();
|
||||
(await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeFalse();
|
||||
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle();
|
||||
(await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty();
|
||||
(await provider.ListUsesAsync([Guid.Parse(a.Id)], CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Uploading_the_same_photo_again_brings_it_back_from_the_trash()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = HeroTestRig.Photo();
|
||||
var first = await rig.Upload(bytes);
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(first.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var again = await rig.Upload(bytes);
|
||||
|
||||
again.Id.Should().Be(first.Id);
|
||||
(await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty();
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_the_hero_without_a_slide_remembers_when_its_photo_was_last_used()
|
||||
{
|
||||
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);
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().BeNull();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(2);
|
||||
await rig.Service.SaveAsync(Save(), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().Be(rig.Time.Now);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_trashed_photo_is_emptied_from_the_trash_after_the_trash_period_and_its_files_go()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
var row = rig.Db.HeroImages.Single();
|
||||
var (set, original) = (row.SetHash, row.OriginalKey);
|
||||
await Provider(rig).TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(6);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(2);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
Generated
+257
@@ -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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user