Mediabibliotheek: endpoints (foto's, opslag, opruimvoorbeeld) en scherm; ASF-verhoudingen in ontwerp en aannamelijst
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaLibraryControllerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
private static MediaLibraryItem Item(int daysOld, bool used)
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1000, 1600, 1067, Now.AddDays(-daysOld), "/media/hero/0123456789abcdef/wide-480.webp");
|
||||
return new MediaLibraryItem(photo, used ? [new MediaUse("hero", photo.Id, "slide", 2, true)] : []);
|
||||
}
|
||||
|
||||
private static MediaLibraryController Controller(params MediaLibraryItem[] items)
|
||||
{
|
||||
var library = Substitute.For<IMediaLibraryService>();
|
||||
library.ListAsync(Arg.Any<CancellationToken>()).Returns(items.OrderByDescending(i => i.Photo.CreatedAt).ToList());
|
||||
library.Modules.Returns(["hero"]);
|
||||
return new MediaLibraryController(library, new Clock());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_administrators_may_use_it()
|
||||
{
|
||||
typeof(MediaLibraryController).GetCustomAttributes(typeof(AuthorizeAttribute), true)
|
||||
.Cast<AuthorizeAttribute>().Should().ContainSingle(a => a.Policy == "AdminOnly");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Photos_lists_each_photo_with_its_uses_and_a_module_prefixed_id()
|
||||
{
|
||||
var used = Item(2, used: true);
|
||||
var result = (OkObjectResult)await Controller(used, Item(9, used: false)).Photos(CancellationToken.None);
|
||||
|
||||
var dto = result.Value.Should().BeOfType<MediaLibraryDto>().Subject;
|
||||
dto.Photos.Should().HaveCount(2);
|
||||
dto.Photos[0].Id.Should().Be($"hero:{used.Photo.Id}");
|
||||
dto.Photos[0].Uses.Should().ContainSingle().Which.Should().Be(new MediaUseDto("hero", "slide", 2, true));
|
||||
dto.Modules.Should().Equal("hero");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_selects_old_unused_photos_and_deletes_nothing()
|
||||
{
|
||||
var oldUnused = Item(20, used: false);
|
||||
var controller = Controller(Item(3, used: false), Item(20, used: true), oldUnused);
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, true, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Count.Should().Be(1);
|
||||
preview.Photos.Single().Id.Should().Be($"hero:{oldUnused.Photo.Id}");
|
||||
preview.Bytes.Should().Be(1000);
|
||||
preview.OnlyUnused.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_can_include_photos_in_use_and_keeps_the_period_in_range()
|
||||
{
|
||||
var controller = Controller(Item(20, used: true), Item(20, used: false));
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(99999, false, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Days.Should().Be(365);
|
||||
preview.Count.Should().Be(0);
|
||||
var shorter = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, false, CancellationToken.None)).Value!;
|
||||
shorter.Count.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Storage_without_a_media_store_reports_zero_and_ok()
|
||||
{
|
||||
var result = (MediaStorageDto)((OkObjectResult)await Controller().Storage(CancellationToken.None)).Value!;
|
||||
|
||||
result.Should().Be(new MediaStorageDto(0, 0, "ok", 80));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaStorageUsageTests
|
||||
{
|
||||
private sealed class Clock(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(79, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(80, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(99, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(100, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 0, MediaStorageLevel.Ok)]
|
||||
public void The_level_follows_the_share_of_the_limit(long used, long limit, MediaStorageLevel expected)
|
||||
=> MediaStorageUsage.LevelFor(used, limit).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public async Task The_measurement_is_kept_for_a_minute_and_then_taken_again()
|
||||
{
|
||||
var store = Substitute.For<IMediaStore>();
|
||||
store.GetTotalBytesAsync(Arg.Any<CancellationToken>()).Returns(850L, 900L);
|
||||
var clock = new Clock(new DateTimeOffset(2026, 11, 17, 12, 0, 0, TimeSpan.Zero));
|
||||
var usage = new MediaStorageUsage(store, Options.Create(new MediaOptions { MaxTotalBytes = 1000 }), clock);
|
||||
|
||||
var first = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(30);
|
||||
var cached = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(31);
|
||||
var later = await usage.GetAsync(CancellationToken.None);
|
||||
|
||||
first.Should().Be(new MediaStorageInfo(850, 1000, MediaStorageLevel.Warning));
|
||||
cached.Should().BeSameAs(first);
|
||||
later.UsedBytes.Should().Be(900);
|
||||
await store.Received(2).GetTotalBytesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,8 @@ public static class ServiceCollectionExtensions
|
||||
services.AddOptions<DataProtectionTokenProviderOptions>()
|
||||
.Configure<IOptions<PasswordResetSettings>>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
// The media library reads from the usage providers of whichever modules are loaded (none is fine).
|
||||
services.TryAddScoped<Media.Library.IMediaLibraryService, Media.Library.MediaLibraryService>();
|
||||
services.TryAddSingleton(sp =>
|
||||
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
|
||||
services.AddScoped<IPasswordResetService, PasswordResetService>();
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
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 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>
|
||||
public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList<MediaPhotoDto> Photos);
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("media-library")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase
|
||||
{
|
||||
[HttpGet("photos")]
|
||||
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Photos(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await library.ListAsync(cancellationToken);
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("storage")]
|
||||
[ProducesResponseType<MediaStorageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Storage(CancellationToken cancellationToken)
|
||||
{
|
||||
// A host without media has nothing stored: zero used, no limit.
|
||||
var info = storage is null ? new MediaStorageInfo(0, 0, MediaStorageLevel.Ok) : await storage.GetAsync(cancellationToken);
|
||||
return Ok(new MediaStorageDto(info.UsedBytes, info.LimitBytes, info.Level.ToString().ToLowerInvariant(), MediaStorageUsage.WarningPercent));
|
||||
}
|
||||
|
||||
[HttpGet("cleanup-preview")]
|
||||
[ProducesResponseType<MediaCleanupPreviewDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CleanupPreview([FromQuery] int days = CleanupSelection.DefaultDays, [FromQuery] bool onlyUnused = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var clamped = CleanupSelection.ClampDays(days);
|
||||
var selected = CleanupSelection.Select(await library.ListAsync(cancellationToken), time.GetUtcNow(), clamped, onlyUnused);
|
||||
return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
private static MediaPhotoDto ToDto(MediaLibraryItem item)
|
||||
=> new(
|
||||
$"{item.Photo.Module}:{item.Photo.Id}",
|
||||
item.Photo.Module,
|
||||
item.Photo.Bytes,
|
||||
item.Photo.Width,
|
||||
item.Photo.Height,
|
||||
item.Photo.CreatedAt,
|
||||
item.Photo.ThumbnailUrl,
|
||||
item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList());
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public enum MediaStorageLevel
|
||||
{
|
||||
Ok,
|
||||
Warning,
|
||||
Full,
|
||||
}
|
||||
|
||||
/// <param name="UsedBytes">Everything in the media directory (originals and variants).</param>
|
||||
/// <param name="LimitBytes">The safety limit; 0 means no limit.</param>
|
||||
public sealed record MediaStorageInfo(long UsedBytes, long LimitBytes, MediaStorageLevel Level);
|
||||
|
||||
/// <summary>
|
||||
/// The space the media directory takes against its limit (<c>Media:MaxTotalBytes</c>). Measuring walks the directory, so
|
||||
/// the answer is kept for a minute (assumption 9 of the media-library list: warning at 80 percent, full at 100).
|
||||
/// </summary>
|
||||
public sealed class MediaStorageUsage(IMediaStore store, IOptions<MediaOptions> options, TimeProvider? time = null)
|
||||
{
|
||||
public const int WarningPercent = 80;
|
||||
private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(60);
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private MediaStorageInfo? _cached;
|
||||
private DateTimeOffset _measuredAt;
|
||||
|
||||
public static MediaStorageLevel LevelFor(long used, long limit)
|
||||
{
|
||||
if (limit <= 0)
|
||||
{
|
||||
return MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
if (used >= limit)
|
||||
{
|
||||
return MediaStorageLevel.Full;
|
||||
}
|
||||
|
||||
return used * 100 >= limit * WarningPercent ? MediaStorageLevel.Warning : MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
public async Task<MediaStorageInfo> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _time.GetUtcNow();
|
||||
if (_cached is { } fresh && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return fresh;
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
now = _time.GetUtcNow();
|
||||
if (_cached is { } again && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return again;
|
||||
}
|
||||
|
||||
var used = await store.GetTotalBytesAsync(cancellationToken);
|
||||
var limit = Math.Max(0, options.Value.MaxTotalBytes);
|
||||
_cached = new MediaStorageInfo(used, limit, LevelFor(used, limit));
|
||||
_measuredAt = now;
|
||||
return _cached;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public static class MediaServiceCollectionExtensions
|
||||
services.TryAddSingleton<MediaAreaRegistry>();
|
||||
services.TryAddSingleton<IMediaStore, FileSystemMediaStore>();
|
||||
services.TryAddSingleton<IMediaUploadGuard, MediaUploadGuard>();
|
||||
services.TryAddScoped<Library.IMediaLibraryService, Library.MediaLibraryService>();
|
||||
services.TryAddSingleton<Library.MediaStorageUsage>();
|
||||
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
|
||||
{
|
||||
services.AddHostedService<ImageProcessorSelfTest>();
|
||||
|
||||
Reference in New Issue
Block a user