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,156 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Texts;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// The hero of the site. <c>GET /hero</c> is what websites read (200 with the hero, 204 when there is none to show);
|
||||
/// management (<c>GET /hero/all</c>, <c>PUT /hero</c>) is for administrators.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("hero")]
|
||||
public class HeroController(IHeroService service, IPublicHeroService publicService) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
[PublicSiteEndpoint]
|
||||
[EnableRateLimiting("hero-public")]
|
||||
[ProducesResponseType<PublicHeroDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> Get(CancellationToken cancellationToken)
|
||||
{
|
||||
Response.Headers.CacheControl = "public, max-age=60";
|
||||
var hero = await publicService.GetActiveAsync(cancellationToken);
|
||||
return hero is null ? NoContent() : Ok(hero);
|
||||
}
|
||||
|
||||
[HttpGet("all")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetForAdmin(CancellationToken cancellationToken)
|
||||
=> Ok(await service.GetAsync(cancellationToken));
|
||||
|
||||
[HttpPut]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Save([FromBody] HeroSaveRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(await service.SaveAsync(request, HeroCaller.Id(User), cancellationToken));
|
||||
}
|
||||
catch (HeroSaveRejectedException exception)
|
||||
{
|
||||
ModelState.AddModelError(exception.Field, exception.Message);
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Images of the hero: upload, focus and delete. Administrators only.</summary>
|
||||
[ApiController]
|
||||
[Route("hero/images")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class HeroImagesController(IHeroImageService service, IOptions<MediaOptions> media) : ControllerBase
|
||||
{
|
||||
/// <summary>The body limit leaves room for the multipart envelope around the file limit of <see cref="MediaOptions.MaxUploadBytes"/>.</summary>
|
||||
private const long RequestLimit = 12 * 1024 * 1024;
|
||||
|
||||
[HttpPost]
|
||||
[RequestSizeLimit(RequestLimit)]
|
||||
[EnableRateLimiting("hero-upload")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[ProducesResponseType<HeroImageDto>(StatusCodes.Status201Created)]
|
||||
public async Task<IActionResult> Upload(IFormFile file, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken);
|
||||
return Created($"/api/v1/hero/images/{image.Id}", image);
|
||||
}
|
||||
catch (ImageRejectedException rejection)
|
||||
{
|
||||
return Rejected(rejection);
|
||||
}
|
||||
catch (MediaStorageFullException)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "storage_full", message = Texts().Get(HeroTexts.Image.StorageFull) });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/focus")]
|
||||
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken));
|
||||
}
|
||||
catch (HeroImageNotFoundException)
|
||||
{
|
||||
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
|
||||
}
|
||||
catch (ImageRejectedException rejection)
|
||||
{
|
||||
return Rejected(rejection);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await service.DeleteAsync(id, HeroCaller.Id(User), cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
catch (HeroImageNotFoundException)
|
||||
{
|
||||
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
|
||||
}
|
||||
catch (HeroImageInUseException)
|
||||
{
|
||||
return Conflict(new { error = "in_use", message = Texts().Get(HeroTexts.Image.InUse) });
|
||||
}
|
||||
}
|
||||
|
||||
private ITextCatalog Texts() => HttpTexts.From(HttpContext);
|
||||
|
||||
private IActionResult Rejected(ImageRejectedException rejection)
|
||||
{
|
||||
var status = rejection.Reason switch
|
||||
{
|
||||
ImageRejection.TooLarge => StatusCodes.Status413PayloadTooLarge,
|
||||
ImageRejection.Busy => StatusCodes.Status429TooManyRequests,
|
||||
ImageRejection.Unavailable => StatusCodes.Status503ServiceUnavailable,
|
||||
_ => StatusCodes.Status400BadRequest,
|
||||
};
|
||||
var key = HeroTexts.Image.For(rejection.Reason);
|
||||
var message = rejection.Reason == ImageRejection.TooLarge
|
||||
? Texts().Get(key, args: ("max", media.Value.MaxUploadBytes / (1024 * 1024)))
|
||||
: Texts().Get(key);
|
||||
return StatusCode(status, new { error = rejection.Code, message });
|
||||
}
|
||||
}
|
||||
|
||||
internal static class HeroCaller
|
||||
{
|
||||
public static Guid Id(ClaimsPrincipal user)
|
||||
{
|
||||
var claim = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub");
|
||||
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using SlpModularCms.Core.Media;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Data.Entities;
|
||||
|
||||
/// <summary>The hero of the site in one language: texts, up to two buttons, the display, the schedule and the slides.</summary>
|
||||
public class HeroContent
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>Unique; only <see cref="HeroLanguages.Default"/> is exposed and edited now, the column keeps the model ready for more.</summary>
|
||||
public string Language { get; set; } = HeroLanguages.Default;
|
||||
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string? Tagline { get; set; }
|
||||
public string? Lead { get; set; }
|
||||
public string Display { get; set; } = HeroDisplays.Single;
|
||||
public string? Button1Label { get; set; }
|
||||
public string? Button1Target { get; set; }
|
||||
public string? Button2Label { get; set; }
|
||||
public string? Button2Target { get; set; }
|
||||
public DateTimeOffset? StartsAt { get; set; }
|
||||
public DateTimeOffset? EndsAt { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
public DateTimeOffset UpdatedAt { get; set; }
|
||||
public Guid LastModifiedByUserId { get; set; }
|
||||
|
||||
public List<HeroSlide> Slides { get; set; } = [];
|
||||
}
|
||||
|
||||
public class HeroSlide
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid HeroId { get; set; }
|
||||
public Guid ImageId { get; set; }
|
||||
public HeroImage? Image { get; set; }
|
||||
public string Alt { get; set; } = string.Empty;
|
||||
public bool Decorative { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>A stored image: the original (never served), where the subject is, and the current set of variants.</summary>
|
||||
public class HeroImage
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>SHA-256 of the file as uploaded (hex); the same photo uploaded twice is one image.</summary>
|
||||
public string OriginalSha256 { get; set; } = string.Empty;
|
||||
public string OriginalKey { get; set; } = string.Empty;
|
||||
public string SourceFormat { get; set; } = string.Empty;
|
||||
public int Width { get; set; }
|
||||
public int Height { get; set; }
|
||||
public long Bytes { get; set; }
|
||||
|
||||
public double FocusX { get; set; } = 0.5;
|
||||
public double FocusY { get; set; } = 0.5;
|
||||
public double Zoom { get; set; } = 1.0;
|
||||
public double? WideFocusX { get; set; }
|
||||
public double? WideFocusY { get; set; }
|
||||
public double? WideZoom { get; set; }
|
||||
public double? TallFocusX { get; set; }
|
||||
public double? TallFocusY { get; set; }
|
||||
public double? TallZoom { get; set; }
|
||||
|
||||
public string SetHash { get; set; } = string.Empty;
|
||||
public List<HeroVariant> Variants { get; set; } = [];
|
||||
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public Guid CreatedByUserId { get; set; }
|
||||
|
||||
public FocusSetting General => new FocusSetting(FocusX, FocusY, Zoom).Normalize();
|
||||
|
||||
public FocusSetting FocusFor(string ratio) => ratio switch
|
||||
{
|
||||
"wide" when WideFocusX is not null && WideFocusY is not null => new FocusSetting(WideFocusX.Value, WideFocusY.Value, WideZoom ?? Zoom).Normalize(),
|
||||
"tall" when TallFocusX is not null && TallFocusY is not null => new FocusSetting(TallFocusX.Value, TallFocusY.Value, TallZoom ?? Zoom).Normalize(),
|
||||
_ => General,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>One file of the current set: the ratio, its pixel size, the type and the file name inside the set.</summary>
|
||||
public record HeroVariant(string Ratio, int Width, int Height, string Type, string FileName, long Bytes);
|
||||
|
||||
/// <summary>A set or an original that nothing uses any more; the clean-up deletes it once the retention time has passed.</summary>
|
||||
public class HeroRetiredFile
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary><c>set</c> (a set hash) or <c>original</c> (an original key).</summary>
|
||||
public string Kind { get; set; } = string.Empty;
|
||||
public string Key { get; set; } = string.Empty;
|
||||
public DateTimeOffset RetiredAt { get; set; }
|
||||
}
|
||||
|
||||
public static class HeroLanguages
|
||||
{
|
||||
public const string Default = "nl";
|
||||
}
|
||||
|
||||
public static class HeroDisplays
|
||||
{
|
||||
public const string Single = "single";
|
||||
public const string Slideshow = "slideshow";
|
||||
|
||||
public static bool IsValid(string? value) => value is Single or Slideshow;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Data;
|
||||
|
||||
public class HeroDbContext(DbContextOptions<HeroDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<HeroContent> Heroes => Set<HeroContent>();
|
||||
public DbSet<HeroSlide> HeroSlides => Set<HeroSlide>();
|
||||
public DbSet<HeroImage> HeroImages => Set<HeroImage>();
|
||||
public DbSet<HeroRetiredFile> HeroRetiredFiles => Set<HeroRetiredFile>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<HeroContent>(entity =>
|
||||
{
|
||||
entity.ToTable("Heroes");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Language).IsRequired().HasMaxLength(10);
|
||||
entity.HasIndex(e => e.Language).IsUnique();
|
||||
entity.Property(e => e.Title).IsRequired().HasMaxLength(1000);
|
||||
entity.Property(e => e.Tagline).HasMaxLength(200);
|
||||
entity.Property(e => e.Lead).HasMaxLength(1000);
|
||||
entity.Property(e => e.Display).IsRequired().HasMaxLength(20);
|
||||
entity.Property(e => e.Button1Label).HasMaxLength(100);
|
||||
entity.Property(e => e.Button1Target).HasMaxLength(500);
|
||||
entity.Property(e => e.Button2Label).HasMaxLength(100);
|
||||
entity.Property(e => e.Button2Target).HasMaxLength(500);
|
||||
entity.Property(e => e.IsActive).IsRequired();
|
||||
entity.Property(e => e.UpdatedAt).IsRequired();
|
||||
entity.Property(e => e.LastModifiedByUserId).IsRequired();
|
||||
entity.HasMany(e => e.Slides).WithOne().HasForeignKey(s => s.HeroId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<HeroSlide>(entity =>
|
||||
{
|
||||
entity.ToTable("HeroSlides");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Alt).IsRequired().HasMaxLength(600);
|
||||
entity.Property(e => e.SortOrder).IsRequired();
|
||||
// Not unique: re-ordering updates several rows in one save and must not trip over itself.
|
||||
entity.HasIndex(e => new { e.HeroId, e.SortOrder });
|
||||
entity.HasIndex(e => e.ImageId);
|
||||
|
||||
// Restrict: an image that a slide still uses cannot be deleted (the service answers 409 first).
|
||||
entity.HasOne(e => e.Image).WithMany().HasForeignKey(e => e.ImageId).OnDelete(DeleteBehavior.Restrict);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<HeroImage>(entity =>
|
||||
{
|
||||
entity.ToTable("HeroImages");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.OriginalSha256).IsRequired().HasMaxLength(64);
|
||||
entity.HasIndex(e => e.OriginalSha256).IsUnique();
|
||||
entity.Property(e => e.OriginalKey).IsRequired().HasMaxLength(200);
|
||||
entity.Property(e => e.SourceFormat).IsRequired().HasMaxLength(10);
|
||||
entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16);
|
||||
entity.Property(e => e.CreatedAt).IsRequired();
|
||||
entity.Property(e => e.CreatedByUserId).IsRequired();
|
||||
entity.Ignore(e => e.General);
|
||||
|
||||
// The variants of the current set: a small list that is always replaced as a whole.
|
||||
entity.Property(e => e.Variants)
|
||||
.HasConversion(
|
||||
variants => JsonSerializer.Serialize(variants, (JsonSerializerOptions?)null),
|
||||
json => JsonSerializer.Deserialize<List<HeroVariant>>(json, (JsonSerializerOptions?)null) ?? new List<HeroVariant>())
|
||||
.HasColumnType("longtext")
|
||||
.Metadata.SetValueComparer(new ValueComparer<List<HeroVariant>>(
|
||||
(a, b) => (a ?? new List<HeroVariant>()).SequenceEqual(b ?? new List<HeroVariant>()),
|
||||
v => v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())),
|
||||
v => v.ToList()));
|
||||
});
|
||||
|
||||
modelBuilder.Entity<HeroRetiredFile>(entity =>
|
||||
{
|
||||
entity.ToTable("HeroRetiredFiles");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Kind).IsRequired().HasMaxLength(10);
|
||||
entity.Property(e => e.Key).IsRequired().HasMaxLength(200);
|
||||
entity.Property(e => e.RetiredAt).IsRequired();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Magick;
|
||||
using SlpModularCms.Core.Modules;
|
||||
using SlpModularCms.Core.Texts;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero;
|
||||
|
||||
/// <summary>The manageable hero of a website: texts, buttons, slides with images, schedule; images are processed and served by the host.</summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HeroModule : IModule
|
||||
{
|
||||
public string Name => "Hero";
|
||||
public string Version => "1.0.0";
|
||||
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddDbContext<HeroDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
var config = serviceProvider.GetRequiredService<IConfiguration>();
|
||||
options.UseMySQL(config.GetConnectionString("DefaultConnection")!);
|
||||
options.ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>();
|
||||
});
|
||||
|
||||
services.AddCmsTextsFrom(typeof(HeroModule).Assembly);
|
||||
services.AddOptions<HeroOptions>().Configure<IConfiguration>((options, configuration) =>
|
||||
configuration.GetSection(HeroOptions.SectionName).Bind(options));
|
||||
|
||||
// Image processing and the media area this module owns (served at /media/hero/...).
|
||||
services.AddCmsMediaArea(HeroMapping.Area);
|
||||
services.AddMagickImageProcessor();
|
||||
|
||||
services.AddScoped<IHeroRepository, HeroRepository>();
|
||||
services.AddScoped<IHeroService, HeroService>();
|
||||
services.AddScoped<IPublicHeroService, PublicHeroService>();
|
||||
services.AddScoped<IHeroImageService, HeroImageService>();
|
||||
services.AddScoped<HeroMediaCleanup>();
|
||||
services.AddHostedService<HeroMediaCleanupService>();
|
||||
}
|
||||
|
||||
public void UseModule(IApplicationBuilder app)
|
||||
{
|
||||
using var scope = app.ApplicationServices.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HeroDbContext>();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Texts;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero;
|
||||
|
||||
/// <summary>The keys of the Hero module texts (<c>Texts/nl.json</c>, <c>Texts/en.json</c>, key path <c>hero.*</c>).</summary>
|
||||
public static class HeroTexts
|
||||
{
|
||||
public static class Validation
|
||||
{
|
||||
public static class Title
|
||||
{
|
||||
public static readonly TextKey Required = new("hero.validation.title.required");
|
||||
public static readonly TextKey TooLong = new("hero.validation.title.tooLong", "max");
|
||||
public static readonly TextKey TooManyLines = new("hero.validation.title.tooManyLines", "max");
|
||||
}
|
||||
|
||||
public static readonly TextKey TaglineTooLong = new("hero.validation.tagline.tooLong", "max");
|
||||
public static readonly TextKey LeadTooLong = new("hero.validation.lead.tooLong", "max");
|
||||
public static readonly TextKey DisplayInvalid = new("hero.validation.display.invalid");
|
||||
|
||||
public static class Button
|
||||
{
|
||||
public static readonly TextKey Incomplete = new("hero.validation.button.incomplete");
|
||||
public static readonly TextKey LabelTooLong = new("hero.validation.button.labelTooLong", "max");
|
||||
public static readonly TextKey TargetTooLong = new("hero.validation.button.targetTooLong", "max");
|
||||
public static readonly TextKey TargetInvalid = new("hero.validation.button.targetInvalid");
|
||||
public static readonly TextKey TooMany = new("hero.validation.button.tooMany", "max");
|
||||
}
|
||||
|
||||
public static readonly TextKey EndAfterStart = new("hero.validation.schedule.endAfterStart");
|
||||
|
||||
public static class Slide
|
||||
{
|
||||
public static readonly TextKey ImageRequired = new("hero.validation.slide.imageRequired");
|
||||
public static readonly TextKey ImageUnknown = new("hero.validation.slide.imageUnknown");
|
||||
public static readonly TextKey AltRequired = new("hero.validation.slide.altRequired");
|
||||
public static readonly TextKey AltTooLong = new("hero.validation.slide.altTooLong", "max");
|
||||
public static readonly TextKey IdUnknown = new("hero.validation.slide.idUnknown");
|
||||
}
|
||||
|
||||
public static readonly TextKey FocusInvalid = new("hero.validation.focus.invalid", "maxZoom");
|
||||
}
|
||||
|
||||
public static class Image
|
||||
{
|
||||
public static readonly TextKey InUse = new("hero.image.inUse");
|
||||
public static readonly TextKey NotFound = new("hero.image.notFound");
|
||||
public static readonly TextKey StorageFull = new("hero.image.storageFull");
|
||||
|
||||
public static readonly TextKey TooLarge = new("hero.image.rejected.tooLarge", "max");
|
||||
public static readonly TextKey UnsupportedFormat = new("hero.image.rejected.unsupportedFormat");
|
||||
public static readonly TextKey Corrupt = new("hero.image.rejected.corrupt");
|
||||
public static readonly TextKey TooManyPixels = new("hero.image.rejected.tooManyPixels");
|
||||
public static readonly TextKey Timeout = new("hero.image.rejected.timeout");
|
||||
public static readonly TextKey Busy = new("hero.image.rejected.busy");
|
||||
public static readonly TextKey Unavailable = new("hero.image.rejected.unavailable");
|
||||
|
||||
/// <summary>The text key for a rejection; the size limit is given in MB for the "too large" message.</summary>
|
||||
public static TextKey For(ImageRejection reason) => reason switch
|
||||
{
|
||||
ImageRejection.TooLarge => TooLarge,
|
||||
ImageRejection.UnsupportedFormat => UnsupportedFormat,
|
||||
ImageRejection.Corrupt => Corrupt,
|
||||
ImageRejection.TooManyPixels => TooManyPixels,
|
||||
ImageRejection.Timeout => Timeout,
|
||||
ImageRejection.Busy => Busy,
|
||||
_ => Unavailable,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The catalogue of the request being validated, or the shared default one outside a request (unit tests).</summary>
|
||||
public static ITextCatalog From(ValidationContext? context)
|
||||
=> context?.GetService(typeof(ITextCatalog)) as ITextCatalog ?? TextCatalog.Default;
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
// <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("20261116142730_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <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<DateTimeOffset?>("EndsAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
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<DateTimeOffset?>("StartsAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
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<double>("FocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("FocusY")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
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,158 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterDatabase()
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Heroes",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Language = table.Column<string>(type: "varchar(10)", maxLength: 10, nullable: false),
|
||||
Title = table.Column<string>(type: "varchar(1000)", maxLength: 1000, nullable: false),
|
||||
Tagline = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: true),
|
||||
Lead = table.Column<string>(type: "varchar(1000)", maxLength: 1000, nullable: true),
|
||||
Display = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
|
||||
Button1Label = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
|
||||
Button1Target = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
|
||||
Button2Label = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
|
||||
Button2Target = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
|
||||
StartsAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
|
||||
EndsAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
LastModifiedByUserId = table.Column<Guid>(type: "char(36)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Heroes", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "HeroImages",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
OriginalSha256 = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false),
|
||||
OriginalKey = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false),
|
||||
SourceFormat = table.Column<string>(type: "varchar(10)", maxLength: 10, nullable: false),
|
||||
Width = table.Column<int>(type: "int", nullable: false),
|
||||
Height = table.Column<int>(type: "int", nullable: false),
|
||||
Bytes = table.Column<long>(type: "bigint", nullable: false),
|
||||
FocusX = table.Column<double>(type: "double", nullable: false),
|
||||
FocusY = table.Column<double>(type: "double", nullable: false),
|
||||
Zoom = table.Column<double>(type: "double", nullable: false),
|
||||
WideFocusX = table.Column<double>(type: "double", nullable: true),
|
||||
WideFocusY = table.Column<double>(type: "double", nullable: true),
|
||||
WideZoom = table.Column<double>(type: "double", nullable: true),
|
||||
TallFocusX = table.Column<double>(type: "double", nullable: true),
|
||||
TallFocusY = table.Column<double>(type: "double", nullable: true),
|
||||
TallZoom = table.Column<double>(type: "double", nullable: true),
|
||||
SetHash = table.Column<string>(type: "varchar(16)", maxLength: 16, nullable: false),
|
||||
Variants = table.Column<string>(type: "longtext", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
CreatedByUserId = table.Column<Guid>(type: "char(36)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_HeroImages", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "HeroRetiredFiles",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Kind = table.Column<string>(type: "varchar(10)", maxLength: 10, nullable: false),
|
||||
Key = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false),
|
||||
RetiredAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_HeroRetiredFiles", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "HeroSlides",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
HeroId = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
ImageId = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Alt = table.Column<string>(type: "varchar(600)", maxLength: 600, nullable: false),
|
||||
Decorative = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
SortOrder = table.Column<int>(type: "int", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_HeroSlides", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_HeroSlides_HeroImages_ImageId",
|
||||
column: x => x.ImageId,
|
||||
principalTable: "HeroImages",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
table.ForeignKey(
|
||||
name: "FK_HeroSlides_Heroes_HeroId",
|
||||
column: x => x.HeroId,
|
||||
principalTable: "Heroes",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Heroes_Language",
|
||||
table: "Heroes",
|
||||
column: "Language",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_HeroImages_OriginalSha256",
|
||||
table: "HeroImages",
|
||||
column: "OriginalSha256",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_HeroSlides_HeroId_SortOrder",
|
||||
table: "HeroSlides",
|
||||
columns: new[] { "HeroId", "SortOrder" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_HeroSlides_ImageId",
|
||||
table: "HeroSlides",
|
||||
column: "ImageId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "HeroRetiredFiles");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "HeroSlides");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "HeroImages");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Heroes");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Migrations
|
||||
{
|
||||
[DbContext(typeof(HeroDbContext))]
|
||||
partial class HeroDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(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<DateTimeOffset?>("EndsAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
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<DateTimeOffset?>("StartsAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
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<double>("FocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("FocusY")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
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,57 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Models;
|
||||
|
||||
public enum ButtonTargetKind
|
||||
{
|
||||
Invalid = 0,
|
||||
Anchor,
|
||||
Path,
|
||||
Https,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The only kinds of button target the CMS accepts: a page anchor (<c>#contact</c>), a path of the site (<c>/over-mij</c>)
|
||||
/// or an absolute https address. Nothing else, so a button can never carry <c>javascript:</c>, <c>data:</c>, a
|
||||
/// protocol-relative address or a backslash trick. Pure.
|
||||
/// </summary>
|
||||
public static partial class ButtonTargetValidator
|
||||
{
|
||||
[GeneratedRegex("^#[A-Za-z][A-Za-z0-9_-]{0,99}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex AnchorPattern();
|
||||
|
||||
public static ButtonTargetKind Validate(string? target)
|
||||
{
|
||||
if (string.IsNullOrEmpty(target) || target != target.Trim())
|
||||
{
|
||||
return ButtonTargetKind.Invalid;
|
||||
}
|
||||
|
||||
if (target.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c == '\\' || c == '"' || c == '<' || c == '>' || c == '`'))
|
||||
{
|
||||
return ButtonTargetKind.Invalid;
|
||||
}
|
||||
|
||||
if (target[0] == '#')
|
||||
{
|
||||
return AnchorPattern().IsMatch(target) ? ButtonTargetKind.Anchor : ButtonTargetKind.Invalid;
|
||||
}
|
||||
|
||||
if (target[0] == '/')
|
||||
{
|
||||
// One leading slash, not "//host"; no scheme in the first segment ("/a:b" is fine, "/:" is not a concern here).
|
||||
return target.Length == 1 || target[1] != '/' ? ButtonTargetKind.Path : ButtonTargetKind.Invalid;
|
||||
}
|
||||
|
||||
if (Uri.TryCreate(target, UriKind.Absolute, out var uri)
|
||||
&& uri.Scheme == Uri.UriSchemeHttps
|
||||
&& !string.IsNullOrEmpty(uri.Host)
|
||||
&& string.IsNullOrEmpty(uri.UserInfo)
|
||||
&& target.StartsWith("https://", StringComparison.Ordinal))
|
||||
{
|
||||
return ButtonTargetKind.Https;
|
||||
}
|
||||
|
||||
return ButtonTargetKind.Invalid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Models;
|
||||
|
||||
public record FocusDto(double X, double Y, double Zoom)
|
||||
{
|
||||
public FocusSetting ToSetting() => new(X, Y, Zoom);
|
||||
|
||||
public static FocusDto From(FocusSetting focus) => new(focus.X, focus.Y, focus.Zoom);
|
||||
}
|
||||
|
||||
public record HeroVariantDto(string Ratio, int Width, int Height, string Type, string Url);
|
||||
|
||||
public record HeroImageDto(
|
||||
string Id,
|
||||
int Width,
|
||||
int Height,
|
||||
FocusDto Focus,
|
||||
FocusDto? WideFocus,
|
||||
FocusDto? TallFocus,
|
||||
string Src,
|
||||
IReadOnlyList<HeroVariantDto> Variants);
|
||||
|
||||
public record HeroButtonDto(string Label, string Target);
|
||||
|
||||
public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image);
|
||||
|
||||
/// <summary>What the admin edits. When no hero exists yet <see cref="Id"/> is null and the fields hold the defaults.</summary>
|
||||
public record HeroAdminDto(
|
||||
string? Id,
|
||||
string Title,
|
||||
string? Tagline,
|
||||
string? Lead,
|
||||
string Display,
|
||||
IReadOnlyList<HeroButtonDto> Buttons,
|
||||
bool IsActive,
|
||||
DateTimeOffset? StartsAt,
|
||||
DateTimeOffset? EndsAt,
|
||||
IReadOnlyList<HeroSlideAdminDto> Slides,
|
||||
bool IsLive,
|
||||
DateTimeOffset? UpdatedAt,
|
||||
int MaxPublishedSlides);
|
||||
|
||||
/// <summary>The image of a published slide. <see cref="Src"/> is the largest WebP of the wide ratio.</summary>
|
||||
public record PublicImageDto(
|
||||
int Width,
|
||||
int Height,
|
||||
FocusDto Focus,
|
||||
string Src,
|
||||
IReadOnlyList<HeroVariantDto> Variants,
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyDictionary<string, FocusDto>? FocusByRatio = null);
|
||||
|
||||
public record PublicSlideDto(string Id, string Alt, bool Decorative, PublicImageDto Image);
|
||||
|
||||
/// <summary>What visitors and websites get: only content, never the schedule or on/off switches. The same shape is written into <c>#cms-data</c>.</summary>
|
||||
public record PublicHeroDto(
|
||||
string Display,
|
||||
string Title,
|
||||
string? Tagline,
|
||||
string? Lead,
|
||||
IReadOnlyList<HeroButtonDto> Buttons,
|
||||
IReadOnlyList<PublicSlideDto> Slides);
|
||||
|
||||
// ----- requests ----------------------------------------------------------------------------------------------------
|
||||
|
||||
public record HeroButtonRequest(string? Label, string? Target);
|
||||
|
||||
public record HeroSlideRequest(Guid? Id, Guid ImageId, string? Alt, bool Decorative = false, bool IsActive = true);
|
||||
|
||||
public record HeroFocusRequest(FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null) : IValidatableObject
|
||||
{
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
var texts = HeroTexts.From(validationContext);
|
||||
foreach (var (name, value) in new[] { (nameof(Focus), Focus), (nameof(Wide), Wide), (nameof(Tall), Tall) })
|
||||
{
|
||||
if (value is not null && !value.ToSetting().IsValid)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [name]);
|
||||
}
|
||||
}
|
||||
|
||||
if (Focus is null)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [nameof(Focus)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The whole hero in one go (full replace). Nothing here is trusted: <see cref="Validate"/> is the one place that checks it.</summary>
|
||||
public record HeroSaveRequest(
|
||||
string? Title,
|
||||
string? Tagline,
|
||||
string? Lead,
|
||||
string? Display,
|
||||
IReadOnlyList<HeroButtonRequest>? Buttons,
|
||||
bool IsActive,
|
||||
DateTimeOffset? StartsAt,
|
||||
DateTimeOffset? EndsAt,
|
||||
IReadOnlyList<HeroSlideRequest>? Slides) : IValidatableObject
|
||||
{
|
||||
public const int TitleMax = 200;
|
||||
public const int TitleMaxLines = 5;
|
||||
public const int TaglineMax = 120;
|
||||
public const int LeadMax = 600;
|
||||
public const int ButtonLabelMax = 50;
|
||||
public const int ButtonTargetMax = 500;
|
||||
public const int ButtonsMax = 2;
|
||||
public const int AltMax = 300;
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
var texts = HeroTexts.From(validationContext);
|
||||
|
||||
var title = HeroText.Clean(Title, keepLineBreaks: true);
|
||||
if (title.Length == 0)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.Required), [nameof(Title)]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (title.Length > TitleMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooLong, args: ("max", TitleMax)), [nameof(Title)]);
|
||||
}
|
||||
|
||||
if (title.Count(c => c == '\n') + 1 > TitleMaxLines)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooManyLines, args: ("max", TitleMaxLines)), [nameof(Title)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (HeroText.Clean(Tagline, keepLineBreaks: false).Length > TaglineMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.TaglineTooLong, args: ("max", TaglineMax)), [nameof(Tagline)]);
|
||||
}
|
||||
|
||||
if (HeroText.Clean(Lead, keepLineBreaks: true).Length > LeadMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.LeadTooLong, args: ("max", LeadMax)), [nameof(Lead)]);
|
||||
}
|
||||
|
||||
if (!HeroDisplays.IsValid(Display ?? HeroDisplays.Single))
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.DisplayInvalid), [nameof(Display)]);
|
||||
}
|
||||
|
||||
var buttons = Buttons ?? [];
|
||||
if (buttons.Count > ButtonsMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TooMany, args: ("max", ButtonsMax)), [nameof(Buttons)]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < buttons.Count; i++)
|
||||
{
|
||||
var label = HeroText.Clean(buttons[i].Label, keepLineBreaks: false);
|
||||
var target = (buttons[i].Target ?? string.Empty).Trim();
|
||||
if (label.Length == 0 && target.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (label.Length == 0 || target.Length == 0)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.Incomplete), [$"{nameof(Buttons)}[{i}]"]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (label.Length > ButtonLabelMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.LabelTooLong, args: ("max", ButtonLabelMax)), [$"{nameof(Buttons)}[{i}].Label"]);
|
||||
}
|
||||
|
||||
if (target.Length > ButtonTargetMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetTooLong, args: ("max", ButtonTargetMax)), [$"{nameof(Buttons)}[{i}].Target"]);
|
||||
}
|
||||
else if (ButtonTargetValidator.Validate(target) == ButtonTargetKind.Invalid)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetInvalid), [$"{nameof(Buttons)}[{i}].Target"]);
|
||||
}
|
||||
}
|
||||
|
||||
if (StartsAt is not null && EndsAt is not null && EndsAt <= StartsAt)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.EndAfterStart), [nameof(EndsAt)]);
|
||||
}
|
||||
|
||||
var slides = Slides ?? [];
|
||||
for (var i = 0; i < slides.Count; i++)
|
||||
{
|
||||
var slide = slides[i];
|
||||
if (slide.ImageId == Guid.Empty)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.ImageRequired), [$"{nameof(Slides)}[{i}].ImageId"]);
|
||||
}
|
||||
|
||||
var alt = HeroText.Clean(slide.Alt, keepLineBreaks: false);
|
||||
if (!slide.Decorative && alt.Length == 0)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltRequired), [$"{nameof(Slides)}[{i}].Alt"]);
|
||||
}
|
||||
else if (alt.Length > AltMax)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltTooLong, args: ("max", AltMax)), [$"{nameof(Slides)}[{i}].Alt"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plain text handling: stored as typed, minus control characters; encoding happens where the text is written.</summary>
|
||||
public static class HeroText
|
||||
{
|
||||
public static string Clean(string? value, bool keepLineBreaks)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var text = value.Replace("\r\n", "\n").Replace('\r', '\n');
|
||||
var builder = new StringBuilder(text.Length);
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (c == '\n')
|
||||
{
|
||||
builder.Append(keepLineBreaks ? '\n' : ' ');
|
||||
}
|
||||
else if (!char.IsControl(c) && c != '\u2028' && c != '\u2029')
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString().Trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
public interface IHeroRepository
|
||||
{
|
||||
/// <summary>The hero of a language with its slides (and their images), tracked for update.</summary>
|
||||
Task<HeroContent?> GetAsync(string language, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The same, not tracked (read paths).</summary>
|
||||
Task<HeroContent?> GetReadOnlyAsync(string language, CancellationToken cancellationToken);
|
||||
|
||||
void Add(HeroContent hero);
|
||||
void AddSlide(HeroSlide slide);
|
||||
void RemoveSlide(HeroSlide slide);
|
||||
|
||||
Task<HeroImage?> GetImageAsync(Guid id, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken);
|
||||
Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken);
|
||||
void AddImage(HeroImage image);
|
||||
void RemoveImage(HeroImage image);
|
||||
Task<bool> ImageInUseAsync(Guid imageId, CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<HeroImage>> GetUnattachedImagesCreatedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
|
||||
Task<HashSet<string>> GetReferencedSetHashesAsync(CancellationToken cancellationToken);
|
||||
Task<HashSet<string>> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken);
|
||||
|
||||
void AddRetired(HeroRetiredFile file);
|
||||
void RemoveRetired(HeroRetiredFile file);
|
||||
Task<IReadOnlyList<HeroRetiredFile>> GetRetiredBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
|
||||
Task<HashSet<string>> GetRetiredSetHashesAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task SaveChangesAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
{
|
||||
public Task<HeroContent?> GetAsync(string language, CancellationToken cancellationToken)
|
||||
=> context.Heroes.Include(h => h.Slides).ThenInclude(s => s.Image)
|
||||
.FirstOrDefaultAsync(h => h.Language == language, cancellationToken);
|
||||
|
||||
public Task<HeroContent?> GetReadOnlyAsync(string language, CancellationToken cancellationToken)
|
||||
=> context.Heroes.AsNoTracking().Include(h => h.Slides).ThenInclude(s => s.Image)
|
||||
.FirstOrDefaultAsync(h => h.Language == language, cancellationToken);
|
||||
|
||||
public void Add(HeroContent hero) => context.Heroes.Add(hero);
|
||||
|
||||
public void AddSlide(HeroSlide slide) => context.HeroSlides.Add(slide);
|
||||
|
||||
public void RemoveSlide(HeroSlide slide) => context.HeroSlides.Remove(slide);
|
||||
|
||||
public Task<HeroImage?> GetImageAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken)
|
||||
=> await context.HeroImages.Where(i => ids.Contains(i.Id)).ToListAsync(cancellationToken);
|
||||
|
||||
public Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
|
||||
|
||||
public void AddImage(HeroImage image) => context.HeroImages.Add(image);
|
||||
|
||||
public void RemoveImage(HeroImage image) => context.HeroImages.Remove(image);
|
||||
|
||||
public Task<bool> ImageInUseAsync(Guid imageId, CancellationToken cancellationToken)
|
||||
=> context.HeroSlides.AnyAsync(s => s.ImageId == imageId, cancellationToken);
|
||||
|
||||
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);
|
||||
return candidates.Where(i => i.CreatedAt < cutoff).ToList();
|
||||
}
|
||||
|
||||
public async Task<HashSet<string>> GetReferencedSetHashesAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
public async Task<HashSet<string>> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.Select(i => i.OriginalKey).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
public void AddRetired(HeroRetiredFile file) => context.HeroRetiredFiles.Add(file);
|
||||
|
||||
public void RemoveRetired(HeroRetiredFile file) => context.HeroRetiredFiles.Remove(file);
|
||||
|
||||
public async Task<IReadOnlyList<HeroRetiredFile>> GetRetiredBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
|
||||
=> (await context.HeroRetiredFiles.ToListAsync(cancellationToken)).Where(f => f.RetiredAt < cutoff).ToList();
|
||||
|
||||
public async Task<HashSet<string>> GetRetiredSetHashesAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroRetiredFiles.Where(f => f.Kind == "set").Select(f => f.Key).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||
<_Parameter1>SlpModularCms.Modules.Hero.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Core.Media.Magick\SlpModularCms.Core.Media.Magick.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Texts\*.json" WithCulture="false" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"hero": {
|
||||
"validation": {
|
||||
"title": {
|
||||
"required": "A title is required.",
|
||||
"tooLong": "The title can have at most {max} characters.",
|
||||
"tooManyLines": "The title can have at most {max} lines."
|
||||
},
|
||||
"tagline": {
|
||||
"tooLong": "The tagline can have at most {max} characters."
|
||||
},
|
||||
"lead": {
|
||||
"tooLong": "The introduction can have at most {max} characters."
|
||||
},
|
||||
"display": {
|
||||
"invalid": "The display must be 'single' or 'slideshow'."
|
||||
},
|
||||
"button": {
|
||||
"incomplete": "A button needs both a label and a target.",
|
||||
"labelTooLong": "The button label can have at most {max} characters.",
|
||||
"targetTooLong": "The button target can have at most {max} characters.",
|
||||
"targetInvalid": "Choose an #anchor, a /path or an https:// address.",
|
||||
"tooMany": "At most {max} buttons are possible."
|
||||
},
|
||||
"schedule": {
|
||||
"endAfterStart": "The end must be after the start."
|
||||
},
|
||||
"slide": {
|
||||
"imageRequired": "Every slide needs an image.",
|
||||
"imageUnknown": "An image of a slide does not exist (any more).",
|
||||
"altRequired": "Give a description (alt text) or mark the image as decorative.",
|
||||
"altTooLong": "The alt text can have at most {max} characters.",
|
||||
"idUnknown": "A slide does not belong to this hero."
|
||||
},
|
||||
"focus": {
|
||||
"invalid": "The focus point must be between 0 and 1 and the zoom between 1 and {maxZoom}."
|
||||
}
|
||||
},
|
||||
"image": {
|
||||
"inUse": "This image is still used by a slide.",
|
||||
"notFound": "This image does not exist.",
|
||||
"rejected": {
|
||||
"tooLarge": "The image is too large (at most {max} MB).",
|
||||
"unsupportedFormat": "This file type is not supported. Choose a JPEG, PNG, WebP or another common image file.",
|
||||
"corrupt": "The image could not be read or is damaged.",
|
||||
"tooManyPixels": "The image has too many pixels. Choose a smaller image.",
|
||||
"timeout": "Processing the image took too long. Try a smaller image.",
|
||||
"busy": "Other images are being processed. Try again in a moment.",
|
||||
"unavailable": "Uploading images is not available at the moment."
|
||||
},
|
||||
"storageFull": "There is not enough storage space for this image."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"hero": {
|
||||
"validation": {
|
||||
"title": {
|
||||
"required": "Een titel is verplicht.",
|
||||
"tooLong": "De titel mag maximaal {max} tekens bevatten.",
|
||||
"tooManyLines": "De titel mag maximaal {max} regels hebben."
|
||||
},
|
||||
"tagline": {
|
||||
"tooLong": "De tagline mag maximaal {max} tekens bevatten."
|
||||
},
|
||||
"lead": {
|
||||
"tooLong": "De introductietekst mag maximaal {max} tekens bevatten."
|
||||
},
|
||||
"display": {
|
||||
"invalid": "De weergave moet 'enkel' of 'diavoorstelling' zijn."
|
||||
},
|
||||
"button": {
|
||||
"incomplete": "Een knop heeft zowel een tekst als een doel nodig.",
|
||||
"labelTooLong": "De knoptekst mag maximaal {max} tekens bevatten.",
|
||||
"targetTooLong": "Het doel van een knop mag maximaal {max} tekens bevatten.",
|
||||
"targetInvalid": "Kies een #anker, een /pad of een https://-adres.",
|
||||
"tooMany": "Er zijn maximaal {max} knoppen mogelijk."
|
||||
},
|
||||
"schedule": {
|
||||
"endAfterStart": "Het einde moet na het begin liggen."
|
||||
},
|
||||
"slide": {
|
||||
"imageRequired": "Elke slide heeft een afbeelding nodig.",
|
||||
"imageUnknown": "Een afbeelding van een slide bestaat niet (meer).",
|
||||
"altRequired": "Geef een beschrijving (alt-tekst) of markeer de afbeelding als decoratief.",
|
||||
"altTooLong": "De alt-tekst mag maximaal {max} tekens bevatten.",
|
||||
"idUnknown": "Een slide hoort niet bij deze hero."
|
||||
},
|
||||
"focus": {
|
||||
"invalid": "Het focuspunt moet tussen 0 en 1 liggen en de zoom tussen 1 en {maxZoom}."
|
||||
}
|
||||
},
|
||||
"image": {
|
||||
"inUse": "Deze afbeelding wordt nog gebruikt door een slide.",
|
||||
"notFound": "Deze afbeelding bestaat niet.",
|
||||
"rejected": {
|
||||
"tooLarge": "De afbeelding is te groot (maximaal {max} MB).",
|
||||
"unsupportedFormat": "Dit bestandstype wordt niet ondersteund. Kies een JPEG-, PNG-, WebP- of ander gangbaar afbeeldingsbestand.",
|
||||
"corrupt": "De afbeelding kon niet worden gelezen of is beschadigd.",
|
||||
"tooManyPixels": "De afbeelding heeft te veel pixels. Kies een kleinere afbeelding.",
|
||||
"timeout": "Het verwerken van de afbeelding duurde te lang. Probeer een kleinere afbeelding.",
|
||||
"busy": "Er worden nu andere afbeeldingen verwerkt. Probeer het zo opnieuw.",
|
||||
"unavailable": "Afbeeldingen uploaden is op dit moment niet beschikbaar."
|
||||
},
|
||||
"storageFull": "Er is te weinig opslagruimte voor deze afbeelding."
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user