H4: hero in de eerste HTML (regio, preload), gedeeld datablok met contributors (Offerings byte-identiek), ASF golden files, volledige pijplijntest
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Magick;
|
||||
using SlpModularCms.Core.Modules;
|
||||
@@ -43,6 +44,9 @@ public class HeroModule : IModule
|
||||
services.AddScoped<IHeroService, HeroService>();
|
||||
services.AddScoped<IPublicHeroService, PublicHeroService>();
|
||||
services.AddScoped<IHeroImageService, HeroImageService>();
|
||||
services.AddScoped<IHeroPageModel, HeroPageModel>();
|
||||
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
|
||||
services.AddScoped<ICmsDataBlockContributor, HeroDataContributor>();
|
||||
services.AddScoped<HeroMediaCleanup>();
|
||||
services.AddHostedService<HeroMediaCleanupService>();
|
||||
}
|
||||
|
||||
@@ -55,7 +55,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
=> 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);
|
||||
{
|
||||
// The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they
|
||||
// are read and filtered here.
|
||||
var wanted = ids.ToHashSet();
|
||||
return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
|
||||
}
|
||||
|
||||
public Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
|
||||
|
||||
@@ -48,8 +48,10 @@ public class HeroImageService(
|
||||
using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken);
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes));
|
||||
|
||||
// The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload
|
||||
// repairs them from the file that was just sent.
|
||||
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
|
||||
if (existing is not null)
|
||||
if (existing is not null && await FilesExistAsync(existing, cancellationToken))
|
||||
{
|
||||
return HeroMapping.ToImageDto(existing);
|
||||
}
|
||||
@@ -62,7 +64,7 @@ public class HeroImageService(
|
||||
var original = stripped ?? admitted.Bytes;
|
||||
var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format;
|
||||
|
||||
var image = new HeroImage
|
||||
var image = existing ?? new HeroImage
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
OriginalSha256 = sha,
|
||||
@@ -79,13 +81,35 @@ public class HeroImageService(
|
||||
|
||||
await store.PutAsync(image.OriginalKey, original, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddImage(image);
|
||||
if (existing is null)
|
||||
{
|
||||
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);
|
||||
logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height, image.Variants.Count);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
private async Task<bool> FilesExistAsync(HeroImage image, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await store.ExistsAsync(image.OriginalKey, cancellationToken))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var variant in image.Variants)
|
||||
{
|
||||
if (!await store.ExistsAsync($"{HeroMapping.Area}/{image.SetHash}/{variant.FileName}", cancellationToken))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The hero as a page may show it: the public hero, but only when the files of its first slide are really in the media
|
||||
/// store. When they are not (a missing or restored directory) nothing of the hero is written, so a page never gets a broken
|
||||
/// first image and the baked hero stays. One answer for the region, the preload and the data block.
|
||||
/// </summary>
|
||||
public interface IHeroPageModel
|
||||
{
|
||||
Task<PublicHeroDto?> GetAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class HeroPageModel(IPublicHeroService publicHero, IMediaStore store, ILogger<HeroPageModel> logger) : IHeroPageModel
|
||||
{
|
||||
public async Task<PublicHeroDto?> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var hero = await publicHero.GetActiveAsync(cancellationToken);
|
||||
if (hero is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var first = hero.Slides.FirstOrDefault();
|
||||
if (first is null)
|
||||
{
|
||||
return hero;
|
||||
}
|
||||
|
||||
foreach (var url in new[] { first.Image.Src }.Concat(first.Image.Variants.Select(v => v.Url)).Distinct())
|
||||
{
|
||||
if (url.StartsWith(MediaPaths.UrlPrefix, StringComparison.Ordinal)
|
||||
&& !await store.ExistsAsync(url[MediaPaths.UrlPrefix.Length..], cancellationToken))
|
||||
{
|
||||
logger.LogWarning("The first hero slide has a file missing in the media store ({Address}); the hero is left out of the page.", url);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return hero;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fills the hero regions of a page: <c><!--CMS:HERO-HTML--></c> in the body and <c><!--CMS:HERO-PRELOAD--></c> in the head. Fail-open: no hero means the baked page stays.</summary>
|
||||
public sealed class HeroHtmlTransform(IHeroPageModel model) : IHtmlPageTransform
|
||||
{
|
||||
public const string HtmlRegion = "CMS:HERO-HTML";
|
||||
public const string PreloadRegion = "CMS:HERO-PRELOAD";
|
||||
|
||||
public bool Wants(string html)
|
||||
=> html.Contains("<!--" + HtmlRegion + "-->", StringComparison.Ordinal)
|
||||
|| html.Contains("<!--" + PreloadRegion + "-->", StringComparison.Ordinal);
|
||||
|
||||
public async Task<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var rendered = HeroPictureRenderer.Render(await model.GetAsync(cancellationToken));
|
||||
if (rendered.IsEmpty)
|
||||
{
|
||||
return html;
|
||||
}
|
||||
|
||||
html = HtmlMarkerEditor.ReplaceRegion(html, HtmlRegion, rendered.Region);
|
||||
return HtmlMarkerEditor.ReplaceRegion(html, PreloadRegion, rendered.Preload);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The <c>hero</c> key of the page data block: the complete public hero (all slides), or null.</summary>
|
||||
public sealed class HeroDataContributor(IHeroPageModel model) : ICmsDataBlockContributor
|
||||
{
|
||||
public string Key => "hero";
|
||||
|
||||
public int Order => 200;
|
||||
|
||||
public async Task<object?> GetAsync(HtmlTransformContext context, CancellationToken cancellationToken)
|
||||
=> await model.GetAsync(cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>The two pieces written into a page: the hero itself and the preload links for the head. Both empty = leave the baked page.</summary>
|
||||
public sealed record HeroInjection(string Region, string Preload)
|
||||
{
|
||||
public static readonly HeroInjection None = new(string.Empty, string.Empty);
|
||||
|
||||
public bool IsEmpty => Region.Length == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plain HTML of the hero for the first response, written exactly as the website's golden files expect
|
||||
/// (aidlc-docs/features/hero-module, site contract; ASF commit 13f78c4). One place produces the picture and the preload,
|
||||
/// so the <c>srcset</c>, <c>sizes</c> and <c>media</c> values are the same text in both. Pure; everything is HTML-encoded.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The rules are those of the website: a hero needs a title and a usable first slide (an id, an own-host path, a size, and
|
||||
/// an alt text or the decorative flag), only WebP is used for the first image (a preload cannot say "AVIF if supported"),
|
||||
/// at most two buttons, and unusable parts are skipped, never repaired. They are deliberately a little wider than what the
|
||||
/// CMS accepts when saving, because the renderer must also cope with data it did not validate itself.
|
||||
/// </remarks>
|
||||
public static class HeroPictureRenderer
|
||||
{
|
||||
private const string Webp = "image/webp";
|
||||
private const string Portrait = "(orientation: portrait)";
|
||||
private const string Landscape = "(orientation: landscape)";
|
||||
|
||||
public static HeroInjection Render(PublicHeroDto? hero)
|
||||
{
|
||||
if (hero is null || string.IsNullOrWhiteSpace(hero.Title))
|
||||
{
|
||||
return HeroInjection.None;
|
||||
}
|
||||
|
||||
var slide = (hero.Slides ?? []).FirstOrDefault(IsUsable);
|
||||
if (slide is null)
|
||||
{
|
||||
return HeroInjection.None;
|
||||
}
|
||||
|
||||
var image = slide.Image;
|
||||
var variants = (image.Variants ?? []).Where(v => IsUsable(v) && v.Type == Webp).ToList();
|
||||
var wide = SrcSet(variants, "wide");
|
||||
var tall = SrcSet(variants, "tall");
|
||||
|
||||
return new HeroInjection(Region(hero, slide, wide, tall), Preload(image.Src, wide, tall));
|
||||
}
|
||||
|
||||
private static string Region(PublicHeroDto hero, PublicSlideDto slide, string wide, string tall)
|
||||
{
|
||||
var image = slide.Image;
|
||||
var html = new StringBuilder();
|
||||
html.Append("<picture class=\"cms-hero-picture\">");
|
||||
if (tall.Length > 0)
|
||||
{
|
||||
html.Append("<source media=\"").Append(Portrait).Append("\" srcset=\"").Append(Encode(tall)).Append("\" sizes=\"100vw\" type=\"image/webp\">");
|
||||
}
|
||||
|
||||
html.Append("<img class=\"cms-hero-image\" src=\"").Append(Encode(image.Src)).Append('"');
|
||||
if (wide.Length > 0)
|
||||
{
|
||||
html.Append(" srcset=\"").Append(Encode(wide)).Append("\" sizes=\"100vw\"");
|
||||
}
|
||||
|
||||
html.Append(" width=\"").Append(image.Width.ToString(CultureInfo.InvariantCulture)).Append("\" height=\"").Append(image.Height.ToString(CultureInfo.InvariantCulture)).Append('"');
|
||||
html.Append(" alt=\"").Append(slide.Decorative ? string.Empty : Encode(slide.Alt)).Append('"');
|
||||
if (Position(image) is { } position)
|
||||
{
|
||||
html.Append(" style=\"object-position:").Append(position).Append('"');
|
||||
}
|
||||
|
||||
html.Append(" fetchpriority=\"high\"></picture>");
|
||||
|
||||
html.Append("<h1 class=\"cms-hero-title\">");
|
||||
if (!string.IsNullOrWhiteSpace(hero.Tagline))
|
||||
{
|
||||
html.Append("<span class=\"cms-hero-tagline\">").Append(Encode(hero.Tagline)).Append("</span> ");
|
||||
}
|
||||
|
||||
html.Append("<span class=\"cms-hero-name\">").Append(string.Join("<br>", hero.Title.Replace("\r\n", "\n").Split('\n').Select(Encode))).Append("</span></h1>");
|
||||
|
||||
var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList();
|
||||
if (buttons.Count > 0)
|
||||
{
|
||||
html.Append("<p class=\"cms-hero-buttons\">");
|
||||
foreach (var button in buttons)
|
||||
{
|
||||
html.Append("<a class=\"cms-hero-button\" href=\"").Append(Encode(button.Target)).Append("\">").Append(Encode(button.Label)).Append("</a>");
|
||||
}
|
||||
|
||||
html.Append("</p>");
|
||||
}
|
||||
|
||||
return html.ToString();
|
||||
}
|
||||
|
||||
private static string Preload(string src, string wide, string tall)
|
||||
{
|
||||
const string head = "<link rel=\"preload\" as=\"image\"";
|
||||
const string tail = " fetchpriority=\"high\">";
|
||||
|
||||
string Link(string set, string? media)
|
||||
{
|
||||
var link = new StringBuilder(head);
|
||||
if (set.Length > 0)
|
||||
{
|
||||
link.Append(" imagesrcset=\"").Append(Encode(set)).Append("\" imagesizes=\"100vw\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
link.Append(" href=\"").Append(Encode(src)).Append('"');
|
||||
}
|
||||
|
||||
if (media is not null)
|
||||
{
|
||||
link.Append(" media=\"").Append(media).Append('"');
|
||||
}
|
||||
|
||||
return link.Append(tail).ToString();
|
||||
}
|
||||
|
||||
return tall.Length > 0 ? Link(tall, Portrait) + Link(wide, Landscape) : Link(wide, null);
|
||||
}
|
||||
|
||||
// ----- what counts as usable (the rules of the website) -------------------------------------------------------
|
||||
|
||||
private static bool IsUsable(PublicSlideDto? slide)
|
||||
=> slide is { Image: not null }
|
||||
&& !string.IsNullOrEmpty(slide.Id)
|
||||
&& IsHostPath(slide.Image.Src)
|
||||
&& slide.Image.Width > 0
|
||||
&& slide.Image.Height > 0
|
||||
&& (slide.Decorative || !string.IsNullOrWhiteSpace(slide.Alt));
|
||||
|
||||
private static bool IsUsable(HeroVariantDto variant)
|
||||
=> !string.IsNullOrEmpty(variant.Ratio) && !string.IsNullOrEmpty(variant.Type) && variant.Width > 0 && IsHostPath(variant.Url);
|
||||
|
||||
private static bool IsUsable(HeroButtonDto button)
|
||||
=> !string.IsNullOrWhiteSpace(button.Label) && IsButtonTarget(button.Target);
|
||||
|
||||
/// <summary>A path of this host: one leading slash, not a protocol-relative address, no backslash.</summary>
|
||||
private static bool IsHostPath(string? value)
|
||||
=> !string.IsNullOrEmpty(value) && value[0] == '/' && !value.StartsWith("//", StringComparison.Ordinal) && !value.Contains('\\');
|
||||
|
||||
private static bool IsButtonTarget(string? target)
|
||||
{
|
||||
if (string.IsNullOrEmpty(target))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (target[0] == '#')
|
||||
{
|
||||
return target.Length > 1 && !target.Any(char.IsWhiteSpace);
|
||||
}
|
||||
|
||||
if (target[0] == '/')
|
||||
{
|
||||
return IsHostPath(target);
|
||||
}
|
||||
|
||||
return target.StartsWith("https://", StringComparison.Ordinal)
|
||||
&& Uri.TryCreate(target, UriKind.Absolute, out var uri)
|
||||
&& uri.Scheme == Uri.UriSchemeHttps
|
||||
&& !string.IsNullOrEmpty(uri.Host);
|
||||
}
|
||||
|
||||
private static string SrcSet(IEnumerable<HeroVariantDto> variants, string ratio)
|
||||
=> string.Join(", ", variants.Where(v => v.Ratio == ratio).OrderBy(v => v.Width).Select(v => v.Url + " " + v.Width.ToString(CultureInfo.InvariantCulture) + "w"));
|
||||
|
||||
/// <summary><c>X% Y%</c> from a focus point inside the image (at most two decimals, no trailing zeros), or null without a valid one.</summary>
|
||||
private static string? Position(PublicImageDto image)
|
||||
{
|
||||
var focus = image.Focus;
|
||||
if (focus is null || focus.X is < 0 or > 1 || focus.Y is < 0 or > 1 || double.IsNaN(focus.X) || double.IsNaN(focus.Y))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Percent(focus.X) + "% " + Percent(focus.Y) + "%";
|
||||
}
|
||||
|
||||
private static string Percent(double fraction)
|
||||
=> Math.Round(fraction * 100, 2, MidpointRounding.AwayFromZero).ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Encode(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(value.Length + 8);
|
||||
foreach (var c in value)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '&': builder.Append("&"); break;
|
||||
case '<': builder.Append("<"); break;
|
||||
case '>': builder.Append(">"); break;
|
||||
case '"': builder.Append("""); break;
|
||||
case '\'': builder.Append("'"); break;
|
||||
default: builder.Append(c); break;
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user