H2: Hero-module (tabellen en migratie, beheer-API, publieke GET /hero, afbeeldingsupload met focus, opschoonservice, teksten) en OpenAPI-snapshot
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>The image is still used by a slide (the administrator gets a 409 and a message).</summary>
|
||||
public sealed class HeroImageInUseException() : Exception("The image is still used by a slide.");
|
||||
|
||||
public sealed class HeroImageNotFoundException() : Exception("The image does not exist.");
|
||||
|
||||
/// <summary>There is not enough room in the media directory for the image.</summary>
|
||||
public sealed class MediaStorageFullException() : Exception("The media directory is full.");
|
||||
|
||||
public interface IHeroImageService
|
||||
{
|
||||
/// <summary>Admits, stores and processes an uploaded image (all variants of the default focus). The same photo twice is one image.</summary>
|
||||
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Changes where the subject is (general and optionally per ratio) and cuts the variants again around it.</summary>
|
||||
Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
|
||||
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class HeroImageService(
|
||||
IMediaUploadGuard guard,
|
||||
IImageProcessor processor,
|
||||
IMediaStore store,
|
||||
MediaProcessingGate gate,
|
||||
IHeroRepository repository,
|
||||
IOptions<MediaOptions> mediaOptions,
|
||||
ILogger<HeroImageService> logger,
|
||||
TimeProvider? time = null,
|
||||
IIndexHtmlCache? indexCache = null) : IHeroImageService
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken);
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes));
|
||||
|
||||
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
|
||||
if (existing is not null)
|
||||
{
|
||||
return HeroMapping.ToImageDto(existing);
|
||||
}
|
||||
|
||||
await EnsureRoomAsync(admitted.Bytes.Length, cancellationToken);
|
||||
|
||||
// The original is kept without metadata (GPS and the like); formats that cannot be written back (HEIC) become JPEG.
|
||||
var format = admitted.Info.Format;
|
||||
var stripped = await processor.StripMetadataAsync(admitted.Bytes, format, cancellationToken);
|
||||
var original = stripped ?? admitted.Bytes;
|
||||
var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format;
|
||||
|
||||
var image = new HeroImage
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
OriginalSha256 = sha,
|
||||
OriginalKey = $"originals/{sha}.{storedFormat.Extension()}",
|
||||
SourceFormat = storedFormat.Extension(),
|
||||
Width = admitted.Info.Width,
|
||||
Height = admitted.Info.Height,
|
||||
Bytes = original.Length,
|
||||
CreatedAt = _time.GetUtcNow(),
|
||||
CreatedByUserId = callerId,
|
||||
};
|
||||
|
||||
var files = await RenderSetAsync(image, original, storedFormat, cancellationToken);
|
||||
|
||||
await store.PutAsync(image.OriginalKey, original, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddImage(image);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} uploaded by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, callerId, image.Width, image.Height, image.Variants.Count);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
public async Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
|
||||
var oldSet = image.SetHash;
|
||||
var general = request.Focus.ToSetting().Normalize();
|
||||
image.FocusX = general.X;
|
||||
image.FocusY = general.Y;
|
||||
image.Zoom = general.Zoom;
|
||||
Apply(request.Wide, v => (image.WideFocusX, image.WideFocusY, image.WideZoom) = v);
|
||||
Apply(request.Tall, v => (image.TallFocusX, image.TallFocusY, image.TallZoom) = v);
|
||||
|
||||
var newSet = SetHashOf(image);
|
||||
if (newSet != oldSet)
|
||||
{
|
||||
using var slot = await gate.EnterAsync(cancellationToken);
|
||||
|
||||
var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken)
|
||||
?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing.");
|
||||
using var memory = new MemoryStream();
|
||||
await using (file.Content)
|
||||
{
|
||||
await file.Content.CopyToAsync(memory, cancellationToken);
|
||||
}
|
||||
|
||||
var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.'));
|
||||
|
||||
var files = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero image {ImageId} focus changed by user {UserId}", imageId, callerId);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
if (await repository.ImageInUseAsync(imageId, cancellationToken))
|
||||
{
|
||||
throw new HeroImageInUseException();
|
||||
}
|
||||
|
||||
var now = _time.GetUtcNow();
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = now });
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = now });
|
||||
repository.RemoveImage(image);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId);
|
||||
}
|
||||
|
||||
private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
assign((null, null, null));
|
||||
return;
|
||||
}
|
||||
|
||||
var f = value.ToSetting().Normalize();
|
||||
assign((f.X, f.Y, f.Zoom));
|
||||
}
|
||||
|
||||
private static string SetHashOf(HeroImage image)
|
||||
=> MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]);
|
||||
|
||||
/// <summary>Cuts and encodes every planned variant of the image and fills its set hash and variant list. Returns the files by name.</summary>
|
||||
private async Task<Dictionary<string, byte[]>> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, CancellationToken cancellationToken)
|
||||
{
|
||||
var ratios = new[] { Ratio.Wide, Ratio.Tall }
|
||||
.Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r)))
|
||||
.ToList();
|
||||
var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput);
|
||||
|
||||
var files = new Dictionary<string, byte[]>();
|
||||
var variants = new List<HeroVariant>();
|
||||
foreach (var spec in specs)
|
||||
{
|
||||
var rendered = await processor.RenderAsync(original, storedFormat, spec, cancellationToken);
|
||||
var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format);
|
||||
files[name] = rendered.Bytes;
|
||||
variants.Add(new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength));
|
||||
}
|
||||
|
||||
image.SetHash = SetHashOf(image);
|
||||
image.Variants = variants;
|
||||
return files;
|
||||
}
|
||||
|
||||
private async Task EnsureRoomAsync(long incomingBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
var limits = mediaOptions.Value;
|
||||
// A set is a few times the size of the original at most; keep a margin so the write cannot fill the disk.
|
||||
var needed = incomingBytes * 4;
|
||||
var total = await store.GetTotalBytesAsync(cancellationToken);
|
||||
if (limits.MaxTotalBytes > 0 && total + needed > limits.MaxTotalBytes)
|
||||
{
|
||||
throw new MediaStorageFullException();
|
||||
}
|
||||
|
||||
if (store.GetFreeBytes() is { } free && free < needed + 64L * 1024 * 1024)
|
||||
{
|
||||
throw new MediaStorageFullException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
public sealed class HeroOptions
|
||||
{
|
||||
public const string SectionName = "Hero";
|
||||
|
||||
/// <summary>
|
||||
/// A technical safety ceiling, not an administrator limit: the public hero, the injected page and the data block never
|
||||
/// carry more slides than this, so the first HTML cannot grow without bound. Everything above stays saved.
|
||||
/// </summary>
|
||||
public int MaxPublishedSlides { get; set; } = 50;
|
||||
}
|
||||
|
||||
/// <summary>Turns stored entities into the shapes of the API and the data block. Pure.</summary>
|
||||
public static class HeroMapping
|
||||
{
|
||||
public const string Area = "hero";
|
||||
|
||||
public static HeroVariantDto ToDto(HeroImage image, HeroVariant variant)
|
||||
=> new(variant.Ratio, variant.Width, variant.Height, variant.Type, MediaPaths.Url(Area, image.SetHash, variant.FileName));
|
||||
|
||||
/// <summary>The address the plain <c>img</c> uses: the largest WebP of the wide ratio, else the largest WebP, else the first variant.</summary>
|
||||
public static string SrcFor(HeroImage image)
|
||||
{
|
||||
var webp = image.Variants.Where(v => v.Type == ImageFormat.WebP.MimeType()).ToList();
|
||||
var pick = webp.Where(v => v.Ratio == "wide").OrderByDescending(v => v.Width).FirstOrDefault()
|
||||
?? webp.OrderByDescending(v => v.Width).FirstOrDefault()
|
||||
?? image.Variants.FirstOrDefault();
|
||||
return pick is null ? string.Empty : MediaPaths.Url(Area, image.SetHash, pick.FileName);
|
||||
}
|
||||
|
||||
public static HeroImageDto ToImageDto(HeroImage image)
|
||||
=> new(
|
||||
image.Id.ToString(),
|
||||
image.Width,
|
||||
image.Height,
|
||||
FocusDto.From(image.General),
|
||||
image.WideFocusX is null ? null : FocusDto.From(image.FocusFor("wide")),
|
||||
image.TallFocusX is null ? null : FocusDto.From(image.FocusFor("tall")),
|
||||
SrcFor(image),
|
||||
image.Variants.Select(v => ToDto(image, v)).ToList());
|
||||
|
||||
public static bool IsLive(HeroContent hero, DateTimeOffset now)
|
||||
=> hero.IsActive
|
||||
&& !string.IsNullOrWhiteSpace(hero.Title)
|
||||
&& (hero.StartsAt is null || hero.StartsAt <= now)
|
||||
&& (hero.EndsAt is null || now < hero.EndsAt);
|
||||
|
||||
private static List<HeroButtonDto> Buttons(HeroContent hero)
|
||||
{
|
||||
var buttons = new List<HeroButtonDto>();
|
||||
if (!string.IsNullOrWhiteSpace(hero.Button1Label) && !string.IsNullOrWhiteSpace(hero.Button1Target))
|
||||
{
|
||||
buttons.Add(new HeroButtonDto(hero.Button1Label, hero.Button1Target));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(hero.Button2Label) && !string.IsNullOrWhiteSpace(hero.Button2Target))
|
||||
{
|
||||
buttons.Add(new HeroButtonDto(hero.Button2Label, hero.Button2Target));
|
||||
}
|
||||
|
||||
return buttons;
|
||||
}
|
||||
|
||||
/// <summary>The published hero, or null when it is not live. Inactive slides and slides without a stored image are left out.</summary>
|
||||
public static PublicHeroDto? ToPublic(HeroContent hero, DateTimeOffset now, int maxPublishedSlides)
|
||||
{
|
||||
if (!IsLive(hero, now))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var slides = hero.Slides
|
||||
.Where(s => s.IsActive && s.Image is { Variants.Count: > 0 } && (s.Decorative || !string.IsNullOrWhiteSpace(s.Alt)))
|
||||
.OrderBy(s => s.SortOrder)
|
||||
.Take(Math.Max(1, maxPublishedSlides))
|
||||
.Select(s => new PublicSlideDto(s.Id.ToString(), s.Decorative ? string.Empty : s.Alt, s.Decorative, ToPublicImage(s.Image!)))
|
||||
.ToList();
|
||||
|
||||
return new PublicHeroDto(hero.Display, hero.Title, hero.Tagline, hero.Lead, Buttons(hero), slides);
|
||||
}
|
||||
|
||||
private static PublicImageDto ToPublicImage(HeroImage image)
|
||||
{
|
||||
Dictionary<string, FocusDto>? byRatio = null;
|
||||
if (image.WideFocusX is not null)
|
||||
{
|
||||
(byRatio ??= new Dictionary<string, FocusDto>())["wide"] = FocusDto.From(image.FocusFor("wide"));
|
||||
}
|
||||
|
||||
if (image.TallFocusX is not null)
|
||||
{
|
||||
(byRatio ??= new Dictionary<string, FocusDto>())["tall"] = FocusDto.From(image.FocusFor("tall"));
|
||||
}
|
||||
|
||||
return new PublicImageDto(
|
||||
image.Width,
|
||||
image.Height,
|
||||
FocusDto.From(image.General),
|
||||
SrcFor(image),
|
||||
image.Variants.Select(v => ToDto(image, v)).ToList(),
|
||||
byRatio);
|
||||
}
|
||||
|
||||
public static HeroAdminDto ToAdmin(HeroContent? hero, DateTimeOffset now, int maxPublishedSlides)
|
||||
{
|
||||
if (hero is null)
|
||||
{
|
||||
return new HeroAdminDto(null, string.Empty, null, null, HeroDisplays.Single, [], true, null, null, [], false, null, maxPublishedSlides);
|
||||
}
|
||||
|
||||
var slides = hero.Slides
|
||||
.Where(s => s.Image is not null)
|
||||
.OrderBy(s => s.SortOrder)
|
||||
.Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(s.Image!)))
|
||||
.ToList();
|
||||
|
||||
return new HeroAdminDto(
|
||||
hero.Id.ToString(),
|
||||
hero.Title,
|
||||
hero.Tagline,
|
||||
hero.Lead,
|
||||
hero.Display,
|
||||
Buttons(hero),
|
||||
hero.IsActive,
|
||||
hero.StartsAt,
|
||||
hero.EndsAt,
|
||||
slides,
|
||||
IsLive(hero, now),
|
||||
hero.UpdatedAt,
|
||||
maxPublishedSlides);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Removes files nothing uses any more, a retention time (7 days) after they stopped being used, so a site that still
|
||||
/// holds older data keeps working for a while. Idempotent and safe to interrupt; a referenced file is never removed
|
||||
/// (a retired set whose hash is used again, because the same photo and focus came back, is simply forgotten as retired).
|
||||
/// </summary>
|
||||
public class HeroMediaCleanup(
|
||||
IHeroRepository repository,
|
||||
IMediaStore store,
|
||||
IOptions<MediaOptions> options,
|
||||
ILogger<HeroMediaCleanup> logger,
|
||||
TimeProvider? time = null)
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
public async Task<int> RunOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _time.GetUtcNow();
|
||||
var cutoff = now.AddDays(-Math.Max(0, options.Value.RetentionDays));
|
||||
var removed = 0;
|
||||
|
||||
// 1. Images that were uploaded but never used by a slide: retire them (their files go on a later run).
|
||||
foreach (var image in await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, 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.
|
||||
var referencedSets = await repository.GetReferencedSetHashesAsync(cancellationToken);
|
||||
var referencedOriginals = await repository.GetReferencedOriginalKeysAsync(cancellationToken);
|
||||
foreach (var file in await repository.GetRetiredBeforeAsync(cutoff, cancellationToken))
|
||||
{
|
||||
if (file.Kind == "set" && !referencedSets.Contains(file.Key))
|
||||
{
|
||||
await store.DeleteSetAsync(HeroMapping.Area, file.Key, cancellationToken);
|
||||
removed++;
|
||||
}
|
||||
else if (file.Kind == "original" && !referencedOriginals.Contains(file.Key))
|
||||
{
|
||||
await store.DeleteAsync(file.Key, cancellationToken);
|
||||
removed++;
|
||||
}
|
||||
|
||||
repository.RemoveRetired(file);
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 3. Sets in the store that no row knows (a crash between writing the files and saving the row).
|
||||
var retiredSets = await repository.GetRetiredSetHashesAsync(cancellationToken);
|
||||
referencedSets = await repository.GetReferencedSetHashesAsync(cancellationToken);
|
||||
foreach (var set in await store.ListSetsAsync(HeroMapping.Area, cancellationToken))
|
||||
{
|
||||
if (set.CreatedUtc < cutoff && !referencedSets.Contains(set.SetHash) && !retiredSets.Contains(set.SetHash))
|
||||
{
|
||||
await store.DeleteSetAsync(HeroMapping.Area, set.SetHash, cancellationToken);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
|
||||
if (removed > 0)
|
||||
{
|
||||
logger.LogInformation("Hero media clean-up removed {Removed} unused sets or originals.", removed);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs <see cref="HeroMediaCleanup"/> shortly after start-up and then once a day.</summary>
|
||||
public sealed class HeroMediaCleanupService(IServiceScopeFactory scopes, ILogger<HeroMediaCleanupService> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMinutes(2), stoppingToken);
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<HeroMediaCleanup>().RunOnceAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(exception, "The hero media clean-up failed; it is tried again tomorrow.");
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Shutting down.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Texts;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>A save that refers to something that is not there (an image or a slide of another hero). The message is for the administrator.</summary>
|
||||
public sealed class HeroSaveRejectedException(string field, string message) : Exception(message)
|
||||
{
|
||||
public string Field { get; } = field;
|
||||
}
|
||||
|
||||
public interface IHeroService
|
||||
{
|
||||
/// <summary>The hero for the admin (empty defaults when none exists yet), with whether it is live right now.</summary>
|
||||
Task<HeroAdminDto> GetAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Replaces the whole hero: texts, buttons, display, schedule and the ordered slide list.</summary>
|
||||
Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class HeroService(
|
||||
IHeroRepository repository,
|
||||
IOptions<HeroOptions> options,
|
||||
ILogger<HeroService> logger,
|
||||
TimeProvider? time = null,
|
||||
IIndexHtmlCache? indexCache = null,
|
||||
ITextCatalog? texts = null) : IHeroService
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
private readonly ITextCatalog _texts = texts ?? TextCatalog.Default;
|
||||
|
||||
public async Task<HeroAdminDto> GetAsync(CancellationToken cancellationToken)
|
||||
=> HeroMapping.ToAdmin(await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken), _time.GetUtcNow(), options.Value.MaxPublishedSlides);
|
||||
|
||||
public async Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _time.GetUtcNow();
|
||||
var slideRequests = request.Slides ?? [];
|
||||
|
||||
var imageIds = slideRequests.Select(s => s.ImageId).Distinct().ToList();
|
||||
var images = (await repository.GetImagesAsync(imageIds, cancellationToken)).ToDictionary(i => i.Id);
|
||||
for (var i = 0; i < slideRequests.Count; i++)
|
||||
{
|
||||
if (!images.ContainsKey(slideRequests[i].ImageId))
|
||||
{
|
||||
throw new HeroSaveRejectedException($"Slides[{i}].ImageId", _texts.Get(HeroTexts.Validation.Slide.ImageUnknown));
|
||||
}
|
||||
}
|
||||
|
||||
var hero = await repository.GetAsync(HeroLanguages.Default, cancellationToken);
|
||||
var created = hero is null;
|
||||
if (hero is null)
|
||||
{
|
||||
hero = new HeroContent { Id = Guid.NewGuid(), Language = HeroLanguages.Default };
|
||||
repository.Add(hero);
|
||||
}
|
||||
|
||||
var existing = hero.Slides.ToDictionary(s => s.Id);
|
||||
for (var i = 0; i < slideRequests.Count; i++)
|
||||
{
|
||||
if (slideRequests[i].Id is { } id && !existing.ContainsKey(id))
|
||||
{
|
||||
throw new HeroSaveRejectedException($"Slides[{i}].Id", _texts.Get(HeroTexts.Validation.Slide.IdUnknown));
|
||||
}
|
||||
}
|
||||
|
||||
Apply(hero, request, now, callerId);
|
||||
|
||||
var keep = new HashSet<Guid>();
|
||||
for (var i = 0; i < slideRequests.Count; i++)
|
||||
{
|
||||
var r = slideRequests[i];
|
||||
HeroSlide slide;
|
||||
if (r.Id is { } id)
|
||||
{
|
||||
slide = existing[id];
|
||||
}
|
||||
else
|
||||
{
|
||||
slide = new HeroSlide { Id = Guid.NewGuid(), HeroId = hero.Id };
|
||||
hero.Slides.Add(slide);
|
||||
repository.AddSlide(slide);
|
||||
}
|
||||
|
||||
keep.Add(slide.Id);
|
||||
slide.ImageId = r.ImageId;
|
||||
slide.Image = images[r.ImageId];
|
||||
slide.Decorative = r.Decorative;
|
||||
slide.Alt = r.Decorative ? string.Empty : HeroText.Clean(r.Alt, keepLineBreaks: false);
|
||||
slide.IsActive = r.IsActive;
|
||||
slide.SortOrder = i;
|
||||
}
|
||||
|
||||
foreach (var removed in hero.Slides.Where(s => !keep.Contains(s.Id)).ToList())
|
||||
{
|
||||
hero.Slides.Remove(removed);
|
||||
if (!created)
|
||||
{
|
||||
repository.RemoveSlide(removed);
|
||||
}
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero {HeroId} {Action} by user {LastModifiedByUserId} ({Slides} slides)", hero.Id, created ? "Created" : "Updated", callerId, keep.Count);
|
||||
|
||||
return HeroMapping.ToAdmin(hero, now, options.Value.MaxPublishedSlides);
|
||||
}
|
||||
|
||||
private static void Apply(HeroContent hero, HeroSaveRequest r, DateTimeOffset now, Guid callerId)
|
||||
{
|
||||
hero.Title = HeroText.Clean(r.Title, keepLineBreaks: true);
|
||||
hero.Tagline = NullIfEmpty(HeroText.Clean(r.Tagline, keepLineBreaks: false));
|
||||
hero.Lead = NullIfEmpty(HeroText.Clean(r.Lead, keepLineBreaks: true));
|
||||
hero.Display = r.Display ?? HeroDisplays.Single;
|
||||
|
||||
var buttons = (r.Buttons ?? [])
|
||||
.Select(b => (Label: HeroText.Clean(b.Label, keepLineBreaks: false), Target: (b.Target ?? string.Empty).Trim()))
|
||||
.Where(b => b.Label.Length > 0 && b.Target.Length > 0)
|
||||
.Take(HeroSaveRequest.ButtonsMax)
|
||||
.ToList();
|
||||
hero.Button1Label = buttons.Count > 0 ? buttons[0].Label : null;
|
||||
hero.Button1Target = buttons.Count > 0 ? buttons[0].Target : null;
|
||||
hero.Button2Label = buttons.Count > 1 ? buttons[1].Label : null;
|
||||
hero.Button2Target = buttons.Count > 1 ? buttons[1].Target : null;
|
||||
|
||||
hero.IsActive = r.IsActive;
|
||||
hero.StartsAt = r.StartsAt;
|
||||
hero.EndsAt = r.EndsAt;
|
||||
hero.UpdatedAt = now;
|
||||
hero.LastModifiedByUserId = callerId;
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string value) => value.Length == 0 ? null : value;
|
||||
}
|
||||
|
||||
public interface IPublicHeroService
|
||||
{
|
||||
/// <summary>The hero as websites get it, or null (no hero, switched off, outside the schedule or without a title).</summary>
|
||||
Task<PublicHeroDto?> GetActiveAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class PublicHeroService(IHeroRepository repository, IOptions<HeroOptions> options, TimeProvider? time = null) : IPublicHeroService
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
public async Task<PublicHeroDto?> GetActiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var hero = await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken);
|
||||
return hero is null ? null : HeroMapping.ToPublic(hero, _time.GetUtcNow(), options.Value.MaxPublishedSlides);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user