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:
@@ -15,6 +15,8 @@
|
||||
"src\\SlpModularCms.Api.Tests\\SlpModularCms.Api.Tests.csproj",
|
||||
"src\\SlpModularCms.Modules.Offerings\\SlpModularCms.Modules.Offerings.csproj",
|
||||
"src\\SlpModularCms.Modules.Offerings.Tests\\SlpModularCms.Modules.Offerings.Tests.csproj",
|
||||
"src\\SlpModularCms.Modules.Hero\\SlpModularCms.Modules.Hero.csproj",
|
||||
"src\\SlpModularCms.Modules.Hero.Tests\\SlpModularCms.Modules.Hero.Tests.csproj",
|
||||
"src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj",
|
||||
"src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj"
|
||||
]
|
||||
|
||||
@@ -46,6 +46,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Conta
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Core.Media.Magick", "src\SlpModularCms.Core.Media.Magick\SlpModularCms.Core.Media.Magick.csproj", "{9EAC8A27-8DB0-4E3B-B144-280882828DE8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero", "src\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj", "{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero.Tests", "src\SlpModularCms.Modules.Hero.Tests\SlpModularCms.Modules.Hero.Tests.csproj", "{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -272,6 +276,30 @@ Global
|
||||
{9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x86.Build.0 = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x64.Build.0 = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x86.Build.0 = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -297,5 +325,7 @@ Global
|
||||
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
||||
{06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
||||
{9EAC8A27-8DB0-4E3B-B144-280882828DE8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
||||
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# H2 Hero module backend: code summary
|
||||
|
||||
Built 2026-11-16 on `feature/hero-module`. The whole CI solution filter is green (Core 912, Hero 100, Offerings 212, Availability 171, Identity 145, Api 46, Contact 349, Master 61); Api and Contact tests ran against MariaDB, so the new migration is proven on a real database and `HasPendingModelChanges` is false.
|
||||
|
||||
| Area | What |
|
||||
|---|---|
|
||||
| Project | `SlpModularCms.Modules.Hero` (+ `.Tests`), in `SlpModularCms.sln` (Application/Modules and Tests/Modules) and `SlpModularCms.Ci.slnf`; referenced by `Api`, `Api.SlpSoftware` and `Api.AndreaSlopFotografie` (not the slave); `SiteContractTests` updated |
|
||||
| Data | `HeroDbContext` with `Heroes`, `HeroSlides`, `HeroImages`, `HeroRetiredFiles`; migration `InitialCreate` generated with the EF tools; slides restrict deletion of an image in use; variants stored as a JSON list |
|
||||
| Rules | `HeroSaveRequest.Validate` (title 200 characters and 5 lines, tagline 120, lead 600, display, 0 to 2 buttons both-or-neither with label 50 and target 500, schedule order, slides with an image and alt text or the decorative flag; no administrator limit on slides), `ButtonTargetValidator` (anchor, path or https only), `HeroText.Clean` (plain text, control characters and U+2028/9 removed) |
|
||||
| Services | `HeroService` (whole-hero save in one transaction, stable slide ids, cache invalidation), `PublicHeroService` + `HeroMapping` (live when switched on, inside the schedule and with a title; only active slides with an image and alt text or decorative; ordered; safety ceiling `Hero:MaxPublishedSlides` 50; `src` is the largest wide WebP), `HeroImageService` (upload: guard, SHA-256 identity so the same photo is one image, metadata removed from the stored original, all variants cut around the focus, atomic set write; focus change: new set and addresses, old set retired; delete refused while in use; room check on size and free space), `HeroMediaCleanup` + `HeroMediaCleanupService` (daily: unused images, retired files after 7 days unless used again, unknown old sets) |
|
||||
| API | `GET /api/v1/hero` (anonymous, public-site endpoint, `hero-public` limit, 204 when none, `max-age=60`), `GET /hero/all` and `PUT /hero` (AdminOnly), `POST /hero/images` (multipart, 12 MB body limit, `hero-upload` per user, rejection codes mapped to 400, 413, 429, 503), `PUT /hero/images/{id}/focus`, `DELETE /hero/images/{id}` (409 while in use) |
|
||||
| Texts | `HeroTexts` and `Texts/nl.json`, `en.json` (validation, rejection and storage messages), audited by `TextAudit` |
|
||||
| Registration | `HeroModule` adds the DbContext, texts, options, `AddCmsMediaArea("hero")`, `AddMagickImageProcessor`, services and the clean-up service; runs its migration at start-up |
|
||||
| Tests | validators and rules (including property tests for the target validator and text cleaning), mapping (schedule matrix, ceiling, decorative, order, focus per ratio, JSON shape), the image service on the real library and a temporary media directory (variants, no upscaling, metadata, duplicates, focus cuts the chosen side, retire, delete rules, refused and truncated uploads store nothing, full storage), the service (create, replace keeping slide ids, reorder, decorative and inactive, bad references, plain text, text-only hero with two buttons, schedule by clock, ceiling), the clean-up (retention, reuse, unattached, in use, unknown sets) and, on the master host with MariaDB, capabilities, 204, authorisation of all management routes, 404 of the media endpoint and migration-matches-model |
|
||||
| OpenAPI | `openapi/slpsoftware.v1.json` regenerated (new Hero paths and schemas) |
|
||||
| Publish | a self-contained win-x64 publish of the ASF host contains only `Magick.Native-Q8-x64.dll` and the Hero assemblies |
|
||||
|
||||
## Notes
|
||||
|
||||
- A hero without slides is valid and live (the SLS hero is text only); the HTML region for ASF is empty without a usable slide (their rule), so the baked hero stays.
|
||||
- `Media:Directory` is not committed anywhere; each host sets it in its environment (see the infrastructure design).
|
||||
- Not yet: the HTML injection and the data block (H4), the admin screens (H5), the seed, docs and smoke test (H6).
|
||||
@@ -506,6 +506,40 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"FocusDto": {
|
||||
"properties": {
|
||||
"x": {
|
||||
"format": "double",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
|
||||
"type": [
|
||||
"number",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"y": {
|
||||
"format": "double",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
|
||||
"type": [
|
||||
"number",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"zoom": {
|
||||
"format": "double",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
|
||||
"type": [
|
||||
"number",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"x",
|
||||
"y",
|
||||
"zoom"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ForgotPasswordRequest": {
|
||||
"properties": {
|
||||
"email": {
|
||||
@@ -517,6 +551,421 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroAdminDto": {
|
||||
"properties": {
|
||||
"buttons": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroButtonDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"display": {
|
||||
"type": "string"
|
||||
},
|
||||
"endsAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"isActive": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"isLive": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"lead": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"maxPublishedSlides": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"slides": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroSlideAdminDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"startsAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"tagline": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"title",
|
||||
"tagline",
|
||||
"lead",
|
||||
"display",
|
||||
"buttons",
|
||||
"isActive",
|
||||
"startsAt",
|
||||
"endsAt",
|
||||
"slides",
|
||||
"isLive",
|
||||
"updatedAt",
|
||||
"maxPublishedSlides"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroButtonDto": {
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"target": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"target"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroButtonRequest": {
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"target": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"target"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroFocusRequest": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"tall": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wide": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"focus"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroImageDto": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"height": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"src": {
|
||||
"type": "string"
|
||||
},
|
||||
"tallFocus": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"variants": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroVariantDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"wideFocus": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"width": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"width",
|
||||
"height",
|
||||
"focus",
|
||||
"wideFocus",
|
||||
"tallFocus",
|
||||
"src",
|
||||
"variants"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroSaveRequest": {
|
||||
"properties": {
|
||||
"buttons": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroButtonRequest"
|
||||
},
|
||||
"type": [
|
||||
"null",
|
||||
"array"
|
||||
]
|
||||
},
|
||||
"display": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"endsAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"isActive": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"lead": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"slides": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroSlideRequest"
|
||||
},
|
||||
"type": [
|
||||
"null",
|
||||
"array"
|
||||
]
|
||||
},
|
||||
"startsAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"tagline": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"title": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"title",
|
||||
"tagline",
|
||||
"lead",
|
||||
"display",
|
||||
"buttons",
|
||||
"isActive",
|
||||
"startsAt",
|
||||
"endsAt",
|
||||
"slides"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroSlideAdminDto": {
|
||||
"properties": {
|
||||
"alt": {
|
||||
"type": "string"
|
||||
},
|
||||
"decorative": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"image": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
},
|
||||
"imageId": {
|
||||
"type": "string"
|
||||
},
|
||||
"isActive": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sortOrder": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"imageId",
|
||||
"alt",
|
||||
"decorative",
|
||||
"isActive",
|
||||
"sortOrder",
|
||||
"image"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroSlideRequest": {
|
||||
"properties": {
|
||||
"alt": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"decorative": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"format": "uuid",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"imageId": {
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
},
|
||||
"isActive": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"imageId",
|
||||
"alt"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroVariantDto": {
|
||||
"properties": {
|
||||
"height": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"ratio": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"width": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ratio",
|
||||
"width",
|
||||
"height",
|
||||
"type",
|
||||
"url"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"IFormFile": {
|
||||
"format": "binary",
|
||||
"type": "string"
|
||||
},
|
||||
"InviteUserRequest": {
|
||||
"properties": {
|
||||
"email": {
|
||||
@@ -667,6 +1116,121 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"PublicHeroDto": {
|
||||
"properties": {
|
||||
"buttons": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroButtonDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"display": {
|
||||
"type": "string"
|
||||
},
|
||||
"lead": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"slides": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PublicSlideDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"tagline": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"display",
|
||||
"title",
|
||||
"tagline",
|
||||
"lead",
|
||||
"buttons",
|
||||
"slides"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"PublicImageDto": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"focusByRatio": {
|
||||
"additionalProperties": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"type": [
|
||||
"null",
|
||||
"object"
|
||||
]
|
||||
},
|
||||
"height": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"src": {
|
||||
"type": "string"
|
||||
},
|
||||
"variants": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroVariantDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"width": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"width",
|
||||
"height",
|
||||
"focus",
|
||||
"src",
|
||||
"variants"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"PublicSlideDto": {
|
||||
"properties": {
|
||||
"alt": {
|
||||
"type": "string"
|
||||
},
|
||||
"decorative": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"image": {
|
||||
"$ref": "#/components/schemas/PublicImageDto"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"alt",
|
||||
"decorative",
|
||||
"image"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"PushStatusRequest": {
|
||||
"properties": {
|
||||
"disableMessage": {
|
||||
@@ -2266,6 +2830,281 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PublicHeroDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PublicHeroDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PublicHeroDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
},
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"Hero"
|
||||
]
|
||||
},
|
||||
"put": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroSaveRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroSaveRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroSaveRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Bad Request"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"Hero"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/all": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroAdminDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"Hero"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/images": {
|
||||
"post": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"multipart/form-data": {
|
||||
"schema": {
|
||||
"properties": {
|
||||
"file": {
|
||||
"$ref": "#/components/schemas/IFormFile"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"201": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Created"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"HeroImages"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/images/{id}": {
|
||||
"delete": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
},
|
||||
"409": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Conflict"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"HeroImages"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/images/{id}/focus": {
|
||||
"put": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"HeroImages"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/offerings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -2685,6 +3524,12 @@
|
||||
{
|
||||
"name": "ContactSettings"
|
||||
},
|
||||
{
|
||||
"name": "Hero"
|
||||
},
|
||||
{
|
||||
"name": "HeroImages"
|
||||
},
|
||||
{
|
||||
"name": "Auth"
|
||||
},
|
||||
|
||||
+1
@@ -30,6 +30,7 @@
|
||||
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Net;
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>The Hero module on the real master host and the real, migrated database.</summary>
|
||||
public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
|
||||
{
|
||||
private readonly ApiWebApplicationFactory _factory;
|
||||
|
||||
public HeroOnTheMasterHostTests(ApiWebApplicationFactory factory) => _factory = factory;
|
||||
|
||||
[Fact]
|
||||
public async Task Capabilities_ListTheHeroModule()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities");
|
||||
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).Should().Contain("Hero");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAHero_ThePublicEndpointAnswers204_WithTheShortCache()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/hero");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
|
||||
response.Headers.CacheControl!.ToString().Should().Be("public, max-age=60");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", "/api/v1/hero/all")]
|
||||
[InlineData("PUT", "/api/v1/hero")]
|
||||
[InlineData("POST", "/api/v1/hero/images")]
|
||||
[InlineData("DELETE", "/api/v1/hero/images/11111111-2222-3333-4444-555555555555")]
|
||||
[InlineData("PUT", "/api/v1/hero/images/11111111-2222-3333-4444-555555555555/focus")]
|
||||
public async Task Management_RequiresAnAdministrator(string method, string url)
|
||||
{
|
||||
var request = new HttpRequestMessage(new HttpMethod(method), url);
|
||||
if (method == "POST")
|
||||
{
|
||||
request.Content = new MultipartFormDataContent { { new ByteArrayContent([1, 2, 3]), "file", "x.jpg" } };
|
||||
}
|
||||
|
||||
var response = await _factory.CreateClient().SendAsync(request);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/media/hero/0123456789abcdef/wide-960.webp")]
|
||||
[InlineData("/media/hero/0123456789abcdef/../../secret")]
|
||||
[InlineData("/media/originals/anything.jpg")]
|
||||
public async Task TheMediaEndpoint_AnswersAPlain404_ForAnythingNotStored(string url)
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync(url);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HeroMigrations_MatchTheModel()
|
||||
{
|
||||
_ = _factory.CreateClient(); // starts the host and migrates
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HeroDbContext>();
|
||||
|
||||
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot");
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public class SiteContractTests
|
||||
public void TheMasterCms_ReferencesEveryModule()
|
||||
{
|
||||
SiteFiles.Modules("SlpModularCms.Api").Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Master", "Offerings"],
|
||||
["Availability", "Contact", "Hero", "Identity", "Master", "Offerings"],
|
||||
"the master Api is the all-modules composition the CI builds and tests");
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public class SiteContractTests
|
||||
public void SlpSoftware_IsTheFullComposition()
|
||||
{
|
||||
SiteFiles.Modules(SiteFiles.SlpSoftware).Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Master", "Offerings"]);
|
||||
["Availability", "Contact", "Hero", "Identity", "Master", "Offerings"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -37,7 +37,7 @@ public class SiteContractTests
|
||||
{
|
||||
// Not a master/slave setup: no Master module, so /System/capabilities does not list it.
|
||||
SiteFiles.Modules(SiteFiles.AndreaSlopFotografie).Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Offerings"]);
|
||||
["Availability", "Contact", "Hero", "Identity", "Offerings"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroTextsTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheTextFiles_MatchTheDeclaredKeys_InDutchAndEnglish()
|
||||
=> SlpModularCms.Core.Texts.TextAudit.Verify(typeof(HeroTexts).Assembly, SlpModularCms.Core.Texts.TextAudit.KeysOf(typeof(HeroTexts)), "nl", "en").Should().BeEmpty();
|
||||
}
|
||||
|
||||
public class ButtonTargetValidatorTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("#contact", ButtonTargetKind.Anchor)]
|
||||
[InlineData("#pakketten", ButtonTargetKind.Anchor)]
|
||||
[InlineData("#a-b_c9", ButtonTargetKind.Anchor)]
|
||||
[InlineData("/over-mij", ButtonTargetKind.Path)]
|
||||
[InlineData("/", ButtonTargetKind.Path)]
|
||||
[InlineData("/a/b/c?x=1&y=2", ButtonTargetKind.Path)]
|
||||
[InlineData("https://andreaslop.nl/portfolio", ButtonTargetKind.Https)]
|
||||
[InlineData("https://sub.example.com:8443/p?q=1#top", ButtonTargetKind.Https)]
|
||||
public void AcceptedTargets(string target, ButtonTargetKind kind) => ButtonTargetValidator.Validate(target).Should().Be(kind);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("contact")]
|
||||
[InlineData("#")]
|
||||
[InlineData("#1abc")]
|
||||
[InlineData("# contact")]
|
||||
[InlineData("#a b")]
|
||||
[InlineData("//evil.example/x")]
|
||||
[InlineData("/\\evil.example")]
|
||||
[InlineData("/a b")]
|
||||
[InlineData("http://example.com")]
|
||||
[InlineData("HTTPS://example.com")]
|
||||
[InlineData("https://user:pw@example.com")]
|
||||
[InlineData("https://")]
|
||||
[InlineData("https:///path")]
|
||||
[InlineData("javascript:alert(1)")]
|
||||
[InlineData("JaVaScRiPt:alert(1)")]
|
||||
[InlineData("data:text/html;base64,AAAA")]
|
||||
[InlineData("mailto:a@b.nl")]
|
||||
[InlineData("tel:+31612345678")]
|
||||
[InlineData("ftp://example.com/x")]
|
||||
[InlineData("/ok\"onmouseover=\"x")]
|
||||
[InlineData("/ok<script>")]
|
||||
[InlineData(" /leading-space")]
|
||||
[InlineData("/trailing-space ")]
|
||||
[InlineData("/tab\tx")]
|
||||
[InlineData("/new\nline")]
|
||||
public void RejectedTargets(string target) => ButtonTargetValidator.Validate(target).Should().Be(ButtonTargetKind.Invalid);
|
||||
|
||||
[Fact]
|
||||
public void Null_IsInvalid() => ButtonTargetValidator.Validate(null).Should().Be(ButtonTargetKind.Invalid);
|
||||
|
||||
[Fact]
|
||||
public void WhateverIsAccepted_IsOneOfTheThreeSafeForms()
|
||||
=> Prop.ForAll(Gen.Elements("a", "#", "/", ":", "\\", " ", "\"", "<", ">", "h", "t", "p", "s", "x", ".", "-", "1", "\n", "\t", "%").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), text =>
|
||||
{
|
||||
var kind = ButtonTargetValidator.Validate(text);
|
||||
if (kind != ButtonTargetKind.Invalid)
|
||||
{
|
||||
text.Should().NotMatchRegex("[\\s\\\\\"<>`]");
|
||||
(text.StartsWith('#') || (text.StartsWith('/') && !text.StartsWith("//")) || text.StartsWith("https://")).Should().BeTrue();
|
||||
}
|
||||
|
||||
return true;
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(3000));
|
||||
}
|
||||
|
||||
public class HeroSaveRequestValidationTests
|
||||
{
|
||||
private static HeroSaveRequest Valid() => new(
|
||||
"Websites,\napps\n& meer.", null, "Een lead.", "single",
|
||||
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")],
|
||||
true, null, null, []);
|
||||
|
||||
private static List<ValidationResult> Run(HeroSaveRequest request)
|
||||
{
|
||||
var results = new List<ValidationResult>();
|
||||
Validator.TryValidateObject(request, new ValidationContext(request), results, validateAllProperties: true);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static string[] Members(List<ValidationResult> results) => results.SelectMany(r => r.MemberNames).ToArray();
|
||||
|
||||
[Fact]
|
||||
public void AValidHero_HasNoErrors() => Run(Valid()).Should().BeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void TheTitle_IsRequired_AndBounded()
|
||||
{
|
||||
Members(Run(Valid() with { Title = " " })).Should().Contain("Title");
|
||||
Members(Run(Valid() with { Title = new string('x', 201) })).Should().Contain("Title");
|
||||
Members(Run(Valid() with { Title = "a\nb\nc\nd\ne\nf" })).Should().Contain("Title");
|
||||
Run(Valid() with { Title = "a\nb\nc\nd\ne" }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOtherTexts_AreBounded()
|
||||
{
|
||||
Members(Run(Valid() with { Tagline = new string('t', 121) })).Should().Contain("Tagline");
|
||||
Members(Run(Valid() with { Lead = new string('l', 601) })).Should().Contain("Lead");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("single", true)]
|
||||
[InlineData("slideshow", true)]
|
||||
[InlineData(null, true)]
|
||||
[InlineData("carousel", false)]
|
||||
[InlineData("SINGLE", false)]
|
||||
public void TheDisplay_IsOneOfTheTwo(string? display, bool valid)
|
||||
=> Run(Valid() with { Display = display }).Any(r => r.MemberNames.Contains("Display")).Should().Be(!valid);
|
||||
|
||||
[Fact]
|
||||
public void Buttons_AreLimitedAndChecked()
|
||||
{
|
||||
var three = new[] { new HeroButtonRequest("a", "#a"), new HeroButtonRequest("b", "#b"), new HeroButtonRequest("c", "#c") };
|
||||
Members(Run(Valid() with { Buttons = three })).Should().Contain("Buttons");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest("Lees meer", null)] })).Should().Contain("Buttons[0]");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest(null, "/x")] })).Should().Contain("Buttons[0]");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest("x", "javascript:alert(1)")] })).Should().Contain("Buttons[0].Target");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest(new string('l', 51), "/x")] })).Should().Contain("Buttons[0].Label");
|
||||
Run(Valid() with { Buttons = [new HeroButtonRequest("", ""), new HeroButtonRequest(null, null)] }).Should().BeEmpty("empty buttons are ignored");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSchedule_MustRunForward()
|
||||
{
|
||||
var t = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
Members(Run(Valid() with { StartsAt = t, EndsAt = t })).Should().Contain("EndsAt");
|
||||
Members(Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(-1) })).Should().Contain("EndsAt");
|
||||
Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(1) }).Should().BeEmpty();
|
||||
Run(Valid() with { StartsAt = null, EndsAt = t }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASlide_NeedsAnImage_AndAnAltTextOrTheDecorativeFlag()
|
||||
{
|
||||
var image = Guid.NewGuid();
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, Guid.Empty, "alt")] })).Should().Contain("Slides[0].ImageId");
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, image, " ")] })).Should().Contain("Slides[0].Alt");
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, image, new string('a', 301))] })).Should().Contain("Slides[0].Alt");
|
||||
Run(Valid() with { Slides = [new HeroSlideRequest(null, image, null, Decorative: true)] }).Should().BeEmpty();
|
||||
Run(Valid() with { Slides = [new HeroSlideRequest(null, image, "Een foto")] }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThereIsNoAdministratorLimitOnTheNumberOfSlides()
|
||||
{
|
||||
var slides = Enumerable.Range(0, 120).Select(_ => new HeroSlideRequest(null, Guid.NewGuid(), "foto")).ToList();
|
||||
|
||||
Run(Valid() with { Slides = slides }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FocusValues_AreChecked()
|
||||
{
|
||||
var ok = new FocusDto(0.5, 0.5, 1);
|
||||
void Check(HeroFocusRequest r, bool valid)
|
||||
{
|
||||
var results = new List<ValidationResult>();
|
||||
Validator.TryValidateObject(r, new ValidationContext(r), results, true);
|
||||
results.Any().Should().Be(!valid);
|
||||
}
|
||||
|
||||
Check(new HeroFocusRequest(ok), true);
|
||||
Check(new HeroFocusRequest(ok, new FocusDto(0.2, 0.9, 2.5), new FocusDto(1, 0, 4)), true);
|
||||
Check(new HeroFocusRequest(new FocusDto(-0.1, 0.5, 1)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 1.1, 1)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 0.5, 0.5)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 0.5, 4.5)), false);
|
||||
Check(new HeroFocusRequest(ok, new FocusDto(double.NaN, 0.5, 1)), false);
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroTextCleanTests
|
||||
{
|
||||
[Fact]
|
||||
public void LineBreaksAreNormalised_AndControlCharactersRemoved()
|
||||
{
|
||||
HeroText.Clean("a\r\nb\rc\u0007d", keepLineBreaks: true).Should().Be("a\nb\ncd");
|
||||
HeroText.Clean("a\nb", keepLineBreaks: false).Should().Be("a b");
|
||||
HeroText.Clean(" x ", keepLineBreaks: false).Should().Be("x");
|
||||
HeroText.Clean(null, keepLineBreaks: true).Should().BeEmpty();
|
||||
HeroText.Clean("a\u2028b\u2029c", keepLineBreaks: true).Should().Be("abc");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HtmlStaysAsTypedText()
|
||||
=> HeroText.Clean("<b>Hallo</b> & \"dag\"", keepLineBreaks: false).Should().Be("<b>Hallo</b> & \"dag\"");
|
||||
|
||||
[Fact]
|
||||
public void CleaningIsIdempotent()
|
||||
=> Prop.ForAll(Gen.Elements("a", " ", "\n", "\r", "\t", "<", "&", "\u0007", "\u2028", "é", "x").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), text =>
|
||||
{
|
||||
var once = HeroText.Clean(text, keepLineBreaks: true);
|
||||
HeroText.Clean(once, keepLineBreaks: true).Should().Be(once);
|
||||
return true;
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
|
||||
}
|
||||
|
||||
public class HeroMappingTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static HeroImage Image(Guid? id = null, string set = "0123456789abcdef", string? wideFocus = null)
|
||||
{
|
||||
var image = new HeroImage
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
SetHash = set,
|
||||
Width = 1600,
|
||||
Height = 1067,
|
||||
Variants =
|
||||
[
|
||||
new HeroVariant("wide", 960, 640, "image/webp", "wide-960.webp", 10),
|
||||
new HeroVariant("wide", 1600, 1067, "image/webp", "wide-1600.webp", 20),
|
||||
new HeroVariant("wide", 1600, 1067, "image/avif", "wide-1600.avif", 15),
|
||||
new HeroVariant("tall", 640, 800, "image/webp", "tall-640.webp", 8),
|
||||
],
|
||||
};
|
||||
if (wideFocus is not null)
|
||||
{
|
||||
image.WideFocusX = 0.2;
|
||||
image.WideFocusY = 0.3;
|
||||
image.WideZoom = 2;
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
private static HeroSlide Slide(int order, bool active = true, string alt = "Een foto", bool decorative = false, HeroImage? image = null)
|
||||
=> new() { Id = Guid.NewGuid(), SortOrder = order, IsActive = active, Alt = alt, Decorative = decorative, Image = image ?? Image(), ImageId = (image ?? Image()).Id };
|
||||
|
||||
private static HeroContent Hero(params HeroSlide[] slides) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Title = "Andrea Slop",
|
||||
Tagline = "Lifestyle fotograaf",
|
||||
Display = "slideshow",
|
||||
Button1Label = "Lees meer",
|
||||
Button1Target = "/over-mij",
|
||||
Slides = [.. slides],
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void ALiveHero_IsPublished_WithItsSlidesInOrder()
|
||||
{
|
||||
var hero = Hero(Slide(2, alt: "derde"), Slide(0, alt: "eerste"), Slide(1, alt: "tweede"));
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Select(s => s.Alt).Should().Equal("eerste", "tweede", "derde");
|
||||
pub.Buttons.Should().ContainSingle().Which.Should().Be(new HeroButtonDto("Lees meer", "/over-mij"));
|
||||
pub.Display.Should().Be("slideshow");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSrc_IsTheLargestWideWebP_AndAllVariantsAreListedWithMediaAddresses()
|
||||
{
|
||||
var pub = HeroMapping.ToPublic(Hero(Slide(0)), Now, 50)!;
|
||||
|
||||
var image = pub.Slides[0].Image;
|
||||
image.Src.Should().Be("/media/hero/0123456789abcdef/wide-1600.webp");
|
||||
image.Variants.Should().HaveCount(4);
|
||||
image.Variants.Should().OnlyContain(v => v.Url.StartsWith("/media/hero/0123456789abcdef/"));
|
||||
image.Width.Should().Be(1600);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhenNothingIsWide_TheSrcFallsBackToTheLargestWebP()
|
||||
{
|
||||
var image = Image();
|
||||
image.Variants = [new HeroVariant("tall", 640, 800, "image/webp", "tall-640.webp", 8), new HeroVariant("tall", 960, 1200, "image/webp", "tall-960.webp", 9)];
|
||||
|
||||
HeroMapping.SrcFor(image).Should().EndWith("tall-960.webp");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADecorativeSlide_HasNoAlt_AndAnInactiveOrEmptyOneIsLeftOut()
|
||||
{
|
||||
var hero = Hero(
|
||||
Slide(0, decorative: true, alt: "ignored"),
|
||||
Slide(1, active: false),
|
||||
Slide(2, alt: " "),
|
||||
new HeroSlide { Id = Guid.NewGuid(), SortOrder = 3, Alt = "x", Image = new HeroImage { SetHash = "0123456789abcdef" }, ImageId = Guid.NewGuid() });
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Should().ContainSingle().Which.Should().Match<PublicSlideDto>(s => s.Decorative && s.Alt == "");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASafetyCeiling_LimitsThePublishedSlides_NotTheSavedOnes()
|
||||
{
|
||||
var hero = Hero(Enumerable.Range(0, 80).Select(i => Slide(i)).ToArray());
|
||||
|
||||
HeroMapping.ToPublic(hero, Now, 50)!.Slides.Should().HaveCount(50);
|
||||
HeroMapping.ToPublic(hero, Now, 50)!.Slides.Select(s => s.Id).Should().Equal(hero.Slides.OrderBy(s => s.SortOrder).Take(50).Select(s => s.Id.ToString()));
|
||||
hero.Slides.Should().HaveCount(80);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, null, null, true)]
|
||||
[InlineData(false, null, null, false)]
|
||||
[InlineData(true, "2026-11-17", null, false)]
|
||||
[InlineData(true, "2026-11-16T12:00:00Z", null, true)]
|
||||
[InlineData(true, null, "2026-11-16T12:00:00Z", false)]
|
||||
[InlineData(true, null, "2026-11-16T12:00:01Z", true)]
|
||||
[InlineData(true, "2026-11-01", "2026-12-01", true)]
|
||||
public void TheScheduleAndTheSwitch_DecideWhetherItIsLive(bool active, string? start, string? end, bool live)
|
||||
{
|
||||
var hero = Hero(Slide(0));
|
||||
hero.IsActive = active;
|
||||
hero.StartsAt = start is null ? null : DateTimeOffset.Parse(start, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
|
||||
hero.EndsAt = end is null ? null : DateTimeOffset.Parse(end, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
|
||||
|
||||
(HeroMapping.ToPublic(hero, Now, 50) is not null).Should().Be(live);
|
||||
HeroMapping.ToAdmin(hero, Now, 50).IsLive.Should().Be(live);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHeroWithoutATitle_IsNotPublished()
|
||||
{
|
||||
var hero = Hero(Slide(0));
|
||||
hero.Title = " ";
|
||||
|
||||
HeroMapping.ToPublic(hero, Now, 50).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHeroWithoutSlides_IsPublished_ForSitesThatShowOnlyText()
|
||||
{
|
||||
var hero = Hero();
|
||||
hero.Button1Label = "Bekijk pakketten";
|
||||
hero.Button1Target = "#pakketten";
|
||||
hero.Button2Label = "Plan een gesprek";
|
||||
hero.Button2Target = "#contact";
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Should().BeEmpty();
|
||||
pub.Buttons.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FocusPerRatio_IsOnlyInTheDataWhenSet()
|
||||
{
|
||||
var plain = HeroMapping.ToPublic(Hero(Slide(0)), Now, 50)!.Slides[0].Image;
|
||||
var withWide = HeroMapping.ToPublic(Hero(Slide(0, image: Image(wideFocus: "x"))), Now, 50)!.Slides[0].Image;
|
||||
|
||||
plain.FocusByRatio.Should().BeNull();
|
||||
plain.Focus.Should().Be(new FocusDto(0.5, 0.5, 1));
|
||||
withWide.FocusByRatio!["wide"].Should().Be(new FocusDto(0.2, 0.3, 2));
|
||||
withWide.FocusByRatio.Should().NotContainKey("tall");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheJson_DoesNotCarryTheScheduleOrSwitches_AndOmitsAnAbsentFocusByRatio()
|
||||
{
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(HeroMapping.ToPublic(Hero(Slide(0)), Now, 50), new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web));
|
||||
|
||||
json.Should().NotContain("startsAt").And.NotContain("endsAt").And.NotContain("isActive").And.NotContain("focusByRatio");
|
||||
json.Should().Contain("\"title\":\"Andrea Slop\"").And.Contain("\"lead\":null");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAdminView_ListsInactiveSlidesAndTheCeiling()
|
||||
{
|
||||
var hero = Hero(Slide(0), Slide(1, active: false));
|
||||
|
||||
var admin = HeroMapping.ToAdmin(hero, Now, 50);
|
||||
|
||||
admin.Slides.Should().HaveCount(2);
|
||||
admin.MaxPublishedSlides.Should().Be(50);
|
||||
HeroMapping.ToAdmin(null, Now, 50).Should().Match<HeroAdminDto>(d => d.Id == null && !d.IsLive && d.Slides.Count == 0 && d.Display == "single");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
using FluentAssertions;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroImageServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AnUpload_IsProcessedIntoVariantsOfBothRatios_AndStored()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
(image.Width, image.Height).Should().Be((1600, 1067));
|
||||
image.Variants.Select(v => v.Ratio).Distinct().Should().BeEquivalentTo("wide", "tall");
|
||||
image.Variants.Should().Contain(v => v.Type == "image/webp" && v.Ratio == "wide" && v.Width == 1600);
|
||||
image.Variants.Should().OnlyContain(v => v.Width <= 1600, "an image is never scaled up");
|
||||
image.Src.Should().Be(image.Variants.Single(v => v.Ratio == "wide" && v.Width == 1600 && v.Type == "image/webp").Url);
|
||||
|
||||
foreach (var variant in image.Variants)
|
||||
{
|
||||
var key = variant.Url["/media/".Length..];
|
||||
(await rig.Store.ExistsAsync(key, CancellationToken.None)).Should().BeTrue(key);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOriginal_IsKeptWithoutMetadata_AndNotPublic()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
var stored = (await rig.Db.HeroImages.FindAsync(Guid.Parse((await rig.Repository.GetImageBySha256Async(rig.Db.HeroImages.Single().OriginalSha256, default))!.Id.ToString())))!;
|
||||
stored.OriginalKey.Should().StartWith("originals/");
|
||||
await using var file = (await rig.Store.OpenReadAsync(stored.OriginalKey, CancellationToken.None))!.Content;
|
||||
var bytes = new MemoryStream();
|
||||
await file.CopyToAsync(bytes);
|
||||
using var back = new ImageMagick.MagickImage();
|
||||
back.Ping(bytes.ToArray());
|
||||
back.GetExifProfile().Should().BeNull("the camera tag was removed from the stored original");
|
||||
SlpModularCms.Core.Media.MediaPaths.TryParse(stored.OriginalKey, out _).Should().BeFalse("originals are never an address");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSamePhotoTwice_IsOneImage()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
|
||||
var first = await rig.Upload(photo);
|
||||
var second = await rig.Upload(photo);
|
||||
|
||||
second.Id.Should().Be(first.Id);
|
||||
rig.Db.HeroImages.Count().Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADefaultFocus_IsTheCentre_ForEveryRatio()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
image.Focus.Should().Be(new FocusDto(0.5, 0.5, 1));
|
||||
image.WideFocus.Should().BeNull();
|
||||
image.TallFocus.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangingTheFocus_CutsNewVariants_AtNewAddresses_AndRetiresTheOldSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var oldSet = rig.Db.HeroImages.Single().SetHash;
|
||||
|
||||
var changed = await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var newSet = rig.Db.HeroImages.Single().SetHash;
|
||||
newSet.Should().NotBe(oldSet);
|
||||
changed.Variants.Should().OnlyContain(v => v.Url.Contains(newSet));
|
||||
changed.TallFocus.Should().Be(new FocusDto(1.0, 0.5, 1));
|
||||
changed.WideFocus.Should().BeNull();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(s => s.SetHash).Should().BeEquivalentTo(oldSet, newSet);
|
||||
rig.Db.HeroRetiredFiles.Should().ContainSingle(f => f.Kind == "set" && f.Key == oldSet);
|
||||
rig.IndexCache.Received().Invalidate();
|
||||
|
||||
// The tall variant now shows the right (blue) side of the photo.
|
||||
var tall = changed.Variants.First(v => v.Ratio == "tall" && v.Type == "image/webp");
|
||||
await using var file = (await rig.Store.OpenReadAsync(tall.Url["/media/".Length..], CancellationToken.None))!.Content;
|
||||
var bytes = new MemoryStream();
|
||||
await file.CopyToAsync(bytes);
|
||||
using var pixels = new ImageMagick.MagickImage(bytes.ToArray());
|
||||
pixels.GetPixels().GetPixel((int)(pixels.Width / 2), (int)(pixels.Height / 2)).ToColor()!.ToString().Should().StartWith("#0000FF");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSameFocus_DoesNotMakeANewSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResettingARatioToTheGeneralPoint_ReturnsToTheSameSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var original = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(0.9, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(original);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADeletedImage_IsRefused_WhileASlideUsesIt_AndRetiredOtherwise()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var inUse = async () => await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
await inUse.Should().ThrowAsync<HeroImageInUseException>();
|
||||
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, []), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
rig.Db.HeroRetiredFiles.Select(f => f.Kind).Should().BeEquivalentTo("set", "original");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnknownImage_IsNotFound()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var focus = async () => await rig.Images.SetFocusAsync(Guid.NewGuid(), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
var delete = async () => await rig.Images.DeleteAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await focus.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
await delete.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>", "unsupported_format")]
|
||||
[InlineData("not an image at all", "unsupported_format")]
|
||||
public async Task ARefusedUpload_StoresNothing(string text, string code)
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
|
||||
|
||||
var act = async () => await rig.Upload(bytes);
|
||||
|
||||
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be(code);
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATruncatedPhoto_StoresNothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
|
||||
var act = async () => await rig.Upload(photo.AsMemory(0, photo.Length / 4).ToArray());
|
||||
|
||||
await act.Should().ThrowAsync<ImageRejectedException>();
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheMediaStorageIsFull_TheUploadIsRefused_AndNothingIsStored()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.MaxTotalBytes = 1000;
|
||||
|
||||
var act = async () => await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await act.Should().ThrowAsync<MediaStorageFullException>();
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APhoto_ThatIsTallerThanItIsWide_GetsSensibleVariants()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo(width: 800, height: 1200, seed: 1));
|
||||
|
||||
image.Variants.Where(v => v.Ratio == "wide").Should().OnlyContain(v => v.Width <= 800);
|
||||
image.Variants.Where(v => v.Ratio == "tall").Should().OnlyContain(v => v.Width <= 800);
|
||||
image.Variants.Should().NotBeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroServiceTests
|
||||
{
|
||||
private static HeroSaveRequest Request(IReadOnlyList<HeroSlideRequest>? slides = null, string title = "Andrea Slop") => new(
|
||||
title, "Lifestyle fotograaf", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null, slides ?? []);
|
||||
|
||||
[Fact]
|
||||
public async Task TheFirstSave_CreatesTheHero_WithItsSlidesInOrder()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
|
||||
var saved = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede foto"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Id.Should().NotBeNull();
|
||||
saved.Slides.Select(s => s.Alt).Should().Equal("tweede foto", "eerste foto");
|
||||
saved.Slides.Select(s => s.SortOrder).Should().Equal(0, 1);
|
||||
saved.IsLive.Should().BeTrue();
|
||||
rig.IndexCache.Received().Invalidate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASecondSave_ReplacesTheWholeHero_KeepingTheIdsOfTheSlidesItKeeps()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var first = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var keep = Guid.Parse(first.Slides[1].Id);
|
||||
|
||||
var second = await rig.Service.SaveAsync(Request([new HeroSlideRequest(keep, Guid.Parse(b.Id), "twee, aangepast")], "Nieuwe titel"), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
second.Id.Should().Be(first.Id);
|
||||
second.Title.Should().Be("Nieuwe titel");
|
||||
second.Slides.Should().ContainSingle().Which.Should().Match<HeroSlideAdminDto>(s => s.Id == keep.ToString() && s.Alt == "twee, aangepast" && s.SortOrder == 0);
|
||||
rig.Db.HeroSlides.Count().Should().Be(1);
|
||||
rig.Db.Heroes.Count().Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderingSlides_ChangesTheirOrder_NotTheirIds()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var first = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var ids = first.Slides.Select(s => Guid.Parse(s.Id)).ToArray();
|
||||
|
||||
var second = await rig.Service.SaveAsync(Request([new HeroSlideRequest(ids[1], Guid.Parse(b.Id), "twee"), new HeroSlideRequest(ids[0], Guid.Parse(a.Id), "een")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
second.Slides.Select(s => s.Id).Should().Equal(ids[1].ToString(), ids[0].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADecorativeSlide_StoresNoAlt_AndAnInactiveOneIsKept_ButNotPublished()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "wordt genegeerd", Decorative: true), new HeroSlideRequest(null, Guid.Parse(b.Id), "uit", IsActive: false)]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
var pub = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
|
||||
admin.Slides.Should().HaveCount(2);
|
||||
admin.Slides[0].Alt.Should().BeEmpty();
|
||||
pub.Slides.Should().ContainSingle().Which.Decorative.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnknownImage_OrASlideOfAnotherHero_IsRejected()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
var unknownImage = async () => await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.NewGuid(), "x")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var unknownSlide = async () => await rig.Service.SaveAsync(Request([new HeroSlideRequest(Guid.NewGuid(), Guid.Parse(a.Id), "x")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await unknownImage.Should().ThrowAsync<HeroSaveRejectedException>()).Which.Field.Should().Be("Slides[0].ImageId");
|
||||
(await unknownSlide.Should().ThrowAsync<HeroSaveRejectedException>()).Which.Field.Should().Be("Slides[0].Id");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheTexts_AreStoredAsPlainText_WithoutControlCharacters()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var saved = await rig.Service.SaveAsync(
|
||||
new HeroSaveRequest("Websites,\r\napps\u0007\n& meer.", " <b>tag</b> ", "lead\nregel twee", "single", [new HeroButtonRequest(" Knop ", " #contact ")], true, null, null, []),
|
||||
HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Title.Should().Be("Websites,\napps\n& meer.");
|
||||
saved.Tagline.Should().Be("<b>tag</b>");
|
||||
saved.Lead.Should().Be("lead\nregel twee");
|
||||
saved.Buttons.Should().ContainSingle().Which.Should().Be(new HeroButtonDto("Knop", "#contact"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASiteWithoutImages_CanHaveATextOnlyHero_WithTwoButtons()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Websites,\napps\n& meer.", null, "Lead.", "single",
|
||||
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")], true, null, null, null), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var pub = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
pub.Title.Should().Be("Websites,\napps\n& meer.");
|
||||
pub.Tagline.Should().BeNull();
|
||||
pub.Buttons.Select(b => b.Target).Should().Equal("#pakketten", "#contact");
|
||||
pub.Slides.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePublicHero_FollowsTheScheduleOfTheClock()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var start = rig.Time.Now.AddDays(1);
|
||||
await rig.Service.SaveAsync(Request() with { StartsAt = start, EndsAt = start.AddDays(7) }, HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
rig.Time.Now = start.AddHours(1);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().NotBeNull();
|
||||
rig.Time.Now = start.AddDays(7);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAHero_TheAdminGetsEmptyDefaults_AndThePublicGetsNothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
|
||||
admin.Id.Should().BeNull();
|
||||
admin.IsLive.Should().BeFalse();
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManySlides_AreSaved_ButOnlyTheCeilingIsPublished()
|
||||
{
|
||||
using var rig = new HeroTestRig(maxPublishedSlides: 3);
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var slides = Enumerable.Range(0, 7).Select(i => new HeroSlideRequest(null, Guid.Parse(image.Id), "foto " + i)).ToList();
|
||||
|
||||
var saved = await rig.Service.SaveAsync(Request(slides), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Slides.Should().HaveCount(7);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides.Should().HaveCount(3);
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroMediaCleanupTests
|
||||
{
|
||||
private static async Task<(string Set, string Original)> RetireAnImage(HeroTestRig rig)
|
||||
{
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var row = rig.Db.HeroImages.Single();
|
||||
var keys = (row.SetHash, row.OriginalKey);
|
||||
await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
return keys;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RetiredFiles_StayForTheRetentionTime_ThenGo()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var (set, original) = await RetireAnImage(rig);
|
||||
|
||||
(await rig.Cleanup.RunOnceAsync(CancellationToken.None)).Should().Be(0);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().ContainSingle(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
(await rig.Cleanup.RunOnceAsync(CancellationToken.None)).Should().Be(2);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARetiredSet_ThatIsUsedAgain_IsNeverDeleted()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
var first = await rig.Upload(photo);
|
||||
var set = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Images.DeleteAsync(Guid.Parse(first.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
// The same photo with the same focus comes back: the same set again, referenced by a new row.
|
||||
var again = await rig.Upload(photo);
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(set);
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(again.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().ContainSingle(s => s.SetHash == set);
|
||||
again.Variants.Should().OnlyContain(v => v.Url.Contains(set));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsRetiredAndRemoved_AfterTheRetentionTime()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageASlideUses_IsNeverRemoved()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(30);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASetNoRowKnows_AndIsOld_IsRemoved_ButARecentOneIsNot()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
await rig.Store.PutSetAsync("hero", "aaaaaaaaaaaaaaaa", new Dictionary<string, byte[]> { ["wide-960.webp"] = [1] }, CancellationToken.None);
|
||||
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
|
||||
rig.Time.Now = DateTimeOffset.UtcNow.AddDays(30);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using ImageMagick;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Magick;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public sealed class TestTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
/// <summary>A hero module over an in-memory database, a temporary media directory and the real image library.</summary>
|
||||
public sealed class HeroTestRig : IDisposable
|
||||
{
|
||||
public static readonly Guid Admin = Guid.Parse("11111111-2222-3333-4444-555555555555");
|
||||
|
||||
public TestTime Time { get; } = new(new DateTimeOffset(2026, 11, 16, 12, 0, 0, TimeSpan.Zero));
|
||||
public string Directory { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-tests-" + Guid.NewGuid().ToString("N"));
|
||||
public MediaOptions Media { get; }
|
||||
public HeroDbContext Db { get; }
|
||||
public IHeroRepository Repository { get; }
|
||||
public FileSystemMediaStore Store { get; }
|
||||
public MagickImageProcessor Processor { get; }
|
||||
public MediaStatus Status { get; } = new();
|
||||
public IIndexHtmlCache IndexCache { get; } = Substitute.For<IIndexHtmlCache>();
|
||||
public HeroImageService Images { get; }
|
||||
public HeroService Service { get; }
|
||||
public PublicHeroService Public { get; }
|
||||
public HeroMediaCleanup Cleanup { get; }
|
||||
public HeroOptions HeroOptions { get; } = new();
|
||||
|
||||
public HeroTestRig(int maxPublishedSlides = 50)
|
||||
{
|
||||
HeroOptions.MaxPublishedSlides = maxPublishedSlides;
|
||||
Media = new MediaOptions { Directory = Directory, BusyWaitSeconds = 0 };
|
||||
var mediaOptions = Options.Create(Media);
|
||||
Db = new HeroDbContext(new DbContextOptionsBuilder<HeroDbContext>().UseInMemoryDatabase("hero-" + Guid.NewGuid()).Options);
|
||||
Repository = new HeroRepository(Db);
|
||||
Store = new FileSystemMediaStore(mediaOptions);
|
||||
Processor = new MagickImageProcessor(mediaOptions, NullLogger<MagickImageProcessor>.Instance);
|
||||
Status.SetProcessor(true, Processor.SupportedInput, Processor.SupportedOutput);
|
||||
Status.SetDirectory(true);
|
||||
var gate = new MediaProcessingGate(mediaOptions);
|
||||
var guard = new MediaUploadGuard(Processor, gate, Status, mediaOptions);
|
||||
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache);
|
||||
Service = new HeroService(Repository, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
|
||||
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
|
||||
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time);
|
||||
}
|
||||
|
||||
/// <summary>A photo-like fixture: the left half red, the right half blue, with a camera tag.</summary>
|
||||
public static byte[] Photo(int width = 1600, int height = 1067, MagickFormat format = MagickFormat.Jpeg, byte seed = 0)
|
||||
{
|
||||
using var image = new MagickImage(MagickColors.Red, (uint)width, (uint)height);
|
||||
using var blue = new MagickImage(MagickColors.Blue, (uint)(width / 2), (uint)height);
|
||||
image.Composite(blue, width - width / 2, 0, CompositeOperator.Over);
|
||||
if (seed > 0)
|
||||
{
|
||||
using var dot = new MagickImage(new MagickColor((byte)(seed * 20), 0, 0), 10, 10);
|
||||
image.Composite(dot, 3, 3, CompositeOperator.Over);
|
||||
}
|
||||
|
||||
var exif = new ExifProfile();
|
||||
exif.SetValue(ExifTag.Software, "camera firmware");
|
||||
image.SetProfile(exif);
|
||||
using var stream = new MemoryStream();
|
||||
image.Write(stream, format);
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
public Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> Upload(byte[] bytes)
|
||||
=> Images.UploadAsync(new MemoryStream(bytes), bytes.Length, Admin, CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Db.Dispose();
|
||||
if (System.IO.Directory.Exists(Directory))
|
||||
{
|
||||
System.IO.Directory.Delete(Directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="FsCheck.Xunit" Version="3.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
|
||||
<!-- Pinned above the version DataProtection pulls transitively (FR-22, OPEN-03) - see Core.csproj -->
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.14" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Microsoft.Extensions.Options" />
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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