Files
slp-modular-cms/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs
T

152 lines
5.6 KiB
C#

using System.Text.Json;
using System.Text.Json.Nodes;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Core.Texts;
using SlpModularCms.Modules.Offerings.Data.Entities;
using SlpModularCms.Modules.Offerings.Models;
namespace SlpModularCms.Modules.Offerings.Services;
/// <summary>
/// Writes the live packages and banners into a prerendered page (see <see cref="HtmlMarkerEditor"/> for the marker
/// formats): the plain lists in the regions, the data block the website reads instead of fetching, the price in the
/// page's JSON-LD and inline prices. It only touches what a page marks; a page without markers is not handed to it.
/// Any exception means "leave the page as it was built" (the injector logs it and serves the baked page).
/// </summary>
public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferingBannersService banners, ITextCatalog? texts = null) : IHtmlPageTransform
{
public const string OfferingsRegion = "CMS:OFFERINGS-HTML";
public const string BannerTopRegion = "CMS:BANNER-TOP-HTML";
public const string BannerBottomRegion = "CMS:BANNER-BOTTOM-HTML";
public const string JsonLdMarker = "CMS:OFFER-JSON-LD";
public const string PriceAttribute = "data-cms-price";
private static readonly JsonSerializerOptions LdJson = new()
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
public bool Wants(string html) => HtmlMarkerEditor.HasMarkers(html);
public async Task<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken)
{
var wantsOfferings = html.Contains("<!--" + OfferingsRegion + "-->", StringComparison.Ordinal)
|| html.Contains("<!--" + JsonLdMarker, StringComparison.Ordinal)
|| html.Contains(PriceAttribute + "=", StringComparison.Ordinal);
var wantsTop = html.Contains("<!--" + BannerTopRegion + "-->", StringComparison.Ordinal);
var wantsBottom = html.Contains("<!--" + BannerBottomRegion + "-->", StringComparison.Ordinal);
var live = wantsOfferings ? await offerings.GetOfferingsAsync() : [];
var top = wantsTop ? await banners.GetActiveAsync(OfferingBannerPositions.Top) : null;
var bottom = wantsBottom ? await banners.GetActiveAsync(OfferingBannerPositions.Bottom) : null;
if (wantsOfferings)
{
html = HtmlMarkerEditor.ReplaceRegion(html, OfferingsRegion, CmsPageHtml.OfferingsList(live, texts));
html = HtmlMarkerEditor.EditJsonLd(html, JsonLdMarker, (slug, json) => EditOfferJsonLd(json, FindPrice(live, slug)));
html = HtmlMarkerEditor.ReplaceInlineValues(html, PriceAttribute,
slug => FindPrice(live, slug) is { } euros ? CmsPageHtml.PriceHtml(euros) : null);
}
if (wantsTop)
{
html = HtmlMarkerEditor.ReplaceRegion(html, BannerTopRegion, CmsPageHtml.Banner(top, OfferingBannerPositions.Top));
}
if (wantsBottom)
{
html = HtmlMarkerEditor.ReplaceRegion(html, BannerBottomRegion, CmsPageHtml.Banner(bottom, OfferingBannerPositions.Bottom));
}
return html;
}
private static int? FindPrice(IReadOnlyList<OfferingDto> live, string slug)
=> live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering
? CmsPageHtml.WholeEuros(offering.Price)
: null;
/// <summary>
/// Sets <c>offers.price</c> (whole euros, a JSON number) on the node of the page's JSON-LD that has an <c>offers</c>
/// object; without a price (no live package, or a price text that is no price) <c>offers</c> is removed. Returns
/// null when the text is not JSON (the baked block is left alone).
/// </summary>
internal static string? EditOfferJsonLd(string json, int? euros)
{
JsonNode? root;
try
{
root = JsonNode.Parse(json);
}
catch (JsonException)
{
return null;
}
if (root is null)
{
return null;
}
var holder = FindOffersHolder(root);
if (holder is null)
{
return json;
}
if (euros is null)
{
holder.Remove("offers");
}
else
{
var offers = holder["offers"] is JsonArray array ? array.OfType<JsonObject>().FirstOrDefault() : holder["offers"] as JsonObject;
if (offers is null)
{
return json;
}
offers["price"] = euros.Value;
}
// Valid JSON never contains a literal "</script": the relaxed encoder does not escape "<", so do it here.
return root.ToJsonString(LdJson).Replace("</", "<\\/", StringComparison.Ordinal);
}
private static JsonObject? FindOffersHolder(JsonNode node)
{
switch (node)
{
case JsonObject obj:
if (obj["offers"] is JsonObject or JsonArray)
{
return obj;
}
foreach (var (_, child) in obj)
{
if (child is not null && FindOffersHolder(child) is { } found)
{
return found;
}
}
return null;
case JsonArray array:
foreach (var child in array)
{
if (child is not null && FindOffersHolder(child) is { } found)
{
return found;
}
}
return null;
default:
return null;
}
}
}